diff --git a/3rdparty/Console/Getopt.php b/3rdparty/Console/Getopt.php deleted file mode 100644 index aec980b34d571e1ff1a28a6ce7b0aabefb42e1a1..0000000000000000000000000000000000000000 --- a/3rdparty/Console/Getopt.php +++ /dev/null @@ -1,251 +0,0 @@ -<?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 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.21.4.7 2003/12/05 21:57:01 andrei 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; - } 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. */; - else - return PEAR::raiseError("Console_Getopt: option requires an argument -- $opt"); - } - } - - $opts[] = array($opt, $opt_arg); - } - } - - /** - * @access private - * - */ - function _parseLongOption($arg, $long_options, &$opts, &$args) - { - @list($opt, $opt_arg) = explode('=', $arg); - $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); - - /* Option doesn't match. Go on to the next one. */ - if ($opt_start != $opt) - continue; - - $opt_rest = substr($long_opt, $opt_len); - - /* Check that the options uniquely matches one of the allowed - options. */ - if ($opt_rest != '' && $opt{0} != '=' && - $i + 1 < count($long_options) && - $opt == substr($long_options[$i+1], 0, $opt_len)) { - 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"); - } - } - } 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; - } - -} - -?> diff --git a/3rdparty/Crypt_Blowfish/Blowfish.php b/3rdparty/Crypt_Blowfish/Blowfish.php deleted file mode 100644 index a7b8948f043679ce6c5870438d82ae4a4a6ba7ff..0000000000000000000000000000000000000000 --- a/3rdparty/Crypt_Blowfish/Blowfish.php +++ /dev/null @@ -1,317 +0,0 @@ -<?php -/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ - -/** - * Crypt_Blowfish allows for encryption and decryption on the fly using - * the Blowfish algorithm. Crypt_Blowfish does not require the mcrypt - * PHP extension, it uses only PHP. - * Crypt_Blowfish support encryption/decryption with or without a secret key. - * - * - * 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 Encryption - * @package Crypt_Blowfish - * @author Matthew Fonda <mfonda@php.net> - * @copyright 2005 Matthew Fonda - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id: Blowfish.php,v 1.81 2005/05/30 18:40:36 mfonda Exp $ - * @link http://pear.php.net/package/Crypt_Blowfish - */ - - -require_once 'PEAR.php'; - - -/** - * - * Example usage: - * $bf = new Crypt_Blowfish('some secret key!'); - * $encrypted = $bf->encrypt('this is some example plain text'); - * $plaintext = $bf->decrypt($encrypted); - * echo "plain text: $plaintext"; - * - * - * @category Encryption - * @package Crypt_Blowfish - * @author Matthew Fonda <mfonda@php.net> - * @copyright 2005 Matthew Fonda - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @link http://pear.php.net/package/Crypt_Blowfish - * @version @package_version@ - * @access public - */ -class Crypt_Blowfish -{ - /** - * P-Array contains 18 32-bit subkeys - * - * @var array - * @access private - */ - var $_P = array(); - - - /** - * Array of four S-Blocks each containing 256 32-bit entries - * - * @var array - * @access private - */ - var $_S = array(); - - /** - * Mcrypt td resource - * - * @var resource - * @access private - */ - var $_td = null; - - /** - * Initialization vector - * - * @var string - * @access private - */ - var $_iv = null; - - - /** - * Crypt_Blowfish Constructor - * Initializes the Crypt_Blowfish object, and gives a sets - * the secret key - * - * @param string $key - * @access public - */ - function Crypt_Blowfish($key) - { - if (extension_loaded('mcrypt')) { - $this->_td = mcrypt_module_open(MCRYPT_BLOWFISH, '', 'ecb', ''); - $this->_iv = mcrypt_create_iv(8, MCRYPT_RAND); - } - $this->setKey($key); - } - - /** - * Deprecated isReady method - * - * @return bool - * @access public - * @deprecated - */ - function isReady() - { - return true; - } - - /** - * Deprecated init method - init is now a private - * method and has been replaced with _init - * - * @return bool - * @access public - * @deprecated - * @see Crypt_Blowfish::_init() - */ - function init() - { - $this->_init(); - } - - /** - * Initializes the Crypt_Blowfish object - * - * @access private - */ - function _init() - { - $defaults = new Crypt_Blowfish_DefaultKey(); - $this->_P = $defaults->P; - $this->_S = $defaults->S; - } - - /** - * Enciphers a single 64 bit block - * - * @param int &$Xl - * @param int &$Xr - * @access private - */ - function _encipher(&$Xl, &$Xr) - { - for ($i = 0; $i < 16; $i++) { - $temp = $Xl ^ $this->_P[$i]; - $Xl = ((($this->_S[0][($temp>>24) & 255] + - $this->_S[1][($temp>>16) & 255]) ^ - $this->_S[2][($temp>>8) & 255]) + - $this->_S[3][$temp & 255]) ^ $Xr; - $Xr = $temp; - } - $Xr = $Xl ^ $this->_P[16]; - $Xl = $temp ^ $this->_P[17]; - } - - - /** - * Deciphers a single 64 bit block - * - * @param int &$Xl - * @param int &$Xr - * @access private - */ - function _decipher(&$Xl, &$Xr) - { - for ($i = 17; $i > 1; $i--) { - $temp = $Xl ^ $this->_P[$i]; - $Xl = ((($this->_S[0][($temp>>24) & 255] + - $this->_S[1][($temp>>16) & 255]) ^ - $this->_S[2][($temp>>8) & 255]) + - $this->_S[3][$temp & 255]) ^ $Xr; - $Xr = $temp; - } - $Xr = $Xl ^ $this->_P[1]; - $Xl = $temp ^ $this->_P[0]; - } - - - /** - * Encrypts a string - * - * @param string $plainText - * @return string Returns cipher text on success, PEAR_Error on failure - * @access public - */ - function encrypt($plainText) - { - if (!is_string($plainText)) { - PEAR::raiseError('Plain text must be a string', 0, PEAR_ERROR_DIE); - } - - if (extension_loaded('mcrypt')) { - return mcrypt_generic($this->_td, $plainText); - } - - $cipherText = ''; - $len = strlen($plainText); - $plainText .= str_repeat(chr(0),(8 - ($len%8))%8); - for ($i = 0; $i < $len; $i += 8) { - list(,$Xl,$Xr) = unpack("N2",substr($plainText,$i,8)); - $this->_encipher($Xl, $Xr); - $cipherText .= pack("N2", $Xl, $Xr); - } - return $cipherText; - } - - - /** - * Decrypts an encrypted string - * - * @param string $cipherText - * @return string Returns plain text on success, PEAR_Error on failure - * @access public - */ - function decrypt($cipherText) - { - if (!is_string($cipherText)) { - PEAR::raiseError('Chiper text must be a string', 1, PEAR_ERROR_DIE); - } - - if (extension_loaded('mcrypt')) { - return mdecrypt_generic($this->_td, $cipherText); - } - - $plainText = ''; - $len = strlen($cipherText); - $cipherText .= str_repeat(chr(0),(8 - ($len%8))%8); - for ($i = 0; $i < $len; $i += 8) { - list(,$Xl,$Xr) = unpack("N2",substr($cipherText,$i,8)); - $this->_decipher($Xl, $Xr); - $plainText .= pack("N2", $Xl, $Xr); - } - return $plainText; - } - - - /** - * Sets the secret key - * The key must be non-zero, and less than or equal to - * 56 characters in length. - * - * @param string $key - * @return bool Returns true on success, PEAR_Error on failure - * @access public - */ - function setKey($key) - { - if (!is_string($key)) { - PEAR::raiseError('Key must be a string', 2, PEAR_ERROR_DIE); - } - - $len = strlen($key); - - if ($len > 56 || $len == 0) { - PEAR::raiseError('Key must be less than 56 characters and non-zero. Supplied key length: ' . $len, 3, PEAR_ERROR_DIE); - } - - if (extension_loaded('mcrypt')) { - mcrypt_generic_init($this->_td, $key, $this->_iv); - return true; - } - - require_once 'Blowfish/DefaultKey.php'; - $this->_init(); - - $k = 0; - $data = 0; - $datal = 0; - $datar = 0; - - for ($i = 0; $i < 18; $i++) { - $data = 0; - for ($j = 4; $j > 0; $j--) { - $data = $data << 8 | ord($key{$k}); - $k = ($k+1) % $len; - } - $this->_P[$i] ^= $data; - } - - for ($i = 0; $i <= 16; $i += 2) { - $this->_encipher($datal, $datar); - $this->_P[$i] = $datal; - $this->_P[$i+1] = $datar; - } - for ($i = 0; $i < 256; $i += 2) { - $this->_encipher($datal, $datar); - $this->_S[0][$i] = $datal; - $this->_S[0][$i+1] = $datar; - } - for ($i = 0; $i < 256; $i += 2) { - $this->_encipher($datal, $datar); - $this->_S[1][$i] = $datal; - $this->_S[1][$i+1] = $datar; - } - for ($i = 0; $i < 256; $i += 2) { - $this->_encipher($datal, $datar); - $this->_S[2][$i] = $datal; - $this->_S[2][$i+1] = $datar; - } - for ($i = 0; $i < 256; $i += 2) { - $this->_encipher($datal, $datar); - $this->_S[3][$i] = $datal; - $this->_S[3][$i+1] = $datar; - } - - return true; - } - -} - -?> diff --git a/3rdparty/Crypt_Blowfish/Blowfish/DefaultKey.php b/3rdparty/Crypt_Blowfish/Blowfish/DefaultKey.php deleted file mode 100644 index 2ff8ac788a6b62a4abde68d476c673612b8bfe01..0000000000000000000000000000000000000000 --- a/3rdparty/Crypt_Blowfish/Blowfish/DefaultKey.php +++ /dev/null @@ -1,327 +0,0 @@ -<?php -/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ - -/** - * Crypt_Blowfish allows for encryption and decryption on the fly using - * the Blowfish algorithm. Crypt_Blowfish does not require the mcrypt - * PHP extension, it uses only PHP. - * Crypt_Blowfish support encryption/decryption with or without a secret key. - * - * - * 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 Encryption - * @package Crypt_Blowfish - * @author Matthew Fonda <mfonda@php.net> - * @copyright 2005 Matthew Fonda - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id: DefaultKey.php,v 1.81 2005/05/30 18:40:37 mfonda Exp $ - * @link http://pear.php.net/package/Crypt_Blowfish - */ - - -/** - * Class containing default key - * - * @category Encryption - * @package Crypt_Blowfish - * @author Matthew Fonda <mfonda@php.net> - * @copyright 2005 Matthew Fonda - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @link http://pear.php.net/package/Crypt_Blowfish - * @version @package_version@ - * @access public - */ -class Crypt_Blowfish_DefaultKey -{ - var $P = array(); - - var $S = array(); - - function Crypt_Blowfish_DefaultKey() - { - $this->P = array( - 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, - 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, - 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, - 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917, - 0x9216D5D9, 0x8979FB1B - ); - - $this->S = array( - array( - 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, - 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, - 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16, - 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, - 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE, - 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, - 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF, - 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, - 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60, - 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, - 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, - 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A, - 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, - 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677, - 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, - 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032, - 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, - 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239, - 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, - 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, - 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3, - 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, - 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88, - 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, - 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6, - 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, - 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B, - 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, - 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, - 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463, - 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, - 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09, - 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, - 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB, - 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, - 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8, - 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, - 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, - 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, - 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, - 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0, - 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, - 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790, - 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, - 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4, - 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, - 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, - 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C, - 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, - 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1, - 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, - 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9, - 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, - 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF, - 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, - 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, - 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA, - 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, - 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41, - 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, - 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400, - 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, - 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664, - 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A - ), - array( - 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, - 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, - 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1, - 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, - 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6, - 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, - 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E, - 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, - 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737, - 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, - 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, - 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD, - 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, - 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7, - 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, - 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331, - 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, - 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF, - 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, - 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, - 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, - 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, - 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16, - 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, - 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B, - 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, - 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E, - 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, - 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, - 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A, - 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, - 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960, - 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, - 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28, - 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, - 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84, - 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, - 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, - 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14, - 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, - 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50, - 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, - 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8, - 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, - 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99, - 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, - 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, - 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, - 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, - 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0, - 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, - 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250, - 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, - 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285, - 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, - 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, - 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB, - 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, - 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735, - 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, - 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9, - 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, - 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20, - 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 - ), - array( - 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, - 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, - 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF, - 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, - 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45, - 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, - 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A, - 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, - 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE, - 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, - 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, - 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, - 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, - 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB, - 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, - 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B, - 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, - 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C, - 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, - 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, - 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17, - 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, - 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B, - 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, - 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922, - 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, - 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0, - 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, - 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, - 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, - 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, - 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B, - 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, - 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB, - 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, - 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C, - 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, - 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, - 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, - 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, - 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D, - 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, - 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F, - 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, - 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2, - 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, - 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, - 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C, - 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, - 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633, - 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, - 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169, - 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, - 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027, - 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, - 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, - 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634, - 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, - 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24, - 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, - 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4, - 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, - 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837, - 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 - ), - array( - 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, - 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, - 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B, - 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, - 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8, - 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, - 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304, - 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, - 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4, - 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, - 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, - 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59, - 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, - 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51, - 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, - 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C, - 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, - 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28, - 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, - 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, - 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A, - 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, - 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB, - 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, - 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991, - 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, - 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680, - 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, - 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, - 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, - 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, - 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47, - 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, - 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D, - 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, - 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048, - 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, - 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, - 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, - 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, - 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38, - 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, - 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C, - 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, - 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1, - 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, - 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, - 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E, - 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, - 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D, - 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, - 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299, - 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, - 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC, - 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, - 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, - 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, - 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, - 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0, - 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, - 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E, - 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, - 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F, - 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 - ) - ); - } - -} - -?> diff --git a/3rdparty/MDB2.php b/3rdparty/MDB2.php deleted file mode 100644 index aa7ec6ba093921a123898f97debe909a8eca00fa..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2.php +++ /dev/null @@ -1,4316 +0,0 @@ -<?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.335 2008/11/29 14:57:01 afz 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); -define('MDB2_ERROR_NO_PERMISSION', -36); -define('MDB2_ERROR_DISCONNECT_FAILED', -37); - -// }}} -// {{{ 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 - */ - static 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 - */ - static 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 - */ - static 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::raiseErrorStatic(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 - */ - static function factory($dsn, $options = false) - { - $dsninfo = MDB2::parseDSN($dsn); - if (empty($dsninfo['phptype'])) { - $err =MDB2::raiseErrorStatic(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_Driver_* 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 $dsn '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 $options 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 - */ - static 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 $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'unable to find: '.$file_name); - } - if (!include_once($file_name)) { - return $this->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.0b2'; - } - - // }}} - // {{{ 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; - } - static function raiseErrorStatic($code = null, - $mode = null, - $options = null, - $userinfo = null, - $dummy1 = null, - $dummy2 = null, - $dummy3 = false) - { - $pear=new PEAR(); - $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 - */ - static function isError($data, $code = null) - { - if ($data instanceof 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 - */ - static function isConnection($value) - { - return ($value instanceof 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 - */ - static function isResult($value) - { - return $value instanceof 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 - */ - static function isResultCommon($value) - { - return ($value instanceof 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 - */ - static function isStatement($value) - { - return $value instanceof 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 - */ - static 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', - MDB2_ERROR_NO_PERMISSION => 'no permission', - MDB2_ERROR_DISCONNECT_FAILED => 'disconnect failed', - ); - } - - 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> - */ - static 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 = substr($proto_opts, strrpos($proto_opts, '/') + 1); - } 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 - */ - static function fileExists($file) - { - // safe_mode does notwork with is_readable() - if (!@ini_get('safe_mode')) { - $dirs = explode(PATH_SEPARATOR, ini_get('include_path')); - array_unshift($dirs,OC::$SERVERROOT); - array_unshift($dirs,OC::$SERVERROOT. DIRECTORY_SEPARATOR .'inc'); -// print_r($dirs);die(); - 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 raPEAR_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, - 'triggers' => 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</li> - * <li>$options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed</li> - * <li>$options['max_identifiers_length'] -> integer: max identifier length</li> - * <li>$options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li> - * <li>$options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li> - * </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_]*)', - 'max_identifiers_length' => 30, - 'default_fk_action_onupdate' => 'RESTRICT', - 'default_fk_action_ondelete' => 'RESTRICT', - ); - - /** - * 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; - } - - - // }}} - // {{{ 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 $code integer error code, or a PEAR error object (all - * other parameters are ignored if this parameter is - * an object - * @param int $mode error mode, see PEAR_Error docs - * @param mixed $options 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 $userinfo Extra debug information. Defaults to the last - * query and native error code. - * @param string $method name of the method that triggered the error - * @param string $dummy1 not used - * @param bool $dummy2 not used - * - * @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, - $dummy1 = null, - $dummy2 = false - ) { - $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"; - } - echo $userinfo; - 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 - */ - static 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__); - } - - // }}} - // {{{ databaseExists() - - /** - * check if given database name is exists? - * - * @param string $name name of the database that should be checked - * - * @return mixed true/false on success, a MDB2 error on failure - * @access public - */ - function databaseExists($name) - { - 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 boolean $force whether 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; - if (!empty($this->connected_database_name) && ($this->connected_database_name != $this->database_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; - } - - // }}} - // {{{ _isNewLinkSet() - - /** - * Check if the 'new_link' option is set - * - * @return boolean - * - * @access protected - */ - function _isNewLinkSet() - { - return (isset($this->dsn['new_link']) - && ($this->dsn['new_link'] === true - || (is_string($this->dsn['new_link']) && preg_match('/^true$/i', $this->dsn['new_link'])) - || (is_numeric($this->dsn['new_link']) && 0 != (int)$this->dsn['new_link']) - ) - ); - } - - // }}} - // {{{ 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 old row is deleted before the new row is inserted. - * - * 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[] = $this->quoteIdentifier($name, true) . '=' . $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 ' . $this->quoteIdentifier($table, true) . $condition; - $result =$this->_doQuery($query, true, $connection); - if (!PEAR::isError($result)) { - $affected_rows = $this->_affectedRows($connection, $result); - $insert = ''; - foreach ($values as $key => $value) { - $insert .= ($insert?', ':'') . $this->quoteIdentifier($key, true); - } - $values = implode(', ', $values); - $query = 'INSERT INTO '. $this->quoteIdentifier($table, true) . "($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; - 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->string_quoting; - $ignores[] = $this->identifier_quoting; - $ignores = array_merge($ignores, $this->sql_comments); - - 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'] - && $end_quote-1 != $start_quote - && $query[($end_quote - 1)] == $ignore['escape'] - && ( $ignore['escape_pattern'] !== $ignore['escape'] - || $query[($end_quote - 2)] != $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 $query the SELECT query statement to be executed. - * @param string $type 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 mixed $colnum the column number (or name) 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 $query the SELECT query statement to be executed. - * @param string $type 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 mixed $colnum the column number (or name) 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 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|string the column number (or name) 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|string the column number (or name) 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]; - } - } -} - -// }}} -// {{{ 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 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->pushErrorHandling(PEAR_ERROR_RETURN); - $this->db->expectError(MDB2_ERROR_NOT_FOUND); - $err = $this->bindValue($parameter, $values[$parameter], $types[$key]); - $this->db->popExpect(); - $this->db->popErrorHandling(); - 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 MDB2_Result or integer (affected rows) 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 (affected rows) 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 &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 =$this->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; -} - -// }}} -?> diff --git a/3rdparty/MDB2/Date.php b/3rdparty/MDB2/Date.php deleted file mode 100644 index ce846543a50e8383fe1fa2140ec8903c8a48daf2..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Date.php +++ /dev/null @@ -1,183 +0,0 @@ -<?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.10 2006/03/01 12:15:32 lsmith 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; - } - // }}} -} - -?> diff --git a/3rdparty/MDB2/Driver/Datatype/Common.php b/3rdparty/MDB2/Driver/Datatype/Common.php deleted file mode 100644 index 85a74f64fca85f3d06ae56284f248eb27428ecae..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Datatype/Common.php +++ /dev/null @@ -1,1824 +0,0 @@ -<?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.139 2008/12/04 11:50:42 afz 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']); - - $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; - $default = ''; - if (array_key_exists('default', $field)) { - if ($field['default'] === '') { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $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'] = ' '; - } - } - if (!is_null($field['default'])) { - $default = ' DEFAULT ' . $this->quote($field['default'], $field['type']); - } - } - - $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('/[^\.\d]/', $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; - } -} -?> diff --git a/3rdparty/MDB2/Driver/Datatype/mysql.php b/3rdparty/MDB2/Driver/Datatype/mysql.php deleted file mode 100644 index 93dd40524e6795ac4f2ee1a5a152df0d9fb22f63..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Datatype/mysql.php +++ /dev/null @@ -1,553 +0,0 @@ -<?php -// vim: set et ts=4 sw=4 fdm=marker: -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 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: mysql.php,v 1.65 2008/02/22 19:23:49 quipo Exp $ -// - -require_once('MDB2/Driver/Datatype/Common.php'); - -/** - * MDB2 MySQL driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Driver_Datatype_mysql extends MDB2_Driver_Datatype_Common -{ - // {{{ _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 'CHARACTER SET '.$charset; - } - - // }}} - // {{{ _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 'COLLATE '.$collation; - } - - // }}} - // {{{ 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': - if (empty($field['length']) && array_key_exists('default', $field)) { - $field['length'] = $db->varchar_max_length; - } - $length = !empty($field['length']) ? $field['length'] : false; - $fixed = !empty($field['fixed']) ? $field['fixed'] : false; - return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)') - : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); - case 'clob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYTEXT'; - } elseif ($length <= 65532) { - return 'TEXT'; - } elseif ($length <= 16777215) { - return 'MEDIUMTEXT'; - } - } - return 'LONGTEXT'; - case 'blob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYBLOB'; - } elseif ($length <= 65532) { - return 'BLOB'; - } elseif ($length <= 16777215) { - return 'MEDIUMBLOB'; - } - } - return 'LONGBLOB'; - case 'integer': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 1) { - return 'TINYINT'; - } elseif ($length == 2) { - return 'SMALLINT'; - } elseif ($length == 3) { - return 'MEDIUMINT'; - } elseif ($length == 4) { - return 'INT'; - } elseif ($length > 4) { - return 'BIGINT'; - } - } - return 'INT'; - case 'boolean': - return 'TINYINT(1)'; - case 'date': - return 'DATE'; - case 'time': - return 'TIME'; - case 'timestamp': - return 'DATETIME'; - case 'float': - return 'DOUBLE'; - case 'decimal': - $length = !empty($field['length']) ? $field['length'] : 18; - $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places']; - return 'DECIMAL('.$length.','.$scale.')'; - } - 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 string $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; - } - - $default = $autoinc = ''; - if (!empty($field['autoincrement'])) { - $autoinc = ' AUTO_INCREMENT PRIMARY KEY'; - } elseif (array_key_exists('default', $field)) { - if ($field['default'] === '') { - $field['default'] = empty($field['notnull']) ? null : 0; - } - $default = ' DEFAULT '.$this->quote($field['default'], 'integer'); - } - - $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; - $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED'; - $name = $db->quoteIdentifier($name, true); - return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc; - } - - // }}} - // {{{ _getFloatDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an float type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param string $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 float if - * possible. - * - * 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) - { - // Since AUTO_INCREMENT can be used for integer or floating-point types, - // reuse the INTEGER declaration - // @see http://bugs.mysql.com/bug.php?id=31032 - return $this->_getIntegerDeclaration($name, $field); - } - - // }}} - // {{{ _getDecimalDeclaration() - - /** - * Obtain DBMS specific SQL code portion needed to declare an decimal type - * field to be used in statements like CREATE TABLE. - * - * @param string $name name the field to be declared. - * @param string $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 - * 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) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $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'; - $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED'; - $name = $db->quoteIdentifier($name, true); - return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull; - } - - // }}} - // {{{ 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.'LIKE '; - break; - // case sensitive - case 'LIKE': - $match = $field.'LIKE BINARY '; - 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; - } - - // }}} - // {{{ _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']); - $db_type = strtok($db_type, '(), '); - if ($db_type == 'national') { - $db_type = strtok('(), '); - } - if (!empty($field['length'])) { - $length = strtok($field['length'], ', '); - $decimal = strtok(', '); - } else { - $length = strtok('(), '); - $decimal = strtok('(), '); - } - $type = array(); - $unsigned = $fixed = null; - switch ($db_type) { - case 'tinyint': - $type[] = 'integer'; - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 1; - break; - case 'smallint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 2; - break; - case 'mediumint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 3; - break; - case 'int': - case 'integer': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 4; - break; - case 'bigint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 8; - break; - case 'tinytext': - case 'mediumtext': - case 'longtext': - case 'text': - case 'varchar': - $fixed = false; - case 'string': - case 'char': - $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'; - if ($decimal == 'binary') { - $type[] = 'blob'; - } - $type = array_reverse($type); - } - if ($fixed !== false) { - $fixed = true; - } - break; - case 'enum': - $type[] = 'text'; - preg_match_all('/\'.+\'/U', $field['type'], $matches); - $length = 0; - $fixed = false; - if (is_array($matches)) { - foreach ($matches[0] as $value) { - $length = max($length, strlen($value)-2); - } - if ($length == '1' && count($matches[0]) == 2) { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } - } - $type[] = 'integer'; - case 'set': - $fixed = false; - $type[] = 'text'; - $type[] = 'integer'; - 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 'double': - case 'real': - $type[] = 'float'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - break; - case 'unknown': - case 'decimal': - case 'numeric': - $type[] = 'decimal'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - if ($decimal !== false) { - $length = $length.','.$decimal; - } - break; - case 'tinyblob': - case 'mediumblob': - case 'longblob': - case 'blob': - $type[] = 'blob'; - $length = null; - break; - case 'binary': - case 'varbinary': - $type[] = 'blob'; - 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); - } - - // }}} -} - -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Datatype/pgsql.php b/3rdparty/MDB2/Driver/Datatype/pgsql.php deleted file mode 100644 index e72aa743b738cc722dab21b2bc3c81d7470ef138..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Datatype/pgsql.php +++ /dev/null @@ -1,554 +0,0 @@ -<?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.93 2008/08/28 20:32:57 afz 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'] : false; - $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'); - } - - $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': - case 'timestamptz': - $type[] = 'timestamp'; - $length = null; - break; - case 'time': - $type[] = 'time'; - $length = null; - break; - case 'float': - case 'float4': - 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 diff --git a/3rdparty/MDB2/Driver/Datatype/sqlite.php b/3rdparty/MDB2/Driver/Datatype/sqlite.php deleted file mode 100644 index 9e57e7e56783eb99714274209e0d26f7e41203ed..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Datatype/sqlite.php +++ /dev/null @@ -1,409 +0,0 @@ -<?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: sqlite.php,v 1.67 2008/02/22 19:58:06 quipo Exp $ -// - -require_once('MDB2/Driver/Datatype/Common.php'); - -/** - * MDB2 SQLite driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Driver_Datatype_sqlite extends MDB2_Driver_Datatype_Common -{ - // {{{ _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 'COLLATE '.$collation; - } - - // }}} - // {{{ 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'] : false; - $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': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYTEXT'; - } elseif ($length <= 65532) { - return 'TEXT'; - } elseif ($length <= 16777215) { - return 'MEDIUMTEXT'; - } - } - return 'LONGTEXT'; - case 'blob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYBLOB'; - } elseif ($length <= 65532) { - return 'BLOB'; - } elseif ($length <= 16777215) { - return 'MEDIUMBLOB'; - } - } - return 'LONGBLOB'; - case 'integer': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 2) { - return 'SMALLINT'; - } elseif ($length == 3 || $length == 4) { - return 'INTEGER'; - } elseif ($length > 4) { - return 'BIGINT'; - } - } - return 'INTEGER'; - case 'boolean': - return 'BOOLEAN'; - case 'date': - return 'DATE'; - case 'time': - return 'TIME'; - case 'timestamp': - return 'DATETIME'; - case 'float': - return 'DOUBLE'.($db->options['fixed_float'] ? '('. - ($db->options['fixed_float']+2).','.$db->options['fixed_float'].')' : ''); - case 'decimal': - $length = !empty($field['length']) ? $field['length'] : 18; - $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places']; - return 'DECIMAL('.$length.','.$scale.')'; - } - 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 string $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; - } - - $default = $autoinc = ''; - if (!empty($field['autoincrement'])) { - $autoinc = ' PRIMARY KEY'; - } elseif (array_key_exists('default', $field)) { - if ($field['default'] === '') { - $field['default'] = empty($field['notnull']) ? null : 0; - } - $default = ' DEFAULT '.$this->quote($field['default'], 'integer'); - } - - $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; - $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED'; - $name = $db->quoteIdentifier($name, true); - return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc; - } - - // }}} - // {{{ 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.'LIKE '; - 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; - } - - // }}} - // {{{ _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 = !empty($field['length']) ? $field['length'] : null; - $unsigned = !empty($field['unsigned']) ? $field['unsigned'] : null; - $fixed = null; - $type = array(); - switch ($db_type) { - case 'boolean': - $type[] = 'boolean'; - break; - case 'tinyint': - $type[] = 'integer'; - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 1; - break; - case 'smallint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 2; - break; - case 'mediumint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 3; - break; - case 'int': - case 'integer': - case 'serial': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 4; - break; - case 'bigint': - case 'bigserial': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 8; - break; - case 'clob': - $type[] = 'clob'; - $fixed = false; - break; - case 'tinytext': - case 'mediumtext': - case 'longtext': - case 'text': - case 'varchar': - case 'varchar2': - $fixed = false; - case 'char': - $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 'double': - case 'real': - $type[] = 'float'; - break; - case 'decimal': - case 'numeric': - $type[] = 'decimal'; - $length = $length.','.$field['decimal']; - break; - case 'tinyblob': - case 'mediumblob': - case 'longblob': - case 'blob': - $type[] = 'blob'; - $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); - } - - // }}} -} - -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Function/Common.php b/3rdparty/MDB2/Driver/Function/Common.php deleted file mode 100644 index 731f06882ce52a603f1a7bd7ecef5b7c8c23a6f4..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Function/Common.php +++ /dev/null @@ -1,293 +0,0 @@ -<?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.21 2008/02/17 18:51:39 quipo 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) - * - * @param string $type 'timestamp' | 'time' | 'date' - * - * @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'; - } - } - - // }}} - // {{{ unixtimestamp() - - /** - * return string to call a function to get the unix timestamp from a iso timestamp - * - * @param string $expression - * - * @return string to call a variable with the timestamp - * @access public - */ - function unixtimestamp($expression) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - return $error; - } - - // }}} - // {{{ 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)"; - } - - // }}} - // {{{ replace() - - /** - * return string to call a function to get replace inside an SQL statement. - * - * @return string to call a function to get a replace - * @access public - */ - function replace($str, $from_str, $to_str) - { - return "REPLACE($str, $from_str , $to_str)"; - } - - // }}} - // {{{ 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 diff --git a/3rdparty/MDB2/Driver/Function/mysql.php b/3rdparty/MDB2/Driver/Function/mysql.php deleted file mode 100644 index 44183c3aa0674baf7f7b50f2f246cb571335bb3f..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Function/mysql.php +++ /dev/null @@ -1,136 +0,0 @@ -<?php -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 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: mysql.php,v 1.12 2008/02/17 18:54:08 quipo 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_mysql 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 = 'CALL '.$name; - $query .= $params ? '('.implode(', ', $params).')' : '()'; - return $db->query($query, $types, $result_class, $result_wrap_class); - } - - // }}} - // {{{ unixtimestamp() - - /** - * return string to call a function to get the unix timestamp from a iso timestamp - * - * @param string $expression - * - * @return string to call a variable with the timestamp - * @access public - */ - function unixtimestamp($expression) - { - return 'UNIX_TIMESTAMP('. $expression.')'; - } - - // }}} - // {{{ 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 "CONCAT(".implode(', ', $args).")"; - } - - // }}} - // {{{ guid() - - /** - * Returns global unique identifier - * - * @return string to get global unique identifier - * @access public - */ - function guid() - { - return 'UUID()'; - } - - // }}} -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Function/pgsql.php b/3rdparty/MDB2/Driver/Function/pgsql.php deleted file mode 100644 index 173bfc9149473d57b3641d1ea134b5bc0f4eda68..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Function/pgsql.php +++ /dev/null @@ -1,115 +0,0 @@ -<?php -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 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.11 2008/11/09 19:46:50 quipo 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); - } - // }}} - // {{{ unixtimestamp() - - /** - * return string to call a function to get the unix timestamp from a iso timestamp - * - * @param string $expression - * - * @return string to call a variable with the timestamp - * @access public - */ - function unixtimestamp($expression) - { - return 'EXTRACT(EPOCH FROM DATE_TRUNC(\'seconds\', CAST ((' . $expression . ') AS TIMESTAMP)))'; - } - - // }}} - // {{{ 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()'; - } - - // }}} -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Function/sqlite.php b/3rdparty/MDB2/Driver/Function/sqlite.php deleted file mode 100644 index 8a5b7ec8fad628c4cfc9cdbe61e57c9dd309c871..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Function/sqlite.php +++ /dev/null @@ -1,162 +0,0 @@ -<?php -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 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: sqlite.php,v 1.10 2008/02/17 18:54:08 quipo Exp $ -// - -require_once('MDB2/Driver/Function/Common.php'); - -/** - * MDB2 SQLite driver for the function modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Driver_Function_sqlite extends MDB2_Driver_Function_Common -{ - // {{{ constructor - - /** - * Constructor - */ - function __construct($db_index) - { - parent::__construct($db_index); - // create all sorts of UDFs - } - - // {{{ 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. - * - * @return string to call a variable with the current timestamp - * @access public - */ - function now($type = 'timestamp') - { - switch ($type) { - case 'time': - return 'time(\'now\')'; - case 'date': - return 'date(\'now\')'; - case 'timestamp': - default: - return 'datetime(\'now\')'; - } - } - - // }}} - // {{{ unixtimestamp() - - /** - * return string to call a function to get the unix timestamp from a iso timestamp - * - * @param string $expression - * - * @return string to call a variable with the timestamp - * @access public - */ - function unixtimestamp($expression) - { - return 'strftime("%s",'. $expression.', "utc")'; - } - - // }}} - // {{{ 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 "substr($value,$position,$length)"; - } - return "substr($value,$position,length($value))"; - } - - // }}} - // {{{ 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()+2147483648)/4294967296)'; - } - - // }}} - // {{{ replace() - - /** - * return string to call a function to get a replacement inside an SQL statement. - * - * @return string to call a function to get a replace - * @access public - */ - function replace($str, $from_str, $to_str) - { - $db =& $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - return $error; - } - - // }}} -} -?> diff --git a/3rdparty/MDB2/Driver/Manager/Common.php b/3rdparty/MDB2/Driver/Manager/Common.php deleted file mode 100644 index 9e16749bffc49b12d2c7ec296f40da06562b7bad..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Manager/Common.php +++ /dev/null @@ -1,1014 +0,0 @@ -<?php -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 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: Lukas Smith <smith@pooteeweet.org> | -// | Lorenzo Alberton <l.alberton@quipo.it> | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php,v 1.72 2009/01/14 15:00:40 quipo Exp $ -// - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - * @author Lorenzo Alberton <l.alberton@quipo.it> - */ - -/** - * 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 - * - * @param string $table [schema and] table name - * - * @return array array(schema, table) - * @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__); - } - - // }}} - // {{{ alterDatabase() - - /** - * alter an existing 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 alterDatabase($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"); - } - - // }}} - // {{{ truncateTable() - - /** - * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported, - * it falls back to a DELETE FROM TABLE query) - * - * @param string $name name of the table that should be truncated - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function truncateTable($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - return $db->exec("DELETE FROM $name"); - } - - // }}} - // {{{ vacuum() - - /** - * Optimize (vacuum) all the tables in the db (or only the specified table) - * and optionally run ANALYZE. - * - * @param string $table table name (all the tables if empty) - * @param array $options an array with driver-specific options: - * - timeout [int] (in seconds) [mssql-only] - * - analyze [boolean] [pgsql and mysql] - * - full [boolean] [pgsql-only] - * - freeze [boolean] [pgsql-only] - * - * @return mixed MDB2_OK success, a MDB2 error on failure - * @access public - */ - function vacuum($table = null, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'method not implemented', __FUNCTION__); - } - - // }}} - // {{{ 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 diff --git a/3rdparty/MDB2/Driver/Manager/mysql.php b/3rdparty/MDB2/Driver/Manager/mysql.php deleted file mode 100644 index 099ed48a84ffbb939face2c8c77f064daa99b486..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Manager/mysql.php +++ /dev/null @@ -1,1432 +0,0 @@ -<?php -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 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: mysql.php,v 1.113 2008/11/23 20:30:29 quipo Exp $ -// - -require_once('MDB2/Driver/Manager/Common.php'); - -/** - * MDB2 MySQL driver for the management modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Driver_Manager_mysql 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, collation 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 .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text'); - } - if (!empty($options['collation'])) { - $query .= ' COLLATE ' . $db->quote($options['collation'], 'text'); - } - return $db->standaloneQuery($query, null, true); - } - - // }}} - // {{{ alterDatabase() - - /** - * alter an existing database - * - * @param string $name name of the database that is intended to be changed - * @param array $options array with charset, collation info - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function alterDatabase($name, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true); - if (!empty($options['charset'])) { - $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text'); - } - if (!empty($options['collation'])) { - $query .= ' COLLATE ' . $db->quote($options['collation'], '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); - $query = "DROP DATABASE $name"; - return $db->standaloneQuery($query, 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']; - } - return $query; - } - - // }}} - // {{{ 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', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * 'type' => 'innodb', - * ); - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createTable($name, $fields, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - // if we have an AUTO_INCREMENT column and a PK on more than one field, - // we have to handle it differently... - $autoincrement = null; - if (empty($options['primary'])) { - $pk_fields = array(); - foreach ($fields as $fieldname => $def) { - if (!empty($def['primary'])) { - $pk_fields[$fieldname] = true; - } - if (!empty($def['autoincrement'])) { - $autoincrement = $fieldname; - } - } - if (!is_null($autoincrement) && count($pk_fields) > 1) { - $options['primary'] = $pk_fields; - } else { - // the PK constraint is on max one field => OK - $autoincrement = null; - } - } - - $query = $this->_getCreateTableQuery($name, $fields, $options); - if (PEAR::isError($query)) { - return $query; - } - - if (!is_null($autoincrement)) { - // we have to remove the PK clause added by _getIntegerDeclaration() - $query = str_replace('AUTO_INCREMENT PRIMARY KEY', 'AUTO_INCREMENT', $query); - } - - $options_strings = array(); - - if (!empty($options['comment'])) { - $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text'); - } - - if (!empty($options['charset'])) { - $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset']; - if (!empty($options['collate'])) { - $options_strings['charset'].= ' COLLATE '.$options['collate']; - } - } - - $type = false; - if (!empty($options['type'])) { - $type = $options['type']; - } elseif ($db->options['default_table_type']) { - $type = $db->options['default_table_type']; - } - if ($type) { - $options_strings[] = "ENGINE = $type"; - } - - if (!empty($options_strings)) { - $query .= ' '.implode(' ', $options_strings); - } - $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; - } - - //delete the triggers associated to existing FK constraints - $constraints = $this->listTableConstraints($name); - if (!PEAR::isError($constraints) && !empty($constraints)) { - $db->loadModule('Reverse', null, true); - foreach ($constraints as $constraint) { - $definition = $db->reverse->getTableConstraintDefinition($name, $constraint); - if (!PEAR::isError($definition) && !empty($definition['foreign'])) { - $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']); - if (PEAR::isError($result)) { - return $result; - } - } - } - } - - return parent::dropTable($name); - } - - // }}} - // {{{ truncateTable() - - /** - * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported, - * it falls back to a DELETE FROM TABLE query) - * - * @param string $name name of the table that should be truncated - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function truncateTable($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - return $db->exec("TRUNCATE TABLE $name"); - } - - // }}} - // {{{ vacuum() - - /** - * Optimize (vacuum) all the tables in the db (or only the specified table) - * and optionally run ANALYZE. - * - * @param string $table table name (all the tables if empty) - * @param array $options an array with driver-specific options: - * - timeout [int] (in seconds) [mssql-only] - * - analyze [boolean] [pgsql and mysql] - * - full [boolean] [pgsql-only] - * - freeze [boolean] [pgsql-only] - * - * @return mixed MDB2_OK success, a MDB2 error on failure - * @access public - */ - function vacuum($table = null, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - if (empty($table)) { - $table = $this->listTables(); - if (PEAR::isError($table)) { - return $table; - } - } - if (is_array($table)) { - foreach (array_keys($table) as $k) { - $table[$k] = $db->quoteIdentifier($table[$k], true); - } - $table = implode(', ', $table); - } else { - $table = $db->quoteIdentifier($table, true); - } - - $result = $db->exec('OPTIMIZE TABLE '.$table); - if (PEAR::isError($result)) { - return $result; - } - if (!empty($options['analyze'])) { - return $db->exec('ANALYZE TABLE '.$table); - } - return MDB2_OK; - } - - // }}} - // {{{ 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 'rename': - case 'name': - break; - default: - return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null, - 'change type "'.$change_name.'" not yet supported', __FUNCTION__); - } - } - - if ($check) { - return MDB2_OK; - } - - $query = ''; - if (!empty($changes['name'])) { - $change_name = $db->quoteIdentifier($changes['name'], true); - $query .= 'RENAME TO ' . $change_name; - } - - if (!empty($changes['add']) && is_array($changes['add'])) { - foreach ($changes['add'] as $field_name => $field) { - if ($query) { - $query.= ', '; - } - $query.= 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field); - } - } - - if (!empty($changes['remove']) && is_array($changes['remove'])) { - foreach ($changes['remove'] as $field_name => $field) { - if ($query) { - $query.= ', '; - } - $field_name = $db->quoteIdentifier($field_name, true); - $query.= 'DROP ' . $field_name; - } - } - - $rename = array(); - if (!empty($changes['rename']) && is_array($changes['rename'])) { - foreach ($changes['rename'] as $field_name => $field) { - $rename[$field['name']] = $field_name; - } - } - - if (!empty($changes['change']) && is_array($changes['change'])) { - foreach ($changes['change'] as $field_name => $field) { - if ($query) { - $query.= ', '; - } - if (isset($rename[$field_name])) { - $old_field_name = $rename[$field_name]; - unset($rename[$field_name]); - } else { - $old_field_name = $field_name; - } - $old_field_name = $db->quoteIdentifier($old_field_name, true); - $query.= "CHANGE $old_field_name " . $db->getDeclaration($field['definition']['type'], $field_name, $field['definition']); - } - } - - if (!empty($rename) && is_array($rename)) { - foreach ($rename as $rename_name => $renamed_field) { - if ($query) { - $query.= ', '; - } - $field = $changes['rename'][$renamed_field]; - $renamed_field = $db->quoteIdentifier($renamed_field, true); - $query.= 'CHANGE ' . $renamed_field . ' ' . $db->getDeclaration($field['definition']['type'], $field['name'], $field['definition']); - } - } - - if (!$query) { - return MDB2_OK; - } - - $name = $db->quoteIdentifier($name, true); - return $db->exec("ALTER TABLE $name $query"); - } - - // }}} - // {{{ 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; - } - - $result = $db->queryCol('SHOW DATABASES'); - 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; - } - - return $db->queryCol('SELECT DISTINCT USER FROM mysql.USER'); - } - - // }}} - // {{{ 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 name FROM mysql.proc"; - /* - SELECT ROUTINE_NAME - FROM INFORMATION_SCHEMA.ROUTINES - WHERE ROUTINE_TYPE = 'FUNCTION' - */ - $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 = 'SHOW TRIGGERS'; - if (!is_null($table)) { - $table = $db->quote($table, 'text'); - $query .= " LIKE $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 - * - * @param string database, the current is default - * @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; - } - - $query = "SHOW /*!50002 FULL*/ TABLES"; - if (!is_null($database)) { - $query .= " FROM $database"; - } - $query.= "/*!50002 WHERE Table_type = 'BASE TABLE'*/"; - - $table_names = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED); - if (PEAR::isError($table_names)) { - return $table_names; - } - - $result = array(); - foreach ($table_names as $table) { - if (!$this->_fixSequenceName($table[0], true)) { - $result[] = $table[0]; - } - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} - // {{{ listViews() - - /** - * list all views in the current database - * - * @param string database, the current is default - * @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; - } - - $query = 'SHOW FULL TABLES'; - if (!is_null($database)) { - $query.= " FROM $database"; - } - $query.= " WHERE Table_type = 'VIEW'"; - - $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); - $result = $db->queryCol("SHOW COLUMNS FROM $table"); - 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; - } - - // }}} - // {{{ createIndex() - - /** - * Get the stucture of a field into an array - * - * @author Leoncx - * @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' - * 'length' => 10 - * ), - * '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 ($definition['fields'] as $field => $fieldinfo) { - if (!empty($fieldinfo['length'])) { - $fields[] = $db->quoteIdentifier($field, true) . '(' . $fieldinfo['length'] . ')'; - } else { - $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; - } - - $table = $db->quoteIdentifier($table, true); - $name = $db->quoteIdentifier($db->getIndexName($name), true); - return $db->exec("DROP INDEX $name ON $table"); - } - - // }}} - // {{{ 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; - } - - $key_name = 'Key_name'; - $non_unique = 'Non_unique'; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $key_name = strtolower($key_name); - $non_unique = strtolower($non_unique); - } else { - $key_name = strtoupper($key_name); - $non_unique = strtoupper($non_unique); - } - } - - $table = $db->quoteIdentifier($table, true); - $query = "SHOW INDEX FROM $table"; - $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($indexes)) { - return $indexes; - } - - $result = array(); - foreach ($indexes as $index_data) { - if ($index_data[$non_unique] && ($index = $this->_fixIndexName($index_data[$key_name]))) { - $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); - } - - // }}} - // {{{ 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. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the constraint fields as array - * constraints. Each entry of this array is set to another type of associative - * array that specifies properties of the constraint that are specific to - * each field. - * - * Example - * array( - * 'fields' => array( - * 'user_name' => array(), - * 'last_login' => array() - * ) - * ) - * @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; - } - - $type = ''; - $idx_name = $db->quoteIdentifier($db->getIndexName($name), true); - if (!empty($definition['primary'])) { - $type = 'PRIMARY'; - $idx_name = 'KEY'; - } elseif (!empty($definition['unique'])) { - $type = 'UNIQUE'; - } elseif (!empty($definition['foreign'])) { - $type = 'CONSTRAINT'; - } - if (empty($type)) { - return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'invalid definition, could not create constraint', __FUNCTION__); - } - - $table_quoted = $db->quoteIdentifier($table, true); - $query = "ALTER TABLE $table_quoted ADD $type $idx_name"; - if (!empty($definition['foreign'])) { - $query .= ' FOREIGN KEY'; - } - $fields = array(); - foreach ($definition['fields'] as $field => $fieldinfo) { - $quoted = $db->quoteIdentifier($field, true); - if (!empty($fieldinfo['length'])) { - $quoted .= '(' . $fieldinfo['length'] . ')'; - } - $fields[] = $quoted; - } - $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); - - // add index on FK column(s) or we can't add a FK constraint - // @see http://forums.mysql.com/read.php?22,19755,226009 - $result = $this->createIndex($table, $name.'_fkidx', $definition); - if (PEAR::isError($result)) { - return $result; - } - } - $res = $db->exec($query); - if (PEAR::isError($res)) { - return $res; - } - if (!empty($definition['foreign'])) { - return $this->_createFKTriggers($table, array($name => $definition)); - } - return MDB2_OK; - } - - // }}} - // {{{ 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; - } - - if ($primary || strtolower($name) == 'primary') { - $query = 'ALTER TABLE '. $db->quoteIdentifier($table, true) .' DROP PRIMARY KEY'; - return $db->exec($query); - } - - //is it a FK constraint? If so, also delete the associated triggers - $db->loadModule('Reverse', null, true); - $definition = $db->reverse->getTableConstraintDefinition($table, $name); - if (!PEAR::isError($definition) && !empty($definition['foreign'])) { - //first drop the FK enforcing triggers - $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']); - if (PEAR::isError($result)) { - return $result; - } - //then drop the constraint itself - $table = $db->quoteIdentifier($table, true); - $name = $db->quoteIdentifier($db->getIndexName($name), true); - $query = "ALTER TABLE $table DROP FOREIGN KEY $name"; - return $db->exec($query); - } - - $table = $db->quoteIdentifier($table, true); - $name = $db->quoteIdentifier($db->getIndexName($name), true); - $query = "ALTER TABLE $table DROP INDEX $name"; - return $db->exec($query); - } - - // }}} - // {{{ _createFKTriggers() - - /** - * Create triggers to enforce the FOREIGN KEY constraint on the table - * - * NB: since there's no RAISE_APPLICATION_ERROR facility in mysql, - * we call a non-existent procedure to raise the FK violation message. - * @see http://forums.mysql.com/read.php?99,55108,71877#msg-71877 - * - * @param string $table table name - * @param array $foreign_keys FOREIGN KEY definitions - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access private - */ - function _createFKTriggers($table, $foreign_keys) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - // create triggers to enforce FOREIGN KEY constraints - if ($db->supports('triggers') && !empty($foreign_keys)) { - $table_quoted = $db->quoteIdentifier($table, true); - foreach ($foreign_keys as $fkname => $fkdef) { - if (empty($fkdef)) { - continue; - } - //set actions to default if not set - $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']); - $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']); - - $trigger_names = array( - 'insert' => $fkname.'_insert_trg', - 'update' => $fkname.'_update_trg', - 'pk_update' => $fkname.'_pk_update_trg', - 'pk_delete' => $fkname.'_pk_delete_trg', - ); - $table_fields = array_keys($fkdef['fields']); - $referenced_fields = array_keys($fkdef['references']['fields']); - - //create the ON [UPDATE|DELETE] triggers on the primary table - $restrict_action = ' IF (SELECT '; - $aliased_fields = array(); - foreach ($table_fields as $field) { - $aliased_fields[] = $table_quoted .'.'.$field .' AS '.$field; - } - $restrict_action .= implode(',', $aliased_fields) - .' FROM '.$table_quoted - .' WHERE '; - $conditions = array(); - $new_values = array(); - $null_values = array(); - for ($i=0; $i<count($table_fields); $i++) { - $conditions[] = $table_fields[$i] .' = OLD.'.$referenced_fields[$i]; - $new_values[] = $table_fields[$i] .' = NEW.'.$referenced_fields[$i]; - $null_values[] = $table_fields[$i] .' = NULL'; - } - $conditions2 = array(); - for ($i=0; $i<count($referenced_fields); $i++) { - $conditions2[] = 'NEW.'.$referenced_fields[$i] .' <> OLD.'.$referenced_fields[$i]; - } - $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL' - .' AND (' .implode(' OR ', $conditions2) .')' - .' THEN CALL %s_ON_TABLE_'.$table.'_VIOLATES_FOREIGN_KEY_CONSTRAINT();' - .' END IF;'; - - $cascade_action_update = 'UPDATE '.$table_quoted.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions). ';'; - $cascade_action_delete = 'DELETE FROM '.$table_quoted.' WHERE '.implode(' AND ', $conditions). ';'; - $setnull_action = 'UPDATE '.$table_quoted.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions). ';'; - - if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) { - $db->loadModule('Reverse', null, true); - $default_values = array(); - foreach ($table_fields as $table_field) { - $field_definition = $db->reverse->getTableFieldDefinition($table, $field); - if (PEAR::isError($field_definition)) { - return $field_definition; - } - $default_values[] = $table_field .' = '. $field_definition[0]['default']; - } - $setdefault_action = 'UPDATE '.$table_quoted.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions). ';'; - } - - $query = 'CREATE TRIGGER %s' - .' %s ON '.$fkdef['references']['table'] - .' FOR EACH ROW BEGIN ' - .' SET FOREIGN_KEY_CHECKS = 0; '; //only really needed for ON UPDATE CASCADE - - if ('CASCADE' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $cascade_action_update; - } elseif ('SET NULL' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action; - } elseif ('SET DEFAULT' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action; - } elseif ('NO ACTION' == $fkdef['onupdate']) { - $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update'); - } elseif ('RESTRICT' == $fkdef['onupdate']) { - $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update'); - } - if ('CASCADE' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $cascade_action_delete; - } elseif ('SET NULL' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action; - } elseif ('SET DEFAULT' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action; - } elseif ('NO ACTION' == $fkdef['ondelete']) { - $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete'); - } elseif ('RESTRICT' == $fkdef['ondelete']) { - $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete'); - } - $sql_update .= ' SET FOREIGN_KEY_CHECKS = 1; END;'; - $sql_delete .= ' SET FOREIGN_KEY_CHECKS = 1; END;'; - - $db->pushErrorHandling(PEAR_ERROR_RETURN); - $db->expectError(MDB2_ERROR_CANNOT_CREATE); - $result = $db->exec($sql_delete); - $expected_errmsg = 'This MySQL version doesn\'t support multiple triggers with the same action time and event for one table'; - $db->popExpect(); - $db->popErrorHandling(); - if (PEAR::isError($result)) { - if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) { - return $result; - } - $db->warnings[] = $expected_errmsg; - } - $db->pushErrorHandling(PEAR_ERROR_RETURN); - $db->expectError(MDB2_ERROR_CANNOT_CREATE); - $result = $db->exec($sql_update); - $db->popExpect(); - $db->popErrorHandling(); - if (PEAR::isError($result) && $result->getCode() != MDB2_ERROR_CANNOT_CREATE) { - if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) { - return $result; - } - $db->warnings[] = $expected_errmsg; - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ _dropFKTriggers() - - /** - * Drop the triggers created to enforce the FOREIGN KEY constraint on the table - * - * @param string $table table name - * @param string $fkname FOREIGN KEY constraint name - * @param string $referenced_table referenced table name - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access private - */ - function _dropFKTriggers($table, $fkname, $referenced_table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $triggers = $this->listTableTriggers($table); - $triggers2 = $this->listTableTriggers($referenced_table); - if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) { - $triggers = array_merge($triggers, $triggers2); - $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i'; - foreach ($triggers as $trigger) { - if (preg_match($pattern, $trigger)) { - $result = $db->exec('DROP TRIGGER '.$trigger); - if (PEAR::isError($result)) { - return $result; - } - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ 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; - } - - $key_name = 'Key_name'; - $non_unique = 'Non_unique'; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $key_name = strtolower($key_name); - $non_unique = strtolower($non_unique); - } else { - $key_name = strtoupper($key_name); - $non_unique = strtoupper($non_unique); - } - } - - $query = 'SHOW INDEX FROM ' . $db->quoteIdentifier($table, true); - $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($indexes)) { - return $indexes; - } - - $result = array(); - foreach ($indexes as $index_data) { - if (!$index_data[$non_unique]) { - if ($index_data[$key_name] !== 'PRIMARY') { - $index = $this->_fixIndexName($index_data[$key_name]); - } else { - $index = 'PRIMARY'; - } - if (!empty($index)) { - $result[$index] = true; - } - } - } - - //list FOREIGN KEY constraints... - $query = 'SHOW CREATE TABLE '. $db->escape($table); - $definition = $db->queryOne($query, 'text', 1); - if (!PEAR::isError($definition) && !empty($definition)) { - $pattern = '/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN KEY\b/Uims'; - if (preg_match_all($pattern, str_replace('`', '', $definition), $matches) > 0) { - foreach ($matches[1] as $constraint) { - $result[$constraint] = true; - } - } - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $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 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * 'type' => 'innodb', - * ); - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createSequence($seq_name, $start = 1, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true); - $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true); - - $options_strings = array(); - - if (!empty($options['comment'])) { - $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text'); - } - - if (!empty($options['charset'])) { - $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset']; - if (!empty($options['collate'])) { - $options_strings['charset'].= ' COLLATE '.$options['collate']; - } - } - - $type = false; - if (!empty($options['type'])) { - $type = $options['type']; - } elseif ($db->options['default_table_type']) { - $type = $db->options['default_table_type']; - } - if ($type) { - $options_strings[] = "ENGINE = $type"; - } - - $query = "CREATE TABLE $sequence_name ($seqcol_name INT NOT NULL AUTO_INCREMENT, PRIMARY KEY ($seqcol_name))"; - if (!empty($options_strings)) { - $query .= ' '.implode(' ', $options_strings); - } - $res = $db->exec($query); - if (PEAR::isError($res)) { - return $res; - } - - if ($start == 1) { - return MDB2_OK; - } - - $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')'; - $res = $db->exec($query); - if (!PEAR::isError($res)) { - return MDB2_OK; - } - - // Handle error - $result = $db->exec("DROP TABLE $sequence_name"); - if (PEAR::isError($result)) { - return $db->raiseError($result, null, null, - 'could not drop inconsistent sequence table', __FUNCTION__); - } - - return $db->raiseError($res, null, null, - 'could not create sequence table', __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($seq_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true); - return $db->exec("DROP TABLE $sequence_name"); - } - - // }}} - // {{{ listSequences() - - /** - * list all sequences in the current database - * - * @param string database, the current is default - * @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; - } - - $query = "SHOW TABLES"; - if (!is_null($database)) { - $query .= " FROM $database"; - } - $table_names = $db->queryCol($query); - if (PEAR::isError($table_names)) { - return $table_names; - } - - $result = array(); - foreach ($table_names as $table_name) { - if ($sqn = $this->_fixSequenceName($table_name, true)) { - $result[] = $sqn; - } - } - 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 diff --git a/3rdparty/MDB2/Driver/Manager/pgsql.php b/3rdparty/MDB2/Driver/Manager/pgsql.php deleted file mode 100644 index 44a611d399d32bf95dd6b79e46e55b6a559737e8..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Manager/pgsql.php +++ /dev/null @@ -1,951 +0,0 @@ -<?php -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 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.87 2008/11/29 14:09:59 afz 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); - } - - // }}} - // {{{ alterDatabase() - - /** - * alter an existing database - * - * @param string $name name of the database that is intended to be changed - * @param array $options array with name, owner info - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function alterDatabase($name, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true); - if (!empty($options['name'])) { - $query .= ' RENAME TO ' . $options['name']; - } - if (!empty($options['owner'])) { - $query .= ' OWNER TO ' . $options['owner']; - } - 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); - $query = "DROP DATABASE $name"; - return $db->standaloneQuery($query, 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; - } - - // }}} - // {{{ truncateTable() - - /** - * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported, - * it falls back to a DELETE FROM TABLE query) - * - * @param string $name name of the table that should be truncated - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function truncateTable($name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $name = $db->quoteIdentifier($name, true); - return $db->exec("TRUNCATE TABLE $name"); - } - - // }}} - // {{{ vacuum() - - /** - * Optimize (vacuum) all the tables in the db (or only the specified table) - * and optionally run ANALYZE. - * - * @param string $table table name (all the tables if empty) - * @param array $options an array with driver-specific options: - * - timeout [int] (in seconds) [mssql-only] - * - analyze [boolean] [pgsql and mysql] - * - full [boolean] [pgsql-only] - * - freeze [boolean] [pgsql-only] - * - * @return mixed MDB2_OK success, a MDB2 error on failure - * @access public - */ - function vacuum($table = null, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $query = 'VACUUM'; - - if (!empty($options['full'])) { - $query .= ' FULL'; - } - if (!empty($options['freeze'])) { - $query .= ' FREEZE'; - } - if (!empty($options['analyze'])) { - $query .= ' ANALYZE'; - } - - if (!empty($table)) { - $query .= ' '.$db->quoteIdentifier($table, true); - } - return $db->exec($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; - } - - $name = $db->quoteIdentifier($name, true); - - 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['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; - } - } - } - - 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['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); - $type = $db->datatype->getTypeDeclaration($field['definition']); - if($type=='SERIAL PRIMARY KEY'){//not correct when altering a table, since serials arent a real type - $type='INTEGER';//use integer instead - } - $query = "ALTER $field_name TYPE $type USING CAST($field_name AS $type)"; - $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['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($database = null) - { - $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($database = null) - { - $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; - } - - list($schema, $table) = $this->splitTableSchema($table); - - $table = $db->quoteIdentifier($table, true); - if (!empty($schema)) { - $table = $db->quoteIdentifier($schema, true) . '.' .$table; - } - $db->setLimit(1); - $result2 = $db->query("SELECT * FROM $table LIMIT 1"); - 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; - } - - list($schema, $table) = $this->splitTableSchema($table); - - $table = $db->quote($table, 'text'); - $subquery = "SELECT indexrelid - FROM pg_index - LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid - LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid - WHERE pg_class.relname = $table - AND indisunique != 't' - AND indisprimary != 't'"; - if (!empty($schema)) { - $subquery .= ' AND pg_namespace.nspname = '.$db->quote($schema, 'text'); - } - $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); - } - - // }}} - // {{{ 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; - } - - // is it an UNIQUE index? - $query = 'SELECT relname - FROM pg_class - WHERE oid IN ( - SELECT indexrelid - FROM pg_index, pg_class - WHERE pg_class.relname = '.$db->quote($table, 'text').' - AND pg_class.oid = pg_index.indrelid - AND indisunique = \'t\') - EXCEPT - SELECT conname - FROM pg_constraint, pg_class - WHERE pg_constraint.conrelid = pg_class.oid - AND relname = '. $db->quote($table, 'text'); - $unique = $db->queryCol($query, 'text'); - if (PEAR::isError($unique) || empty($unique)) { - // not an UNIQUE index, maybe a CONSTRAINT - return parent::dropConstraint($table, $name, $primary); - } - - if (in_array($name, $unique)) { - return $db->exec('DROP INDEX '.$db->quoteIdentifier($name, true)); - } - $idxname = $db->getIndexName($name); - if (in_array($idxname, $unique)) { - return $db->exec('DROP INDEX '.$db->quoteIdentifier($idxname, true)); - } - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $name . ' is not an existing constraint for table ' . $table, __FUNCTION__); - } - - // }}} - // {{{ 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; - } - - list($schema, $table) = $this->splitTableSchema($table); - - $table = $db->quote($table, 'text'); - $query = 'SELECT conname - FROM pg_constraint - LEFT JOIN pg_class ON pg_constraint.conrelid = pg_class.oid - LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid - WHERE relname = ' .$table; - if (!empty($schema)) { - $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text'); - } - $query .= ' - UNION DISTINCT - SELECT relname - FROM pg_class - WHERE oid IN ( - SELECT indexrelid - FROM pg_index - LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid - LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid - WHERE pg_class.relname = '.$table.' - AND indisunique = \'t\''; - if (!empty($schema)) { - $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text'); - } - $query .= ')'; - $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($database = null) - { - $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 diff --git a/3rdparty/MDB2/Driver/Manager/sqlite.php b/3rdparty/MDB2/Driver/Manager/sqlite.php deleted file mode 100644 index 1b7239876f115f29d7f2cbc637b073186ee555ff..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Manager/sqlite.php +++ /dev/null @@ -1,1366 +0,0 @@ -<?php -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, | -// | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton | -// | 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: Lukas Smith <smith@pooteeweet.org> | -// | Lorenzo Alberton <l.alberton@quipo.it> | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php,v 1.76 2008/05/31 11:48:48 quipo Exp $ -// - -require_once('MDB2/Driver/Manager/Common.php'); - -/** - * MDB2 SQLite driver for the management modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - * @author Lorenzo Alberton <l.alberton@quipo.it> - */ -class MDB2_Driver_Manager_sqlite 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()) - { - $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ); - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $database_file = $db->_getDatabaseFile($name); - if (file_exists($database_file)) { - return $db->raiseError(MDB2_ERROR_ALREADY_EXISTS, null, null, - 'database already exists', __FUNCTION__); - } - $php_errormsg = ''; - $database_file="$datadir/$database_file.db"; - $handle = sqlite_open($database_file, $db->dsn['mode'], $php_errormsg); - if (!$handle) { - return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null, - (isset($php_errormsg) ? $php_errormsg : 'could not create the database file'), __FUNCTION__); - } - if (!empty($options['charset'])) { - $query = 'PRAGMA encoding = ' . $db->quote($options['charset'], 'text'); - @sqlite_query($query, $handle); - } - @sqlite_close($handle); - return MDB2_OK; - } - - // }}} - // {{{ 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; - } - - $database_file = $db->_getDatabaseFile($name); - if (!@file_exists($database_file)) { - return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null, - 'database does not exist', __FUNCTION__); - } - $result = @unlink($database_file); - if (!$result) { - return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null, - (isset($php_errormsg) ? $php_errormsg : 'could not remove the database file'), __FUNCTION__); - } - return MDB2_OK; - } - - // }}} - // {{{ _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']) && (strtoupper($definition['onupdate']) != 'NO ACTION')) { - $query .= ' ON UPDATE '.$definition['onupdate']; - } - if (!empty($definition['ondelete']) && (strtoupper($definition['ondelete']) != 'NO ACTION')) { - $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; - } - - // }}} - // {{{ _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'])).')'; - } - if (!empty($options['foreign_keys'])) { - foreach ($options['foreign_keys'] as $fkname => $fkdef) { - if (empty($fkdef)) { - continue; - } - $query_fields.= ', CONSTRAINT '.$fkname.' FOREIGN KEY ('.implode(', ', array_keys($fkdef['fields'])).')'; - $query_fields.= ' REFERENCES '.$fkdef['references']['table'].' ('.implode(', ', array_keys($fkdef['references']['fields'])).')'; - $query_fields.= $this->_getAdvancedFKOptions($fkdef); - } - } - - $name = $db->quoteIdentifier($name, true); - $result = 'CREATE '; - if (!empty($options['temporary'])) { - $result .= $this->_getTemporaryTableQuery(); - } - $result .= " TABLE $name ($query_fields)"; - return $result; - } - - // }}} - // {{{ 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 - * @param array $options An associative array of table options - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access public - */ - function createTable($name, $fields, $options = array()) - { - $result = parent::createTable($name, $fields, $options); - if (PEAR::isError($result)) { - return $result; - } - // create triggers to enforce FOREIGN KEY constraints - if (!empty($options['foreign_keys'])) { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - foreach ($options['foreign_keys'] as $fkname => $fkdef) { - if (empty($fkdef)) { - continue; - } - //set actions to default if not set - $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']); - $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']); - - $trigger_names = array( - 'insert' => $fkname.'_insert_trg', - 'update' => $fkname.'_update_trg', - 'pk_update' => $fkname.'_pk_update_trg', - 'pk_delete' => $fkname.'_pk_delete_trg', - ); - - //create the [insert|update] triggers on the FK table - $table_fields = array_keys($fkdef['fields']); - $referenced_fields = array_keys($fkdef['references']['fields']); - $query = 'CREATE TRIGGER %s BEFORE %s ON '.$name - .' FOR EACH ROW BEGIN' - .' SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')' - .' WHERE (SELECT '; - $aliased_fields = array(); - foreach ($referenced_fields as $field) { - $aliased_fields[] = $fkdef['references']['table'] .'.'.$field .' AS '.$field; - } - $query .= implode(',', $aliased_fields) - .' FROM '.$fkdef['references']['table'] - .' WHERE '; - $conditions = array(); - for ($i=0; $i<count($table_fields); $i++) { - $conditions[] = $referenced_fields[$i] .' = NEW.'.$table_fields[$i]; - } - $query .= implode(' AND ', $conditions).') IS NULL; END;'; - $result = $db->exec(sprintf($query, $trigger_names['insert'], 'INSERT', 'insert')); - if (PEAR::isError($result)) { - return $result; - } - - $result = $db->exec(sprintf($query, $trigger_names['update'], 'UPDATE', 'update')); - if (PEAR::isError($result)) { - return $result; - } - - //create the ON [UPDATE|DELETE] triggers on the primary table - $restrict_action = 'SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')' - .' WHERE (SELECT '; - $aliased_fields = array(); - foreach ($table_fields as $field) { - $aliased_fields[] = $name .'.'.$field .' AS '.$field; - } - $restrict_action .= implode(',', $aliased_fields) - .' FROM '.$name - .' WHERE '; - $conditions = array(); - $new_values = array(); - $null_values = array(); - for ($i=0; $i<count($table_fields); $i++) { - $conditions[] = $table_fields[$i] .' = OLD.'.$referenced_fields[$i]; - $new_values[] = $table_fields[$i] .' = NEW.'.$referenced_fields[$i]; - $null_values[] = $table_fields[$i] .' = NULL'; - } - $conditions2 = array(); - for ($i=0; $i<count($referenced_fields); $i++) { - $conditions2[] = 'NEW.'.$referenced_fields[$i] .' <> OLD.'.$referenced_fields[$i]; - } - $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL' - .' AND (' .implode(' OR ', $conditions2) .')'; - - $cascade_action_update = 'UPDATE '.$name.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions); - $cascade_action_delete = 'DELETE FROM '.$name.' WHERE '.implode(' AND ', $conditions); - $setnull_action = 'UPDATE '.$name.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions); - - if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) { - $db->loadModule('Reverse', null, true); - $default_values = array(); - foreach ($table_fields as $table_field) { - $field_definition = $db->reverse->getTableFieldDefinition($name, $field); - if (PEAR::isError($field_definition)) { - return $field_definition; - } - $default_values[] = $table_field .' = '. $field_definition[0]['default']; - } - $setdefault_action = 'UPDATE '.$name.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions); - } - - $query = 'CREATE TRIGGER %s' - .' %s ON '.$fkdef['references']['table'] - .' FOR EACH ROW BEGIN '; - - if ('CASCADE' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . $cascade_action_update. '; END;'; - } elseif ('SET NULL' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action. '; END;'; - } elseif ('SET DEFAULT' == $fkdef['onupdate']) { - $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action. '; END;'; - } elseif ('NO ACTION' == $fkdef['onupdate']) { - $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . '; END;'; - } elseif ('RESTRICT' == $fkdef['onupdate']) { - $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . '; END;'; - } - if ('CASCADE' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete') . $cascade_action_delete. '; END;'; - } elseif ('SET NULL' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action. '; END;'; - } elseif ('SET DEFAULT' == $fkdef['ondelete']) { - $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action. '; END;'; - } elseif ('NO ACTION' == $fkdef['ondelete']) { - $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete') . '; END;'; - } elseif ('RESTRICT' == $fkdef['ondelete']) { - $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . '; END;'; - } - - if (PEAR::isError($result)) { - return $result; - } - $result = $db->exec($sql_delete); - if (PEAR::isError($result)) { - return $result; - } - $result = $db->exec($sql_update); - if (PEAR::isError($result)) { - return $result; - } - } - } - 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; - } - - //delete the triggers associated to existing FK constraints - $constraints = $this->listTableConstraints($name); - if (!PEAR::isError($constraints) && !empty($constraints)) { - $db->loadModule('Reverse', null, true); - foreach ($constraints as $constraint) { - $definition = $db->reverse->getTableConstraintDefinition($name, $constraint); - if (!PEAR::isError($definition) && !empty($definition['foreign'])) { - $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']); - if (PEAR::isError($result)) { - return $result; - } - } - } - } - - $name = $db->quoteIdentifier($name, true); - return $db->exec("DROP TABLE $name"); - } - - // }}} - // {{{ vacuum() - - /** - * Optimize (vacuum) all the tables in the db (or only the specified table) - * and optionally run ANALYZE. - * - * @param string $table table name (all the tables if empty) - * @param array $options an array with driver-specific options: - * - timeout [int] (in seconds) [mssql-only] - * - analyze [boolean] [pgsql and mysql] - * - full [boolean] [pgsql-only] - * - freeze [boolean] [pgsql-only] - * - * @return mixed MDB2_OK success, a MDB2 error on failure - * @access public - */ - function vacuum($table = null, $options = array()) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'VACUUM'; - if (!empty($table)) { - $query .= ' '.$db->quoteIdentifier($table, true); - } - return $db->exec($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, $options = array()) - { - $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; - } - - $db->loadModule('Reverse', null, true); - - // actually sqlite 2.x supports no ALTER TABLE at all .. so we emulate it - $fields = $db->manager->listTableFields($name); - if (PEAR::isError($fields)) { - return $fields; - } - - $fields = array_flip($fields); - foreach ($fields as $field => $value) { - $definition = $db->reverse->getTableFieldDefinition($name, $field); - if (PEAR::isError($definition)) { - return $definition; - } - $fields[$field] = $definition[0]; - } - - $indexes = $db->manager->listTableIndexes($name); - if (PEAR::isError($indexes)) { - return $indexes; - } - - $indexes = array_flip($indexes); - foreach ($indexes as $index => $value) { - $definition = $db->reverse->getTableIndexDefinition($name, $index); - if (PEAR::isError($definition)) { - return $definition; - } - $indexes[$index] = $definition; - } - - $constraints = $db->manager->listTableConstraints($name); - if (PEAR::isError($constraints)) { - return $constraints; - } - - if (!array_key_exists('foreign_keys', $options)) { - $options['foreign_keys'] = array(); - } - $constraints = array_flip($constraints); - foreach ($constraints as $constraint => $value) { - if (!empty($definition['primary'])) { - if (!array_key_exists('primary', $options)) { - $options['primary'] = $definition['fields']; - //remove from the $constraint array, it's already handled by createTable() - unset($constraints[$constraint]); - } - } else { - $c_definition = $db->reverse->getTableConstraintDefinition($name, $constraint); - if (PEAR::isError($c_definition)) { - return $c_definition; - } - if (!empty($c_definition['foreign'])) { - if (!array_key_exists($constraint, $options['foreign_keys'])) { - $options['foreign_keys'][$constraint] = $c_definition; - } - //remove from the $constraint array, it's already handled by createTable() - unset($constraints[$constraint]); - } else { - $constraints[$constraint] = $c_definition; - } - } - } - - $name_new = $name; - $create_order = $select_fields = array_keys($fields); - foreach ($changes as $change_name => $change) { - switch ($change_name) { - case 'add': - foreach ($change as $field_name => $field) { - $fields[$field_name] = $field; - $create_order[] = $field_name; - } - break; - case 'remove': - foreach ($change as $field_name => $field) { - unset($fields[$field_name]); - $select_fields = array_diff($select_fields, array($field_name)); - $create_order = array_diff($create_order, array($field_name)); - } - break; - case 'change': - foreach ($change as $field_name => $field) { - $fields[$field_name] = $field['definition']; - } - break; - case 'name': - $name_new = $change; - break; - case 'rename': - foreach ($change as $field_name => $field) { - unset($fields[$field_name]); - $fields[$field['name']] = $field['definition']; - $create_order[array_search($field_name, $create_order)] = $field['name']; - } - break; - default: - return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null, - 'change type "'.$change_name.'" not yet supported', __FUNCTION__); - } - } - - $data = null; - if (!empty($select_fields)) { - $query = 'SELECT '.implode(', ', $select_fields).' FROM '.$db->quoteIdentifier($name, true); - $data = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED); - } - - $result = $this->dropTable($name); - if (PEAR::isError($result)) { - return $result; - } - - $result = $this->createTable($name_new, $fields, $options); - if (PEAR::isError($result)) { - return $result; - } - - foreach ($indexes as $index => $definition) { - $this->createIndex($name_new, $index, $definition); - } - - foreach ($constraints as $constraint => $definition) { - if(empty($definition['primary']) and empty($definition['foreign'])){ - $this->createConstraint($name_new, $constraint, $definition); - } - } - - if (!empty($select_fields) && !empty($data)) { - $query = 'INSERT INTO '.$db->quoteIdentifier($name_new, true); - $query.= '('.implode(', ', array_slice(array_keys($fields), 0, count($select_fields))).')'; - $query.=' VALUES (?'.str_repeat(', ?', (count($select_fields) - 1)).')'; - $stmt =$db->prepare($query, null, MDB2_PREPARE_MANIP); - if (PEAR::isError($stmt)) { - return $stmt; - } - foreach ($data as $row) { - $result = $stmt->execute($row); - 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; - } - - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'list databases is not supported', __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, - 'list databases is not supported', __FUNCTION__); - } - - // }}} - // {{{ 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($dummy=null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT name FROM sqlite_master WHERE type='view' AND sql NOT NULL"; - $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 name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL"; - $views = $db->queryAll($query, array('text', 'text'), MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($views)) { - return $views; - } - $result = array(); - foreach ($views as $row) { - if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i", $row['sql'])) { - if (!empty($row['name'])) { - $result[$row['name']] = true; - } - } - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_change_key_case($result, $db->options['field_case']); - } - return array_keys($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($dummy=null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name"; - $table_names = $db->queryCol($query); - if (PEAR::isError($table_names)) { - return $table_names; - } - $result = array(); - foreach ($table_names as $table_name) { - if (!$this->_fixSequenceName($table_name, true)) { - $result[] = $table_name; - } - } - 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; - } - - $result = $db->loadModule('Reverse', null, true); - if (PEAR::isError($result)) { - return $result; - } - $query = "SELECT sql FROM sqlite_master WHERE type='table' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text'); - } else { - $query.= 'name='.$db->quote($table, 'text'); - } - $sql = $db->queryOne($query); - if (PEAR::isError($sql)) { - return $sql; - } - $columns = $db->reverse->_getTableColumns($sql); - $fields = array(); - foreach ($columns as $column) { - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $column['name'] = strtolower($column['name']); - } else { - $column['name'] = strtoupper($column['name']); - } - } else { - $column = array_change_key_case($column, $db->options['field_case']); - } - $fields[] = $column['name']; - } - return $fields; - } - - // }}} - // {{{ 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 name FROM sqlite_master WHERE type='trigger' AND sql NOT NULL"; - if (!is_null($table)) { - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= ' AND LOWER(tbl_name)='.$db->quote(strtolower($table), 'text'); - } else { - $query.= ' AND tbl_name='.$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; - } - - // }}} - // {{{ 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 support() 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->getIndexName($name); - $query = "CREATE INDEX $name ON $table"; - $fields = array(); - foreach ($definition['fields'] as $field_name => $field) { - $field_string = $field_name; - if (!empty($field['sorting'])) { - switch ($field['sorting']) { - case 'ascending': - $field_string.= ' ASC'; - break; - case 'descending': - $field_string.= ' DESC'; - break; - } - } - $fields[] = $field_string; - } - $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->getIndexName($name); - 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; - } - - $table = $db->quote($table, 'text'); - $query = "SELECT sql FROM sqlite_master WHERE type='index' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(tbl_name)='.strtolower($table); - } else { - $query.= "tbl_name=$table"; - } - $query.= " AND sql NOT NULL ORDER BY name"; - $indexes = $db->queryCol($query, 'text'); - if (PEAR::isError($indexes)) { - return $indexes; - } - - $result = array(); - foreach ($indexes as $sql) { - if (preg_match("/^create index ([^ ]+) on /i", $sql, $tmp)) { - $index = $this->_fixIndexName($tmp[1]); - 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); - } - - // }}} - // {{{ 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. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the constraint fields as array - * constraints. Each entry of this array is set to another type of associative - * array that specifies properties of the constraint that are specific to - * each field. - * - * Example - * array( - * 'fields' => array( - * 'user_name' => array(), - * 'last_login' => array() - * ) - * ) - * @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; - } - - if (!empty($definition['primary'])) { - return $db->manager->alterTable($table, array(), false, array('primary' => $definition['fields'])); - } - - if (!empty($definition['foreign'])) { - return $db->manager->alterTable($table, array(), false, array('foreign_keys' => array($name => $definition))); - } - - $table = $db->quoteIdentifier($table, true); - $name = $db->getIndexName($name); - $query = "CREATE UNIQUE INDEX $name ON $table"; - $fields = array(); - foreach ($definition['fields'] as $field_name => $field) { - $field_string = $field_name; - if (!empty($field['sorting'])) { - switch ($field['sorting']) { - case 'ascending': - $field_string.= ' ASC'; - break; - case 'descending': - $field_string.= ' DESC'; - break; - } - } - $fields[] = $field_string; - } - $query .= ' ('.implode(', ', $fields) . ')'; - 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) - { - if ($primary || $name == 'PRIMARY') { - return $this->alterTable($table, array(), false, array('primary' => null)); - } - - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - //is it a FK constraint? If so, also delete the associated triggers - $db->loadModule('Reverse', null, true); - $definition = $db->reverse->getTableConstraintDefinition($table, $name); - if (!PEAR::isError($definition) && !empty($definition['foreign'])) { - //first drop the FK enforcing triggers - $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']); - if (PEAR::isError($result)) { - return $result; - } - //then drop the constraint itself - return $this->alterTable($table, array(), false, array('foreign_keys' => array($name => null))); - } - - $name = $db->getIndexName($name); - return $db->exec("DROP INDEX $name"); - } - - // }}} - // {{{ _dropFKTriggers() - - /** - * Drop the triggers created to enforce the FOREIGN KEY constraint on the table - * - * @param string $table table name - * @param string $fkname FOREIGN KEY constraint name - * @param string $referenced_table referenced table name - * - * @return mixed MDB2_OK on success, a MDB2 error on failure - * @access private - */ - function _dropFKTriggers($table, $fkname, $referenced_table) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $triggers = $this->listTableTriggers($table); - $triggers2 = $this->listTableTriggers($referenced_table); - if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) { - $triggers = array_merge($triggers, $triggers2); - $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i'; - foreach ($triggers as $trigger) { - if (preg_match($pattern, $trigger)) { - $result = $db->exec('DROP TRIGGER '.$trigger); - if (PEAR::isError($result)) { - return $result; - } - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ 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'); - $query = "SELECT sql FROM sqlite_master WHERE type='index' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(tbl_name)='.strtolower($table); - } else { - $query.= "tbl_name=$table"; - } - $query.= " AND sql NOT NULL ORDER BY name"; - $indexes = $db->queryCol($query, 'text'); - if (PEAR::isError($indexes)) { - return $indexes; - } - - $result = array(); - foreach ($indexes as $sql) { - if (preg_match("/^create unique index ([^ ]+) on /i", $sql, $tmp)) { - $index = $this->_fixIndexName($tmp[1]); - if (!empty($index)) { - $result[$index] = true; - } - } - } - - // also search in table definition for PRIMARY KEYs... - $query = "SELECT sql FROM sqlite_master WHERE type='table' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)='.strtolower($table); - } else { - $query.= "name=$table"; - } - $query.= " AND sql NOT NULL ORDER BY name"; - $table_def = $db->queryOne($query, 'text'); - if (PEAR::isError($table_def)) { - return $table_def; - } - if (preg_match("/\bPRIMARY\s+KEY\b/i", $table_def, $tmp)) { - $result['primary'] = true; - } - - // ...and for FOREIGN KEYs - if (preg_match_all("/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN\s+KEY/imsx", $table_def, $tmp)) { - foreach ($tmp[1] as $fk) { - $result[$fk] = true; - } - } - - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $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); - $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true); - $query = "CREATE TABLE $sequence_name ($seqcol_name INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)"; - $res = $db->exec($query); - if (PEAR::isError($res)) { - return $res; - } - if ($start == 1) { - return MDB2_OK; - } - $res = $db->exec("INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')'); - if (!PEAR::isError($res)) { - return MDB2_OK; - } - // Handle error - $result = $db->exec("DROP TABLE $sequence_name"); - if (PEAR::isError($result)) { - return $db->raiseError($result, null, null, - 'could not drop inconsistent sequence table', __FUNCTION__); - } - return $db->raiseError($res, null, null, - 'could not create sequence table', __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($seq_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true); - return $db->exec("DROP TABLE $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($dummy=null) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name"; - $table_names = $db->queryCol($query); - if (PEAR::isError($table_names)) { - return $table_names; - } - $result = array(); - foreach ($table_names as $table_name) { - if ($sqn = $this->_fixSequenceName($table_name, true)) { - $result[] = $sqn; - } - } - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - } - return $result; - } - - // }}} -} -?> diff --git a/3rdparty/MDB2/Driver/Native/Common.php b/3rdparty/MDB2/Driver/Native/Common.php deleted file mode 100644 index c01caa35b716fce134664134956f8c635e3adc7a..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Native/Common.php +++ /dev/null @@ -1,61 +0,0 @@ -<?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.2 2007/09/09 13:47:36 quipo 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 diff --git a/3rdparty/MDB2/Driver/Native/mysql.php b/3rdparty/MDB2/Driver/Native/mysql.php deleted file mode 100644 index 90ff068e6ffb21d26ab3b5dc7517e6614f331e61..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Native/mysql.php +++ /dev/null @@ -1,60 +0,0 @@ -<?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: mysql.php,v 1.9 2006/06/18 21:59:05 lsmith Exp $ -// - -require_once 'MDB2/Driver/Native/Common.php'; - -/** - * MDB2 MySQL driver for the native module - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Driver_Native_mysql extends MDB2_Driver_Native_Common -{ -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Native/pgsql.php b/3rdparty/MDB2/Driver/Native/pgsql.php deleted file mode 100644 index acab8389c892ec0f0c95289d7be63af8cd8dff2e..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Native/pgsql.php +++ /dev/null @@ -1,88 +0,0 @@ -<?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.12 2006/07/15 13:07:15 lsmith 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 diff --git a/3rdparty/MDB2/Driver/Native/sqlite.php b/3rdparty/MDB2/Driver/Native/sqlite.php deleted file mode 100644 index 0213293a50a6f351a173727faab816fa7c0b2252..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Native/sqlite.php +++ /dev/null @@ -1,60 +0,0 @@ -<?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: sqlite.php,v 1.9 2006/06/18 21:59:05 lsmith Exp $ -// - -require_once 'MDB2/Driver/Native/Common.php'; - -/** - * MDB2 SQLite driver for the native module - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Driver_Native_sqlite extends MDB2_Driver_Native_Common -{ -} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Reverse/Common.php b/3rdparty/MDB2/Driver/Reverse/Common.php deleted file mode 100644 index c78d84f760a490a62ebcb858edbfe02c9b8f6b05..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Reverse/Common.php +++ /dev/null @@ -1,517 +0,0 @@ -<?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.43 2009/01/14 15:01:21 quipo 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 - * - * @param string $table [schema and] table name - * - * @return array array(schema, table) - * @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; - } - } - } - } - - $res = array(); - - 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 diff --git a/3rdparty/MDB2/Driver/Reverse/mysql.php b/3rdparty/MDB2/Driver/Reverse/mysql.php deleted file mode 100644 index 6e366c22a5e09b78cbd351a3fd37e9953f8be290..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Reverse/mysql.php +++ /dev/null @@ -1,536 +0,0 @@ -<?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: mysql.php,v 1.80 2008/03/26 21:15:37 quipo Exp $ -// - -require_once('MDB2/Driver/Reverse/Common.php'); - -/** - * MDB2 MySQL driver for the schema reverse engineering module - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - * @author Lorenzo Alberton <l.alberton@quipo.it> - */ -class MDB2_Driver_Reverse_mysql 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); - - $table = $db->quoteIdentifier($table, true); - $query = "SHOW FULL COLUMNS FROM $table LIKE ".$db->quote($field_name); - $columns = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($columns)) { - return $columns; - } - foreach ($columns as $column) { - $column = array_change_key_case($column, CASE_LOWER); - $column['name'] = $column['field']; - unset($column['field']); - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $column['name'] = strtolower($column['name']); - } else { - $column['name'] = strtoupper($column['name']); - } - } else { - $column = array_change_key_case($column, $db->options['field_case']); - } - if ($field_name == $column['name']) { - $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['null']) || $column['null'] !== 'YES') { - $notnull = true; - } - $default = false; - if (array_key_exists('default', $column)) { - $default = $column['default']; - if (is_null($default) && $notnull) { - $default = ''; - } - } - $autoincrement = false; - if (!empty($column['extra']) && $column['extra'] == 'auto_increment') { - $autoincrement = true; - } - $collate = null; - if (!empty($column['collation'])) { - $collate = $column['collation']; - $charset = preg_replace('/(.+?)(_.+)?/', '$1', $collate); - } - - $definition[0] = array( - 'notnull' => $notnull, - 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $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; - } - if (!is_null($collate)) { - $definition[0]['collate'] = $collate; - $definition[0]['charset'] = $charset; - } - foreach ($types as $key => $type) { - $definition[$key] = $definition[0]; - if ($type == 'clob' || $type == 'blob') { - unset($definition[$key]['default']); - } elseif ($type == 'timestamp' && $notnull && empty($definition[$key]['default'])) { - $definition[$key]['default'] = '0000-00-00 00:00:00'; - } - $definition[$key]['type'] = $type; - $definition[$key]['mdb2type'] = $type; - } - return $definition; - } - } - - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table column', __FUNCTION__); - } - - // }}} - // {{{ 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); - - $table = $db->quoteIdentifier($table, true); - $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */"; - $index_name_mdb2 = $db->getIndexName($index_name); - $result = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2))); - if (!PEAR::isError($result) && !is_null($result)) { - // apply 'idxname_format' only if the query succeeded, otherwise - // fallback to the given $index_name, without transformation - $index_name = $index_name_mdb2; - } - $result = $db->query(sprintf($query, $db->quote($index_name))); - if (PEAR::isError($result)) { - return $result; - } - $colpos = 1; - $definition = array(); - while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) { - $row = array_change_key_case($row, CASE_LOWER); - $key_name = $row['key_name']; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $key_name = strtolower($key_name); - } else { - $key_name = strtoupper($key_name); - } - } - if ($index_name == $key_name) { - if (!$row['non_unique']) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $index_name . ' is not an existing table index', __FUNCTION__); - } - $column_name = $row['column_name']; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $column_name = strtolower($column_name); - } else { - $column_name = strtoupper($column_name); - } - } - $definition['fields'][$column_name] = array( - 'position' => $colpos++ - ); - if (!empty($row['collation'])) { - $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A' - ? 'ascending' : 'descending'); - } - } - } - $result->free(); - if (empty($definition['fields'])) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $index_name . ' is not an existing table index', __FUNCTION__); - } - 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); - $constraint_name_original = $constraint_name; - - $table = $db->quoteIdentifier($table, true); - $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */"; - if (strtolower($constraint_name) != 'primary') { - $constraint_name_mdb2 = $db->getIndexName($constraint_name); - $result = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2))); - if (!PEAR::isError($result) && !is_null($result)) { - // apply 'idxname_format' only if the query succeeded, otherwise - // fallback to the given $index_name, without transformation - $constraint_name = $constraint_name_mdb2; - } - } - $result = $db->query(sprintf($query, $db->quote($constraint_name))); - if (PEAR::isError($result)) { - return $result; - } - $colpos = 1; - //default values, eventually overridden - $definition = array( - 'primary' => false, - 'unique' => false, - 'foreign' => false, - 'check' => false, - 'fields' => array(), - 'references' => array( - 'table' => '', - 'fields' => array(), - ), - 'onupdate' => '', - 'ondelete' => '', - 'match' => '', - 'deferrable' => false, - 'initiallydeferred' => false, - ); - while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) { - $row = array_change_key_case($row, CASE_LOWER); - $key_name = $row['key_name']; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $key_name = strtolower($key_name); - } else { - $key_name = strtoupper($key_name); - } - } - if ($constraint_name == $key_name) { - if ($row['non_unique']) { - //FOREIGN KEY? - return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition); - } - if ($row['key_name'] == 'PRIMARY') { - $definition['primary'] = true; - } elseif (!$row['non_unique']) { - $definition['unique'] = true; - } - $column_name = $row['column_name']; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $column_name = strtolower($column_name); - } else { - $column_name = strtoupper($column_name); - } - } - $definition['fields'][$column_name] = array( - 'position' => $colpos++ - ); - if (!empty($row['collation'])) { - $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A' - ? 'ascending' : 'descending'); - } - } - } - $result->free(); - if (empty($definition['fields'])) { - return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition); - } - return $definition; - } - - // }}} - // {{{ _getTableFKConstraintDefinition() - - /** - * Get the FK definition from the CREATE TABLE statement - * - * @param string $table table name - * @param string $constraint_name constraint name - * @param array $definition default values for constraint definition - * - * @return array|PEAR_Error - * @access private - */ - function _getTableFKConstraintDefinition($table, $constraint_name, $definition) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $query = 'SHOW CREATE TABLE '. $db->escape($table); - $constraint = $db->queryOne($query, 'text', 1); - if (!PEAR::isError($constraint) && !empty($constraint)) { - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $constraint = strtolower($constraint); - } else { - $constraint = strtoupper($constraint); - } - } - $constraint_name_original = $constraint_name; - $constraint_name = $db->getIndexName($constraint_name); - $pattern = '/\bCONSTRAINT\s+'.$constraint_name.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i'; - if (!preg_match($pattern, str_replace('`', '', $constraint), $matches)) { - //fallback to original constraint name - $pattern = '/\bCONSTRAINT\s+'.$constraint_name_original.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i'; - } - if (preg_match($pattern, str_replace('`', '', $constraint), $matches)) { - $definition['foreign'] = true; - $column_names = explode(',', $matches[1]); - $referenced_cols = explode(',', $matches[3]); - $definition['references'] = array( - 'table' => $matches[2], - 'fields' => array(), - ); - $colpos = 1; - foreach ($column_names as $column_name) { - $definition['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - $colpos = 1; - foreach ($referenced_cols as $column_name) { - $definition['references']['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - $definition['onupdate'] = 'NO ACTION'; - $definition['ondelete'] = 'NO ACTION'; - $definition['match'] = 'SIMPLE'; - return $definition; - } - } - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $constraint_name . ' is not an existing table constraint', __FUNCTION__); - } - - // }}} - // {{{ 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 - */ - function getTriggerDefinition($trigger) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = 'SELECT trigger_name, - event_object_table AS table_name, - action_statement AS trigger_body, - action_timing AS trigger_type, - event_manipulation AS trigger_event - FROM information_schema.triggers - WHERE trigger_name = '. $db->quote($trigger, 'text'); - $types = array( - 'trigger_name' => 'text', - 'table_name' => 'text', - 'trigger_body' => 'text', - 'trigger_type' => 'text', - 'trigger_event' => 'text', - ); - $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($def)) { - return $def; - } - $def['trigger_comment'] = ''; - $def['trigger_enabled'] = true; - return $def; - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set - * - * @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::setOption() - */ - 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 = @mysql_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' => $case_func(@mysql_field_table($resource, $i)), - 'name' => $case_func(@mysql_field_name($resource, $i)), - 'type' => @mysql_field_type($resource, $i), - 'length' => @mysql_field_len($resource, $i), - 'flags' => @mysql_field_flags($resource, $i), - ); - if ($res[$i]['type'] == 'string') { - $res[$i]['type'] = 'char'; - } elseif ($res[$i]['type'] == 'unknown') { - $res[$i]['type'] = 'decimal'; - } - $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 diff --git a/3rdparty/MDB2/Driver/Reverse/pgsql.php b/3rdparty/MDB2/Driver/Reverse/pgsql.php deleted file mode 100644 index 8669c2b919b176b0c2ab465ad436e2cbccf178e1..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Reverse/pgsql.php +++ /dev/null @@ -1,573 +0,0 @@ -<?php -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 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.75 2008/08/22 16:36:20 quipo 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; - } - $uniqueIndex = false; - if (empty($row)) { - // We might be looking for a UNIQUE index that was not created - // as a constraint but should be treated as such. - $query = 'SELECT relname AS constraint_name, - indkey, - 0 AS "check", - 0 AS "foreign", - 0 AS "primary", - 1 AS "unique", - 0 AS deferrable, - 0 AS initiallydeferred, - NULL AS references_table, - NULL AS onupdate, - NULL AS ondelete, - NULL AS match - FROM pg_index, pg_class - WHERE pg_class.oid = pg_index.indexrelid - AND indisunique = \'t\' - AND pg_class.relname = %s'; - $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__); - } - $uniqueIndex = true; - } - - $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'], - ); - - if ($uniqueIndex) { - $db->loadModule('Manager', null, true); - $columns = $db->manager->listTableFields($table_name); - $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; - } - - $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'); - $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.confkey) - WHERE c.conname = %s - AND t.relname = ' . $db->quote($definition['references']['table'], 'text'); - $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, - CASE trg.tgenabled - WHEN 'O' THEN 't' - ELSE trg.tgenabled - END 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 diff --git a/3rdparty/MDB2/Driver/Reverse/sqlite.php b/3rdparty/MDB2/Driver/Reverse/sqlite.php deleted file mode 100644 index 60c686c418a1d54339897b08e101ea9f2e122889..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/Reverse/sqlite.php +++ /dev/null @@ -1,609 +0,0 @@ -<?php -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, | -// | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton | -// | 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: Lukas Smith <smith@pooteeweet.org> | -// | Lorenzo Alberton <l.alberton@quipo.it> | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php,v 1.80 2008/05/03 10:30:14 quipo Exp $ -// - -require_once('MDB2/Driver/Reverse/Common.php'); - -/** - * MDB2 SQlite driver for the schema reverse engineering module - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common -{ - /** - * Remove SQL comments from the field definition - * - * @access private - */ - function _removeComments($sql) { - $lines = explode("\n", $sql); - foreach ($lines as $k => $line) { - $pieces = explode('--', $line); - if (count($pieces) > 1 && (substr_count($pieces[0], '\'') % 2) == 0) { - $lines[$k] = substr($line, 0, strpos($line, '--')); - } - } - return implode("\n", $lines); - } - - /** - * - */ - function _getTableColumns($sql) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $start_pos = strpos($sql, '('); - $end_pos = strrpos($sql, ')'); - $column_def = substr($sql, $start_pos+1, $end_pos-$start_pos-1); - // replace the decimal length-places-separator with a colon - $column_def = preg_replace('/(\d),(\d)/', '\1:\2', $column_def); - $column_def = $this->_removeComments($column_def); - $column_sql = explode(',', $column_def); - $columns = array(); - $count = count($column_sql); - if ($count == 0) { - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'unexpected empty table column definition list', __FUNCTION__); - } - $regexp = '/^\s*([^\s]+) +(CHAR|VARCHAR|VARCHAR2|TEXT|BOOLEAN|SMALLINT|INT|INTEGER|DECIMAL|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( ?\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?( NULL| NOT NULL)?( UNSIGNED)?( NULL| NOT NULL)?( PRIMARY KEY)?( DEFAULT (\'[^\']*\'|[^ ]+))?( NULL| NOT NULL)?( PRIMARY KEY)?(\s*\-\-.*)?$/i'; - $regexp2 = '/^\s*([^ ]+) +(PRIMARY|UNIQUE|CHECK)$/i'; - for ($i=0, $j=0; $i<$count; ++$i) { - if (!preg_match($regexp, trim($column_sql[$i]), $matches)) { - if (!preg_match($regexp2, trim($column_sql[$i]))) { - continue; - } - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'unexpected table column SQL definition: "'.$column_sql[$i].'"', __FUNCTION__); - } - $columns[$j]['name'] = trim($matches[1], implode('', $db->identifier_quoting)); - $columns[$j]['type'] = strtolower($matches[2]); - if (isset($matches[4]) && strlen($matches[4])) { - $columns[$j]['length'] = $matches[4]; - } - if (isset($matches[6]) && strlen($matches[6])) { - $columns[$j]['decimal'] = $matches[6]; - } - if (isset($matches[8]) && strlen($matches[8])) { - $columns[$j]['unsigned'] = true; - } - if (isset($matches[9]) && strlen($matches[9])) { - $columns[$j]['autoincrement'] = true; - } - if (isset($matches[12]) && strlen($matches[12])) { - $default = $matches[12]; - if (strlen($default) && $default[0]=="'") { - $default = str_replace("''", "'", substr($default, 1, strlen($default)-2)); - } - if ($default === 'NULL') { - $default = null; - } - $columns[$j]['default'] = $default; - } - if (isset($matches[7]) && strlen($matches[7])) { - $columns[$j]['notnull'] = ($matches[7] === ' NOT NULL'); - } else if (isset($matches[9]) && strlen($matches[9])) { - $columns[$j]['notnull'] = ($matches[9] === ' NOT NULL'); - } else if (isset($matches[13]) && strlen($matches[13])) { - $columns[$j]['notnull'] = ($matches[13] === ' NOT NULL'); - } - ++$j; - } - return $columns; - } - - // {{{ getTableFieldDefinition() - - /** - * Get the stucture 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. - * The returned array contains an array for each field definition, - * with (some of) these indices: - * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type] - * @access public - */ - function getTableFieldDefinition($table_name, $field_name) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - list($schema, $table) = $this->splitTableSchema($table_name); - - $result = $db->loadModule('Datatype', null, true); - if (PEAR::isError($result)) { - return $result; - } - $query = "SELECT sql FROM sqlite_master WHERE type='table' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text'); - } else { - $query.= 'name='.$db->quote($table, 'text'); - } - $sql = $db->queryOne($query); - if (PEAR::isError($sql)) { - return $sql; - } - $columns = $this->_getTableColumns($sql); - foreach ($columns as $column) { - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - if ($db->options['field_case'] == CASE_LOWER) { - $column['name'] = strtolower($column['name']); - } else { - $column['name'] = strtoupper($column['name']); - } - } else { - $column = array_change_key_case($column, $db->options['field_case']); - } - if ($field_name == $column['name']) { - $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['notnull'])) { - $notnull = $column['notnull']; - } - $default = false; - if (array_key_exists('default', $column)) { - $default = $column['default']; - if (is_null($default) && $notnull) { - $default = ''; - } - } - $autoincrement = false; - if (!empty($column['autoincrement'])) { - $autoincrement = true; - } - - $definition[0] = array( - 'notnull' => $notnull, - 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $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; - } - } - - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table column', __FUNCTION__); - } - - // }}} - // {{{ getTableIndexDefinition() - - /** - * Get the stucture 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 sql FROM sqlite_master WHERE type='index' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text'); - } else { - $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text'); - } - $query.= ' AND sql NOT NULL ORDER BY name'; - $index_name_mdb2 = $db->getIndexName($index_name); - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $qry = sprintf($query, $db->quote(strtolower($index_name_mdb2), 'text')); - } else { - $qry = sprintf($query, $db->quote($index_name_mdb2, 'text')); - } - $sql = $db->queryOne($qry, 'text'); - if (PEAR::isError($sql) || empty($sql)) { - // fallback to the given $index_name, without transformation - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $qry = sprintf($query, $db->quote(strtolower($index_name), 'text')); - } else { - $qry = sprintf($query, $db->quote($index_name, 'text')); - } - $sql = $db->queryOne($qry, 'text'); - } - if (PEAR::isError($sql)) { - return $sql; - } - if (!$sql) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table index', __FUNCTION__); - } - - $sql = strtolower($sql); - $start_pos = strpos($sql, '('); - $end_pos = strrpos($sql, ')'); - $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1); - $column_names = explode(',', $column_names); - - if (preg_match("/^create unique/", $sql)) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table index', __FUNCTION__); - } - - $definition = array(); - $count = count($column_names); - for ($i=0; $i<$count; ++$i) { - $column_name = strtok($column_names[$i], ' '); - $collation = strtok(' '); - $definition['fields'][$column_name] = array( - 'position' => $i+1 - ); - if (!empty($collation)) { - $definition['fields'][$column_name]['sorting'] = - ($collation=='ASC' ? 'ascending' : 'descending'); - } - } - - if (empty($definition['fields'])) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing table index', __FUNCTION__); - } - return $definition; - } - - // }}} - // {{{ getTableConstraintDefinition() - - /** - * Get the stucture 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 sql FROM sqlite_master WHERE type='index' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text'); - } else { - $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text'); - } - $query.= ' AND sql NOT NULL ORDER BY name'; - $constraint_name_mdb2 = $db->getIndexName($constraint_name); - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $qry = sprintf($query, $db->quote(strtolower($constraint_name_mdb2), 'text')); - } else { - $qry = sprintf($query, $db->quote($constraint_name_mdb2, 'text')); - } - $sql = $db->queryOne($qry, 'text'); - if (PEAR::isError($sql) || empty($sql)) { - // fallback to the given $index_name, without transformation - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $qry = sprintf($query, $db->quote(strtolower($constraint_name), 'text')); - } else { - $qry = sprintf($query, $db->quote($constraint_name, 'text')); - } - $sql = $db->queryOne($qry, 'text'); - } - if (PEAR::isError($sql)) { - return $sql; - } - //default values, eventually overridden - $definition = array( - 'primary' => false, - 'unique' => false, - 'foreign' => false, - 'check' => false, - 'fields' => array(), - 'references' => array( - 'table' => '', - 'fields' => array(), - ), - 'onupdate' => '', - 'ondelete' => '', - 'match' => '', - 'deferrable' => false, - 'initiallydeferred' => false, - ); - if (!$sql) { - $query = "SELECT sql FROM sqlite_master WHERE type='table' AND "; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text'); - } else { - $query.= 'name='.$db->quote($table, 'text'); - } - $query.= " AND sql NOT NULL ORDER BY name"; - $sql = $db->queryOne($query, 'text'); - if (PEAR::isError($sql)) { - return $sql; - } - if ($constraint_name == 'primary') { - // search in table definition for PRIMARY KEYs - if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i", $sql, $tmp)) { - $definition['primary'] = true; - $definition['fields'] = array(); - $column_names = explode(',', $tmp[1]); - $colpos = 1; - foreach ($column_names as $column_name) { - $definition['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - return $definition; - } - if (preg_match("/\"([^\"]+)\"[^\,\"]+\bPRIMARY\s+KEY\b[^\,\)]*/i", $sql, $tmp)) { - $definition['primary'] = true; - $definition['fields'] = array(); - $column_names = explode(',', $tmp[1]); - $colpos = 1; - foreach ($column_names as $column_name) { - $definition['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - return $definition; - } - } else { - // search in table definition for FOREIGN KEYs - $pattern = "/\bCONSTRAINT\b\s+%s\s+ - \bFOREIGN\s+KEY\b\s*\(([^\)]+)\)\s* - \bREFERENCES\b\s+([^\s]+)\s*\(([^\)]+)\)\s* - (?:\bMATCH\s*([^\s]+))?\s* - (?:\bON\s+UPDATE\s+([^\s,\)]+))?\s* - (?:\bON\s+DELETE\s+([^\s,\)]+))?\s* - /imsx"; - $found_fk = false; - if (preg_match(sprintf($pattern, $constraint_name_mdb2), $sql, $tmp)) { - $found_fk = true; - } elseif (preg_match(sprintf($pattern, $constraint_name), $sql, $tmp)) { - $found_fk = true; - } - if ($found_fk) { - $definition['foreign'] = true; - $definition['match'] = 'SIMPLE'; - $definition['onupdate'] = 'NO ACTION'; - $definition['ondelete'] = 'NO ACTION'; - $definition['references']['table'] = $tmp[2]; - $column_names = explode(',', $tmp[1]); - $colpos = 1; - foreach ($column_names as $column_name) { - $definition['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - $referenced_cols = explode(',', $tmp[3]); - $colpos = 1; - foreach ($referenced_cols as $column_name) { - $definition['references']['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - if (isset($tmp[4])) { - $definition['match'] = $tmp[4]; - } - if (isset($tmp[5])) { - $definition['onupdate'] = $tmp[5]; - } - if (isset($tmp[6])) { - $definition['ondelete'] = $tmp[6]; - } - return $definition; - } - } - $sql = false; - } - if (!$sql) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $constraint_name . ' is not an existing table constraint', __FUNCTION__); - } - - $sql = strtolower($sql); - $start_pos = strpos($sql, '('); - $end_pos = strrpos($sql, ')'); - $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1); - $column_names = explode(',', $column_names); - - if (!preg_match("/^create unique/", $sql)) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $constraint_name . ' is not an existing table constraint', __FUNCTION__); - } - - $definition['unique'] = true; - $count = count($column_names); - for ($i=0; $i<$count; ++$i) { - $column_name = strtok($column_names[$i]," "); - $collation = strtok(" "); - $definition['fields'][$column_name] = array( - 'position' => $i+1 - ); - if (!empty($collation)) { - $definition['fields'][$column_name]['sorting'] = - ($collation=='ASC' ? 'ascending' : 'descending'); - } - } - - if (empty($definition['fields'])) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - $constraint_name . ' is not an existing table constraint', __FUNCTION__); - } - 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 - */ - function getTriggerDefinition($trigger) - { - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - $query = "SELECT name as trigger_name, - tbl_name AS table_name, - sql AS trigger_body, - NULL AS trigger_type, - NULL AS trigger_event, - NULL AS trigger_comment, - 1 AS trigger_enabled - FROM sqlite_master - WHERE type='trigger'"; - if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger), 'text'); - } else { - $query.= ' AND name='.$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', - ); - $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC); - if (PEAR::isError($def)) { - return $def; - } - if (empty($def)) { - return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'it was not specified an existing trigger', __FUNCTION__); - } - if (preg_match("/^create\s+(?:temp|temporary)?trigger\s+(?:if\s+not\s+exists\s+)?.*(before|after)?\s+(insert|update|delete)/Uims", $def['trigger_body'], $tmp)) { - $def['trigger_type'] = strtoupper($tmp[1]); - $def['trigger_event'] = strtoupper($tmp[2]); - } - return $def; - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table - * - * @param string $result a string containing the name of a table - * @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() - * @since Method available since Release 1.7.0 - */ - function tableInfo($result, $mode = null) - { - if (is_string($result)) { - return parent::tableInfo($result, $mode); - } - - $db =$this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - - return $db->raiseError(MDB2_ERROR_NOT_CAPABLE, null, null, - 'This DBMS can not obtain tableInfo from result sets', __FUNCTION__); - } -} - -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/mysql.php b/3rdparty/MDB2/Driver/mysql.php deleted file mode 100644 index b9b46c0d762f445a384320a9fd6bc9b3870fc40d..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/mysql.php +++ /dev/null @@ -1,1700 +0,0 @@ -<?php -// vim: set et ts=4 sw=4 fdm=marker: -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 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: mysql.php,v 1.214 2008/11/16 21:45:08 quipo Exp $ -// - -/** - * MDB2 MySQL driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Driver_mysql extends MDB2_Driver_Common -{ - // {{{ properties - - var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\'); - - var $identifier_quoting = array('start' => '`', 'end' => '`', 'escape' => '`'); - - var $sql_comments = array( - array('start' => '-- ', 'end' => "\n", 'escape' => false), - array('start' => '#', 'end' => "\n", 'escape' => false), - array('start' => '/*', 'end' => '*/', 'escape' => false), - ); - - var $server_capabilities_checked = false; - - var $start_transaction = false; - - var $varchar_max_length = 255; - - // }}} - // {{{ constructor - - /** - * Constructor - */ - function __construct() - { - parent::__construct(); - - $this->phptype = 'mysql'; - $this->dbsyntax = 'mysql'; - - $this->supported['sequences'] = 'emulated'; - $this->supported['indexes'] = true; - $this->supported['affected_rows'] = true; - $this->supported['transactions'] = false; - $this->supported['savepoints'] = false; - $this->supported['summary_functions'] = true; - $this->supported['order_by_text'] = true; - $this->supported['current_id'] = 'emulated'; - $this->supported['limit_queries'] = true; - $this->supported['LOBs'] = true; - $this->supported['replace'] = true; - $this->supported['sub_selects'] = 'emulated'; - $this->supported['triggers'] = false; - $this->supported['auto_increment'] = true; - $this->supported['primary_key'] = true; - $this->supported['result_introspection'] = true; - $this->supported['prepared_statements'] = 'emulated'; - $this->supported['identifier_quoting'] = true; - $this->supported['pattern_escaping'] = true; - $this->supported['new_link'] = true; - - $this->options['DBA_username'] = false; - $this->options['DBA_password'] = false; - $this->options['default_table_type'] = ''; - $this->options['max_identifiers_length'] = 64; - - $this->_reCheckSupportedOptions(); - } - - // }}} - // {{{ _reCheckSupportedOptions() - - /** - * If the user changes certain options, other capabilities may depend - * on the new settings, so we need to check them (again). - * - * @access private - */ - function _reCheckSupportedOptions() - { - $this->supported['transactions'] = $this->options['use_transactions']; - $this->supported['savepoints'] = $this->options['use_transactions']; - if ($this->options['default_table_type']) { - switch (strtoupper($this->options['default_table_type'])) { - case 'BLACKHOLE': - case 'MEMORY': - case 'ARCHIVE': - case 'CSV': - case 'HEAP': - case 'ISAM': - case 'MERGE': - case 'MRG_ISAM': - case 'ISAM': - case 'MRG_MYISAM': - case 'MYISAM': - $this->supported['savepoints'] = false; - $this->supported['transactions'] = false; - $this->warnings[] = $this->options['default_table_type'] . - ' is not a supported default table type'; - break; - } - } - } - - // }}} - // {{{ 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) - { - $res = parent::setOption($option, $value); - $this->_reCheckSupportedOptions(); - } - - // }}} - // {{{ errorInfo() - - /** - * This method is used to collect information about an error - * - * @param integer $error - * @return array - * @access public - */ - function errorInfo($error = null) - { - if ($this->connection) { - $native_code = @mysql_errno($this->connection); - $native_msg = @mysql_error($this->connection); - } else { - $native_code = @mysql_errno(); - $native_msg = @mysql_error(); - } - if (is_null($error)) { - static $ecode_map; - if (empty($ecode_map)) { - $ecode_map = array( - 1000 => MDB2_ERROR_INVALID, //hashchk - 1001 => MDB2_ERROR_INVALID, //isamchk - 1004 => MDB2_ERROR_CANNOT_CREATE, - 1005 => MDB2_ERROR_CANNOT_CREATE, - 1006 => MDB2_ERROR_CANNOT_CREATE, - 1007 => MDB2_ERROR_ALREADY_EXISTS, - 1008 => MDB2_ERROR_CANNOT_DROP, - 1009 => MDB2_ERROR_CANNOT_DROP, - 1010 => MDB2_ERROR_CANNOT_DROP, - 1011 => MDB2_ERROR_CANNOT_DELETE, - 1022 => MDB2_ERROR_ALREADY_EXISTS, - 1029 => MDB2_ERROR_NOT_FOUND, - 1032 => MDB2_ERROR_NOT_FOUND, - 1044 => MDB2_ERROR_ACCESS_VIOLATION, - 1045 => MDB2_ERROR_ACCESS_VIOLATION, - 1046 => MDB2_ERROR_NODBSELECTED, - 1048 => MDB2_ERROR_CONSTRAINT, - 1049 => MDB2_ERROR_NOSUCHDB, - 1050 => MDB2_ERROR_ALREADY_EXISTS, - 1051 => MDB2_ERROR_NOSUCHTABLE, - 1054 => MDB2_ERROR_NOSUCHFIELD, - 1060 => MDB2_ERROR_ALREADY_EXISTS, - 1061 => MDB2_ERROR_ALREADY_EXISTS, - 1062 => MDB2_ERROR_ALREADY_EXISTS, - 1064 => MDB2_ERROR_SYNTAX, - 1067 => MDB2_ERROR_INVALID, - 1072 => MDB2_ERROR_NOT_FOUND, - 1086 => MDB2_ERROR_ALREADY_EXISTS, - 1091 => MDB2_ERROR_NOT_FOUND, - 1100 => MDB2_ERROR_NOT_LOCKED, - 1109 => MDB2_ERROR_NOT_FOUND, - 1125 => MDB2_ERROR_ALREADY_EXISTS, - 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW, - 1138 => MDB2_ERROR_INVALID, - 1142 => MDB2_ERROR_ACCESS_VIOLATION, - 1143 => MDB2_ERROR_ACCESS_VIOLATION, - 1146 => MDB2_ERROR_NOSUCHTABLE, - 1149 => MDB2_ERROR_SYNTAX, - 1169 => MDB2_ERROR_CONSTRAINT, - 1176 => MDB2_ERROR_NOT_FOUND, - 1177 => MDB2_ERROR_NOSUCHTABLE, - 1213 => MDB2_ERROR_DEADLOCK, - 1216 => MDB2_ERROR_CONSTRAINT, - 1217 => MDB2_ERROR_CONSTRAINT, - 1227 => MDB2_ERROR_ACCESS_VIOLATION, - 1235 => MDB2_ERROR_CANNOT_CREATE, - 1299 => MDB2_ERROR_INVALID_DATE, - 1300 => MDB2_ERROR_INVALID, - 1304 => MDB2_ERROR_ALREADY_EXISTS, - 1305 => MDB2_ERROR_NOT_FOUND, - 1306 => MDB2_ERROR_CANNOT_DROP, - 1307 => MDB2_ERROR_CANNOT_CREATE, - 1334 => MDB2_ERROR_CANNOT_ALTER, - 1339 => MDB2_ERROR_NOT_FOUND, - 1356 => MDB2_ERROR_INVALID, - 1359 => MDB2_ERROR_ALREADY_EXISTS, - 1360 => MDB2_ERROR_NOT_FOUND, - 1363 => MDB2_ERROR_NOT_FOUND, - 1365 => MDB2_ERROR_DIVZERO, - 1451 => MDB2_ERROR_CONSTRAINT, - 1452 => MDB2_ERROR_CONSTRAINT, - 1542 => MDB2_ERROR_CANNOT_DROP, - 1546 => MDB2_ERROR_CONSTRAINT, - 1582 => MDB2_ERROR_CONSTRAINT, - 2003 => MDB2_ERROR_CONNECT_FAILED, - 2019 => MDB2_ERROR_INVALID, - ); - } - if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) { - $ecode_map[1022] = MDB2_ERROR_CONSTRAINT; - $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL; - $ecode_map[1062] = MDB2_ERROR_CONSTRAINT; - } else { - // Doing this in case mode changes during runtime. - $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS; - $ecode_map[1048] = MDB2_ERROR_CONSTRAINT; - $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS; - } - if (isset($ecode_map[$native_code])) { - $error = $ecode_map[$native_code]; - } - } - return array($error, $native_code, $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; - } - $text = @mysql_real_escape_string($text, $connection); - 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)); - $this->_getServerCapabilities(); - if (!is_null($savepoint)) { - if (!$this->supports('savepoints')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } - 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'); - } - $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0'; - $result =& $this->_doQuery($query, 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)) { - if (!$this->supports('savepoints')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } - $server_info = $this->getServerVersion(); - if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) { - return MDB2_OK; - } - $query = 'RELEASE SAVEPOINT '.$savepoint; - return $this->_doQuery($query, true); - } - - if (!$this->supports('transactions')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'transactions are not supported', __FUNCTION__); - } - - $result =& $this->_doQuery('COMMIT', true); - if (PEAR::isError($result)) { - return $result; - } - if (!$this->start_transaction) { - $query = 'SET AUTOCOMMIT = 1'; - $result =& $this->_doQuery($query, 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)) { - if (!$this->supports('savepoints')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } - $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; - return $this->_doQuery($query, true); - } - - $query = 'ROLLBACK'; - $result =& $this->_doQuery($query, true); - if (PEAR::isError($result)) { - return $result; - } - if (!$this->start_transaction) { - $query = 'SET AUTOCOMMIT = 1'; - $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 - */ - static function setTransactionIsolation($isolation, $options = array()) - { - $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true)); - if (!$this->supports('transactions')) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'transactions are not supported', __FUNCTION__); - } - 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 TRANSACTION ISOLATION LEVEL $isolation"; - return $this->_doQuery($query, true); - } - - // }}} - // {{{ _doConnect() - - /** - * do the grunt work of the connect - * - * @return connection on success or MDB2 Error Object on failure - * @access protected - */ - function _doConnect($username, $password, $persistent = false) - { - if (!PEAR::loadExtension($this->phptype)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__); - } - - $params = array(); - if ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix') { - $params[0] = ':' . $this->dsn['socket']; - } else { - $params[0] = $this->dsn['hostspec'] ? $this->dsn['hostspec'] - : 'localhost'; - if ($this->dsn['port']) { - $params[0].= ':' . $this->dsn['port']; - } - } - $params[] = $username ? $username : null; - $params[] = $password ? $password : null; - if (!$persistent) { - if ($this->_isNewLinkSet()) { - $params[] = true; - } else { - $params[] = false; - } - } - if (version_compare(phpversion(), '4.3.0', '>=')) { - $params[] = isset($this->dsn['client_flags']) - ? $this->dsn['client_flags'] : null; - } - $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect'; - - $connection = @call_user_func_array($connect_function, $params); - if (!$connection) { - if (($err = @mysql_error()) != '') { - return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, - $err, __FUNCTION__); - } else { - return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, - 'unable to establish a connection', __FUNCTION__); - } - } - - if (!empty($this->dsn['charset'])) { - $result = $this->setCharset($this->dsn['charset'], $connection); - if (PEAR::isError($result)) { - $this->disconnect(false); - return $result; - } - } - - return $connection; - } - - // }}} - // {{{ connect() - - /** - * Connect to the database - * - * @return MDB2_OK 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->opened_persistent == $this->options['persistent'] - ) { - return MDB2_OK; - } - $this->disconnect(false); - } - - $connection = $this->_doConnect( - $this->dsn['username'], - $this->dsn['password'], - $this->options['persistent'] - ); - if (PEAR::isError($connection)) { - return $connection; - } - - $this->connection = $connection; - $this->connected_dsn = $this->dsn; - $this->connected_database_name = ''; - $this->opened_persistent = $this->options['persistent']; - $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype; - - if ($this->database_name) { - if ($this->database_name != $this->connected_database_name) { - if (!@mysql_select_db($this->database_name, $connection)) { - $err = $this->raiseError(null, null, null, - 'Could not select the database: '.$this->database_name, __FUNCTION__); - return $err; - } - $this->connected_database_name = $this->database_name; - } - } - - $this->_getServerCapabilities(); - - return MDB2_OK; - } - - // }}} - // {{{ setCharset() - - /** - * Set the charset on the current connection - * - * @param string charset (or array(charset, collation)) - * @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; - } - } - $collation = null; - if (is_array($charset) && 2 == count($charset)) { - $collation = array_pop($charset); - $charset = array_pop($charset); - } - $client_info = mysql_get_client_info(); - if (function_exists('mysql_set_charset') && version_compare($client_info, '5.0.6')) { - if (!$result = mysql_set_charset($charset, $connection)) { - $err =& $this->raiseError(null, null, null, - 'Could not set client character set', __FUNCTION__); - return $err; - } - return $result; - } - $query = "SET NAMES '".mysql_real_escape_string($charset, $connection)."'"; - if (!is_null($collation)) { - $query .= " COLLATE '".mysqli_real_escape_string($connection, $collation)."'"; - } - return $this->_doQuery($query, true, $connection); - } - - // }}} - // {{{ databaseExists() - - /** - * check if given database name is exists? - * - * @param string $name name of the database that should be checked - * - * @return mixed true/false on success, a MDB2 error on failure - * @access public - */ - function databaseExists($name) - { - $connection = $this->_doConnect($this->dsn['username'], - $this->dsn['password'], - $this->options['persistent']); - if (PEAR::isError($connection)) { - return $connection; - } - - $result = @mysql_select_db($name, $connection); - @mysql_close($connection); - - return $result; - } - - // }}} - // {{{ 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) { - $ok = @mysql_close($this->connection); - if (!$ok) { - return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED, - null, null, null, __FUNCTION__); - } - } - } else { - return false; - } - 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) - { - $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username']; - $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password']; - $connection = $this->_doConnect($user, $pass, $this->options['persistent']); - if (PEAR::isError($connection)) { - return $connection; - } - - $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, $this->database_name); - if (!PEAR::isError($result)) { - $result = $this->_affectedRows($connection, $result); - } - - @mysql_close($connection); - 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; - } - } - if (is_null($database_name)) { - $database_name = $this->database_name; - } - - if ($database_name) { - if ($database_name != $this->connected_database_name) { - if (!@mysql_select_db($database_name, $connection)) { - $err = $this->raiseError(null, null, null, - 'Could not select the database: '.$database_name, __FUNCTION__); - return $err; - } - $this->connected_database_name = $database_name; - } - } - - $function = $this->options['result_buffering'] - ? 'mysql_query' : 'mysql_unbuffered_query'; - $result = @$function($query, $connection); - if (!$result) { - $err =& $this->raiseError(null, null, null, - 'Could not execute statement', __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 @mysql_affected_rows($connection); - } - - // }}} - // {{{ _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 ($this->options['portability'] & MDB2_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); - } - } - 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); - } - - // LIMIT doesn't always come last in the query - // @see http://dev.mysql.com/doc/refman/5.0/en/select.html - $after = ''; - if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) { - $after = $matches[0]; - $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query); - } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) { - $after = $matches[0]; - $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query); - } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) { - $after = $matches[0]; - $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query); - } - - if ($is_manip) { - return $query . " LIMIT $limit" . $after; - } else { - return $query . " LIMIT $offset, $limit" . $after; - } - } - 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) - { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - if ($this->connected_server_info) { - $server_info = $this->connected_server_info; - } else { - $server_info = @mysql_get_server_info($connection); - } - if (!$server_info) { - return $this->raiseError(null, null, null, - 'Could not get server information', __FUNCTION__); - } - // cache server_info - $this->connected_server_info = $server_info; - if (!$native) { - $tmp = explode('.', $server_info, 3); - if (isset($tmp[2]) && strpos($tmp[2], '-')) { - $tmp2 = explode('-', @$tmp[2], 2); - } else { - $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null; - $tmp2[1] = null; - } - $server_info = array( - 'major' => isset($tmp[0]) ? $tmp[0] : null, - 'minor' => isset($tmp[1]) ? $tmp[1] : null, - 'patch' => $tmp2[0], - 'extra' => $tmp2[1], - 'native' => $server_info, - ); - } - return $server_info; - } - - // }}} - // {{{ _getServerCapabilities() - - /** - * Fetch some information about the server capabilities - * (transactions, subselects, prepared statements, etc). - * - * @access private - */ - function _getServerCapabilities() - { - if (!$this->server_capabilities_checked) { - $this->server_capabilities_checked = true; - - //set defaults - $this->supported['sub_selects'] = 'emulated'; - $this->supported['prepared_statements'] = 'emulated'; - $this->supported['triggers'] = false; - $this->start_transaction = false; - $this->varchar_max_length = 255; - - $server_info = $this->getServerVersion(); - if (is_array($server_info)) { - $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch']; - - if (!version_compare($server_version, '4.1.0', '<')) { - $this->supported['sub_selects'] = true; - $this->supported['prepared_statements'] = true; - } - - // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB) - if (version_compare($server_version, '4.1.0', '>=')) { - if (version_compare($server_version, '4.1.1', '<')) { - $this->supported['savepoints'] = false; - } - } elseif (version_compare($server_version, '4.0.14', '<')) { - $this->supported['savepoints'] = false; - } - - if (!version_compare($server_version, '4.0.11', '<')) { - $this->start_transaction = true; - } - - if (!version_compare($server_version, '5.0.3', '<')) { - $this->varchar_max_length = 65532; - } - - if (!version_compare($server_version, '5.0.2', '<')) { - $this->supported['triggers'] = true; - } - } - } - } - - // }}} - // {{{ function _skipUserDefinedVariable($query, $position) - - /** - * Utility method, used by prepare() to avoid misinterpreting MySQL user - * defined variables (SELECT @x:=5) for placeholders. - * Check if the placeholder is a false positive, i.e. if it is an user defined - * variable instead. 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 - * @return integer $new_position - * @access protected - */ - function _skipUserDefinedVariable($query, $position) - { - $found = strpos(strrev(substr($query, 0, $position)), '@'); - if ($found === false) { - return $position; - } - $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1; - $substring = substr($query, $pos, $position - $pos + 2); - if (preg_match('/^@\w+\s*:=$/', $substring)) { - return $position + 1; //found an user defined variable: skip it - } - return $position; - } - - // }}} - // {{{ 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'] - || $this->supported['prepared_statements'] !== true - ) { - $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; - $query = $this->_modifyQuery($query, $is_manip, $limit, $offset); - $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; - 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 - } - - //make sure this is not part of an user defined variable - $new_pos = $this->_skipUserDefinedVariable($query, $position); - 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 ($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); - } else { - $positions[$p_position] = count($positions); - } - $position = $p_position + 1; - } 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, $prep_statement_counter++ . sha1(microtime() + mt_rand())); - $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']); - $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text'); - $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; - } - - // }}} - // {{{ replace() - - /** - * 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 old row is deleted before the new row is inserted. - * - * The REPLACE type of query does not make part of the SQL standards. Since - * practically only MySQL implements it natively, this type of query is - * emulated through this method for other DBMS using standard types of - * queries inside a transaction to assure the atomicity of the operation. - * - * @access public - * - * @param string $table name of the table on which the REPLACE query will - * be executed. - * @param array $fields 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 Metabase - * are supported except for clob and blob. - * - * Default: no type conversion - * - * null - * Boolean 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 - * Boolean 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 - * - * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html - * @return mixed MDB2_OK on success, a MDB2 error on failure - */ - function replace($table, $fields) - { - $count = count($fields); - $query = $values = ''; - $keys = $colnum = 0; - for (reset($fields); $colnum < $count; next($fields), $colnum++) { - $name = key($fields); - if ($colnum > 0) { - $query .= ','; - $values.= ','; - } - $query.= $this->quoteIdentifier($name, true); - 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); - if (PEAR::isError($value)) { - return $value; - } - } - $values.= $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__); - } - $keys++; - } - } - if ($keys == 0) { - return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null, - 'not specified which fields are keys', __FUNCTION__); - } - - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - $table = $this->quoteIdentifier($table, true); - $query = "REPLACE INTO $table ($query) VALUES ($values)"; - $result =& $this->_doQuery($query, true, $connection); - if (PEAR::isError($result)) { - return $result; - } - return $this->_affectedRows($connection, $result); - } - - // }}} - // {{{ 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); - $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true); - $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)"; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $this->expectError(MDB2_ERROR_NOSUCHTABLE); - $result =& $this->_doQuery($query, true); - $this->popExpect(); - $this->popErrorHandling(); - 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 '.$seq_name.' could not be created', __FUNCTION__); - } else { - return $this->nextID($seq_name, false); - } - } - return $result; - } - $value = $this->lastInsertID(); - if (is_numeric($value)) { - $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value"; - $result =& $this->_doQuery($query, true); - if (PEAR::isError($result)) { - $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name; - } - } - return $value; - } - - // }}} - // {{{ 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) - { - // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051 - return $this->queryOne('SELECT LAST_INSERT_ID()', '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); - $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true); - $query = "SELECT MAX($seqcol_name) FROM $sequence_name"; - return $this->queryOne($query, 'integer'); - } -} - -/** - * MDB2 MySQL result driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Result_mysql 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 = @mysql_fetch_assoc($this->result); - 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 = @mysql_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 = @mysql_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. - * - * @return mixed integer value with the number of columns, a MDB2 error - * on failure - * @access public - */ - function numCols() - { - $cols = @mysql_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; - } - - // }}} - // {{{ 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 = @mysql_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 MySQL buffered result driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_BufferedResult_mysql extends MDB2_Result_mysql -{ - // }}} - // {{{ 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) && !@mysql_data_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 = @mysql_num_rows($this->result); - if (false === $rows) { - if (false === $this->result) { - 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 MySQL statement driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Statement_mysql 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 MDB2_Result or integer (affected rows) 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 = 'EXECUTE '.$this->statement; - if (!empty($this->positions)) { - $parameters = array(); - 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); - if (PEAR::isError($quoted)) { - return $quoted; - } - $param_query = 'SET @'.$parameter.' = '.$quoted; - $result = $this->db->_doQuery($param_query, true, $connection); - if (PEAR::isError($result)) { - return $result; - } - } - $query.= ' USING @'.implode(', @', array_values($this->positions)); - } - - $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 diff --git a/3rdparty/MDB2/Driver/pgsql.php b/3rdparty/MDB2/Driver/pgsql.php deleted file mode 100644 index 13fea6906806f2b3f41b85b204181ce67a75eae4..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/pgsql.php +++ /dev/null @@ -1,1519 +0,0 @@ -<?php -// vim: set et ts=4 sw=4 fdm=marker: -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 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.203 2008/11/29 14:04:46 afz 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['triggers'] = 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['DBA_username'] = false; - $this->options['DBA_password'] = false; - $this->options['multi_query'] = false; - $this->options['disable_smart_seqname'] = true; - $this->options['max_identifiers_length'] = 63; - } - - // }}} - // {{{ 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; - } - } else { - $native_msg = @pg_last_error(); - } - - 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, - '/database .* does not exist/' - => MDB2_ERROR_NOT_FOUND, - '/constraint .* does not exist/' - => MDB2_ERROR_NOT_FOUND, - '/index .* does not exist/' - => MDB2_ERROR_NOT_FOUND, - '/database .* already exists/i' - => MDB2_ERROR_ALREADY_EXISTS, - '/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 (is_resource($connection) && 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 - */ - static function setTransactionIsolation($isolation, $options = array()) - { - $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() - - /** - * Do the grunt work of connecting to the database - * - * @return mixed connection resource on success, MDB2 Error Object on failure - * @access protected - */ - function _doConnect($username, $password, $database_name, $persistent = 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 ($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 ($username) { - $params[0].= ' user=\'' . addslashes($username) . '\''; - } - if ($password) { - $params[0].= ' password=\'' . addslashes($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 ($this->_isNewLinkSet()) { - 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 ($this->database_name) { - $connection = $this->_doConnect($this->dsn['username'], - $this->dsn['password'], - $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; - } - } - if (is_array($charset)) { - $charset = array_shift($charset); - $this->warnings[] = 'postgresql does not support setting client collation'; - } - $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; - } - - // }}} - // {{{ databaseExists() - - /** - * check if given database name is exists? - * - * @param string $name name of the database that should be checked - * - * @return mixed true/false on success, a MDB2 error on failure - * @access public - */ - function databaseExists($name) - { - $res = $this->_doConnect($this->dsn['username'], - $this->dsn['password'], - $this->escape($name), - $this->options['persistent']); - if (!PEAR::isError($res)) { - return true; - } - - return false; - } - - // }}} - // {{{ 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) { - $ok = @pg_close($this->connection); - if (!$ok) { - return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED, - null, null, null, __FUNCTION__); - } - } - } else { - return false; - } - 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) - { - $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username']; - $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password']; - $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']); - if (PEAR::isError($connection)) { - return $connection; - } - - $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, $this->database_name); - if (!PEAR::isError($result)) { - if ($is_manip) { - $result = $this->_affectedRows($connection, $result); - } else { - $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset); - } - } - - @pg_close($connection); - 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, $prep_statement_counter++ . sha1(microtime() + mt_rand())); - $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']); - 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 parent::getSequenceName($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->pushErrorHandling(PEAR_ERROR_RETURN); - $this->expectError(MDB2_ERROR_NOSUCHTABLE); - $result = $this->queryOne($query, 'integer'); - $this->popExpect(); - $this->popErrorHandling(); - 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->quoteIdentifier($this->getSequenceName($seq), true); - 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 MDB2_Result or integer (affected rows) 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 diff --git a/3rdparty/MDB2/Driver/sqlite.php b/3rdparty/MDB2/Driver/sqlite.php deleted file mode 100644 index 5d2ad27d01635d94b0fe112d63f1e9f205448f52..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Driver/sqlite.php +++ /dev/null @@ -1,1088 +0,0 @@ -<?php -// vim: set et ts=4 sw=4 fdm=marker: -// +----------------------------------------------------------------------+ -// | PHP versions 4 and 5 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1998-2008 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: sqlite.php,v 1.165 2008/11/30 14:28:01 afz Exp $ -// - -/** - * MDB2 SQLite driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Driver_sqlite extends MDB2_Driver_Common -{ - // {{{ properties - var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false); - - var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"'); - - var $_lasterror = ''; - - var $fix_assoc_fields_names = false; - - // }}} - // {{{ constructor - - /** - * Constructor - */ - function __construct() - { - parent::__construct(); - - $this->phptype = 'sqlite'; - $this->dbsyntax = 'sqlite'; - - $this->supported['sequences'] = 'emulated'; - $this->supported['indexes'] = true; - $this->supported['affected_rows'] = true; - $this->supported['summary_functions'] = true; - $this->supported['order_by_text'] = true; - $this->supported['current_id'] = 'emulated'; - $this->supported['limit_queries'] = true; - $this->supported['LOBs'] = true; - $this->supported['replace'] = true; - $this->supported['transactions'] = true; - $this->supported['savepoints'] = false; - $this->supported['sub_selects'] = true; - $this->supported['triggers'] = true; - $this->supported['auto_increment'] = true; - $this->supported['primary_key'] = false; // requires alter table implementation - $this->supported['result_introspection'] = false; // not implemented - $this->supported['prepared_statements'] = 'emulated'; - $this->supported['identifier_quoting'] = true; - $this->supported['pattern_escaping'] = false; - $this->supported['new_link'] = false; - - $this->options['DBA_username'] = false; - $this->options['DBA_password'] = false; - $this->options['base_transaction_name'] = '___php_MDB2_sqlite_auto_commit_off'; - $this->options['fixed_float'] = 0; - $this->options['database_path'] = ''; - $this->options['database_extension'] = ''; - $this->options['server_version'] = ''; - $this->options['max_identifiers_length'] = 128; //no real limit - } - - // }}} - // {{{ errorInfo() - - /** - * This method is used to collect information about an error - * - * @param integer $error - * @return array - * @access public - */ - function errorInfo($error = null) - { - $native_code = null; - if ($this->connection) { - $native_code = @sqlite_last_error($this->connection); - } - $native_msg = $this->_lasterror - ? html_entity_decode($this->_lasterror) : @sqlite_error_string($native_code); - - // PHP 5.2+ prepends the function name to $php_errormsg, so we need - // this hack to work around it, per bug #9599. - $native_msg = preg_replace('/^sqlite[a-z_]+\(\)[^:]*: /', '', $native_msg); - - if (is_null($error)) { - static $error_regexps; - if (empty($error_regexps)) { - $error_regexps = array( - '/^no such table:/' => MDB2_ERROR_NOSUCHTABLE, - '/^no such index:/' => MDB2_ERROR_NOT_FOUND, - '/^(table|index) .* already exists$/' => MDB2_ERROR_ALREADY_EXISTS, - '/PRIMARY KEY must be unique/i' => MDB2_ERROR_CONSTRAINT, - '/is not unique/' => MDB2_ERROR_CONSTRAINT, - '/columns .* are not unique/i' => MDB2_ERROR_CONSTRAINT, - '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT, - '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL, - '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD, - '/no column named/' => MDB2_ERROR_NOSUCHFIELD, - '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD, - '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX, - '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW, - ); - } - foreach ($error_regexps as $regexp => $code) { - if (preg_match($regexp, $native_msg)) { - $error = $code; - break; - } - } - } - return array($error, $native_code, $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) - { - $text = @sqlite_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)) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } 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'); - } - $query = 'BEGIN TRANSACTION '.$this->options['base_transaction_name']; - $result =$this->_doQuery($query, 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)) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } - - $query = 'COMMIT TRANSACTION '.$this->options['base_transaction_name']; - $result =$this->_doQuery($query, true); - if (PEAR::isError($result)) { - return $result; - } - $this->in_transaction = false; - return MDB2_OK; - } - - // }}} - // {{{ - - /** - * 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)) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } - - $query = 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name']; - $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 - */ - static function setTransactionIsolation($isolation,$options=array()) - { - $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true)); - switch ($isolation) { - case 'READ UNCOMMITTED': - $isolation = 0; - break; - case 'READ COMMITTED': - case 'REPEATABLE READ': - case 'SERIALIZABLE': - $isolation = 1; - break; - default: - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'isolation level is not supported: '.$isolation, __FUNCTION__); - } - - $query = "PRAGMA read_uncommitted=$isolation"; - return $this->_doQuery($query, true); - } - - // }}} - // {{{ getDatabaseFile() - - /** - * Builds the string with path+dbname+extension - * - * @return string full database path+file - * @access protected - */ - function _getDatabaseFile($database_name) - { - if ($database_name === '' || $database_name === ':memory:') { - return $database_name; - } - return $this->options['database_path'].$database_name.$this->options['database_extension']; - } - - // }}} - // {{{ connect() - - /** - * Connect to the database - * - * @return true on success, MDB2 Error Object on failure - **/ - function connect() - { - $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ); - $database_file = $this->_getDatabaseFile($this->database_name); - 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 == $database_file - && $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 (empty($this->database_name)) { - return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, - 'unable to establish a connection', __FUNCTION__); - } - - if ($database_file !== ':memory:') { - if(!strpos($database_file,'.db')){ - $database_file="$datadir/$database_file.db"; - } - if (!file_exists($database_file)) { - if (!touch($database_file)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'Could not create database file', __FUNCTION__); - } - if (!isset($this->dsn['mode']) - || !is_numeric($this->dsn['mode']) - ) { - $mode = 0644; - } else { - $mode = octdec($this->dsn['mode']); - } - if (!chmod($database_file, $mode)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'Could not be chmodded database file', __FUNCTION__); - } - if (!file_exists($database_file)) { - return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, - 'Could not be found database file', __FUNCTION__); - } - } - if (!is_file($database_file)) { - return $this->raiseError(MDB2_ERROR_INVALID, null, null, - 'Database is a directory name', __FUNCTION__); - } - if (!is_readable($database_file)) { - return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null, - 'Could not read database file', __FUNCTION__); - } - } - - $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open'); - $php_errormsg = ''; - if (version_compare('5.1.0', PHP_VERSION, '>')) { - @ini_set('track_errors', true); - echo 1; - $connection = @$connect_function($database_file); - echo 2; - @ini_restore('track_errors'); - } else { - $connection = @$connect_function($database_file, 0666, $php_errormsg); - } - $this->_lasterror = $php_errormsg; - if (!$connection) { - return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, - 'unable to establish a connection', __FUNCTION__); - } - - if ($this->fix_assoc_fields_names || - $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES) - { - @sqlite_query("PRAGMA short_column_names = 1", $connection); - $this->fix_assoc_fields_names = true; - } - - $this->connection = $connection; - $this->connected_dsn = $this->dsn; - $this->connected_database_name = $database_file; - $this->opened_persistent = $this->getoption('persistent'); - $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype; - - return MDB2_OK; - } - - // }}} - // {{{ databaseExists() - - /** - * check if given database name is exists? - * - * @param string $name name of the database that should be checked - * - * @return mixed true/false on success, a MDB2 error on failure - * @access public - */ - function databaseExists($name) - { - $database_file = $this->_getDatabaseFile($name); - $result = file_exists($database_file); - return $result; - } - - // }}} - // {{{ 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) { - @sqlite_close($this->connection); - } - } else { - return false; - } - return parent::disconnect($force); - } - - // }}} - // {{{ _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['result_buffering'] - ? 'sqlite_query' : 'sqlite_unbuffered_query'; - $php_errormsg = ''; - if (version_compare('5.1.0', PHP_VERSION, '>')) { - @ini_set('track_errors', true); - do { - $result = @$function($query.';', $connection); - } while (sqlite_last_error($connection) == SQLITE_SCHEMA); - @ini_restore('track_errors'); - } else { - do { - $result = @$function($query.';', $connection, SQLITE_BOTH, $php_errormsg); - } while (sqlite_last_error($connection) == SQLITE_SCHEMA); - } - $this->_lasterror = $php_errormsg; - - if (!$result) { - $err =$this->raiseError(null, null, null, - 'Could not execute statement', __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 @sqlite_changes($connection); - } - - // }}} - // {{{ _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 ($this->options['portability'] & MDB2_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); - } - } - 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.= " LIMIT $limit"; - } else { - $query.= " LIMIT $offset,$limit"; - } - } - 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) - { - $server_info = false; - if ($this->connected_server_info) { - $server_info = $this->connected_server_info; - } elseif ($this->options['server_version']) { - $server_info = $this->options['server_version']; - } elseif (function_exists('sqlite_libversion')) { - $server_info = @sqlite_libversion(); - } - if (!$server_info) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'Requires either the "server_version" option or the sqlite_libversion() function', __FUNCTION__); - } - // cache server_info - $this->connected_server_info = $server_info; - if (!$native) { - $tmp = explode('.', $server_info, 3); - $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; - } - - // }}} - // {{{ replace() - - /** - * 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 old row is deleted before the new row is inserted. - * - * The REPLACE type of query does not make part of the SQL standards. Since - * practically only SQLite implements it natively, this type of query is - * emulated through this method for other DBMS using standard types of - * queries inside a transaction to assure the atomicity of the operation. - * - * @access public - * - * @param string $table name of the table on which the REPLACE query will - * be executed. - * @param array $fields 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 Metabase - * are supported except for clob and blob. - * - * Default: no type conversion - * - * null - * Boolean 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 - * Boolean 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 - */ - function replace($table, $fields) - { - $count = count($fields); - $query = $values = ''; - $keys = $colnum = 0; - for (reset($fields); $colnum < $count; next($fields), $colnum++) { - $name = key($fields); - if ($colnum > 0) { - $query .= ','; - $values.= ','; - } - $query.= $this->quoteIdentifier($name, true); - 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); - if (PEAR::isError($value)) { - return $value; - } - } - $values.= $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__); - } - $keys++; - } - } - if ($keys == 0) { - return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null, - 'not specified which fields are keys', __FUNCTION__); - } - - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - $table = $this->quoteIdentifier($table, true); - $query = "REPLACE INTO $table ($query) VALUES ($values)"; - $result =$this->_doQuery($query, true, $connection); - if (PEAR::isError($result)) { - return $result; - } - return $this->_affectedRows($connection, $result); - } - - // }}} - // {{{ 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); - $seqcol_name = $this->options['seqcol_name']; - $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)"; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $this->expectError(MDB2_ERROR_NOSUCHTABLE); - $result =$this->_doQuery($query, true); - $this->popExpect(); - $this->popErrorHandling(); - 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 '.$seq_name.' could not be created', __FUNCTION__); - } else { - return $this->nextID($seq_name, false); - } - } - return $result; - } - $value = $this->lastInsertID(); - if (is_numeric($value)) { - $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value"; - $result =$this->_doQuery($query, true); - if (PEAR::isError($result)) { - $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name; - } - } - return $value; - } - - // }}} - // {{{ 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) - { - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - $value = @sqlite_last_insert_rowid($connection); - if (!$value) { - return $this->raiseError(null, null, null, - 'Could not get last insert ID', __FUNCTION__); - } - return $value; - } - - // }}} - // {{{ 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); - $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true); - $query = "SELECT MAX($seqcol_name) FROM $sequence_name"; - return $this->queryOne($query, 'integer'); - } -} - -/** - * MDB2 SQLite result driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Result_sqlite 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 = @sqlite_fetch_array($this->result, SQLITE_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 = @sqlite_fetch_array($this->result, SQLITE_NUM); - } - 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 = @sqlite_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 = @sqlite_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; - } -} - -/** - * MDB2 SQLite buffered result driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_BufferedResult_sqlite extends MDB2_Result_sqlite -{ - // {{{ 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 (!@sqlite_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 = @sqlite_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 SQLite statement driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith <smith@pooteeweet.org> - */ -class MDB2_Statement_sqlite extends MDB2_Statement_Common -{ - -} - -?> diff --git a/3rdparty/MDB2/Extended.php b/3rdparty/MDB2/Extended.php deleted file mode 100644 index 864ab9235432bd0e839d6093269b627062d27f8d..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Extended.php +++ /dev/null @@ -1,721 +0,0 @@ -<?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.60 2007/11/28 19:49:34 quipo 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 diff --git a/3rdparty/MDB2/Iterator.php b/3rdparty/MDB2/Iterator.php deleted file mode 100644 index ca5e7b69c27df7091c4b01483ada57d2435f2440..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Iterator.php +++ /dev/null @@ -1,259 +0,0 @@ -<?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.22 2006/05/06 14:03:41 lsmith 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 diff --git a/3rdparty/MDB2/LOB.php b/3rdparty/MDB2/LOB.php deleted file mode 100644 index ae67224020e84d944a450b5e1c6be5010d1c3893..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/LOB.php +++ /dev/null @@ -1,264 +0,0 @@ -<?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.34 2006/10/25 11:52:21 lsmith 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; -} - -?> diff --git a/3rdparty/MDB2/Schema.php b/3rdparty/MDB2/Schema.php deleted file mode 100644 index 25818460a629b6a37f9d5c884429c2bbbb08d34b..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema.php +++ /dev/null @@ -1,2763 +0,0 @@ -<?php -/** - * PHP version 4, 5 - * - * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, - * Stig. S. Bakken, Lukas Smith, Igor Feghali - * All rights reserved. - * - * MDB2_Schema enables users to maintain RDBMS independant schema files - * in XML that can be used to manipulate both data and database schemas - * 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, Igor Feghali 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> - * Author: Igor Feghali <ifeghali@php.net> - * - * @category Database - * @package MDB2_Schema - * @author Lukas Smith <smith@pooteeweet.org> - * @author Igor Feghali <ifeghali@php.net> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Schema.php,v 1.132 2009/02/22 21:43:22 ifeghali Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - -// require_once('MDB2.php'); - -define('MDB2_SCHEMA_DUMP_ALL', 0); -define('MDB2_SCHEMA_DUMP_STRUCTURE', 1); -define('MDB2_SCHEMA_DUMP_CONTENT', 2); - -/** - * If you add an error code here, make sure you also add a textual - * version of it in MDB2_Schema::errorMessage(). - */ - -define('MDB2_SCHEMA_ERROR', -1); -define('MDB2_SCHEMA_ERROR_PARSE', -2); -define('MDB2_SCHEMA_ERROR_VALIDATE', -3); -define('MDB2_SCHEMA_ERROR_UNSUPPORTED', -4); // Driver does not support this function -define('MDB2_SCHEMA_ERROR_INVALID', -5); // Invalid attribute value -define('MDB2_SCHEMA_ERROR_WRITER', -6); - -/** - * The database manager is a class that provides a set of database - * management services like installing, altering and dumping the data - * structures of databases. - * - * @category Database - * @package MDB2_Schema - * @author Lukas Smith <smith@pooteeweet.org> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema extends PEAR -{ - // {{{ properties - - var $db; - - var $warnings = array(); - - var $options = array( - 'fail_on_invalid_names' => true, - 'dtd_file' => false, - 'valid_types' => array(), - 'force_defaults' => true, - 'parser' => 'MDB2_Schema_Parser', - 'writer' => 'MDB2_Schema_Writer', - 'validate' => 'MDB2_Schema_Validate', - 'drop_missing_tables' => false - ); - - // }}} - // {{{ apiVersion() - - /** - * Return the MDB2 API version - * - * @return string the MDB2 API version number - * @access public - */ - function apiVersion() - { - return '0.4.3'; - } - - // }}} - // {{{ arrayMergeClobber() - - /** - * Clobbers two arrays together - * - * @param array $a1 array that should be clobbered - * @param array $a2 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] = MDB2_Schema::arrayMergeClobber($a1[$key], $val); - } else { - $a1[$key] = $val; - } - } - return $a1; - } - - // }}} - // {{{ resetWarnings() - - /** - * reset the warning array - * - * @access public - * @return void - */ - function resetWarnings() - { - $this->warnings = array(); - } - - // }}} - // {{{ 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); - } - - // }}} - // {{{ setOption() - - /** - * Sets the option for the db class - * - * @param string $option option name - * @param mixed $value value for the option - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function setOption($option, $value) - { - if (isset($this->options[$option])) { - if (is_null($value)) { - return $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'may not set an option to value null'); - } - $this->options[$option] = $value; - return MDB2_OK; - } - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - "unknown option $option"); - } - - // }}} - // {{{ getOption() - - /** - * returns the value of an option - * - * @param string $option option name - * - * @return mixed the option value or error object - * @access public - */ - function getOption($option) - { - if (isset($this->options[$option])) { - return $this->options[$option]; - } - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, - null, null, "unknown option $option"); - } - - // }}} - // {{{ factory() - - /** - * Create a new MDB2 object for the specified database type - * type - * - * @param string|array|MDB2_Driver_Common &$db '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 @see MDB2::parseDSN. - * Finally you can also pass an existing db object to be used. - * @param array $options An associative array of option names and their values. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - * @see MDB2::parseDSN - */ - static function factory(&$db, $options = array()) - { - $obj =new MDB2_Schema(); - $result = $obj->connect($db, $options); - if (PEAR::isError($result)) { - return $result; - } - return $obj; - } - - // }}} - // {{{ connect() - - /** - * Create a new MDB2 connection object and connect to the specified - * database - * - * @param string|array|MDB2_Driver_Common &$db '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. - * Finally you can also pass an existing db object to be used. - * @param array $options An associative array of option names and their values. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - * @see MDB2::parseDSN - */ - function connect(&$db, $options = array()) - { - $db_options = array(); - if (is_array($options)) { - foreach ($options as $option => $value) { - if (array_key_exists($option, $this->options)) { - $result = $this->setOption($option, $value); - if (PEAR::isError($result)) { - return $result; - } - } else { - $db_options[$option] = $value; - } - } - } - $this->disconnect(); - if (!MDB2::isConnection($db)) { - $db =MDB2::factory($db, $db_options); - } - - if (PEAR::isError($db)) { - return $db; - } - $this->db =& $db; - $this->db->loadModule('Datatype'); - $this->db->loadModule('Manager'); - $this->db->loadModule('Reverse'); - $this->db->loadModule('Function'); - if (empty($this->options['valid_types'])) { - $this->options['valid_types'] = $this->db->datatype->getValidTypes(); - } - - return MDB2_OK; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @access public - * @return void - */ - function disconnect() - { - if (MDB2::isConnection($this->db)) { - $this->db->disconnect(); - unset($this->db); - } - } - - // }}} - // {{{ parseDatabaseDefinition() - - /** - * Parse a database definition from a file or an array - * - * @param string|array $schema the database schema array or file name - * @param bool $skip_unreadable if non readable files should be skipped - * @param array $variables associative array that the defines the text string values - * that are meant to be used to replace the variables that are - * used in the schema description. - * @param bool $fail_on_invalid_names make function fail on invalid names - * @param array $structure database structure definition - * - * @access public - * @return array - */ - function parseDatabaseDefinition($schema, $skip_unreadable = false, $variables = array(), - $fail_on_invalid_names = true, $structure = false) - { - $database_definition = false; - if (is_string($schema)) { - // if $schema is not readable then we just skip it - // and simply copy the $current_schema file to that file name - if (is_readable($schema)) { - $database_definition = $this->parseDatabaseDefinitionFile($schema, $variables, $fail_on_invalid_names, $structure); - } - } elseif (is_array($schema)) { - $database_definition = $schema; - } - if (!$database_definition && !$skip_unreadable) { - $database_definition = $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'invalid data type of schema or unreadable data source'); - } - return $database_definition; - } - - // }}} - // {{{ parseDatabaseDefinitionFile() - - /** - * Parse a database definition file by creating a schema format - * parser object and passing the file contents as parser input data stream. - * - * @param string $input_file the database schema file. - * @param array $variables associative array that the defines the text string values - * that are meant to be used to replace the variables that are - * used in the schema description. - * @param bool $fail_on_invalid_names make function fail on invalid names - * @param array $structure database structure definition - * - * @access public - * @return array - */ - function parseDatabaseDefinitionFile($input_file, $variables = array(), - $fail_on_invalid_names = true, $structure = false) - { - $dtd_file = $this->options['dtd_file']; - if ($dtd_file) { - include_once 'XML/DTD/XmlValidator.php'; - $dtd =new XML_DTD_XmlValidator; - if (!$dtd->isValid($dtd_file, $input_file)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_PARSE, null, null, $dtd->getMessage()); - } - } - - $class_name = $this->options['parser']; - - $result = MDB2::loadClass($class_name, $this->db->getOption('debug')); - if (PEAR::isError($result)) { - return $result; - } - - $parser =new $class_name($variables, $fail_on_invalid_names, $structure, $this->options['valid_types'], $this->options['force_defaults']); - $result = $parser->setInputFile($input_file); - if (PEAR::isError($result)) { - return $result; - } - - $result = $parser->parse(); - if (PEAR::isError($result)) { - return $result; - } - if (PEAR::isError($parser->error)) { - return $parser->error; - } - - return $parser->database_definition; - } - - // }}} - // {{{ getDefinitionFromDatabase() - - /** - * Attempt to reverse engineer a schema structure from an existing MDB2 - * This method can be used if no xml schema file exists yet. - * The resulting xml schema file may need some manual adjustments. - * - * @return array|MDB2_Error array with definition or error object - * @access public - */ - function getDefinitionFromDatabase() - { - $database = $this->db->database_name; - if (empty($database)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'it was not specified a valid database name'); - } - $class_name = $this->options['validate']; - - $result = MDB2::loadClass($class_name, $this->db->getOption('debug')); - if (PEAR::isError($result)) { - return $result; - } - - $val =new $class_name($this->options['fail_on_invalid_names'], $this->options['valid_types'], $this->options['force_defaults']); - - $database_definition = array( - 'name' => $database, - 'create' => true, - 'overwrite' => false, - 'charset' => 'utf8', - 'description' => '', - 'comments' => '', - 'tables' => array(), - 'sequences' => array(), - ); - - $tables = $this->db->manager->listTables(); - if (PEAR::isError($tables)) { - return $tables; - } - - foreach ($tables as $table_name) { - $fields = $this->db->manager->listTableFields($table_name); - if (PEAR::isError($fields)) { - return $fields; - } - - $database_definition['tables'][$table_name] = array( - 'was' => '', - 'description' => '', - 'comments' => '', - 'fields' => array(), - 'indexes' => array(), - 'constraints' => array(), - 'initialization' => array() - ); - - $table_definition =& $database_definition['tables'][$table_name]; - foreach ($fields as $field_name) { - $definition = $this->db->reverse->getTableFieldDefinition($table_name, $field_name); - if (PEAR::isError($definition)) { - return $definition; - } - - if (!empty($definition[0]['autoincrement'])) { - $definition[0]['default'] = '0'; - } - - $table_definition['fields'][$field_name] = $definition[0]; - - $field_choices = count($definition); - if ($field_choices > 1) { - $warning = "There are $field_choices type choices in the table $table_name field $field_name (#1 is the default): "; - - $field_choice_cnt = 1; - - $table_definition['fields'][$field_name]['choices'] = array(); - foreach ($definition as $field_choice) { - $table_definition['fields'][$field_name]['choices'][] = $field_choice; - - $warning .= 'choice #'.($field_choice_cnt).': '.serialize($field_choice); - $field_choice_cnt++; - } - $this->warnings[] = $warning; - } - - /** - * The first parameter is used to verify if there are duplicated - * fields which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateField(array(), $table_definition['fields'][$field_name], $field_name); - if (PEAR::isError($result)) { - return $result; - } - } - - $keys = array(); - - $indexes = $this->db->manager->listTableIndexes($table_name); - if (PEAR::isError($indexes)) { - return $indexes; - } - - if (is_array($indexes)) { - foreach ($indexes as $index_name) { - $this->db->expectError(MDB2_ERROR_NOT_FOUND); - $definition = $this->db->reverse->getTableIndexDefinition($table_name, $index_name); - $this->db->popExpect(); - if (PEAR::isError($definition)) { - if (PEAR::isError($definition, MDB2_ERROR_NOT_FOUND)) { - continue; - } - return $definition; - } - - $keys[$index_name] = $definition; - } - } - - $constraints = $this->db->manager->listTableConstraints($table_name); - if (PEAR::isError($constraints)) { - return $constraints; - } - - if (is_array($constraints)) { - foreach ($constraints as $constraint_name) { - $this->db->expectError(MDB2_ERROR_NOT_FOUND); - $definition = $this->db->reverse->getTableConstraintDefinition($table_name, $constraint_name); - $this->db->popExpect(); - if (PEAR::isError($definition)) { - if (PEAR::isError($definition, MDB2_ERROR_NOT_FOUND)) { - continue; - } - return $definition; - } - - $keys[$constraint_name] = $definition; - } - } - - foreach ($keys as $key_name => $definition) { - if (array_key_exists('foreign', $definition) - && $definition['foreign'] - ) { - /** - * The first parameter is used to verify if there are duplicated - * foreign keys which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateConstraint(array(), $definition, $key_name); - if (PEAR::isError($result)) { - return $result; - } - - foreach ($definition['fields'] as $field_name => $field) { - /** - * The first parameter is used to verify if there are duplicated - * referencing fields which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateConstraintField(array(), $field_name); - if (PEAR::isError($result)) { - return $result; - } - - $definition['fields'][$field_name] = ''; - } - - foreach ($definition['references']['fields'] as $field_name => $field) { - /** - * The first parameter is used to verify if there are duplicated - * referenced fields which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateConstraintReferencedField(array(), $field_name); - if (PEAR::isError($result)) { - return $result; - } - - $definition['references']['fields'][$field_name] = ''; - } - - $table_definition['constraints'][$key_name] = $definition; - } else { - /** - * The first parameter is used to verify if there are duplicated - * indices which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateIndex(array(), $definition, $key_name); - if (PEAR::isError($result)) { - return $result; - } - - foreach ($definition['fields'] as $field_name => $field) { - /** - * The first parameter is used to verify if there are duplicated - * index fields which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateIndexField(array(), $field, $field_name); - if (PEAR::isError($result)) { - return $result; - } - - $definition['fields'][$field_name] = $field; - } - - $table_definition['indexes'][$key_name] = $definition; - } - } - - /** - * The first parameter is used to verify if there are duplicated - * tables which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateTable(array(), $table_definition, $table_name); - if (PEAR::isError($result)) { - return $result; - } - - } - - $sequences = $this->db->manager->listSequences(); - if (PEAR::isError($sequences)) { - return $sequences; - } - - if (is_array($sequences)) { - foreach ($sequences as $sequence_name) { - $definition = $this->db->reverse->getSequenceDefinition($sequence_name); - if (PEAR::isError($definition)) { - return $definition; - } - if (isset($database_definition['tables'][$sequence_name]) - && isset($database_definition['tables'][$sequence_name]['indexes']) - ) { - foreach ($database_definition['tables'][$sequence_name]['indexes'] as $index) { - if (isset($index['primary']) && $index['primary'] - && count($index['fields'] == 1) - ) { - $definition['on'] = array( - 'table' => $sequence_name, - 'field' => key($index['fields']), - ); - break; - } - } - } - - /** - * The first parameter is used to verify if there are duplicated - * sequences which we can guarantee that won't happen when reverse engineering - */ - $result = $val->validateSequence(array(), $definition, $sequence_name); - if (PEAR::isError($result)) { - return $result; - } - - $database_definition['sequences'][$sequence_name] = $definition; - } - } - - $result = $val->validateDatabase($database_definition); - if (PEAR::isError($result)) { - return $result; - } - - return $database_definition; - } - - // }}} - // {{{ createTableIndexes() - - /** - * A method to create indexes for an existing table - * - * @param string $table_name Name of the table - * @param array $indexes An array of indexes to be created - * @param boolean $overwrite If the table/index should be overwritten if it already exists - * - * @return mixed MDB2_Error if there is an error creating an index, MDB2_OK otherwise - * @access public - */ - function createTableIndexes($table_name, $indexes, $overwrite = false) - { - if (!$this->db->supports('indexes')) { - $this->db->debug('Indexes are not supported', __FUNCTION__); - return MDB2_OK; - } - - $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE); - foreach ($indexes as $index_name => $index) { - - // Does the index already exist, and if so, should it be overwritten? - $create_index = true; - $this->db->expectError($errorcodes); - if (!empty($index['primary']) || !empty($index['unique'])) { - $current_indexes = $this->db->manager->listTableConstraints($table_name); - } else { - $current_indexes = $this->db->manager->listTableIndexes($table_name); - } - - $this->db->popExpect(); - if (PEAR::isError($current_indexes)) { - if (!MDB2::isError($current_indexes, $errorcodes)) { - return $current_indexes; - } - } elseif (is_array($current_indexes) && in_array($index_name, $current_indexes)) { - if (!$overwrite) { - $this->db->debug('Index already exists: '.$index_name, __FUNCTION__); - $create_index = false; - } else { - $this->db->debug('Preparing to overwrite index: '.$index_name, __FUNCTION__); - - $this->db->expectError(MDB2_ERROR_NOT_FOUND); - if (!empty($index['primary']) || !empty($index['unique'])) { - $result = $this->db->manager->dropConstraint($table_name, $index_name); - } else { - $result = $this->db->manager->dropIndex($table_name, $index_name); - } - $this->db->popExpect(); - if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_NOT_FOUND)) { - return $result; - } - } - } - - // Check if primary is being used and if it's supported - if (!empty($index['primary']) && !$this->db->supports('primary_key')) { - - // Primary not supported so we fallback to UNIQUE and making the field NOT NULL - $index['unique'] = true; - - $changes = array(); - - foreach ($index['fields'] as $field => $empty) { - $field_info = $this->db->reverse->getTableFieldDefinition($table_name, $field); - if (PEAR::isError($field_info)) { - return $field_info; - } - if (!$field_info[0]['notnull']) { - $changes['change'][$field] = $field_info[0]; - - $changes['change'][$field]['notnull'] = true; - } - } - if (!empty($changes)) { - $this->db->manager->alterTable($table_name, $changes, false); - } - } - - // Should the index be created? - if ($create_index) { - if (!empty($index['primary']) || !empty($index['unique'])) { - $result = $this->db->manager->createConstraint($table_name, $index_name, $index); - } else { - $result = $this->db->manager->createIndex($table_name, $index_name, $index); - } - if (PEAR::isError($result)) { - return $result; - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ createTableConstraints() - - /** - * A method to create foreign keys for an existing table - * - * @param string $table_name Name of the table - * @param array $constraints An array of foreign keys to be created - * @param boolean $overwrite If the foreign key should be overwritten if it already exists - * - * @return mixed MDB2_Error if there is an error creating a foreign key, MDB2_OK otherwise - * @access public - */ - function createTableConstraints($table_name, $constraints, $overwrite = false) - { - if (!$this->db->supports('indexes')) { - $this->db->debug('Indexes are not supported', __FUNCTION__); - return MDB2_OK; - } - - $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE); - foreach ($constraints as $constraint_name => $constraint) { - - // Does the foreign key already exist, and if so, should it be overwritten? - $create_constraint = true; - $this->db->expectError($errorcodes); - $current_constraints = $this->db->manager->listTableConstraints($table_name); - $this->db->popExpect(); - if (PEAR::isError($current_constraints)) { - if (!MDB2::isError($current_constraints, $errorcodes)) { - return $current_constraints; - } - } elseif (is_array($current_constraints) && in_array($constraint_name, $current_constraints)) { - if (!$overwrite) { - $this->db->debug('Foreign key already exists: '.$constraint_name, __FUNCTION__); - $create_constraint = false; - } else { - $this->db->debug('Preparing to overwrite foreign key: '.$constraint_name, __FUNCTION__); - $result = $this->db->manager->dropConstraint($table_name, $constraint_name); - if (PEAR::isError($result)) { - return $result; - } - } - } - - // Should the foreign key be created? - if ($create_constraint) { - $result = $this->db->manager->createConstraint($table_name, $constraint_name, $constraint); - if (PEAR::isError($result)) { - return $result; - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ createTable() - - /** - * Create a table and inititialize the table if data is available - * - * @param string $table_name name of the table to be created - * @param array $table multi dimensional array that contains the - * structure and optional data of the table - * @param bool $overwrite if the table/index should be overwritten if it already exists - * @param array $options an array of options to be passed to the database specific driver - * version of MDB2_Driver_Manager_Common::createTable(). - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function createTable($table_name, $table, $overwrite = false, $options = array()) - { - $create = true; - - $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE); - - $this->db->expectError($errorcodes); - - $tables = $this->db->manager->listTables(); - - $this->db->popExpect(); - if (PEAR::isError($tables)) { - if (!MDB2::isError($tables, $errorcodes)) { - return $tables; - } - } elseif (is_array($tables) && in_array($table_name, $tables)) { - if (!$overwrite) { - $create = false; - $this->db->debug('Table already exists: '.$table_name, __FUNCTION__); - } else { - $result = $this->db->manager->dropTable($table_name); - if (PEAR::isError($result)) { - return $result; - } - $this->db->debug('Overwritting table: '.$table_name, __FUNCTION__); - } - } - - if ($create) { - $result = $this->db->manager->createTable($table_name, $table['fields'], $options); - if (PEAR::isError($result)) { - return $result; - } - } - - if (!empty($table['initialization']) && is_array($table['initialization'])) { - $result = $this->initializeTable($table_name, $table); - if (PEAR::isError($result)) { - return $result; - } - } - - if (!empty($table['indexes']) && is_array($table['indexes'])) { - $result = $this->createTableIndexes($table_name, $table['indexes'], $overwrite); - if (PEAR::isError($result)) { - return $result; - } - } - - if (!empty($table['constraints']) && is_array($table['constraints'])) { - $result = $this->createTableConstraints($table_name, $table['constraints'], $overwrite); - if (PEAR::isError($result)) { - return $result; - } - } - - return MDB2_OK; - } - - // }}} - // {{{ initializeTable() - - /** - * Inititialize the table with data - * - * @param string $table_name name of the table - * @param array $table multi dimensional array that contains the - * structure and optional data of the table - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function initializeTable($table_name, $table) - { - $query_insertselect = 'INSERT INTO %s (%s) (SELECT %s FROM %s %s)'; - - $query_insert = 'INSERT INTO %s (%s) VALUES (%s)'; - $query_update = 'UPDATE %s SET %s %s'; - $query_delete = 'DELETE FROM %s %s'; - - $table_name = $this->db->quoteIdentifier($table_name, true); - - $result = MDB2_OK; - - $support_transactions = $this->db->supports('transactions'); - - foreach ($table['initialization'] as $instruction) { - $query = ''; - switch ($instruction['type']) { - case 'insert': - if (!isset($instruction['data']['select'])) { - $data = $this->getInstructionFields($instruction['data'], $table['fields']); - if (!empty($data)) { - $fields = implode(', ', array_keys($data)); - $values = implode(', ', array_values($data)); - - $query = sprintf($query_insert, $table_name, $fields, $values); - } - } else { - $data = $this->getInstructionFields($instruction['data']['select'], $table['fields']); - $where = $this->getInstructionWhere($instruction['data']['select'], $table['fields']); - - $select_table_name = $this->db->quoteIdentifier($instruction['data']['select']['table'], true); - if (!empty($data)) { - $fields = implode(', ', array_keys($data)); - $values = implode(', ', array_values($data)); - - $query = sprintf($query_insertselect, $table_name, $fields, $values, $select_table_name, $where); - } - } - break; - case 'update': - $data = $this->getInstructionFields($instruction['data'], $table['fields']); - $where = $this->getInstructionWhere($instruction['data'], $table['fields']); - if (!empty($data)) { - array_walk($data, array($this, 'buildFieldValue')); - $fields_values = implode(', ', $data); - - $query = sprintf($query_update, $table_name, $fields_values, $where); - } - break; - case 'delete': - $where = $this->getInstructionWhere($instruction['data'], $table['fields']); - $query = sprintf($query_delete, $table_name, $where); - break; - } - if ($query) { - if ($support_transactions && PEAR::isError($res = $this->db->beginNestedTransaction())) { - return $res; - } - - $result = $this->db->exec($query); - if (PEAR::isError($result)) { - return $result; - } - - if ($support_transactions && PEAR::isError($res = $this->db->completeNestedTransaction())) { - return $res; - } - } - } - return $result; - } - - // }}} - // {{{ buildFieldValue() - - /** - * Appends the contents of second argument + '=' to the beginning of first - * argument. - * - * Used with array_walk() in initializeTable() for UPDATEs. - * - * @param string &$element value of array's element - * @param string $key key of array's element - * - * @return void - * - * @access public - * @see MDB2_Schema::initializeTable() - */ - function buildFieldValue(&$element, $key) - { - $element = $key."=$element"; - } - - // }}} - // {{{ getExpression() - - /** - * Generates a string that represents a value that would be associated - * with a column in a DML instruction. - * - * @param array $element multi dimensional array that contains the - * structure of the current DML instruction. - * @param array $fields_definition multi dimensional array that contains the - * definition for current table's fields - * @param string $type type of given field - * - * @return string - * - * @access public - * @see MDB2_Schema::getInstructionFields(), MDB2_Schema::getInstructionWhere() - */ - function getExpression($element, $fields_definition = array(), $type = null) - { - $str = ''; - switch ($element['type']) { - case 'null': - $str .= 'NULL'; - break; - case 'value': - $str .= $this->db->quote($element['data'], $type); - break; - case 'column': - $str .= $this->db->quoteIdentifier($element['data'], true); - break; - case 'function': - $arguments = array(); - if (!empty($element['data']['arguments']) - && is_array($element['data']['arguments']) - ) { - foreach ($element['data']['arguments'] as $v) { - $arguments[] = $this->getExpression($v, $fields_definition); - } - } - if (method_exists($this->db->function, $element['data']['name'])) { - $user_func = array(&$this->db->function, $element['data']['name']); - - $str .= call_user_func_array($user_func, $arguments); - } else { - $str .= $element['data']['name'].'('; - $str .= implode(', ', $arguments); - $str .= ')'; - } - break; - case 'expression': - $type0 = $type1 = null; - if ($element['data']['operants'][0]['type'] == 'column' - && array_key_exists($element['data']['operants'][0]['data'], $fields_definition) - ) { - $type0 = $fields_definition[$element['data']['operants'][0]['data']]['type']; - } - - if ($element['data']['operants'][1]['type'] == 'column' - && array_key_exists($element['data']['operants'][1]['data'], $fields_definition) - ) { - $type1 = $fields_definition[$element['data']['operants'][1]['data']]['type']; - } - - $str .= '('; - $str .= $this->getExpression($element['data']['operants'][0], $fields_definition, $type1); - $str .= $this->getOperator($element['data']['operator']); - $str .= $this->getExpression($element['data']['operants'][1], $fields_definition, $type0); - $str .= ')'; - break; - } - - return $str; - } - - // }}} - // {{{ getOperator() - - /** - * Returns the matching SQL operator - * - * @param string $op parsed descriptive operator - * - * @return string matching SQL operator - * - * @access public - * @static - * @see MDB2_Schema::getExpression() - */ - function getOperator($op) - { - switch ($op) { - case 'PLUS': - return ' + '; - case 'MINUS': - return ' - '; - case 'TIMES': - return ' * '; - case 'DIVIDED': - return ' / '; - case 'EQUAL': - return ' = '; - case 'NOT EQUAL': - return ' != '; - case 'LESS THAN': - return ' < '; - case 'GREATER THAN': - return ' > '; - case 'LESS THAN OR EQUAL': - return ' <= '; - case 'GREATER THAN OR EQUAL': - return ' >= '; - default: - return ' '.$op.' '; - } - } - - // }}} - // {{{ getInstructionFields() - - /** - * Walks the parsed DML instruction array, field by field, - * storing them and their processed values inside a new array. - * - * @param array $instruction multi dimensional array that contains the - * structure of the current DML instruction. - * @param array $fields_definition multi dimensional array that contains the - * definition for current table's fields - * - * @return array array of strings in the form 'field_name' => 'value' - * - * @access public - * @static - * @see MDB2_Schema::initializeTable() - */ - function getInstructionFields($instruction, $fields_definition = array()) - { - $fields = array(); - if (!empty($instruction['field']) && is_array($instruction['field'])) { - foreach ($instruction['field'] as $field) { - $field_name = $this->db->quoteIdentifier($field['name'], true); - - $fields[$field_name] = $this->getExpression($field['group'], $fields_definition); - } - } - return $fields; - } - - // }}} - // {{{ getInstructionWhere() - - /** - * Translates the parsed WHERE expression of a DML instruction - * (array structure) to a SQL WHERE clause (string). - * - * @param array $instruction multi dimensional array that contains the - * structure of the current DML instruction. - * @param array $fields_definition multi dimensional array that contains the - * definition for current table's fields. - * - * @return string SQL WHERE clause - * - * @access public - * @static - * @see MDB2_Schema::initializeTable() - */ - function getInstructionWhere($instruction, $fields_definition = array()) - { - $where = ''; - if (!empty($instruction['where'])) { - $where = 'WHERE '.$this->getExpression($instruction['where'], $fields_definition); - } - return $where; - } - - // }}} - // {{{ createSequence() - - /** - * Create a sequence - * - * @param string $sequence_name name of the sequence to be created - * @param array $sequence multi dimensional array that contains the - * structure and optional data of the table - * @param bool $overwrite if the sequence should be overwritten if it already exists - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function createSequence($sequence_name, $sequence, $overwrite = false) - { - if (!$this->db->supports('sequences')) { - $this->db->debug('Sequences are not supported', __FUNCTION__); - return MDB2_OK; - } - - $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE); - $this->db->expectError($errorcodes); - $sequences = $this->db->manager->listSequences(); - $this->db->popExpect(); - if (PEAR::isError($sequences)) { - if (!MDB2::isError($sequences, $errorcodes)) { - return $sequences; - } - } elseif (is_array($sequence) && in_array($sequence_name, $sequences)) { - if (!$overwrite) { - $this->db->debug('Sequence already exists: '.$sequence_name, __FUNCTION__); - return MDB2_OK; - } - - $result = $this->db->manager->dropSequence($sequence_name); - if (PEAR::isError($result)) { - return $result; - } - $this->db->debug('Overwritting sequence: '.$sequence_name, __FUNCTION__); - } - - $start = 1; - $field = ''; - if (!empty($sequence['on'])) { - $table = $sequence['on']['table']; - $field = $sequence['on']['field']; - - $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE); - $this->db->expectError($errorcodes); - $tables = $this->db->manager->listTables(); - $this->db->popExpect(); - if (PEAR::isError($tables) && !MDB2::isError($tables, $errorcodes)) { - return $tables; - } - - if (!PEAR::isError($tables) && is_array($tables) && in_array($table, $tables)) { - if ($this->db->supports('summary_functions')) { - $query = "SELECT MAX($field) FROM ".$this->db->quoteIdentifier($table, true); - } else { - $query = "SELECT $field FROM ".$this->db->quoteIdentifier($table, true)." ORDER BY $field DESC"; - } - $start = $this->db->queryOne($query, 'integer'); - if (PEAR::isError($start)) { - return $start; - } - ++$start; - } else { - $this->warnings[] = 'Could not sync sequence: '.$sequence_name; - } - } elseif (!empty($sequence['start']) && is_numeric($sequence['start'])) { - $start = $sequence['start']; - $table = ''; - } - - $result = $this->db->manager->createSequence($sequence_name, $start); - if (PEAR::isError($result)) { - return $result; - } - - return MDB2_OK; - } - - // }}} - // {{{ createDatabase() - - /** - * Create a database space within which may be created database objects - * like tables, indexes and sequences. The implementation of this function - * is highly DBMS specific and may require special permissions to run - * successfully. Consult the documentation or the DBMS drivers that you - * use to be aware of eventual configuration requirements. - * - * @param array $database_definition multi dimensional array that contains the current definition - * @param array $options an array of options to be passed to the - * database specific driver version of - * MDB2_Driver_Manager_Common::createTable(). - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function createDatabase($database_definition, $options = array()) - { - if (!isset($database_definition['name']) || !$database_definition['name']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'no valid database name specified'); - } - - $create = (isset($database_definition['create']) && $database_definition['create']); - $overwrite = (isset($database_definition['overwrite']) && $database_definition['overwrite']); - - /** - * - * We need to clean up database name before any query to prevent - * database driver from using a inexistent database - * - */ - $previous_database_name = $this->db->setDatabase(''); - - // Lower / Upper case the db name if the portability deems so. - if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { - $func = $this->db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'; - - $db_name = $func($database_definition['name']); - } else { - $db_name = $database_definition['name']; - } - - if ($create) { - - $dbExists = $this->db->databaseExists($db_name); - if (PEAR::isError($dbExists)) { - return $dbExists; - } - - if ($dbExists && $overwrite) { - $this->db->expectError(MDB2_ERROR_CANNOT_DROP); - $result = $this->db->manager->dropDatabase($db_name); - $this->db->popExpect(); - if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_CANNOT_DROP)) { - return $result; - } - $dbExists = false; - $this->db->debug('Overwritting database: ' . $db_name, __FUNCTION__); - } - - $dbOptions = array(); - if (array_key_exists('charset', $database_definition) - && !empty($database_definition['charset'])) { - $dbOptions['charset'] = $database_definition['charset']; - } - - if ($dbExists) { - $this->db->debug('Database already exists: ' . $db_name, __FUNCTION__); -// if (!empty($dbOptions)) { -// $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NO_PERMISSION); -// $this->db->expectError($errorcodes); -// $result = $this->db->manager->alterDatabase($db_name, $dbOptions); -// $this->db->popExpect(); -// if (PEAR::isError($result) && !MDB2::isError($result, $errorcodes)) { -// return $result; -// } -// } - $create = false; - } else { - $this->db->expectError(MDB2_ERROR_UNSUPPORTED); - $result = $this->db->manager->createDatabase($db_name, $dbOptions); - $this->db->popExpect(); - if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_UNSUPPORTED)) { - return $result; - } - $this->db->debug('Creating database: ' . $db_name, __FUNCTION__); - } - } - - $this->db->setDatabase($db_name); - if (($support_transactions = $this->db->supports('transactions')) - && PEAR::isError($result = $this->db->beginNestedTransaction()) - ) { - return $result; - } - - $created_objects = 0; - if (isset($database_definition['tables']) - && is_array($database_definition['tables']) - ) { - foreach ($database_definition['tables'] as $table_name => $table) { - $result = $this->createTable($table_name, $table, $overwrite, $options); - if (PEAR::isError($result)) { - break; - } - $created_objects++; - } - } - if (!PEAR::isError($result) - && isset($database_definition['sequences']) - && is_array($database_definition['sequences']) - ) { - foreach ($database_definition['sequences'] as $sequence_name => $sequence) { - $result = $this->createSequence($sequence_name, $sequence, false, $overwrite); - - if (PEAR::isError($result)) { - break; - } - $created_objects++; - } - } - - if ($support_transactions) { - $res = $this->db->completeNestedTransaction(); - if (PEAR::isError($res)) { - $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'Could not end transaction ('. - $res->getMessage().' ('.$res->getUserinfo().'))'); - } - } elseif (PEAR::isError($result) && $created_objects) { - $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'the database was only partially created ('. - $result->getMessage().' ('.$result->getUserinfo().'))'); - } - - $this->db->setDatabase($previous_database_name); - - if (PEAR::isError($result) && $create - && PEAR::isError($result2 = $this->db->manager->dropDatabase($db_name)) - ) { - if (!MDB2::isError($result2, MDB2_ERROR_UNSUPPORTED)) { - return $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'Could not drop the created database after unsuccessful creation attempt ('. - $result2->getMessage().' ('.$result2->getUserinfo().'))'); - } - } - - return $result; - } - - // }}} - // {{{ compareDefinitions() - - /** - * Compare a previous definition with the currently parsed definition - * - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * - * @return array|MDB2_Error array of changes on success, or a error object - * @access public - */ - function compareDefinitions($current_definition, $previous_definition) - { - $changes = array(); - - if (!empty($current_definition['tables']) && is_array($current_definition['tables'])) { - $changes['tables'] = $defined_tables = array(); - foreach ($current_definition['tables'] as $table_name => $table) { - $previous_tables = array(); - if (!empty($previous_definition) && is_array($previous_definition)) { - $previous_tables = $previous_definition['tables']; - } - $change = $this->compareTableDefinitions($table_name, $table, $previous_tables, $defined_tables); - if (PEAR::isError($change)) { - return $change; - } - if (!empty($change)) { - $changes['tables'] = MDB2_Schema::arrayMergeClobber($changes['tables'], $change); - } - } - - if (!empty($previous_definition['tables']) - && is_array($previous_definition['tables'])) { - foreach ($previous_definition['tables'] as $table_name => $table) { - if (empty($defined_tables[$table_name])) { - $changes['tables']['remove'][$table_name] = true; - } - } - } - } - if (!empty($current_definition['sequences']) && is_array($current_definition['sequences'])) { - $changes['sequences'] = $defined_sequences = array(); - foreach ($current_definition['sequences'] as $sequence_name => $sequence) { - $previous_sequences = array(); - if (!empty($previous_definition) && is_array($previous_definition)) { - $previous_sequences = $previous_definition['sequences']; - } - - $change = $this->compareSequenceDefinitions($sequence_name, - $sequence, - $previous_sequences, - $defined_sequences); - if (PEAR::isError($change)) { - return $change; - } - if (!empty($change)) { - $changes['sequences'] = MDB2_Schema::arrayMergeClobber($changes['sequences'], $change); - } - } - if (!empty($previous_definition['sequences']) && is_array($previous_definition['sequences'])) { - foreach ($previous_definition['sequences'] as $sequence_name => $sequence) { - if (empty($defined_sequences[$sequence_name])) { - $changes['sequences']['remove'][$sequence_name] = true; - } - } - } - } - return $changes; - } - - // }}} - // {{{ compareTableFieldsDefinitions() - - /** - * Compare a previous definition with the currently parsed definition - * - * @param string $table_name name of the table - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * - * @return array|MDB2_Error array of changes on success, or a error object - * @access public - */ - function compareTableFieldsDefinitions($table_name, $current_definition, - $previous_definition) - { - $changes = $defined_fields = array(); - - if (is_array($current_definition)) { - foreach ($current_definition as $field_name => $field) { - $was_field_name = $field['was']; - if (!empty($previous_definition[$field_name]) - && ( - (isset($previous_definition[$field_name]['was']) - && $previous_definition[$field_name]['was'] == $was_field_name) - || !isset($previous_definition[$was_field_name]) - )) { - $was_field_name = $field_name; - } - - if (!empty($previous_definition[$was_field_name])) { - if ($was_field_name != $field_name) { - $changes['rename'][$was_field_name] = array('name' => $field_name, 'definition' => $field); - } - - if (!empty($defined_fields[$was_field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'the field "'.$was_field_name. - '" was specified for more than one field of table'); - } - - $defined_fields[$was_field_name] = true; - - $change = $this->db->compareDefinition($field, $previous_definition[$was_field_name]); - if (PEAR::isError($change)) { - return $change; - } - - if (!empty($change)) { - if (array_key_exists('default', $change) - && $change['default'] - && !array_key_exists('default', $field)) { - $field['default'] = null; - } - - $change['definition'] = $field; - - $changes['change'][$field_name] = $change; - } - } else { - if ($field_name != $was_field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'it was specified a previous field name ("'. - $was_field_name.'") for field "'.$field_name.'" of table "'. - $table_name.'" that does not exist'); - } - - $changes['add'][$field_name] = $field; - } - } - } - - if (isset($previous_definition) && is_array($previous_definition)) { - foreach ($previous_definition as $field_previous_name => $field_previous) { - if (empty($defined_fields[$field_previous_name])) { - $changes['remove'][$field_previous_name] = true; - } - } - } - - return $changes; - } - - // }}} - // {{{ compareTableIndexesDefinitions() - - /** - * Compare a previous definition with the currently parsed definition - * - * @param string $table_name name of the table - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * - * @return array|MDB2_Error array of changes on success, or a error object - * @access public - */ - function compareTableIndexesDefinitions($table_name, $current_definition, - $previous_definition) - { - $changes = $defined_indexes = array(); - - if (is_array($current_definition)) { - foreach ($current_definition as $index_name => $index) { - $was_index_name = $index['was']; - if (!empty($previous_definition[$index_name]) - && isset($previous_definition[$index_name]['was']) - && $previous_definition[$index_name]['was'] == $was_index_name - ) { - $was_index_name = $index_name; - } - if (!empty($previous_definition[$was_index_name])) { - $change = array(); - if ($was_index_name != $index_name) { - $change['name'] = $was_index_name; - } - - if (!empty($defined_indexes[$was_index_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'the index "'.$was_index_name.'" was specified for'. - ' more than one index of table "'.$table_name.'"'); - } - $defined_indexes[$was_index_name] = true; - - $previous_unique = array_key_exists('unique', $previous_definition[$was_index_name]) - ? $previous_definition[$was_index_name]['unique'] : false; - - $unique = array_key_exists('unique', $index) ? $index['unique'] : false; - if ($previous_unique != $unique) { - $change['unique'] = $unique; - } - - $previous_primary = array_key_exists('primary', $previous_definition[$was_index_name]) - ? $previous_definition[$was_index_name]['primary'] : false; - - $primary = array_key_exists('primary', $index) ? $index['primary'] : false; - if ($previous_primary != $primary) { - $change['primary'] = $primary; - } - - $defined_fields = array(); - $previous_fields = $previous_definition[$was_index_name]['fields']; - if (!empty($index['fields']) && is_array($index['fields'])) { - foreach ($index['fields'] as $field_name => $field) { - if (!empty($previous_fields[$field_name])) { - $defined_fields[$field_name] = true; - - $previous_sorting = array_key_exists('sorting', $previous_fields[$field_name]) - ? $previous_fields[$field_name]['sorting'] : ''; - - $sorting = array_key_exists('sorting', $field) ? $field['sorting'] : ''; - if ($previous_sorting != $sorting) { - $change['change'] = true; - } - } else { - $change['change'] = true; - } - } - } - if (isset($previous_fields) && is_array($previous_fields)) { - foreach ($previous_fields as $field_name => $field) { - if (empty($defined_fields[$field_name])) { - $change['change'] = true; - } - } - } - if (!empty($change)) { - $changes['change'][$index_name] = $current_definition[$index_name]; - } - } else { - if ($index_name != $was_index_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'it was specified a previous index name ("'.$was_index_name. - ') for index "'.$index_name.'" of table "'.$table_name.'" that does not exist'); - } - $changes['add'][$index_name] = $current_definition[$index_name]; - } - } - } - foreach ($previous_definition as $index_previous_name => $index_previous) { - if (empty($defined_indexes[$index_previous_name])) { - $changes['remove'][$index_previous_name] = $index_previous; - } - } - return $changes; - } - - // }}} - // {{{ compareTableDefinitions() - - /** - * Compare a previous definition with the currently parsed definition - * - * @param string $table_name name of the table - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * @param array &$defined_tables table names in the schema - * - * @return array|MDB2_Error array of changes on success, or a error object - * @access public - */ - function compareTableDefinitions($table_name, $current_definition, - $previous_definition, &$defined_tables) - { - $changes = array(); - - if (is_array($current_definition)) { - $was_table_name = $table_name; - if (!empty($current_definition['was'])) { - $was_table_name = $current_definition['was']; - } - if (!empty($previous_definition[$was_table_name])) { - $changes['change'][$was_table_name] = array(); - if ($was_table_name != $table_name) { - $changes['change'][$was_table_name] = array('name' => $table_name); - } - if (!empty($defined_tables[$was_table_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'the table "'.$was_table_name. - '" was specified for more than one table of the database'); - } - $defined_tables[$was_table_name] = true; - if (!empty($current_definition['fields']) && is_array($current_definition['fields'])) { - $previous_fields = array(); - if (isset($previous_definition[$was_table_name]['fields']) - && is_array($previous_definition[$was_table_name]['fields'])) { - $previous_fields = $previous_definition[$was_table_name]['fields']; - } - - $change = $this->compareTableFieldsDefinitions($table_name, - $current_definition['fields'], - $previous_fields); - - if (PEAR::isError($change)) { - return $change; - } - if (!empty($change)) { - $changes['change'][$was_table_name] = - MDB2_Schema::arrayMergeClobber($changes['change'][$was_table_name], $change); - } - } - if (!empty($current_definition['indexes']) && is_array($current_definition['indexes'])) { - $previous_indexes = array(); - if (isset($previous_definition[$was_table_name]['indexes']) - && is_array($previous_definition[$was_table_name]['indexes'])) { - $previous_indexes = $previous_definition[$was_table_name]['indexes']; - } - $change = $this->compareTableIndexesDefinitions($table_name, - $current_definition['indexes'], - $previous_indexes); - - if (PEAR::isError($change)) { - return $change; - } - if (!empty($change)) { - $changes['change'][$was_table_name]['indexes'] = $change; - } - } - if (empty($changes['change'][$was_table_name])) { - unset($changes['change'][$was_table_name]); - } - if (empty($changes['change'])) { - unset($changes['change']); - } - } else { - if ($table_name != $was_table_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'it was specified a previous table name ("'.$was_table_name. - '") for table "'.$table_name.'" that does not exist'); - } - $changes['add'][$table_name] = true; - } - } - - return $changes; - } - - // }}} - // {{{ compareSequenceDefinitions() - - /** - * Compare a previous definition with the currently parsed definition - * - * @param string $sequence_name name of the sequence - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * @param array &$defined_sequences names in the schema - * - * @return array|MDB2_Error array of changes on success, or a error object - * @access public - */ - function compareSequenceDefinitions($sequence_name, $current_definition, - $previous_definition, &$defined_sequences) - { - $changes = array(); - - if (is_array($current_definition)) { - $was_sequence_name = $sequence_name; - if (!empty($previous_definition[$sequence_name]) - && isset($previous_definition[$sequence_name]['was']) - && $previous_definition[$sequence_name]['was'] == $was_sequence_name - ) { - $was_sequence_name = $sequence_name; - } elseif (!empty($current_definition['was'])) { - $was_sequence_name = $current_definition['was']; - } - if (!empty($previous_definition[$was_sequence_name])) { - if ($was_sequence_name != $sequence_name) { - $changes['change'][$was_sequence_name]['name'] = $sequence_name; - } - - if (!empty($defined_sequences[$was_sequence_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'the sequence "'.$was_sequence_name.'" was specified as base'. - ' of more than of sequence of the database'); - } - - $defined_sequences[$was_sequence_name] = true; - - $change = array(); - if (!empty($current_definition['start']) - && isset($previous_definition[$was_sequence_name]['start']) - && $current_definition['start'] != $previous_definition[$was_sequence_name]['start'] - ) { - $change['start'] = $previous_definition[$sequence_name]['start']; - } - if (isset($current_definition['on']['table']) - && isset($previous_definition[$was_sequence_name]['on']['table']) - && $current_definition['on']['table'] != $previous_definition[$was_sequence_name]['on']['table'] - && isset($current_definition['on']['field']) - && isset($previous_definition[$was_sequence_name]['on']['field']) - && $current_definition['on']['field'] != $previous_definition[$was_sequence_name]['on']['field'] - ) { - $change['on'] = $current_definition['on']; - } - if (!empty($change)) { - $changes['change'][$was_sequence_name][$sequence_name] = $change; - } - } else { - if ($sequence_name != $was_sequence_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null, - 'it was specified a previous sequence name ("'.$was_sequence_name. - '") for sequence "'.$sequence_name.'" that does not exist'); - } - $changes['add'][$sequence_name] = true; - } - } - return $changes; - } - // }}} - // {{{ verifyAlterDatabase() - - /** - * Verify that the changes requested are supported - * - * @param array $changes associative array that contains the definition of the changes - * that are meant to be applied to the database structure. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function verifyAlterDatabase($changes) - { - if (!empty($changes['tables']['change']) && is_array($changes['tables']['change'])) { - foreach ($changes['tables']['change'] as $table_name => $table) { - if (!empty($table['indexes']) && is_array($table['indexes'])) { - if (!$this->db->supports('indexes')) { - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - 'indexes are not supported'); - } - $table_changes = count($table['indexes']); - if (!empty($table['indexes']['add'])) { - $table_changes--; - } - if (!empty($table['indexes']['remove'])) { - $table_changes--; - } - if (!empty($table['indexes']['change'])) { - $table_changes--; - } - if ($table_changes) { - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - 'index alteration not yet supported: '.implode(', ', array_keys($table['indexes']))); - } - } - unset($table['indexes']); - $result = $this->db->manager->alterTable($table_name, $table, true); - if (PEAR::isError($result)) { - return $result; - } - } - } - if (!empty($changes['sequences']) && is_array($changes['sequences'])) { - if (!$this->db->supports('sequences')) { - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - 'sequences are not supported'); - } - $sequence_changes = count($changes['sequences']); - if (!empty($changes['sequences']['add'])) { - $sequence_changes--; - } - if (!empty($changes['sequences']['remove'])) { - $sequence_changes--; - } - if (!empty($changes['sequences']['change'])) { - $sequence_changes--; - } - if ($sequence_changes) { - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - 'sequence alteration not yet supported: '.implode(', ', array_keys($changes['sequences']))); - } - } - return MDB2_OK; - } - - // }}} - // {{{ alterDatabaseIndexes() - - /** - * Execute the necessary actions to implement the requested changes - * in the indexes inside a database structure. - * - * @param string $table_name name of the table - * @param array $changes associative array that contains the definition of the changes - * that are meant to be applied to the database structure. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function alterDatabaseIndexes($table_name, $changes) - { - $alterations = 0; - if (empty($changes)) { - return $alterations; - } - - if (!empty($changes['remove']) && is_array($changes['remove'])) { - foreach ($changes['remove'] as $index_name => $index) { - $this->db->expectError(MDB2_ERROR_NOT_FOUND); - if (!empty($index['primary']) || !empty($index['unique'])) { - $result = $this->db->manager->dropConstraint($table_name, $index_name, !empty($index['primary'])); - } else { - $result = $this->db->manager->dropIndex($table_name, $index_name); - } - $this->db->popExpect(); - if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_NOT_FOUND)) { - return $result; - } - $alterations++; - } - } - if (!empty($changes['change']) && is_array($changes['change'])) { - foreach ($changes['change'] as $index_name => $index) { - /** - * Drop existing index/constraint first. - * Since $changes doesn't tell us whether it's an index or a constraint before the change, - * we have to find out and call the appropriate method. - */ - if (in_array($index_name, $this->db->manager->listTableIndexes($table_name))) { - $result = $this->db->manager->dropIndex($table_name, $index_name); - } elseif (in_array($index_name, $this->db->manager->listTableConstraints($table_name))) { - $result = $this->db->manager->dropConstraint($table_name, $index_name); - } - if (!empty($result) && PEAR::isError($result)) { - return $result; - } - - if (!empty($index['primary']) || !empty($index['unique'])) { - $result = $this->db->manager->createConstraint($table_name, $index_name, $index); - } else { - $result = $this->db->manager->createIndex($table_name, $index_name, $index); - } - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - if (!empty($changes['add']) && is_array($changes['add'])) { - foreach ($changes['add'] as $index_name => $index) { - if (!empty($index['primary']) || !empty($index['unique'])) { - $result = $this->db->manager->createConstraint($table_name, $index_name, $index); - } else { - $result = $this->db->manager->createIndex($table_name, $index_name, $index); - } - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - return $alterations; - } - - // }}} - // {{{ alterDatabaseTables() - - /** - * Execute the necessary actions to implement the requested changes - * in the tables inside a database structure. - * - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * @param array $changes associative array that contains the definition of the changes - * that are meant to be applied to the database structure. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function alterDatabaseTables($current_definition, $previous_definition, $changes) - { - /* FIXME: tables marked to be added are initialized by createTable(), others don't */ - $alterations = 0; - if (empty($changes)) { - return $alterations; - } - - if (!empty($changes['add']) && is_array($changes['add'])) { - foreach ($changes['add'] as $table_name => $table) { - $result = $this->createTable($table_name, $current_definition[$table_name]); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - if ($this->options['drop_missing_tables'] - && !empty($changes['remove']) - && is_array($changes['remove'])) { - foreach ($changes['remove'] as $table_name => $table) { - $result = $this->db->manager->dropTable($table_name); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - if (!empty($changes['change']) && is_array($changes['change'])) { - foreach ($changes['change'] as $table_name => $table) { - $indexes = array(); - if (!empty($table['indexes'])) { - $indexes = $table['indexes']; - unset($table['indexes']); - } - if (!empty($indexes['remove'])) { - $result = $this->alterDatabaseIndexes($table_name, array('remove' => $indexes['remove'])); - if (PEAR::isError($result)) { - return $result; - } - unset($indexes['remove']); - $alterations += $result; - } - $result = $this->db->manager->alterTable($table_name, $table, false); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - - // table may be renamed at this point - if (!empty($table['name'])) { - $table_name = $table['name']; - } - - if (!empty($indexes)) { - $result = $this->alterDatabaseIndexes($table_name, $indexes); - if (PEAR::isError($result)) { - return $result; - } - $alterations += $result; - } - } - } - - return $alterations; - } - - // }}} - // {{{ alterDatabaseSequences() - - /** - * Execute the necessary actions to implement the requested changes - * in the sequences inside a database structure. - * - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * @param array $changes associative array that contains the definition of the changes - * that are meant to be applied to the database structure. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function alterDatabaseSequences($current_definition, $previous_definition, $changes) - { - $alterations = 0; - if (empty($changes)) { - return $alterations; - } - - if (!empty($changes['add']) && is_array($changes['add'])) { - foreach ($changes['add'] as $sequence_name => $sequence) { - $result = $this->createSequence($sequence_name, $current_definition[$sequence_name]); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - if (!empty($changes['remove']) && is_array($changes['remove'])) { - foreach ($changes['remove'] as $sequence_name => $sequence) { - $result = $this->db->manager->dropSequence($sequence_name); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - if (!empty($changes['change']) && is_array($changes['change'])) { - foreach ($changes['change'] as $sequence_name => $sequence) { - $result = $this->db->manager->dropSequence($previous_definition[$sequence_name]['was']); - if (PEAR::isError($result)) { - return $result; - } - $result = $this->createSequence($sequence_name, $sequence); - if (PEAR::isError($result)) { - return $result; - } - $alterations++; - } - } - - return $alterations; - } - - // }}} - // {{{ alterDatabase() - - /** - * Execute the necessary actions to implement the requested changes - * in a database structure. - * - * @param array $current_definition multi dimensional array that contains the current definition - * @param array $previous_definition multi dimensional array that contains the previous definition - * @param array $changes associative array that contains the definition of the changes - * that are meant to be applied to the database structure. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function alterDatabase($current_definition, $previous_definition, $changes) - { - $alterations = 0; - if (empty($changes)) { - return $alterations; - } - - $result = $this->verifyAlterDatabase($changes); - if (PEAR::isError($result)) { - return $result; - } - - if (!empty($current_definition['name'])) { - $previous_database_name = $this->db->setDatabase($current_definition['name']); - } - - if (($support_transactions = $this->db->supports('transactions')) - && PEAR::isError($result = $this->db->beginNestedTransaction()) - ) { - return $result; - } - - if (!empty($changes['tables']) && !empty($current_definition['tables'])) { - $current_tables = isset($current_definition['tables']) ? $current_definition['tables'] : array(); - $previous_tables = isset($previous_definition['tables']) ? $previous_definition['tables'] : array(); - - $result = $this->alterDatabaseTables($current_tables, $previous_tables, $changes['tables']); - if (is_numeric($result)) { - $alterations += $result; - } - } - - if (!PEAR::isError($result) && !empty($changes['sequences'])) { - $current_sequences = isset($current_definition['sequences']) ? $current_definition['sequences'] : array(); - $previous_sequences = isset($previous_definition['sequences']) ? $previous_definition['sequences'] : array(); - - $result = $this->alterDatabaseSequences($current_sequences, $previous_sequences, $changes['sequences']); - if (is_numeric($result)) { - $alterations += $result; - } - } - - if ($support_transactions) { - $res = $this->db->completeNestedTransaction(); - if (PEAR::isError($res)) { - $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'Could not end transaction ('. - $res->getMessage().' ('.$res->getUserinfo().'))'); - } - } elseif (PEAR::isError($result) && $alterations) { - $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'the requested database alterations were only partially implemented ('. - $result->getMessage().' ('.$result->getUserinfo().'))'); - } - - if (isset($previous_database_name)) { - $this->db->setDatabase($previous_database_name); - } - return $result; - } - - // }}} - // {{{ dumpDatabaseChanges() - - /** - * Dump the changes between two database definitions. - * - * @param array $changes associative array that specifies the list of database - * definitions changes as returned by the _compareDefinitions - * manager class function. - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function dumpDatabaseChanges($changes) - { - if (!empty($changes['tables'])) { - if (!empty($changes['tables']['add']) && is_array($changes['tables']['add'])) { - foreach ($changes['tables']['add'] as $table_name => $table) { - $this->db->debug("$table_name:", __FUNCTION__); - $this->db->debug("\tAdded table '$table_name'", __FUNCTION__); - } - } - - if (!empty($changes['tables']['remove']) && is_array($changes['tables']['remove'])) { - if ($this->options['drop_missing_tables']) { - foreach ($changes['tables']['remove'] as $table_name => $table) { - $this->db->debug("$table_name:", __FUNCTION__); - $this->db->debug("\tRemoved table '$table_name'", __FUNCTION__); - } - } else { - foreach ($changes['tables']['remove'] as $table_name => $table) { - $this->db->debug("\tObsolete table '$table_name' left as is", __FUNCTION__); - } - } - } - - if (!empty($changes['tables']['change']) && is_array($changes['tables']['change'])) { - foreach ($changes['tables']['change'] as $table_name => $table) { - if (array_key_exists('name', $table)) { - $this->db->debug("\tRenamed table '$table_name' to '".$table['name']."'", __FUNCTION__); - } - if (!empty($table['add']) && is_array($table['add'])) { - foreach ($table['add'] as $field_name => $field) { - $this->db->debug("\tAdded field '".$field_name."'", __FUNCTION__); - } - } - if (!empty($table['remove']) && is_array($table['remove'])) { - foreach ($table['remove'] as $field_name => $field) { - $this->db->debug("\tRemoved field '".$field_name."'", __FUNCTION__); - } - } - if (!empty($table['rename']) && is_array($table['rename'])) { - foreach ($table['rename'] as $field_name => $field) { - $this->db->debug("\tRenamed field '".$field_name."' to '".$field['name']."'", __FUNCTION__); - } - } - if (!empty($table['change']) && is_array($table['change'])) { - foreach ($table['change'] as $field_name => $field) { - $field = $field['definition']; - if (array_key_exists('type', $field)) { - $this->db->debug("\tChanged field '$field_name' type to '".$field['type']."'", __FUNCTION__); - } - - if (array_key_exists('unsigned', $field)) { - $this->db->debug("\tChanged field '$field_name' type to '". - (!empty($field['unsigned']) && $field['unsigned'] ? '' : 'not ')."unsigned'", - __FUNCTION__); - } - - if (array_key_exists('length', $field)) { - $this->db->debug("\tChanged field '$field_name' length to '". - (!empty($field['length']) ? $field['length']: 'no length')."'", __FUNCTION__); - } - if (array_key_exists('default', $field)) { - $this->db->debug("\tChanged field '$field_name' default to ". - (isset($field['default']) ? "'".$field['default']."'" : 'NULL'), __FUNCTION__); - } - - if (array_key_exists('notnull', $field)) { - $this->db->debug("\tChanged field '$field_name' notnull to ". - (!empty($field['notnull']) && $field['notnull'] ? 'true' : 'false'), - __FUNCTION__); - } - } - } - if (!empty($table['indexes']) && is_array($table['indexes'])) { - if (!empty($table['indexes']['add']) && is_array($table['indexes']['add'])) { - foreach ($table['indexes']['add'] as $index_name => $index) { - $this->db->debug("\tAdded index '".$index_name. - "' of table '$table_name'", __FUNCTION__); - } - } - if (!empty($table['indexes']['remove']) && is_array($table['indexes']['remove'])) { - foreach ($table['indexes']['remove'] as $index_name => $index) { - $this->db->debug("\tRemoved index '".$index_name. - "' of table '$table_name'", __FUNCTION__); - } - } - if (!empty($table['indexes']['change']) && is_array($table['indexes']['change'])) { - foreach ($table['indexes']['change'] as $index_name => $index) { - if (array_key_exists('name', $index)) { - $this->db->debug("\tRenamed index '".$index_name."' to '".$index['name']. - "' on table '$table_name'", __FUNCTION__); - } - if (array_key_exists('unique', $index)) { - $this->db->debug("\tChanged index '".$index_name."' unique to '". - !empty($index['unique'])."' on table '$table_name'", __FUNCTION__); - } - if (array_key_exists('primary', $index)) { - $this->db->debug("\tChanged index '".$index_name."' primary to '". - !empty($index['primary'])."' on table '$table_name'", __FUNCTION__); - } - if (array_key_exists('change', $index)) { - $this->db->debug("\tChanged index '".$index_name. - "' on table '$table_name'", __FUNCTION__); - } - } - } - } - } - } - } - if (!empty($changes['sequences'])) { - if (!empty($changes['sequences']['add']) && is_array($changes['sequences']['add'])) { - foreach ($changes['sequences']['add'] as $sequence_name => $sequence) { - $this->db->debug("$sequence_name:", __FUNCTION__); - $this->db->debug("\tAdded sequence '$sequence_name'", __FUNCTION__); - } - } - if (!empty($changes['sequences']['remove']) && is_array($changes['sequences']['remove'])) { - foreach ($changes['sequences']['remove'] as $sequence_name => $sequence) { - $this->db->debug("$sequence_name:", __FUNCTION__); - $this->db->debug("\tAdded sequence '$sequence_name'", __FUNCTION__); - } - } - if (!empty($changes['sequences']['change']) && is_array($changes['sequences']['change'])) { - foreach ($changes['sequences']['change'] as $sequence_name => $sequence) { - if (array_key_exists('name', $sequence)) { - $this->db->debug("\tRenamed sequence '$sequence_name' to '". - $sequence['name']."'", __FUNCTION__); - } - if (!empty($sequence['change']) && is_array($sequence['change'])) { - foreach ($sequence['change'] as $sequence_name => $sequence) { - if (array_key_exists('start', $sequence)) { - $this->db->debug("\tChanged sequence '$sequence_name' start to '". - $sequence['start']."'", __FUNCTION__); - } - } - } - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ dumpDatabase() - - /** - * Dump a previously parsed database structure in the Metabase schema - * XML based format suitable for the Metabase parser. This function - * may optionally dump the database definition with initialization - * commands that specify the data that is currently present in the tables. - * - * @param array $database_definition multi dimensional array that contains the current definition - * @param array $arguments associative array that takes pairs of tag - * names and values that define dump options. - * <pre>array ( - * 'output_mode' => String - * 'file' : dump into a file - * default: dump using a function - * 'output' => String - * depending on the 'Output_Mode' - * name of the file - * name of the function - * 'end_of_line' => String - * end of line delimiter that should be used - * default: "\n" - * );</pre> - * @param int $dump Int that determines what data to dump - * + MDB2_SCHEMA_DUMP_ALL : the entire db - * + MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db - * + MDB2_SCHEMA_DUMP_CONTENT : only the content of the db - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function dumpDatabase($database_definition, $arguments, $dump = MDB2_SCHEMA_DUMP_ALL) - { - $class_name = $this->options['writer']; - - $result = MDB2::loadClass($class_name, $this->db->getOption('debug')); - if (PEAR::isError($result)) { - return $result; - } - - // get initialization data - if (isset($database_definition['tables']) && is_array($database_definition['tables']) - && $dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT - ) { - foreach ($database_definition['tables'] as $table_name => $table) { - $fields = array(); - $fieldsq = array(); - foreach ($table['fields'] as $field_name => $field) { - $fields[$field_name] = $field['type']; - - $fieldsq[] = $this->db->quoteIdentifier($field_name, true); - } - - $query = 'SELECT '.implode(', ', $fieldsq).' FROM '; - $query .= $this->db->quoteIdentifier($table_name, true); - - $data = $this->db->queryAll($query, $fields, MDB2_FETCHMODE_ASSOC); - - if (PEAR::isError($data)) { - return $data; - } - - if (!empty($data)) { - $initialization = array(); - $lob_buffer_length = $this->db->getOption('lob_buffer_length'); - foreach ($data as $row) { - $rows = array(); - foreach ($row as $key => $lob) { - if (is_resource($lob)) { - $value = ''; - while (!feof($lob)) { - $value .= fread($lob, $lob_buffer_length); - } - $row[$key] = $value; - } - $rows[] = array('name' => $key, 'group' => array('type' => 'value', 'data' => $row[$key])); - } - $initialization[] = array('type' => 'insert', 'data' => array('field' => $rows)); - } - $database_definition['tables'][$table_name]['initialization'] = $initialization; - } - } - } - - $writer = new $class_name($this->options['valid_types']); - return $writer->dumpDatabase($database_definition, $arguments, $dump); - } - - // }}} - // {{{ writeInitialization() - - /** - * Write initialization and sequences - * - * @param string|array $data data file or data array - * @param string|array $structure structure file or array - * @param array $variables associative array that is passed to the argument - * of the same name to the parseDatabaseDefinitionFile function. (there third - * param) - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function writeInitialization($data, $structure = false, $variables = array()) - { - if ($structure) { - $structure = $this->parseDatabaseDefinition($structure, false, $variables); - if (PEAR::isError($structure)) { - return $structure; - } - } - - $data = $this->parseDatabaseDefinition($data, false, $variables, false, $structure); - if (PEAR::isError($data)) { - return $data; - } - - $previous_database_name = null; - if (!empty($data['name'])) { - $previous_database_name = $this->db->setDatabase($data['name']); - } elseif (!empty($structure['name'])) { - $previous_database_name = $this->db->setDatabase($structure['name']); - } - - if (!empty($data['tables']) && is_array($data['tables'])) { - foreach ($data['tables'] as $table_name => $table) { - if (empty($table['initialization'])) { - continue; - } - $result = $this->initializeTable($table_name, $table); - if (PEAR::isError($result)) { - return $result; - } - } - } - - if (!empty($structure['sequences']) && is_array($structure['sequences'])) { - foreach ($structure['sequences'] as $sequence_name => $sequence) { - if (isset($data['sequences'][$sequence_name]) - || !isset($sequence['on']['table']) - || !isset($data['tables'][$sequence['on']['table']]) - ) { - continue; - } - $result = $this->createSequence($sequence_name, $sequence, true); - if (PEAR::isError($result)) { - return $result; - } - } - } - if (!empty($data['sequences']) && is_array($data['sequences'])) { - foreach ($data['sequences'] as $sequence_name => $sequence) { - $result = $this->createSequence($sequence_name, $sequence, true); - if (PEAR::isError($result)) { - return $result; - } - } - } - - if (isset($previous_database_name)) { - $this->db->setDatabase($previous_database_name); - } - - return MDB2_OK; - } - - // }}} - // {{{ updateDatabase() - - /** - * Compare the correspondent files of two versions of a database schema - * definition: the previously installed and the one that defines the schema - * that is meant to update the database. - * If the specified previous definition file does not exist, this function - * will create the database from the definition specified in the current - * schema file. - * If both files exist, the function assumes that the database was previously - * installed based on the previous schema file and will update it by just - * applying the changes. - * If this function succeeds, the contents of the current schema file are - * copied to replace the previous schema file contents. Any subsequent schema - * changes should only be done on the file specified by the $current_schema_file - * to let this function make a consistent evaluation of the exact changes that - * need to be applied. - * - * @param string|array $current_schema filename or array of the updated database schema definition. - * @param string|array $previous_schema filename or array of the previously installed database schema definition. - * @param array $variables associative array that is passed to the argument of the same - * name to the parseDatabaseDefinitionFile function. (there third param) - * @param bool $disable_query determines if the disable_query option should be set to true - * for the alterDatabase() or createDatabase() call - * @param bool $overwrite_old_schema_file Overwrite? - * - * @return bool|MDB2_Error MDB2_OK or error object - * @access public - */ - function updateDatabase($current_schema, $previous_schema = false, - $variables = array(), $disable_query = false, - $overwrite_old_schema_file = false) - { - $current_definition = $this->parseDatabaseDefinition($current_schema, false, $variables, - $this->options['fail_on_invalid_names']); - - if (PEAR::isError($current_definition)) { - return $current_definition; - } - - $previous_definition = false; - if ($previous_schema) { - $previous_definition = $this->parseDatabaseDefinition($previous_schema, true, $variables, - $this->options['fail_on_invalid_names']); - if (PEAR::isError($previous_definition)) { - return $previous_definition; - } - } - - if ($previous_definition) { - $dbExists = $this->db->databaseExists($current_definition['name']); - if (PEAR::isError($dbExists)) { - return $dbExists; - } - - if (!$dbExists) { - return $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'database to update does not exist: '.$current_definition['name']); - } - - $changes = $this->compareDefinitions($current_definition, $previous_definition); - if (PEAR::isError($changes)) { - return $changes; - } - - if (is_array($changes)) { - $this->db->setOption('disable_query', $disable_query); - $result = $this->alterDatabase($current_definition, $previous_definition, $changes); - $this->db->setOption('disable_query', false); - if (PEAR::isError($result)) { - return $result; - } - $copy = true; - if ($this->db->options['debug']) { - $result = $this->dumpDatabaseChanges($changes); - if (PEAR::isError($result)) { - return $result; - } - } - } - } else { - $this->db->setOption('disable_query', $disable_query); - $result = $this->createDatabase($current_definition); - $this->db->setOption('disable_query', false); - if (PEAR::isError($result)) { - return $result; - } - } - - if ($overwrite_old_schema_file - && !$disable_query - && is_string($previous_schema) && is_string($current_schema) - && !copy($current_schema, $previous_schema)) { - - return $this->raiseError(MDB2_SCHEMA_ERROR, null, null, - 'Could not copy the new database definition file to the current file'); - } - - return MDB2_OK; - } - // }}} - // {{{ errorMessage() - - /** - * Return a textual error message for a MDB2 error code - * - * @param int|array $value integer error code, <code>null</code> 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; - } elseif (!isset($errorMessages)) { - $errorMessages = array( - MDB2_SCHEMA_ERROR => 'unknown error', - MDB2_SCHEMA_ERROR_PARSE => 'schema parse error', - MDB2_SCHEMA_ERROR_VALIDATE => 'schema validation error', - MDB2_SCHEMA_ERROR_INVALID => 'invalid', - MDB2_SCHEMA_ERROR_UNSUPPORTED => 'not supported', - MDB2_SCHEMA_ERROR_WRITER => 'schema writer error', - ); - } - - if (is_null($value)) { - return $errorMessages; - } - - if (PEAR::isError($value)) { - $value = $value->getCode(); - } - - return !empty($errorMessages[$value]) ? - $errorMessages[$value] : $errorMessages[MDB2_SCHEMA_ERROR]; - } - - // }}} - // {{{ raiseError() - - /** - * This method is used to communicate an error and invoke error - * callbacks etc. Basically a wrapper for PEAR::raiseError - * without the message string. - * - * @param int|PEAR_Error $code integer error code or and PEAR_Error instance - * @param int $mode error mode, see PEAR_Error docs - * 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 array $options Options, depending on the mode, @see PEAR::setErrorHandling - * @param string $userinfo Extra debug information. Defaults to the last - * query and native error code. - * - * @return object a PEAR error object - * @access public - * @see PEAR_Error - */ - function raiseError($code = null, $mode = null, $options = null, $userinfo = null,$a=null,$b=null,$c=null) - { - $err =PEAR::raiseError(null, $code, $mode, $options, - $userinfo, 'MDB2_Schema_Error', true); - return $err; - } - - // }}} - // {{{ isError() - - /** - * Tell whether a value is an MDB2_Schema 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 $db->getMessage() == $code or - * $code is an integer and $db->getCode() == $code - * - * @return bool true if parameter is an error - * @access public - */ - static function isError($data, $code = null) - { - if (is_a($data, 'MDB2_Schema_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; - } - - // }}} -} - -/** - * MDB2_Schema_Error implements a class for reporting portable database error - * messages. - * - * @category Database - * @package MDB2_Schema - * @author Stig Bakken <ssb@fast.no> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Error extends PEAR_Error -{ - /** - * MDB2_Schema_Error constructor. - * - * @param mixed $code error code, or string with error message. - * @param int $mode what 'error mode' to operate in - * @param int $level what error level to use for $mode & PEAR_ERROR_TRIGGER - * @param mixed $debuginfo additional debug info, such as the last query - * - * @access public - */ - function MDB2_Schema_Error($code = MDB2_SCHEMA_ERROR, $mode = PEAR_ERROR_RETURN, - $level = E_USER_NOTICE, $debuginfo = null) - { - $this->PEAR_Error('MDB2_Schema Error: ' . MDB2_Schema::errorMessage($code), $code, - $mode, $level, $debuginfo); - } -} -?> diff --git a/3rdparty/MDB2/Schema/Parser.php b/3rdparty/MDB2/Schema/Parser.php deleted file mode 100644 index b740ef55fa85d17fc82dfb1fb08ecccdc493e02b..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema/Parser.php +++ /dev/null @@ -1,812 +0,0 @@ -<?php -/** - * PHP versions 4 and 5 - * - * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, - * Stig. S. Bakken, Lukas Smith, Igor Feghali - * All rights reserved. - * - * MDB2_Schema enables users to maintain RDBMS independant schema files - * in XML that can be used to manipulate both data and database schemas - * 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, Igor Feghali 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: Christian Dickmann <dickmann@php.net> - * Author: Igor Feghali <ifeghali@php.net> - * - * $Id: Parser.php,v 1.68 2008/11/30 03:34:00 clockwerx Exp $ - * - * @category Database - * @package MDB2_Schema - * @author Christian Dickmann <dickmann@php.net> - * @author Igor Feghali <ifeghali@php.net> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Parser.php,v 1.68 2008/11/30 03:34:00 clockwerx Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - - -require_once('XML/Parser.php'); -require_once('MDB2/Schema/Validate.php'); - -/** - * Parses an XML schema file - * - * @category Database - * @package MDB2_Schema - * @author Christian Dickmann <dickmann@php.net> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Parser extends XML_Parser -{ - var $database_definition = array(); - - var $elements = array(); - - var $element = ''; - - var $count = 0; - - var $table = array(); - - var $table_name = ''; - - var $field = array(); - - var $field_name = ''; - - var $init = array(); - - var $init_function = array(); - - var $init_expression = array(); - - var $init_field = array(); - - var $index = array(); - - var $index_name = ''; - - var $constraint = array(); - - var $constraint_name = ''; - - var $var_mode = false; - - var $variables = array(); - - var $sequence = array(); - - var $sequence_name = ''; - - var $error; - - var $structure = false; - - var $val; - - function __construct($variables, $fail_on_invalid_names = true, - $structure = false, $valid_types = array(), - $force_defaults = true) - { - // force ISO-8859-1 due to different defaults for PHP4 and PHP5 - // todo: this probably needs to be investigated some more andcleaned up - parent::__construct('ISO-8859-1'); - - $this->variables = $variables; - $this->structure = $structure; - $this->val =new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults); - } - - function startHandler($xp, $element, $attribs) - { - if (strtolower($element) == 'variable') { - $this->var_mode = true; - return; - } - - $this->elements[$this->count++] = strtolower($element); - - $this->element = implode('-', $this->elements); - - switch ($this->element) { - /* Initialization */ - case 'database-table-initialization': - $this->table['initialization'] = array(); - break; - - /* Insert */ - /* insert: field+ */ - case 'database-table-initialization-insert': - $this->init = array('type' => 'insert', 'data' => array('field' => array())); - break; - /* insert-select: field+, table, where? */ - case 'database-table-initialization-insert-select': - $this->init['data']['table'] = ''; - break; - - /* Update */ - /* update: field+, where? */ - case 'database-table-initialization-update': - $this->init = array('type' => 'update', 'data' => array('field' => array())); - break; - - /* Delete */ - /* delete: where */ - case 'database-table-initialization-delete': - $this->init = array('type' => 'delete', 'data' => array('where' => array())); - break; - - /* Insert and Update */ - case 'database-table-initialization-insert-field': - case 'database-table-initialization-insert-select-field': - case 'database-table-initialization-update-field': - $this->init_field = array('name' => '', 'group' => array()); - break; - case 'database-table-initialization-insert-field-value': - case 'database-table-initialization-insert-select-field-value': - case 'database-table-initialization-update-field-value': - /* if value tag is empty cdataHandler is not called so we must force value element creation here */ - $this->init_field['group'] = array('type' => 'value', 'data' => ''); - break; - case 'database-table-initialization-insert-field-null': - case 'database-table-initialization-insert-select-field-null': - case 'database-table-initialization-update-field-null': - $this->init_field['group'] = array('type' => 'null'); - break; - case 'database-table-initialization-insert-field-function': - case 'database-table-initialization-insert-select-field-function': - case 'database-table-initialization-update-field-function': - $this->init_function = array('name' => ''); - break; - case 'database-table-initialization-insert-field-expression': - case 'database-table-initialization-insert-select-field-expression': - case 'database-table-initialization-update-field-expression': - $this->init_expression = array(); - break; - - /* All */ - case 'database-table-initialization-insert-select-where': - case 'database-table-initialization-update-where': - case 'database-table-initialization-delete-where': - $this->init['data']['where'] = array('type' => '', 'data' => array()); - break; - case 'database-table-initialization-insert-select-where-expression': - case 'database-table-initialization-update-where-expression': - case 'database-table-initialization-delete-where-expression': - $this->init_expression = array(); - break; - - /* One level simulation of expression-function recursion */ - case 'database-table-initialization-insert-field-expression-function': - case 'database-table-initialization-insert-select-field-expression-function': - case 'database-table-initialization-insert-select-where-expression-function': - case 'database-table-initialization-update-field-expression-function': - case 'database-table-initialization-update-where-expression-function': - case 'database-table-initialization-delete-where-expression-function': - $this->init_function = array('name' => ''); - break; - - /* One level simulation of function-expression recursion */ - case 'database-table-initialization-insert-field-function-expression': - case 'database-table-initialization-insert-select-field-function-expression': - case 'database-table-initialization-insert-select-where-function-expression': - case 'database-table-initialization-update-field-function-expression': - case 'database-table-initialization-update-where-function-expression': - case 'database-table-initialization-delete-where-function-expression': - $this->init_expression = array(); - break; - - /* Definition */ - case 'database': - $this->database_definition = array( - 'name' => '', - 'create' => '', - 'overwrite' => '', - 'charset' => '', - 'description' => '', - 'comments' => '', - 'tables' => array(), - 'sequences' => array() - ); - break; - case 'database-table': - $this->table_name = ''; - - $this->table = array( - 'was' => '', - 'description' => '', - 'comments' => '', - 'fields' => array(), - 'indexes' => array(), - 'constraints' => array(), - 'initialization' => array() - ); - break; - case 'database-table-declaration-field': - case 'database-table-declaration-foreign-field': - case 'database-table-declaration-foreign-references-field': - $this->field_name = ''; - - $this->field = array(); - break; - case 'database-table-declaration-index-field': - $this->field_name = ''; - - $this->field = array('sorting' => '', 'length' => ''); - break; - /* force field attributes to be initialized when the tag is empty in the XML */ - case 'database-table-declaration-field-was': - $this->field['was'] = ''; - break; - case 'database-table-declaration-field-type': - $this->field['type'] = ''; - break; - case 'database-table-declaration-field-fixed': - $this->field['fixed'] = ''; - break; - case 'database-table-declaration-field-default': - $this->field['default'] = ''; - break; - case 'database-table-declaration-field-notnull': - $this->field['notnull'] = ''; - break; - case 'database-table-declaration-field-autoincrement': - $this->field['autoincrement'] = ''; - break; - case 'database-table-declaration-field-unsigned': - $this->field['unsigned'] = ''; - break; - case 'database-table-declaration-field-length': - $this->field['length'] = ''; - break; - case 'database-table-declaration-field-description': - $this->field['description'] = ''; - break; - case 'database-table-declaration-field-comments': - $this->field['comments'] = ''; - break; - case 'database-table-declaration-index': - $this->index_name = ''; - - $this->index = array( - 'was' => '', - 'unique' =>'', - 'primary' => '', - 'fields' => array() - ); - break; - case 'database-table-declaration-foreign': - $this->constraint_name = ''; - - $this->constraint = array( - 'was' => '', - 'match' => '', - 'ondelete' => '', - 'onupdate' => '', - 'deferrable' => '', - 'initiallydeferred' => '', - 'foreign' => true, - 'fields' => array(), - 'references' => array('table' => '', 'fields' => array()) - ); - break; - case 'database-sequence': - $this->sequence_name = ''; - - $this->sequence = array( - 'was' => '', - 'start' => '', - 'description' => '', - 'comments' => '', - 'on' => array('table' => '', 'field' => '') - ); - break; - } - } - - function endHandler($xp, $element) - { - if (strtolower($element) == 'variable') { - $this->var_mode = false; - return; - } - - switch ($this->element) { - /* Initialization */ - - /* Insert */ - case 'database-table-initialization-insert-select': - $this->init['data'] = array('select' => $this->init['data']); - break; - - /* Insert and Delete */ - case 'database-table-initialization-insert-field': - case 'database-table-initialization-insert-select-field': - case 'database-table-initialization-update-field': - $result = $this->val->validateDataField($this->table['fields'], $this->init['data']['field'], $this->init_field); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->init['data']['field'][] = $this->init_field; - } - break; - case 'database-table-initialization-insert-field-function': - case 'database-table-initialization-insert-select-field-function': - case 'database-table-initialization-update-field-function': - $this->init_field['group'] = array('type' => 'function', 'data' => $this->init_function); - break; - case 'database-table-initialization-insert-field-expression': - case 'database-table-initialization-insert-select-field-expression': - case 'database-table-initialization-update-field-expression': - $this->init_field['group'] = array('type' => 'expression', 'data' => $this->init_expression); - break; - - /* All */ - case 'database-table-initialization-insert-select-where-expression': - case 'database-table-initialization-update-where-expression': - case 'database-table-initialization-delete-where-expression': - $this->init['data']['where']['type'] = 'expression'; - $this->init['data']['where']['data'] = $this->init_expression; - break; - case 'database-table-initialization-insert': - case 'database-table-initialization-delete': - case 'database-table-initialization-update': - $this->table['initialization'][] = $this->init; - break; - - /* One level simulation of expression-function recursion */ - case 'database-table-initialization-insert-field-expression-function': - case 'database-table-initialization-insert-select-field-expression-function': - case 'database-table-initialization-insert-select-where-expression-function': - case 'database-table-initialization-update-field-expression-function': - case 'database-table-initialization-update-where-expression-function': - case 'database-table-initialization-delete-where-expression-function': - $this->init_expression['operants'][] = array('type' => 'function', 'data' => $this->init_function); - break; - - /* One level simulation of function-expression recursion */ - case 'database-table-initialization-insert-field-function-expression': - case 'database-table-initialization-insert-select-field-function-expression': - case 'database-table-initialization-insert-select-where-function-expression': - case 'database-table-initialization-update-field-function-expression': - case 'database-table-initialization-update-where-function-expression': - case 'database-table-initialization-delete-where-function-expression': - $this->init_function['arguments'][] = array('type' => 'expression', 'data' => $this->init_expression); - break; - - /* Table definition */ - case 'database-table': - $result = $this->val->validateTable($this->database_definition['tables'], $this->table, $this->table_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->database_definition['tables'][$this->table_name] = $this->table; - } - break; - case 'database-table-name': - if (isset($this->structure['tables'][$this->table_name])) { - $this->table = $this->structure['tables'][$this->table_name]; - } - break; - - /* Field declaration */ - case 'database-table-declaration-field': - $result = $this->val->validateField($this->table['fields'], $this->field, $this->field_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->table['fields'][$this->field_name] = $this->field; - } - break; - - /* Index declaration */ - case 'database-table-declaration-index': - $result = $this->val->validateIndex($this->table['indexes'], $this->index, $this->index_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->table['indexes'][$this->index_name] = $this->index; - } - break; - case 'database-table-declaration-index-field': - $result = $this->val->validateIndexField($this->index['fields'], $this->field, $this->field_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->index['fields'][$this->field_name] = $this->field; - } - break; - - /* Foreign Key declaration */ - case 'database-table-declaration-foreign': - $result = $this->val->validateConstraint($this->table['constraints'], $this->constraint, $this->constraint_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->table['constraints'][$this->constraint_name] = $this->constraint; - } - break; - case 'database-table-declaration-foreign-field': - $result = $this->val->validateConstraintField($this->constraint['fields'], $this->field_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->constraint['fields'][$this->field_name] = ''; - } - break; - case 'database-table-declaration-foreign-references-field': - $result = $this->val->validateConstraintReferencedField($this->constraint['references']['fields'], $this->field_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->constraint['references']['fields'][$this->field_name] = ''; - } - break; - - /* Sequence declaration */ - case 'database-sequence': - $result = $this->val->validateSequence($this->database_definition['sequences'], $this->sequence, $this->sequence_name); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } else { - $this->database_definition['sequences'][$this->sequence_name] = $this->sequence; - } - break; - - /* End of File */ - case 'database': - $result = $this->val->validateDatabase($this->database_definition); - if (PEAR::isError($result)) { - $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode()); - } - break; - } - - unset($this->elements[--$this->count]); - $this->element = implode('-', $this->elements); - } - - function raiseError($msg = null, $xmlecode = 0, $xp = null, $ecode = MDB2_SCHEMA_ERROR_PARSE,$a=null,$b=null,$c=null) - { - if (is_null($this->error)) { - $error = ''; - if (is_resource($msg)) { - $error .= 'Parser error: '.xml_error_string(xml_get_error_code($msg)); - $xp = $msg; - } else { - $error .= 'Parser error: '.$msg; - if (!is_resource($xp)) { - $xp = $this->parser; - } - } - - if ($error_string = xml_error_string($xmlecode)) { - $error .= ' - '.$error_string; - } - - if (is_resource($xp)) { - $byte = @xml_get_current_byte_index($xp); - $line = @xml_get_current_line_number($xp); - $column = @xml_get_current_column_number($xp); - $error .= " - Byte: $byte; Line: $line; Col: $column"; - } - - $error .= "\n"; - - $this->error =& MDB2_Schema::raiseError($ecode, null, null, $error); - } - return $this->error; - } - - function cdataHandler($xp, $data) - { - if ($this->var_mode == true) { - if (!isset($this->variables[$data])) { - $this->raiseError('variable "'.$data.'" not found', null, $xp); - return; - } - $data = $this->variables[$data]; - } - - switch ($this->element) { - /* Initialization */ - - /* Insert */ - case 'database-table-initialization-insert-select-table': - $this->init['data']['table'] = $data; - break; - - /* Insert and Update */ - case 'database-table-initialization-insert-field-name': - case 'database-table-initialization-insert-select-field-name': - case 'database-table-initialization-update-field-name': - $this->init_field['name'] .= $data; - break; - case 'database-table-initialization-insert-field-value': - case 'database-table-initialization-insert-select-field-value': - case 'database-table-initialization-update-field-value': - $this->init_field['group']['data'] .= $data; - break; - case 'database-table-initialization-insert-field-function-name': - case 'database-table-initialization-insert-select-field-function-name': - case 'database-table-initialization-update-field-function-name': - $this->init_function['name'] .= $data; - break; - case 'database-table-initialization-insert-field-function-value': - case 'database-table-initialization-insert-select-field-function-value': - case 'database-table-initialization-update-field-function-value': - $this->init_function['arguments'][] = array('type' => 'value', 'data' => $data); - break; - case 'database-table-initialization-insert-field-function-column': - case 'database-table-initialization-insert-select-field-function-column': - case 'database-table-initialization-update-field-function-column': - $this->init_function['arguments'][] = array('type' => 'column', 'data' => $data); - break; - case 'database-table-initialization-insert-field-column': - case 'database-table-initialization-insert-select-field-column': - case 'database-table-initialization-update-field-column': - $this->init_field['group'] = array('type' => 'column', 'data' => $data); - break; - - /* All */ - case 'database-table-initialization-insert-field-expression-operator': - case 'database-table-initialization-insert-select-field-expression-operator': - case 'database-table-initialization-insert-select-where-expression-operator': - case 'database-table-initialization-update-field-expression-operator': - case 'database-table-initialization-update-where-expression-operator': - case 'database-table-initialization-delete-where-expression-operator': - $this->init_expression['operator'] = $data; - break; - case 'database-table-initialization-insert-field-expression-value': - case 'database-table-initialization-insert-select-field-expression-value': - case 'database-table-initialization-insert-select-where-expression-value': - case 'database-table-initialization-update-field-expression-value': - case 'database-table-initialization-update-where-expression-value': - case 'database-table-initialization-delete-where-expression-value': - $this->init_expression['operants'][] = array('type' => 'value', 'data' => $data); - break; - case 'database-table-initialization-insert-field-expression-column': - case 'database-table-initialization-insert-select-field-expression-column': - case 'database-table-initialization-insert-select-where-expression-column': - case 'database-table-initialization-update-field-expression-column': - case 'database-table-initialization-update-where-expression-column': - case 'database-table-initialization-delete-where-expression-column': - $this->init_expression['operants'][] = array('type' => 'column', 'data' => $data); - break; - - case 'database-table-initialization-insert-field-function-function': - case 'database-table-initialization-insert-field-function-expression': - case 'database-table-initialization-insert-field-expression-expression': - case 'database-table-initialization-update-field-function-function': - case 'database-table-initialization-update-field-function-expression': - case 'database-table-initialization-update-field-expression-expression': - case 'database-table-initialization-update-where-expression-expression': - case 'database-table-initialization-delete-where-expression-expression': - /* Recursion to be implemented yet */ - break; - - /* One level simulation of expression-function recursion */ - case 'database-table-initialization-insert-field-expression-function-name': - case 'database-table-initialization-insert-select-field-expression-function-name': - case 'database-table-initialization-insert-select-where-expression-function-name': - case 'database-table-initialization-update-field-expression-function-name': - case 'database-table-initialization-update-where-expression-function-name': - case 'database-table-initialization-delete-where-expression-function-name': - $this->init_function['name'] .= $data; - break; - case 'database-table-initialization-insert-field-expression-function-value': - case 'database-table-initialization-insert-select-field-expression-function-value': - case 'database-table-initialization-insert-select-where-expression-function-value': - case 'database-table-initialization-update-field-expression-function-value': - case 'database-table-initialization-update-where-expression-function-value': - case 'database-table-initialization-delete-where-expression-function-value': - $this->init_function['arguments'][] = array('type' => 'value', 'data' => $data); - break; - case 'database-table-initialization-insert-field-expression-function-column': - case 'database-table-initialization-insert-select-field-expression-function-column': - case 'database-table-initialization-insert-select-where-expression-function-column': - case 'database-table-initialization-update-field-expression-function-column': - case 'database-table-initialization-update-where-expression-function-column': - case 'database-table-initialization-delete-where-expression-function-column': - $this->init_function['arguments'][] = array('type' => 'column', 'data' => $data); - break; - - /* One level simulation of function-expression recursion */ - case 'database-table-initialization-insert-field-function-expression-operator': - case 'database-table-initialization-insert-select-field-function-expression-operator': - case 'database-table-initialization-update-field-function-expression-operator': - $this->init_expression['operator'] = $data; - break; - case 'database-table-initialization-insert-field-function-expression-value': - case 'database-table-initialization-insert-select-field-function-expression-value': - case 'database-table-initialization-update-field-function-expression-value': - $this->init_expression['operants'][] = array('type' => 'value', 'data' => $data); - break; - case 'database-table-initialization-insert-field-function-expression-column': - case 'database-table-initialization-insert-select-field-function-expression-column': - case 'database-table-initialization-update-field-function-expression-column': - $this->init_expression['operants'][] = array('type' => 'column', 'data' => $data); - break; - - /* Database */ - case 'database-name': - $this->database_definition['name'] .= $data; - break; - case 'database-create': - $this->database_definition['create'] .= $data; - break; - case 'database-overwrite': - $this->database_definition['overwrite'] .= $data; - break; - case 'database-charset': - $this->database_definition['charset'] .= $data; - break; - case 'database-description': - $this->database_definition['description'] .= $data; - break; - case 'database-comments': - $this->database_definition['comments'] .= $data; - break; - - /* Table declaration */ - case 'database-table-name': - $this->table_name .= $data; - break; - case 'database-table-was': - $this->table['was'] .= $data; - break; - case 'database-table-description': - $this->table['description'] .= $data; - break; - case 'database-table-comments': - $this->table['comments'] .= $data; - break; - - /* Field declaration */ - case 'database-table-declaration-field-name': - $this->field_name .= $data; - break; - case 'database-table-declaration-field-was': - $this->field['was'] .= $data; - break; - case 'database-table-declaration-field-type': - $this->field['type'] .= $data; - break; - case 'database-table-declaration-field-fixed': - $this->field['fixed'] .= $data; - break; - case 'database-table-declaration-field-default': - $this->field['default'] .= $data; - break; - case 'database-table-declaration-field-notnull': - $this->field['notnull'] .= $data; - break; - case 'database-table-declaration-field-autoincrement': - $this->field['autoincrement'] .= $data; - break; - case 'database-table-declaration-field-unsigned': - $this->field['unsigned'] .= $data; - break; - case 'database-table-declaration-field-length': - $this->field['length'] .= $data; - break; - case 'database-table-declaration-field-description': - $this->field['description'] .= $data; - break; - case 'database-table-declaration-field-comments': - $this->field['comments'] .= $data; - break; - - /* Index declaration */ - case 'database-table-declaration-index-name': - $this->index_name .= $data; - break; - case 'database-table-declaration-index-was': - $this->index['was'] .= $data; - break; - case 'database-table-declaration-index-unique': - $this->index['unique'] .= $data; - break; - case 'database-table-declaration-index-primary': - $this->index['primary'] .= $data; - break; - case 'database-table-declaration-index-field-name': - $this->field_name .= $data; - break; - case 'database-table-declaration-index-field-sorting': - $this->field['sorting'] .= $data; - break; - /* Add by Leoncx */ - case 'database-table-declaration-index-field-length': - $this->field['length'] .= $data; - break; - - /* Foreign Key declaration */ - case 'database-table-declaration-foreign-name': - $this->constraint_name .= $data; - break; - case 'database-table-declaration-foreign-was': - $this->constraint['was'] .= $data; - break; - case 'database-table-declaration-foreign-match': - $this->constraint['match'] .= $data; - break; - case 'database-table-declaration-foreign-ondelete': - $this->constraint['ondelete'] .= $data; - break; - case 'database-table-declaration-foreign-onupdate': - $this->constraint['onupdate'] .= $data; - break; - case 'database-table-declaration-foreign-deferrable': - $this->constraint['deferrable'] .= $data; - break; - case 'database-table-declaration-foreign-initiallydeferred': - $this->constraint['initiallydeferred'] .= $data; - break; - case 'database-table-declaration-foreign-field': - $this->field_name .= $data; - break; - case 'database-table-declaration-foreign-references-table': - $this->constraint['references']['table'] .= $data; - break; - case 'database-table-declaration-foreign-references-field': - $this->field_name .= $data; - break; - - /* Sequence declaration */ - case 'database-sequence-name': - $this->sequence_name .= $data; - break; - case 'database-sequence-was': - $this->sequence['was'] .= $data; - break; - case 'database-sequence-start': - $this->sequence['start'] .= $data; - break; - case 'database-sequence-description': - $this->sequence['description'] .= $data; - break; - case 'database-sequence-comments': - $this->sequence['comments'] .= $data; - break; - case 'database-sequence-on-table': - $this->sequence['on']['table'] .= $data; - break; - case 'database-sequence-on-field': - $this->sequence['on']['field'] .= $data; - break; - } - } -} - -?> diff --git a/3rdparty/MDB2/Schema/Parser2.php b/3rdparty/MDB2/Schema/Parser2.php deleted file mode 100644 index 01318473fddf0163f89626aa14d0002ce5ed53f3..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema/Parser2.php +++ /dev/null @@ -1,624 +0,0 @@ -<?php -/** - * PHP versions 4 and 5 - * - * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, - * Stig. S. Bakken, Lukas Smith, Igor Feghali - * All rights reserved. - * - * MDB2_Schema enables users to maintain RDBMS independant schema files - * in XML that can be used to manipulate both data and database schemas - * 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, Igor Feghali 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: Igor Feghali <ifeghali@php.net> - * - * @category Database - * @package MDB2_Schema - * @author Igor Feghali <ifeghali@php.net> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Parser2.php,v 1.12 2008/11/30 03:34:00 clockwerx Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - -require_once 'XML/Unserializer.php'; -require_once 'MDB2/Schema/Validate.php'; - -/** - * Parses an XML schema file - * - * @category Database - * @package MDB2_Schema - * @author Lukas Smith <smith@pooteeweet.org> - * @author Igor Feghali <ifeghali@php.net> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Parser2 extends XML_Unserializer -{ - var $database_definition = array(); - - var $database_loaded = array(); - - var $variables = array(); - - var $error; - - var $structure = false; - - var $val; - - var $options = array(); - - var $table = array(); - - var $table_name = ''; - - var $field = array(); - - var $field_name = ''; - - var $index = array(); - - var $index_name = ''; - - var $constraint = array(); - - var $constraint_name = ''; - - var $sequence = array(); - - var $sequence_name = ''; - - var $init = array(); - - function __construct($variables, $fail_on_invalid_names = true, $structure = false, $valid_types = array(), $force_defaults = true) - { - // force ISO-8859-1 due to different defaults for PHP4 and PHP5 - // todo: this probably needs to be investigated some more and cleaned up - $this->options['encoding'] = 'ISO-8859-1'; - - $this->options['XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE'] = true; - $this->options['XML_UNSERIALIZER_OPTION_ATTRIBUTES_ARRAYKEY'] = false; - - $this->options['forceEnum'] = array('table', 'field', 'index', 'foreign', 'insert', 'update', 'delete', 'sequence'); - - /* - * todo: find a way to force the following items not to be parsed as arrays - * as it cause problems in functions with multiple arguments - */ - //$this->options['forceNEnum'] = array('value', 'column'); - $this->variables = $variables; - $this->structure = $structure; - - $this->val =& new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults); - parent::XML_Unserializer($this->options); - } - - function MDB2_Schema_Parser2($variables, $fail_on_invalid_names = true, $structure = false, $valid_types = array(), $force_defaults = true) - { - $this->__construct($variables, $fail_on_invalid_names, $structure, $valid_types, $force_defaults); - } - - function parse() - { - $result = $this->unserialize($this->filename, true); - - if (PEAR::isError($result)) { - return $result; - } else { - $this->database_loaded = $this->getUnserializedData(); - return $this->fixDatabaseKeys($this->database_loaded); - } - } - - function setInputFile($filename) - { - $this->filename = $filename; - return MDB2_OK; - } - - function renameKey(&$arr, $oKey, $nKey) - { - $arr[$nKey] = &$arr[$oKey]; - unset($arr[$oKey]); - } - - function fixDatabaseKeys($database) - { - $this->database_definition = array( - 'name' => '', - 'create' => '', - 'overwrite' => '', - 'charset' => '', - 'description' => '', - 'comments' => '', - 'tables' => array(), - 'sequences' => array() - ); - - if (!empty($database['name'])) { - $this->database_definition['name'] = $database['name']; - } - if (!empty($database['create'])) { - $this->database_definition['create'] = $database['create']; - } - if (!empty($database['overwrite'])) { - $this->database_definition['overwrite'] = $database['overwrite']; - } - if (!empty($database['charset'])) { - $this->database_definition['charset'] = $database['charset']; - } - if (!empty($database['description'])) { - $this->database_definition['description'] = $database['description']; - } - if (!empty($database['comments'])) { - $this->database_definition['comments'] = $database['comments']; - } - - if (!empty($database['table']) && is_array($database['table'])) { - foreach ($database['table'] as $table) { - $this->fixTableKeys($table); - } - } - - if (!empty($database['sequence']) && is_array($database['sequence'])) { - foreach ($database['sequence'] as $sequence) { - $this->fixSequenceKeys($sequence); - } - } - - $result = $this->val->validateDatabase($this->database_definition); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } - - return MDB2_OK; - } - - function fixTableKeys($table) - { - $this->table = array( - 'was' => '', - 'description' => '', - 'comments' => '', - 'fields' => array(), - 'indexes' => array(), - 'constraints' => array(), - 'initialization' => array() - ); - - if (!empty($table['name'])) { - $this->table_name = $table['name']; - } else { - $this->table_name = ''; - } - if (!empty($table['was'])) { - $this->table['was'] = $table['was']; - } - if (!empty($table['description'])) { - $this->table['description'] = $table['description']; - } - if (!empty($table['comments'])) { - $this->table['comments'] = $table['comments']; - } - - if (!empty($table['declaration']) && is_array($table['declaration'])) { - if (!empty($table['declaration']['field']) && is_array($table['declaration']['field'])) { - foreach ($table['declaration']['field'] as $field) { - $this->fixTableFieldKeys($field); - } - } - - if (!empty($table['declaration']['index']) && is_array($table['declaration']['index'])) { - foreach ($table['declaration']['index'] as $index) { - $this->fixTableIndexKeys($index); - } - } - - if (!empty($table['declaration']['foreign']) && is_array($table['declaration']['foreign'])) { - foreach ($table['declaration']['foreign'] as $constraint) { - $this->fixTableConstraintKeys($constraint); - } - } - } - - if (!empty($table['initialization']) && is_array($table['initialization'])) { - if (!empty($table['initialization']['insert']) && is_array($table['initialization']['insert'])) { - foreach ($table['initialization']['insert'] as $init) { - $this->fixTableInitializationKeys($init, 'insert'); - } - } - if (!empty($table['initialization']['update']) && is_array($table['initialization']['update'])) { - foreach ($table['initialization']['update'] as $init) { - $this->fixTableInitializationKeys($init, 'update'); - } - } - if (!empty($table['initialization']['delete']) && is_array($table['initialization']['delete'])) { - foreach ($table['initialization']['delete'] as $init) { - $this->fixTableInitializationKeys($init, 'delete'); - } - } - } - - $result = $this->val->validateTable($this->database_definition['tables'], $this->table, $this->table_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } else { - $this->database_definition['tables'][$this->table_name] = $this->table; - } - - return MDB2_OK; - } - - function fixTableFieldKeys($field) - { - $this->field = array(); - if (!empty($field['name'])) { - $this->field_name = $field['name']; - } else { - $this->field_name = ''; - } - if (!empty($field['was'])) { - $this->field['was'] = $field['was']; - } - if (!empty($field['type'])) { - $this->field['type'] = $field['type']; - } - if (!empty($field['fixed'])) { - $this->field['fixed'] = $field['fixed']; - } - if (isset($field['default'])) { - $this->field['default'] = $field['default']; - } - if (!empty($field['notnull'])) { - $this->field['notnull'] = $field['notnull']; - } - if (!empty($field['autoincrement'])) { - $this->field['autoincrement'] = $field['autoincrement']; - } - if (!empty($field['unsigned'])) { - $this->field['unsigned'] = $field['unsigned']; - } - if (!empty($field['length'])) { - $this->field['length'] = $field['length']; - } - if (!empty($field['description'])) { - $this->field['description'] = $field['description']; - } - if (!empty($field['comments'])) { - $this->field['comments'] = $field['comments']; - } - - $result = $this->val->validateField($this->table['fields'], $this->field, $this->field_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } else { - $this->table['fields'][$this->field_name] = $this->field; - } - - return MDB2_OK; - } - - function fixTableIndexKeys($index) - { - $this->index = array( - 'was' => '', - 'unique' =>'', - 'primary' => '', - 'fields' => array() - ); - - if (!empty($index['name'])) { - $this->index_name = $index['name']; - } else { - $this->index_name = ''; - } - if (!empty($index['was'])) { - $this->index['was'] = $index['was']; - } - if (!empty($index['unique'])) { - $this->index['unique'] = $index['unique']; - } - if (!empty($index['primary'])) { - $this->index['primary'] = $index['primary']; - } - if (!empty($index['field'])) { - foreach ($index['field'] as $field) { - if (!empty($field['name'])) { - $this->field_name = $field['name']; - } else { - $this->field_name = ''; - } - $this->field = array( - 'sorting' => '', - 'length' => '' - ); - - if (!empty($field['sorting'])) { - $this->field['sorting'] = $field['sorting']; - } - if (!empty($field['length'])) { - $this->field['length'] = $field['length']; - } - - $result = $this->val->validateIndexField($this->index['fields'], $this->field, $this->field_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } - - $this->index['fields'][$this->field_name] = $this->field; - } - } - - $result = $this->val->validateIndex($this->table['indexes'], $this->index, $this->index_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } else { - $this->table['indexes'][$this->index_name] = $this->index; - } - - return MDB2_OK; - } - - function fixTableConstraintKeys($constraint) - { - $this->constraint = array( - 'was' => '', - 'match' => '', - 'ondelete' => '', - 'onupdate' => '', - 'deferrable' => '', - 'initiallydeferred' => '', - 'foreign' => true, - 'fields' => array(), - 'references' => array('table' => '', 'fields' => array()) - ); - - if (!empty($constraint['name'])) { - $this->constraint_name = $constraint['name']; - } else { - $this->constraint_name = ''; - } - if (!empty($constraint['was'])) { - $this->constraint['was'] = $constraint['was']; - } - if (!empty($constraint['match'])) { - $this->constraint['match'] = $constraint['match']; - } - if (!empty($constraint['ondelete'])) { - $this->constraint['ondelete'] = $constraint['ondelete']; - } - if (!empty($constraint['onupdate'])) { - $this->constraint['onupdate'] = $constraint['onupdate']; - } - if (!empty($constraint['deferrable'])) { - $this->constraint['deferrable'] = $constraint['deferrable']; - } - if (!empty($constraint['initiallydeferred'])) { - $this->constraint['initiallydeferred'] = $constraint['initiallydeferred']; - } - if (!empty($constraint['field']) && is_array($constraint['field'])) { - foreach ($constraint['field'] as $field) { - $result = $this->val->validateConstraintField($this->constraint['fields'], $field); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } - - $this->constraint['fields'][$field] = ''; - } - } - - if (!empty($constraint['references']) && is_array($constraint['references'])) { - /** - * As we forced 'table' to be enumerated - * we have to fix it on the foreign-references-table context - */ - if (!empty($constraint['references']['table']) && is_array($constraint['references']['table'])) { - $this->constraint['references']['table'] = $constraint['references']['table'][0]; - } - - if (!empty($constraint['references']['field']) && is_array($constraint['references']['field'])) { - foreach ($constraint['references']['field'] as $field) { - $result = $this->val->validateConstraintReferencedField($this->constraint['references']['fields'], $field); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } - - $this->constraint['references']['fields'][$field] = ''; - } - } - } - - $result = $this->val->validateConstraint($this->table['constraints'], $this->constraint, $this->constraint_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } else { - $this->table['constraints'][$this->constraint_name] = $this->constraint; - } - - return MDB2_OK; - } - - function fixTableInitializationKeys($element, $type = '') - { - if (!empty($element['select']) && is_array($element['select'])) { - $this->fixTableInitializationDataKeys($element['select']); - $this->init = array( 'select' => $this->init ); - } else { - $this->fixTableInitializationDataKeys($element); - } - - $this->table['initialization'][] = array( 'type' => $type, 'data' => $this->init ); - } - - function fixTableInitializationDataKeys($element) - { - $this->init = array(); - if (!empty($element['field']) && is_array($element['field'])) { - foreach ($element['field'] as $field) { - $name = $field['name']; - unset($field['name']); - - $this->setExpression($field); - $this->init['field'][] = array( 'name' => $name, 'group' => $field ); - } - } - /** - * As we forced 'table' to be enumerated - * we have to fix it on the insert-select context - */ - if (!empty($element['table']) && is_array($element['table'])) { - $this->init['table'] = $element['table'][0]; - } - if (!empty($element['where']) && is_array($element['where'])) { - $this->init['where'] = $element['where']; - $this->setExpression($this->init['where']); - } - } - - function setExpression(&$arr) - { - $element = each($arr); - - $arr = array( 'type' => $element['key'] ); - - $element = $element['value']; - - switch ($arr['type']) { - case 'null': - break; - case 'value': - case 'column': - $arr['data'] = $element; - break; - case 'function': - if (!empty($element) - && is_array($element) - ) { - $arr['data'] = array( 'name' => $element['name'] ); - unset($element['name']); - - foreach ($element as $type => $value) { - if (!empty($value)) { - if (is_array($value)) { - foreach ($value as $argument) { - $argument = array( $type => $argument ); - $this->setExpression($argument); - $arr['data']['arguments'][] = $argument; - } - } else { - $arr['data']['arguments'][] = array( 'type' => $type, 'data' => $value ); - } - } - } - } - break; - case 'expression': - $arr['data'] = array( 'operants' => array(), 'operator' => $element['operator'] ); - unset($element['operator']); - - foreach ($element as $k => $v) { - $argument = array( $k => $v ); - $this->setExpression($argument); - $arr['data']['operants'][] = $argument; - } - break; - } - } - - function fixSequenceKeys($sequence) - { - $this->sequence = array( - 'was' => '', - 'start' => '', - 'description' => '', - 'comments' => '', - 'on' => array('table' => '', 'field' => '') - ); - - if (!empty($sequence['name'])) { - $this->sequence_name = $sequence['name']; - } else { - $this->sequence_name = ''; - } - if (!empty($sequence['was'])) { - $this->sequence['was'] = $sequence['was']; - } - if (!empty($sequence['start'])) { - $this->sequence['start'] = $sequence['start']; - } - if (!empty($sequence['description'])) { - $this->sequence['description'] = $sequence['description']; - } - if (!empty($sequence['comments'])) { - $this->sequence['comments'] = $sequence['comments']; - } - if (!empty($sequence['on']) && is_array($sequence['on'])) { - /** - * As we forced 'table' to be enumerated - * we have to fix it on the sequence-on-table context - */ - if (!empty($sequence['on']['table']) && is_array($sequence['on']['table'])) { - $this->sequence['on']['table'] = $sequence['on']['table'][0]; - } - - /** - * As we forced 'field' to be enumerated - * we have to fix it on the sequence-on-field context - */ - if (!empty($sequence['on']['field']) && is_array($sequence['on']['field'])) { - $this->sequence['on']['field'] = $sequence['on']['field'][0]; - } - } - - $result = $this->val->validateSequence($this->database_definition['sequences'], $this->sequence, $this->sequence_name); - if (PEAR::isError($result)) { - return $this->raiseError($result->getUserinfo()); - } else { - $this->database_definition['sequences'][$this->sequence_name] = $this->sequence; - } - - return MDB2_OK; - } - - function &raiseError($msg = null, $ecode = MDB2_SCHEMA_ERROR_PARSE) - { - if (is_null($this->error)) { - $error = 'Parser error: '.$msg."\n"; - - $this->error =& MDB2_Schema::raiseError($ecode, null, null, $error); - } - return $this->error; - } -} - -?> diff --git a/3rdparty/MDB2/Schema/Reserved/ibase.php b/3rdparty/MDB2/Schema/Reserved/ibase.php deleted file mode 100644 index b208abc83a383c6a4d792b7c25b9bbcedb10b6a8..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema/Reserved/ibase.php +++ /dev/null @@ -1,436 +0,0 @@ -<?php -// {{{ Disclaimer, Licence, copyrights -// +----------------------------------------------------------------------+ -// | 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: Lorenzo Alberton <l.alberton@quipo.it> | -// +----------------------------------------------------------------------+ -// -// }}} -// {{{ $GLOBALS['_MDB2_Schema_Reserved']['ibase'] -/** - * Has a list of reserved words of Interbase/Firebird - * - * @package MDB2_Schema - * @category Database - * @access protected - * @author Lorenzo Alberton <l.alberton@quipo.it> - */ -$GLOBALS['_MDB2_Schema_Reserved']['ibase'] = array( - 'ABS', - 'ABSOLUTE', - 'ACTION', - 'ACTIVE', - 'ADD', - 'ADMIN', - 'AFTER', - 'ALL', - 'ALLOCATE', - 'ALTER', - 'AND', - 'ANY', - 'ARE', - 'AS', - 'ASC', - 'ASCENDING', - 'ASSERTION', - 'AT', - 'AUTHORIZATION', - 'AUTO', - 'AUTODDL', - 'AVG', - 'BACKUP', - 'BASE_NAME', - 'BASED', - 'BASENAME', - 'BEFORE', - 'BEGIN', - 'BETWEEN', - 'BIGINT', - 'BIT', - 'BIT_LENGTH', - 'BLOB', - 'BLOCK', - 'BLOBEDIT', - 'BOOLEAN', - 'BOTH', - 'BOTH', - 'BREAK', - 'BUFFER', - 'BY', - 'CACHE', - 'CASCADE', - 'CASCADED', - 'CASE', - 'CASE', - 'CAST', - 'CATALOG', - 'CHAR', - 'CHAR_LENGTH', - 'CHARACTER', - 'CHARACTER_LENGTH', - 'CHECK', - 'CHECK_POINT_LEN', - 'CHECK_POINT_LENGTH', - 'CLOSE', - 'COALESCE', - 'COLLATE', - 'COLLATION', - 'COLUMN', - 'COMMENT', - 'COMMIT', - 'COMMITTED', - 'COMPILETIME', - 'COMPUTED', - 'CONDITIONAL', - 'CONNECT', - 'CONNECTION', - 'CONSTRAINT', - 'CONSTRAINTS', - 'CONTAINING', - 'CONTINUE', - 'CONVERT', - 'CORRESPONDING', - 'COUNT', - 'CREATE', - 'CROSS', - 'CSTRING', - 'CURRENT', - 'CURRENT_CONNECTION', - 'CURRENT_DATE', - 'CURRENT_ROLE', - 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', - 'CURRENT_TRANSACTION', - 'CURRENT_USER', - 'DATABASE', - 'DATE', - 'DAY', - 'DB_KEY', - 'DEALLOCATE', - 'DEBUG', - 'DEC', - 'DECIMAL', - 'DECLARE', - 'DEFAULT', - 'DEFERRABLE', - 'DEFERRED', - 'DELETE', - 'DELETING', - 'DESC', - 'DESCENDING', - 'DESCRIBE', - 'DESCRIPTOR', - 'DIAGNOSTICS', - 'DIFFERENCE', - 'DISCONNECT', - 'DISPLAY', - 'DISTINCT', - 'DO', - 'DOMAIN', - 'DOUBLE', - 'DROP', - 'ECHO', - 'EDIT', - 'ELSE', - 'END', - 'END-EXEC', - 'ENTRY_POINT', - 'ESCAPE', - 'EVENT', - 'EXCEPT', - 'EXCEPTION', - 'EXEC', - 'EXECUTE', - 'EXISTS', - 'EXIT', - 'EXTERN', - 'EXTERNAL', - 'EXTRACT', - 'FALSE', - 'FETCH', - 'FILE', - 'FILTER', - 'FIRST', - 'FLOAT', - 'FOR', - 'FOREIGN', - 'FOUND', - 'FREE_IT', - 'FROM', - 'FULL', - 'FUNCTION', - 'GDSCODE', - 'GEN_ID', - 'GENERATOR', - 'GET', - 'GLOBAL', - 'GO', - 'GOTO', - 'GRANT', - 'GROUP', - 'GROUP_COMMIT_WAIT', - 'GROUP_COMMIT_WAIT_TIME', - 'HAVING', - 'HELP', - 'HOUR', - 'IDENTITY', - 'IF', - 'IIF', - 'IMMEDIATE', - 'IN', - 'INACTIVE', - 'INDEX', - 'INDICATOR', - 'INIT', - 'INITIALLY', - 'INNER', - 'INPUT', - 'INPUT_TYPE', - 'INSENSITIVE', - 'INSERT', - 'INSERTING', - 'INT', - 'INTEGER', - 'INTERSECT', - 'INTERVAL', - 'INTO', - 'IS', - 'ISOLATION', - 'ISQL', - 'JOIN', - 'KEY', - 'LANGUAGE', - 'LAST', - 'LC_MESSAGES', - 'LC_TYPE', - 'LEADING', - 'LEADING', - 'LEADING', - 'LEAVE', - 'LEFT', - 'LENGTH', - 'LEV', - 'LEVEL', - 'LIKE', - 'LOCAL', - 'LOCK', - 'LOG_BUF_SIZE', - 'LOG_BUFFER_SIZE', - 'LOGFILE', - 'LONG', - 'LOWER', - 'MANUAL', - 'MATCH', - 'MAX', - 'MAX_SEGMENT', - 'MAXIMUM', - 'MAXIMUM_SEGMENT', - 'MERGE', - 'MESSAGE', - 'MIN', - 'MINIMUM', - 'MINUTE', - 'MODULE', - 'MODULE_NAME', - 'MONTH', - 'NAMES', - 'NATIONAL', - 'NATURAL', - 'NCHAR', - 'NEXT', - 'NO', - 'NOAUTO', - 'NOT', - 'NULL', - 'NULLIF', - 'NULLS', - 'NUM_LOG_BUFFERS', - 'NUM_LOG_BUFS', - 'NUMERIC', - 'OCTET_LENGTH', - 'OF', - 'ON', - 'ONLY', - 'OPEN', - 'OPTION', - 'OR', - 'ORDER', - 'OUTER', - 'OUTPUT', - 'OUTPUT_TYPE', - 'OVERFLOW', - 'OVERLAPS', - 'PAD', - 'PAGE', - 'PAGE_SIZE', - 'PAGELENGTH', - 'PAGES', - 'PARAMETER', - 'PARTIAL', - 'PASSWORD', - 'PERCENT', - 'PLAN', - 'POSITION', - 'POST_EVENT', - 'PRECISION', - 'PREPARE', - 'PRESERVE', - 'PRIMARY', - 'PRIOR', - 'PRIVILEGES', - 'PROCEDURE', - 'PUBLIC', - 'QUIT', - 'RAW_PARTITIONS', - 'RDB$DB_KEY', - 'READ', - 'REAL', - 'RECORD_VERSION', - 'RECREATE', - 'RECREATE ROW_COUNT', - 'REFERENCES', - 'RELATIVE', - 'RELEASE', - 'RESERV', - 'RESERVING', - 'RESTART', - 'RESTRICT', - 'RETAIN', - 'RETURN', - 'RETURNING', - 'RETURNING_VALUES', - 'RETURNS', - 'REVOKE', - 'RIGHT', - 'ROLE', - 'ROLLBACK', - 'ROW_COUNT', - 'ROWS', - 'RUNTIME', - 'SAVEPOINT', - 'SCALAR_ARRAY', - 'SCHEMA', - 'SCROLL', - 'SECOND', - 'SECTION', - 'SELECT', - 'SEQUENCE', - 'SESSION', - 'SESSION_USER', - 'SET', - 'SHADOW', - 'SHARED', - 'SHELL', - 'SHOW', - 'SINGULAR', - 'SIZE', - 'SKIP', - 'SMALLINT', - 'SNAPSHOT', - 'SOME', - 'SORT', - 'SPACE', - 'SQL', - 'SQLCODE', - 'SQLERROR', - 'SQLSTATE', - 'SQLWARNING', - 'STABILITY', - 'STARTING', - 'STARTS', - 'STATEMENT', - 'STATIC', - 'STATISTICS', - 'SUB_TYPE', - 'SUBSTRING', - 'SUM', - 'SUSPEND', - 'SYSTEM_USER', - 'TABLE', - 'TEMPORARY', - 'TERMINATOR', - 'THEN', - 'TIES', - 'TIME', - 'TIMESTAMP', - 'TIMEZONE_HOUR', - 'TIMEZONE_MINUTE', - 'TO', - 'TRAILING', - 'TRANSACTION', - 'TRANSLATE', - 'TRANSLATION', - 'TRIGGER', - 'TRIM', - 'TRUE', - 'TYPE', - 'UNCOMMITTED', - 'UNION', - 'UNIQUE', - 'UNKNOWN', - 'UPDATE', - 'UPDATING', - 'UPPER', - 'USAGE', - 'USER', - 'USING', - 'VALUE', - 'VALUES', - 'VARCHAR', - 'VARIABLE', - 'VARYING', - 'VERSION', - 'VIEW', - 'WAIT', - 'WEEKDAY', - 'WHEN', - 'WHENEVER', - 'WHERE', - 'WHILE', - 'WITH', - 'WORK', - 'WRITE', - 'YEAR', - 'YEARDAY', - 'ZONE', -); -// }}} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Schema/Reserved/mssql.php b/3rdparty/MDB2/Schema/Reserved/mssql.php deleted file mode 100644 index 74ac688578015f7c552854918cbe97ee4977a96e..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema/Reserved/mssql.php +++ /dev/null @@ -1,258 +0,0 @@ -<?php -// {{{ Disclaimer, Licence, copyrights -// +----------------------------------------------------------------------+ -// | 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: David Coallier <davidc@php.net> | -// +----------------------------------------------------------------------+ -// }}} -// {{{ $GLOBALS['_MDB2_Schema_Reserved']['mssql'] -/** - * Has a list of all the reserved words for mssql. - * - * @package MDB2_Schema - * @category Database - * @access protected - * @author David Coallier <davidc@php.net> - */ -$GLOBALS['_MDB2_Schema_Reserved']['mssql'] = array( - 'ADD', - 'CURRENT_TIMESTAMP', - 'GROUP', - 'OPENQUERY', - 'SERIALIZABLE', - 'ALL', - 'CURRENT_USER', - 'HAVING', - 'OPENROWSET', - 'SESSION_USER', - 'ALTER', - 'CURSOR', - 'HOLDLOCK', - 'OPTION', - 'SET', - 'AND', - 'DATABASE', - 'IDENTITY', - 'OR', - 'SETUSER', - 'ANY', - 'DBCC', - 'IDENTITYCOL', - 'ORDER', - 'SHUTDOWN', - 'AS', - 'DEALLOCATE', - 'IDENTITY_INSERT', - 'OUTER', - 'SOME', - 'ASC', - 'DECLARE', - 'IF', - 'OVER', - 'STATISTICS', - 'AUTHORIZATION', - 'DEFAULT', - 'IN', - 'PERCENT', - 'SUM', - 'AVG', - 'DELETE', - 'INDEX', - 'PERM', - 'SYSTEM_USER', - 'BACKUP', - 'DENY', - 'INNER', - 'PERMANENT', - 'TABLE', - 'BEGIN', - 'DESC', - 'INSERT', - 'PIPE', - 'TAPE', - 'BETWEEN', - 'DISK', - 'INTERSECT', - 'PLAN', - 'TEMP', - 'BREAK', - 'DISTINCT', - 'INTO', - 'PRECISION', - 'TEMPORARY', - 'BROWSE', - 'DISTRIBUTED', - 'IS', - 'PREPARE', - 'TEXTSIZE', - 'BULK', - 'DOUBLE', - 'ISOLATION', - 'PRIMARY', - 'THEN', - 'BY', - 'DROP', - 'JOIN', - 'PRINT', - 'TO', - 'CASCADE', - 'DUMMY', - 'KEY', - 'PRIVILEGES', - 'TOP', - 'CASE', - 'DUMP', - 'KILL', - 'PROC', - 'TRAN', - 'CHECK', - 'ELSE', - 'LEFT', - 'PROCEDURE', - 'TRANSACTION', - 'CHECKPOINT', - 'END', - 'LEVEL', - 'PROCESSEXIT', - 'TRIGGER', - 'CLOSE', - 'ERRLVL', - 'LIKE', - 'PUBLIC', - 'TRUNCATE', - 'CLUSTERED', - 'ERROREXIT', - 'LINENO', - 'RAISERROR', - 'TSEQUAL', - 'COALESCE', - 'ESCAPE', - 'LOAD', - 'READ', - 'UNCOMMITTED', - 'COLUMN', - 'EXCEPT', - 'MAX', - 'READTEXT', - 'UNION', - 'COMMIT', - 'EXEC', - 'MIN', - 'RECONFIGURE', - 'UNIQUE', - 'COMMITTED', - 'EXECUTE', - 'MIRROREXIT', - 'REFERENCES', - 'UPDATE', - 'COMPUTE', - 'EXISTS', - 'NATIONAL', - 'REPEATABLE', - 'UPDATETEXT', - 'CONFIRM', - 'EXIT', - 'NOCHECK', - 'REPLICATION', - 'USE', - 'CONSTRAINT', - 'FETCH', - 'NONCLUSTERED', - 'RESTORE', - 'USER', - 'CONTAINS', - 'FILE', - 'NOT', - 'RESTRICT', - 'VALUES', - 'CONTAINSTABLE', - 'FILLFACTOR', - 'NULL', - 'RETURN', - 'VARYING', - 'CONTINUE', - 'FLOPPY', - 'NULLIF', - 'REVOKE', - 'VIEW', - 'CONTROLROW', - 'FOR', - 'OF', - 'RIGHT', - 'WAITFOR', - 'CONVERT', - 'FOREIGN', - 'OFF', - 'ROLLBACK', - 'WHEN', - 'COUNT', - 'FREETEXT', - 'OFFSETS', - 'ROWCOUNT', - 'WHERE', - 'CREATE', - 'FREETEXTTABLE', - 'ON', - 'ROWGUIDCOL', - 'WHILE', - 'CROSS', - 'FROM', - 'ONCE', - 'RULE', - 'WITH', - 'CURRENT', - 'FULL', - 'ONLY', - 'SAVE', - 'WORK', - 'CURRENT_DATE', - 'GOTO', - 'OPEN', - 'SCHEMA', - 'WRITETEXT', - 'CURRENT_TIME', - 'GRANT', - 'OPENDATASOURCE', - 'SELECT', -); -//}}} - -?> diff --git a/3rdparty/MDB2/Schema/Reserved/mysql.php b/3rdparty/MDB2/Schema/Reserved/mysql.php deleted file mode 100644 index 4f0575e0bb1018d21ad7cdc1f50c124f8f5b98f6..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema/Reserved/mysql.php +++ /dev/null @@ -1,284 +0,0 @@ -<?php -// {{{ Disclaimer, Licence, copyrights -// +----------------------------------------------------------------------+ -// | 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: David Coallier <davidc@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php,v 1.3 2006/03/01 12:16:40 lsmith Exp $ -// }}} -// {{{ $GLOBALS['_MDB2_Schema_Reserved']['mysql'] -/** - * Has a list of reserved words of mysql - * - * @package MDB2_Schema - * @category Database - * @access protected - * @author David Coalier <davidc@php.net> - */ -$GLOBALS['_MDB2_Schema_Reserved']['mysql'] = array( - 'ADD', - 'ALL', - 'ALTER', - 'ANALYZE', - 'AND', - 'AS', - 'ASC', - 'ASENSITIVE', - 'BEFORE', - 'BETWEEN', - 'BIGINT', - 'BINARY', - 'BLOB', - 'BOTH', - 'BY', - 'CALL', - 'CASCADE', - 'CASE', - 'CHANGE', - 'CHAR', - 'CHARACTER', - 'CHECK', - 'COLLATE', - 'COLUMN', - 'CONDITION', - 'CONNECTION', - 'CONSTRAINT', - 'CONTINUE', - 'CONVERT', - 'CREATE', - 'CROSS', - 'CURRENT_DATE', - 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', - 'CURRENT_USER', - 'CURSOR', - 'DATABASE', - 'DATABASES', - 'DAY_HOUR', - 'DAY_MICROSECOND', - 'DAY_MINUTE', - 'DAY_SECOND', - 'DEC', - 'DECIMAL', - 'DECLARE', - 'DEFAULT', - 'DELAYED', - 'DELETE', - 'DESC', - 'DESCRIBE', - 'DETERMINISTIC', - 'DISTINCT', - 'DISTINCTROW', - 'DIV', - 'DOUBLE', - 'DROP', - 'DUAL', - 'EACH', - 'ELSE', - 'ELSEIF', - 'ENCLOSED', - 'ESCAPED', - 'EXISTS', - 'EXIT', - 'EXPLAIN', - 'FALSE', - 'FETCH', - 'FLOAT', - 'FLOAT4', - 'FLOAT8', - 'FOR', - 'FORCE', - 'FOREIGN', - 'FROM', - 'FULLTEXT', - 'GOTO', - 'GRANT', - 'GROUP', - 'HAVING', - 'HIGH_PRIORITY', - 'HOUR_MICROSECOND', - 'HOUR_MINUTE', - 'HOUR_SECOND', - 'IF', - 'IGNORE', - 'IN', - 'INDEX', - 'INFILE', - 'INNER', - 'INOUT', - 'INSENSITIVE', - 'INSERT', - 'INT', - 'INT1', - 'INT2', - 'INT3', - 'INT4', - 'INT8', - 'INTEGER', - 'INTERVAL', - 'INTO', - 'IS', - 'ITERATE', - 'JOIN', - 'KEY', - 'KEYS', - 'KILL', - 'LABEL', - 'LEADING', - 'LEAVE', - 'LEFT', - 'LIKE', - 'LIMIT', - 'LINES', - 'LOAD', - 'LOCALTIME', - 'LOCALTIMESTAMP', - 'LOCK', - 'LONG', - 'LONGBLOB', - 'LONGTEXT', - 'LOOP', - 'LOW_PRIORITY', - 'MATCH', - 'MEDIUMBLOB', - 'MEDIUMINT', - 'MEDIUMTEXT', - 'MIDDLEINT', - 'MINUTE_MICROSECOND', - 'MINUTE_SECOND', - 'MOD', - 'MODIFIES', - 'NATURAL', - 'NOT', - 'NO_WRITE_TO_BINLOG', - 'NULL', - 'NUMERIC', - 'ON', - 'OPTIMIZE', - 'OPTION', - 'OPTIONALLY', - 'OR', - 'ORDER', - 'OUT', - 'OUTER', - 'OUTFILE', - 'PRECISION', - 'PRIMARY', - 'PROCEDURE', - 'PURGE', - 'RAID0', - 'READ', - 'READS', - 'REAL', - 'REFERENCES', - 'REGEXP', - 'RELEASE', - 'RENAME', - 'REPEAT', - 'REPLACE', - 'REQUIRE', - 'RESTRICT', - 'RETURN', - 'REVOKE', - 'RIGHT', - 'RLIKE', - 'SCHEMA', - 'SCHEMAS', - 'SECOND_MICROSECOND', - 'SELECT', - 'SENSITIVE', - 'SEPARATOR', - 'SET', - 'SHOW', - 'SMALLINT', - 'SONAME', - 'SPATIAL', - 'SPECIFIC', - 'SQL', - 'SQLEXCEPTION', - 'SQLSTATE', - 'SQLWARNING', - 'SQL_BIG_RESULT', - 'SQL_CALC_FOUND_ROWS', - 'SQL_SMALL_RESULT', - 'SSL', - 'STARTING', - 'STRAIGHT_JOIN', - 'TABLE', - 'TERMINATED', - 'THEN', - 'TINYBLOB', - 'TINYINT', - 'TINYTEXT', - 'TO', - 'TRAILING', - 'TRIGGER', - 'TRUE', - 'UNDO', - 'UNION', - 'UNIQUE', - 'UNLOCK', - 'UNSIGNED', - 'UPDATE', - 'USAGE', - 'USE', - 'USING', - 'UTC_DATE', - 'UTC_TIME', - 'UTC_TIMESTAMP', - 'VALUES', - 'VARBINARY', - 'VARCHAR', - 'VARCHARACTER', - 'VARYING', - 'WHEN', - 'WHERE', - 'WHILE', - 'WITH', - 'WRITE', - 'X509', - 'XOR', - 'YEAR_MONTH', - 'ZEROFILL', - ); - // }}} -?> diff --git a/3rdparty/MDB2/Schema/Reserved/oci8.php b/3rdparty/MDB2/Schema/Reserved/oci8.php deleted file mode 100644 index 57fe12ddcab96ac1835ce133c68291add516a2f3..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema/Reserved/oci8.php +++ /dev/null @@ -1,171 +0,0 @@ -<?php -// {{{ Disclaimer, Licence, copyrights -// +----------------------------------------------------------------------+ -// | 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: David Coallier <davidc@php.net> | -// +----------------------------------------------------------------------+ -// }}} -// {{{ $GLOBALS['_MDB2_Schema_Reserved']['oci8'] -/** - * Has a list of all the reserved words for oracle. - * - * @package MDB2_Schema - * @category Database - * @access protected - * @author David Coallier <davidc@php.net> - */ -$GLOBALS['_MDB2_Schema_Reserved']['oci8'] = array( - 'ACCESS', - 'ELSE', - 'MODIFY', - 'START', - 'ADD', - 'EXCLUSIVE', - 'NOAUDIT', - 'SELECT', - 'ALL', - 'EXISTS', - 'NOCOMPRESS', - 'SESSION', - 'ALTER', - 'FILE', - 'NOT', - 'SET', - 'AND', - 'FLOAT', - 'NOTFOUND ', - 'SHARE', - 'ANY', - 'FOR', - 'NOWAIT', - 'SIZE', - 'ARRAYLEN', - 'FROM', - 'NULL', - 'SMALLINT', - 'AS', - 'GRANT', - 'NUMBER', - 'SQLBUF', - 'ASC', - 'GROUP', - 'OF', - 'SUCCESSFUL', - 'AUDIT', - 'HAVING', - 'OFFLINE ', - 'SYNONYM', - 'BETWEEN', - 'IDENTIFIED', - 'ON', - 'SYSDATE', - 'BY', - 'IMMEDIATE', - 'ONLINE', - 'TABLE', - 'CHAR', - 'IN', - 'OPTION', - 'THEN', - 'CHECK', - 'INCREMENT', - 'OR', - 'TO', - 'CLUSTER', - 'INDEX', - 'ORDER', - 'TRIGGER', - 'COLUMN', - 'INITIAL', - 'PCTFREE', - 'UID', - 'COMMENT', - 'INSERT', - 'PRIOR', - 'UNION', - 'COMPRESS', - 'INTEGER', - 'PRIVILEGES', - 'UNIQUE', - 'CONNECT', - 'INTERSECT', - 'PUBLIC', - 'UPDATE', - 'CREATE', - 'INTO', - 'RAW', - 'USER', - 'CURRENT', - 'IS', - 'RENAME', - 'VALIDATE', - 'DATE', - 'LEVEL', - 'RESOURCE', - 'VALUES', - 'DECIMAL', - 'LIKE', - 'REVOKE', - 'VARCHAR', - 'DEFAULT', - 'LOCK', - 'ROW', - 'VARCHAR2', - 'DELETE', - 'LONG', - 'ROWID', - 'VIEW', - 'DESC', - 'MAXEXTENTS', - 'ROWLABEL', - 'WHENEVER', - 'DISTINCT', - 'MINUS', - 'ROWNUM', - 'WHERE', - 'DROP', - 'MODE', - 'ROWS', - 'WITH', -); -// }}} - -?> diff --git a/3rdparty/MDB2/Schema/Reserved/pgsql.php b/3rdparty/MDB2/Schema/Reserved/pgsql.php deleted file mode 100644 index d358e9c12f033a42b806fb5645a4caa9d1a74ed5..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema/Reserved/pgsql.php +++ /dev/null @@ -1,147 +0,0 @@ -<?php -// {{{ Disclaimer, Licence, copyrights -// +----------------------------------------------------------------------+ -// | 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: Marcelo Santos Araujo <msaraujo@php.net> | -// +----------------------------------------------------------------------+ -// -// }}} -// {{{ $GLOBALS['_MDB2_Schema_Reserved']['pgsql'] -/** - * Has a list of reserved words of pgsql - * - * @package MDB2_Schema - * @category Database - * @access protected - * @author Marcelo Santos Araujo <msaraujo@php.net> - */ -$GLOBALS['_MDB2_Schema_Reserved']['pgsql'] = array( - 'ALL', - 'ANALYSE', - 'ANALYZE', - 'AND', - 'ANY', - 'AS', - 'ASC', - 'AUTHORIZATION', - 'BETWEEN', - 'BINARY', - 'BOTH', - 'CASE', - 'CAST', - 'CHECK', - 'COLLATE', - 'COLUMN', - 'CONSTRAINT', - 'CREATE', - 'CURRENT_DATE', - 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', - 'CURRENT_USER', - 'DEFAULT', - 'DEFERRABLE', - 'DESC', - 'DISTINCT', - 'DO', - 'ELSE', - 'END', - 'EXCEPT', - 'FALSE', - 'FOR', - 'FOREIGN', - 'FREEZE', - 'FROM', - 'FULL', - 'GRANT', - 'GROUP', - 'HAVING', - 'ILIKE', - 'IN', - 'INITIALLY', - 'INNER', - 'INTERSECT', - 'INTO', - 'IS', - 'ISNULL', - 'JOIN', - 'LEADING', - 'LEFT', - 'LIKE', - 'LIMIT', - 'LOCALTIME', - 'LOCALTIMESTAMP', - 'NATURAL', - 'NEW', - 'NOT', - 'NOTNULL', - 'NULL', - 'OFF', - 'OFFSET', - 'OLD', - 'ON', - 'ONLY', - 'OR', - 'ORDER', - 'OUTER', - 'OVERLAPS', - 'PLACING', - 'PRIMARY', - 'REFERENCES', - 'SELECT', - 'SESSION_USER', - 'SIMILAR', - 'SOME', - 'TABLE', - 'THEN', - 'TO', - 'TRAILING', - 'TRUE', - 'UNION', - 'UNIQUE', - 'USER', - 'USING', - 'VERBOSE', - 'WHEN', - 'WHERE' -); -// }}} -?> - diff --git a/3rdparty/MDB2/Schema/Tool.php b/3rdparty/MDB2/Schema/Tool.php deleted file mode 100644 index 9689a0f6d73ef6ee01d01246a1f4e1b449af6333..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema/Tool.php +++ /dev/null @@ -1,560 +0,0 @@ -<?php -/** - * PHP versions 4 and 5 - * - * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, - * Stig. S. Bakken, Lukas Smith, Igor Feghali - * All rights reserved. - * - * MDB2_Schema enables users to maintain RDBMS independant schema files - * in XML that can be used to manipulate both data and database schemas - * 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, Igor Feghali 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: Christian Weiske <cweiske@php.net> - * $Id: Tool.php,v 1.6 2008/12/13 00:26:07 clockwerx Exp $ - * - * @category Database - * @package MDB2_Schema - * @author Christian Weiske <cweiske@php.net> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Tool.php,v 1.6 2008/12/13 00:26:07 clockwerx Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - -require_once 'MDB2/Schema.php'; -require_once 'MDB2/Schema/Tool/ParameterException.php'; - -/** -* Command line tool to work with database schemas -* -* Functionality: -* - dump a database schema to stdout -* - import schema into database -* - create a diff between two schemas -* - apply diff to database -* - * @category Database - * @package MDB2_Schema - * @author Christian Weiske <cweiske@php.net> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Tool -{ - /** - * Run the schema tool - * - * @param array $args Array of command line arguments - */ - public function __construct($args) - { - $strAction = $this->getAction($args); - try { - $this->{'do' . ucfirst($strAction)}($args); - } catch (MDB2_Schema_Tool_ParameterException $e) { - $this->{'doHelp' . ucfirst($strAction)}($e->getMessage()); - } - }//public function __construct($args) - - - - /** - * Runs the tool with command line arguments - * - * @return void - */ - public static function run() - { - $args = $GLOBALS['argv']; - array_shift($args); - - try { - $tool = new MDB2_Schema_Tool($args); - } catch (Exception $e) { - self::toStdErr($e->getMessage() . "\n"); - } - }//public static function run() - - - - /** - * Reads the first parameter from the argument array and - * returns the action. - * - * @param array &$args Command line parameters - * - * @return string Action to execute - */ - protected function getAction(&$args) - { - if (count($args) == 0) { - return 'help'; - } - $arg = array_shift($args); - switch ($arg) { - case 'h': - case 'help': - case '-h': - case '--help': - return 'help'; - case 'd': - case 'dump': - case '-d': - case '--dump': - return 'dump'; - case 'l': - case 'load': - case '-l': - case '--load': - return 'load'; - case 'i': - case 'diff': - case '-i': - case '--diff': - return 'diff'; - case 'a': - case 'apply': - case '-a': - case '--apply': - return 'apply'; - case 'n': - case 'init': - case '-i': - case '--init': - return 'init'; - default: - throw new MDB2_Schema_Tool_ParameterException("Unknown mode \"$arg\""); - } - }//protected function getAction(&$args) - - - - /** - * Writes the message to stderr - * - * @param string $msg Message to print - * - * @return void - */ - protected static function toStdErr($msg) - { - file_put_contents('php://stderr', $msg); - }//protected static function toStdErr($msg) - - - - /** - * Displays generic help to stdout - * - * @return void - */ - protected function doHelp() - { - self::toStdErr(<<<EOH -Usage: mdb2_schematool mode parameters - -Works with database schemas - -mode: (- and -- are optional) - h, help Show this help screen - d, dump Dump a schema to stdout - l, load Load a schema into database - i, diff Create a diff between two schemas and dump it to stdout - a, apply Apply a diff to a database - n, init Initialize a database with data - -EOH - ); - }//protected function doHelp() - - - - /** - * Displays the help screen for "dump" command - * - * @return void - */ - protected function doHelpDump() - { - self::toStdErr( <<<EOH -Usage: mdb2_schematool dump [all|data|schema] [-p] DSN - -Dumps a database schema to stdout - -If dump type is not specified, defaults to "schema". - -DSN: Data source name in the form of - driver://user:password@host/database - -User and password may be omitted. -Using -p reads password from stdin which is more secure than passing it in the parameter. - -EOH - ); - }//protected function doHelpDump() - - - - /** - * Displays the help screen for "init" command - * - * @return void - */ - protected function doHelpInit() - { - self::toStdErr( <<<EOH -Usage: mdb2_schematool init source [-p] destination - -Initializes a database with data - (Inserts data on a previous created database at destination) - -source should be a schema file containing data, -destination should be a DSN - -DSN: Data source name in the form of - driver://user:password@host/database - -User and password may be omitted. -Using -p reads password from stdin which is more secure than passing it in the parameter. - -EOH - ); - }//protected function doHelpInit() - - - - /** - * Displays the help screen for "load" command - * - * @return void - */ - protected function doHelpLoad() - { - self::toStdErr( <<<EOH -Usage: mdb2_schematool load [-p] source [-p] destination - -Loads a database schema from source to destination - (Creates the database schema at destination) - -source can be a DSN or a schema file, -destination should be a DSN - -DSN: Data source name in the form of - driver://user:password@host/database - -User and password may be omitted. -Using -p reads password from stdin which is more secure than passing it in the parameter. - -EOH - ); - }//protected function doHelpLoad() - - - - /** - * Returns an array of options for MDB2_Schema constructor - * - * @return array Options for MDB2_Schema constructor - */ - protected function getSchemaOptions() - { - $options = array( - 'log_line_break' => '<br>', - 'idxname_format' => '%s', - 'debug' => true, - 'quote_identifier' => true, - 'force_defaults' => false, - 'portability' => true, - 'use_transactions' => false, - ); - return $options; - }//protected function getSchemaOptions() - - - - /** - * Checks if the passed parameter is a PEAR_Error object - * and throws an exception in that case. - * - * @param mixed $object Some variable to check - * @param string $location Where the error occured - * - * @return void - */ - protected function throwExceptionOnError($object, $location = '') - { - if (PEAR::isError($object)) { - //FIXME: exception class - //debug_print_backtrace(); - throw new Exception('Error ' . $location - . "\n" . $object->getMessage() - . "\n" . $object->getUserInfo() - ); - } - }//protected function throwExceptionOnError($object, $location = '') - - - - /** - * Loads a file or a dsn from the arguments - * - * @param array &$args Array of arguments to the program - * - * @return array Array of ('file'|'dsn', $value) - */ - protected function getFileOrDsn(&$args) - { - if (count($args) == 0) { - throw new MDB2_Schema_Tool_ParameterException('File or DSN expected'); - } - - $arg = array_shift($args); - if ($arg == '-p') { - $bAskPassword = true; - $arg = array_shift($args); - } else { - $bAskPassword = false; - } - - if (strpos($arg, '://') === false) { - if (file_exists($arg)) { - //File - return array('file', $arg); - } else { - throw new Exception('Schema file does not exist'); - } - } - - //read password if necessary - if ($bAskPassword) { - $password = $this->readPasswordFromStdin($arg); - $arg = self::setPasswordIntoDsn($arg, $password); - self::toStdErr($arg); - } - return array('dsn', $arg); - }//protected function getFileOrDsn(&$args) - - - - /** - * Takes a DSN data source name and integrates the given - * password into it. - * - * @param string $dsn Data source name - * @param string $password Password - * - * @return string DSN with password - */ - protected function setPasswordIntoDsn($dsn, $password) - { - //simple try to integrate password - if (strpos($dsn, '@') === false) { - //no @ -> no user and no password - return str_replace('://', '://:' . $password . '@', $dsn); - } else if (preg_match('|://[^:]+@|', $dsn)) { - //user only, no password - return str_replace('@', ':' . $password . '@', $dsn); - } else if (strpos($dsn, ':@') !== false) { - //abstract version - return str_replace(':@', ':' . $password . '@', $dsn); - } - - return $dsn; - }//protected function setPasswordIntoDsn($dsn, $password) - - - - /** - * Reads a password from stdin - * - * @param string $dsn DSN name to put into the message - * - * @return string Password - */ - protected function readPasswordFromStdin($dsn) - { - $stdin = fopen('php://stdin', 'r'); - self::toStdErr('Please insert password for ' . $dsn . "\n"); - $password = ''; - $breakme = false; - while (false !== ($char = fgetc($stdin))) { - if (ord($char) == 10 || $char == "\n" || $char == "\r") { - break; - } - $password .= $char; - } - fclose($stdin); - - return trim($password); - }//protected function readPasswordFromStdin() - - - - /** - * Creates a database schema dump and sends it to stdout - * - * @param array $args Command line arguments - * - * @return void - */ - protected function doDump($args) - { - $dump_what = MDB2_SCHEMA_DUMP_STRUCTURE; - $arg = ''; - if (count($args)) { - $arg = $args[0]; - } - - switch (strtolower($arg)) { - case 'all': - $dump_what = MDB2_SCHEMA_DUMP_ALL; - array_shift($args); - break; - case 'data': - $dump_what = MDB2_SCHEMA_DUMP_CONTENT; - array_shift($args); - break; - case 'schema': - array_shift($args); - } - - list($type, $dsn) = $this->getFileOrDsn($args); - if ($type == 'file') { - throw new MDB2_Schema_Tool_ParameterException( - 'Dumping a schema file as a schema file does not make much sense' - ); - } - - $schema = MDB2_Schema::factory($dsn, $this->getSchemaOptions()); - $this->throwExceptionOnError($schema); - - $definition = $schema->getDefinitionFromDatabase(); - $this->throwExceptionOnError($definition); - - - $dump_options = array( - 'output_mode' => 'file', - 'output' => 'php://stdout', - 'end_of_line' => "\r\n" - ); - $op = $schema->dumpDatabase( - $definition, $dump_options, $dump_what - ); - $this->throwExceptionOnError($op); - - $schema->disconnect(); - }//protected function doDump($args) - - - - /** - * Loads a database schema - * - * @param array $args Command line arguments - * - * @return void - */ - protected function doLoad($args) - { - list($typeSource, $dsnSource) = $this->getFileOrDsn($args); - list($typeDest, $dsnDest) = $this->getFileOrDsn($args); - - if ($typeDest == 'file') { - throw new MDB2_Schema_Tool_ParameterException( - 'A schema can only be loaded into a database, not a file' - ); - } - - - $schemaDest = MDB2_Schema::factory($dsnDest, $this->getSchemaOptions()); - $this->throwExceptionOnError($schemaDest); - - //load definition - if ($typeSource == 'file') { - $definition = $schemaDest->parseDatabaseDefinitionFile($dsnSource); - $where = 'loading schema file'; - } else { - $schemaSource = MDB2_Schema::factory($dsnSource, $this->getSchemaOptions()); - $this->throwExceptionOnError($schemaSource, 'connecting to source database'); - - $definition = $schemaSource->getDefinitionFromDatabase(); - $where = 'loading definition from database'; - } - $this->throwExceptionOnError($definition, $where); - - - //create destination database from definition - $simulate = false; - $op = $schemaDest->createDatabase($definition, array(), $simulate); - $this->throwExceptionOnError($op, 'creating the database'); - }//protected function doLoad($args) - - - - /** - * Initializes a database with data - * - * @param array $args Command line arguments - * - * @return void - */ - protected function doInit($args) - { - list($typeSource, $dsnSource) = $this->getFileOrDsn($args); - list($typeDest, $dsnDest) = $this->getFileOrDsn($args); - - if ($typeSource != 'file') { - throw new MDB2_Schema_Tool_ParameterException( - 'Data must come from a source file' - ); - } - - if ($typeDest != 'dsn') { - throw new MDB2_Schema_Tool_ParameterException( - 'A schema can only be loaded into a database, not a file' - ); - } - - $schemaDest = MDB2_Schema::factory($dsnDest, $this->getSchemaOptions()); - $this->throwExceptionOnError($schemaDest, 'connecting to destination database'); - - $definition = $schemaDest->getDefinitionFromDatabase(); - $this->throwExceptionOnError($definition, 'loading definition from database'); - - $op = $schemaDest->writeInitialization($dsnSource, $definition); - $this->throwExceptionOnError($op, 'initializing database'); - }//protected function doInit($args) - - -}//class MDB2_Schema_Tool - -?> diff --git a/3rdparty/MDB2/Schema/Tool/ParameterException.php b/3rdparty/MDB2/Schema/Tool/ParameterException.php deleted file mode 100644 index fab1e03e250de7206d7ccf7f195354fb8edfc4a2..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema/Tool/ParameterException.php +++ /dev/null @@ -1,6 +0,0 @@ -<?php - -class MDB2_Schema_Tool_ParameterException extends Exception -{} - -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Schema/Validate.php b/3rdparty/MDB2/Schema/Validate.php deleted file mode 100644 index 217cf51b9592545c892d16e2108912f7e8606750..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema/Validate.php +++ /dev/null @@ -1,917 +0,0 @@ -<?php -/** - * PHP versions 4 and 5 - * - * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, - * Stig. S. Bakken, Lukas Smith, Igor Feghali - * All rights reserved. - * - * MDB2_Schema enables users to maintain RDBMS independant schema files - * in XML that can be used to manipulate both data and database schemas - * 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, Igor Feghali 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: Christian Dickmann <dickmann@php.net> - * Author: Igor Feghali <ifeghali@php.net> - * - * @category Database - * @package MDB2_Schema - * @author Christian Dickmann <dickmann@php.net> - * @author Igor Feghali <ifeghali@php.net> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Validate.php,v 1.42 2008/11/30 03:34:00 clockwerx Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - -/** - * Validates an XML schema file - * - * @category Database - * @package MDB2_Schema - * @author Igor Feghali <ifeghali@php.net> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Validate -{ - // {{{ properties - - var $fail_on_invalid_names = true; - - var $valid_types = array(); - - var $force_defaults = true; - - // }}} - // {{{ constructor - - function __construct($fail_on_invalid_names = true, $valid_types = array(), $force_defaults = true) - { - if (empty($GLOBALS['_MDB2_Schema_Reserved'])) { - $GLOBALS['_MDB2_Schema_Reserved'] = array(); - } - - if (is_array($fail_on_invalid_names)) { - $this->fail_on_invalid_names = array_intersect($fail_on_invalid_names, - array_keys($GLOBALS['_MDB2_Schema_Reserved'])); - } elseif ($fail_on_invalid_names === true) { - $this->fail_on_invalid_names = array_keys($GLOBALS['_MDB2_Schema_Reserved']); - } else { - $this->fail_on_invalid_names = array(); - } - $this->valid_types = $valid_types; - $this->force_defaults = $force_defaults; - } - - // }}} - // {{{ raiseError() - - function &raiseError($ecode, $msg = null) - { - $error =& MDB2_Schema::raiseError($ecode, null, null, $msg); - return $error; - } - - // }}} - // {{{ isBoolean() - - /** - * Verifies if a given value can be considered boolean. If yes, set value - * to true or false according to its actual contents and return true. If - * not, keep its contents untouched and return false. - * - * @param mixed &$value value to be checked - * - * @return bool - * - * @access public - * @static - */ - function isBoolean(&$value) - { - if (is_bool($value)) { - return true; - } - - if ($value === 0 || $value === 1 || $value === '') { - $value = (bool)$value; - return true; - } - - if (!is_string($value)) { - return false; - } - - switch ($value) { - case '0': - case 'N': - case 'n': - case 'no': - case 'false': - $value = false; - break; - case '1': - case 'Y': - case 'y': - case 'yes': - case 'true': - $value = true; - break; - default: - return false; - } - return true; - } - - // }}} - // {{{ validateTable() - - /* Definition */ - /** - * Checks whether the definition of a parsed table is valid. Modify table - * definition when necessary. - * - * @param array $tables multi dimensional array that contains the - * tables of current database. - * @param array &$table multi dimensional array that contains the - * structure and optional data of the table. - * @param string $table_name name of the parsed table - * - * @return bool|error object - * - * @access public - */ - function validateTable($tables, &$table, $table_name) - { - /* Have we got a name? */ - if (!$table_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'a table has to have a name'); - } - - /* Table name duplicated? */ - if (is_array($tables) && isset($tables[$table_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'table "'.$table_name.'" already exists'); - } - - /* Table name reserved? */ - if (is_array($this->fail_on_invalid_names)) { - $name = strtoupper($table_name); - foreach ($this->fail_on_invalid_names as $rdbms) { - if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'table name "'.$table_name.'" is a reserved word in: '.$rdbms); - } - } - } - - /* Was */ - if (empty($table['was'])) { - $table['was'] = $table_name; - } - - /* Have we got fields? */ - if (empty($table['fields']) || !is_array($table['fields'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'tables need one or more fields'); - } - - /* Autoincrement */ - $autoinc = $primary = false; - foreach ($table['fields'] as $field_name => $field) { - if (!empty($field['autoincrement'])) { - if ($autoinc) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'there was already an autoincrement field in "'.$table_name.'" before "'.$field_name.'"'); - } - $autoinc = $field_name; - } - } - - /* - * Checking Indexes - * this have to be done here otherwise we can't - * guarantee that all table fields were already - * defined in the moment we are parsing indexes - */ - if (!empty($table['indexes']) && is_array($table['indexes'])) { - foreach ($table['indexes'] as $name => $index) { - $skip_index = false; - if (!empty($index['primary'])) { - /* - * Lets see if we should skip this index since there is - * already an auto increment on this field this implying - * a primary key index. - */ - if (count($index['fields']) == '1' - && $autoinc - && array_key_exists($autoinc, $index['fields'])) { - $skip_index = true; - } elseif ($autoinc || $primary) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'there was already an primary index or autoincrement field in "'.$table_name.'" before "'.$name.'"'); - } else { - $primary = true; - } - } - - if (!$skip_index && is_array($index['fields'])) { - foreach ($index['fields'] as $field_name => $field) { - if (!isset($table['fields'][$field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'index field "'.$field_name.'" does not exist'); - } - if (!empty($index['primary']) - && !$table['fields'][$field_name]['notnull'] - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'all primary key fields must be defined notnull in "'.$table_name.'"'); - } - } - } else { - unset($table['indexes'][$name]); - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ validateField() - - /** - * Checks whether the definition of a parsed field is valid. Modify field - * definition when necessary. - * - * @param array $fields multi dimensional array that contains the - * fields of current table. - * @param array &$field multi dimensional array that contains the - * structure of the parsed field. - * @param string $field_name name of the parsed field - * - * @return bool|error object - * - * @access public - */ - function validateField($fields, &$field, $field_name) - { - /* Have we got a name? */ - if (!$field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field name missing'); - } - - /* Field name duplicated? */ - if (is_array($fields) && isset($fields[$field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "'.$field_name.'" already exists'); - } - - /* Field name reserverd? */ - if (is_array($this->fail_on_invalid_names)) { - $name = strtoupper($field_name); - foreach ($this->fail_on_invalid_names as $rdbms) { - if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field name "'.$field_name.'" is a reserved word in: '.$rdbms); - } - } - } - - /* Type check */ - if (empty($field['type'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'no field type specified'); - } - if (!empty($this->valid_types) && !array_key_exists($field['type'], $this->valid_types)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'no valid field type ("'.$field['type'].'") specified'); - } - - /* Unsigned */ - if (array_key_exists('unsigned', $field) && !$this->isBoolean($field['unsigned'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'unsigned has to be a boolean value'); - } - - /* Fixed */ - if (array_key_exists('fixed', $field) && !$this->isBoolean($field['fixed'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'fixed has to be a boolean value'); - } - - /* Length */ - if (array_key_exists('length', $field) && $field['length'] <= 0) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'length has to be an integer greater 0'); - } - - // if it's a DECIMAL datatype, check if a 'scale' value is provided: - // <length>8,4</length> should be translated to DECIMAL(8,4) - if (is_float($this->valid_types[$field['type']]) - && !empty($field['length']) - && strpos($field['length'], ',') !== false - ) { - list($field['length'], $field['scale']) = explode(',', $field['length']); - } - - /* Was */ - if (empty($field['was'])) { - $field['was'] = $field_name; - } - - /* Notnull */ - if (empty($field['notnull'])) { - $field['notnull'] = false; - } - if (!$this->isBoolean($field['notnull'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "notnull" has to be a boolean value'); - } - - /* Default */ - if ($this->force_defaults - && !array_key_exists('default', $field) - && $field['type'] != 'clob' && $field['type'] != 'blob' - ) { - $field['default'] = $this->valid_types[$field['type']]; - } - if (array_key_exists('default', $field)) { - if ($field['type'] == 'clob' || $field['type'] == 'blob') { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field['type'].'"-fields are not allowed to have a default value'); - } - if ($field['default'] === '' && !$field['notnull']) { - $field['default'] = null; - } - } - if (isset($field['default']) - && PEAR::isError($result = $this->validateDataFieldValue($field, $field['default'], $field_name)) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'default value of "'.$field_name.'" is incorrect: '.$result->getUserinfo()); - } - - /* Autoincrement */ - if (!empty($field['autoincrement'])) { - if (!$field['notnull']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'all autoincrement fields must be defined notnull'); - } - - if (empty($field['default'])) { - $field['default'] = '0'; - } elseif ($field['default'] !== '0' && $field['default'] !== 0) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'all autoincrement fields must be defined default "0"'); - } - } - return MDB2_OK; - } - - // }}} - // {{{ validateIndex() - - /** - * Checks whether a parsed index is valid. Modify index definition when - * necessary. - * - * @param array $table_indexes multi dimensional array that contains the - * indexes of current table. - * @param array &$index multi dimensional array that contains the - * structure of the parsed index. - * @param string $index_name name of the parsed index - * - * @return bool|error object - * - * @access public - */ - function validateIndex($table_indexes, &$index, $index_name) - { - if (!$index_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'an index has to have a name'); - } - if (is_array($table_indexes) && isset($table_indexes[$index_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'index "'.$index_name.'" already exists'); - } - if (array_key_exists('unique', $index) && !$this->isBoolean($index['unique'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "unique" has to be a boolean value'); - } - if (array_key_exists('primary', $index) && !$this->isBoolean($index['primary'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "primary" has to be a boolean value'); - } - - /* Have we got fields? */ - if (empty($index['fields']) || !is_array($index['fields'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'indexes need one or more fields'); - } - - if (empty($index['was'])) { - $index['was'] = $index_name; - } - return MDB2_OK; - } - - // }}} - // {{{ validateIndexField() - - /** - * Checks whether a parsed index-field is valid. Modify its definition when - * necessary. - * - * @param array $index_fields multi dimensional array that contains the - * fields of current index. - * @param array &$field multi dimensional array that contains the - * structure of the parsed index-field. - * @param string $field_name name of the parsed index-field - * - * @return bool|error object - * - * @access public - */ - function validateIndexField($index_fields, &$field, $field_name) - { - if (is_array($index_fields) && isset($index_fields[$field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'index field "'.$field_name.'" already exists'); - } - if (!$field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'the index-field-name is required'); - } - if (empty($field['sorting'])) { - $field['sorting'] = 'ascending'; - } elseif ($field['sorting'] !== 'ascending' && $field['sorting'] !== 'descending') { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'sorting type unknown'); - } - return MDB2_OK; - } - - // }}} - // {{{ validateConstraint() - - /** - * Checks whether a parsed foreign key is valid. Modify its definition when - * necessary. - * - * @param array $table_constraints multi dimensional array that contains the - * constraints of current table. - * @param array &$constraint multi dimensional array that contains the - * structure of the parsed foreign key. - * @param string $constraint_name name of the parsed foreign key - * - * @return bool|error object - * - * @access public - */ - function validateConstraint($table_constraints, &$constraint, $constraint_name) - { - if (!$constraint_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'a foreign key has to have a name'); - } - if (is_array($table_constraints) && isset($table_constraints[$constraint_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign key "'.$constraint_name.'" already exists'); - } - - /* Have we got fields? */ - if (empty($constraint['fields']) || !is_array($constraint['fields'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign key "'.$constraint_name.'" need one or more fields'); - } - - /* Have we got referenced fields? */ - if (empty($constraint['references']) || !is_array($constraint['references'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign key "'.$constraint_name.'" need to reference one or more fields'); - } - - /* Have we got referenced table? */ - if (empty($constraint['references']['table'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign key "'.$constraint_name.'" need to reference a table'); - } - - if (empty($constraint['was'])) { - $constraint['was'] = $constraint_name; - } - return MDB2_OK; - } - - // }}} - // {{{ validateConstraintField() - - /** - * Checks whether a foreign-field is valid. - * - * @param array $constraint_fields multi dimensional array that contains the - * fields of current foreign key. - * @param string $field_name name of the parsed foreign-field - * - * @return bool|error object - * - * @access public - */ - function validateConstraintField($constraint_fields, $field_name) - { - if (!$field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'empty value for foreign-field'); - } - if (is_array($constraint_fields) && isset($constraint_fields[$field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign field "'.$field_name.'" already exists'); - } - return MDB2_OK; - } - - // }}} - // {{{ validateConstraintReferencedField() - - /** - * Checks whether a foreign-referenced field is valid. - * - * @param array $referenced_fields multi dimensional array that contains the - * fields of current foreign key. - * @param string $field_name name of the parsed foreign-field - * - * @return bool|error object - * - * @access public - */ - function validateConstraintReferencedField($referenced_fields, $field_name) - { - if (!$field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'empty value for referenced foreign-field'); - } - if (is_array($referenced_fields) && isset($referenced_fields[$field_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'foreign field "'.$field_name.'" already referenced'); - } - return MDB2_OK; - } - - // }}} - // {{{ validateSequence() - - /** - * Checks whether the definition of a parsed sequence is valid. Modify - * sequence definition when necessary. - * - * @param array $sequences multi dimensional array that contains the - * sequences of current database. - * @param array &$sequence multi dimensional array that contains the - * structure of the parsed sequence. - * @param string $sequence_name name of the parsed sequence - * - * @return bool|error object - * - * @access public - */ - function validateSequence($sequences, &$sequence, $sequence_name) - { - if (!$sequence_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'a sequence has to have a name'); - } - - if (is_array($sequences) && isset($sequences[$sequence_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'sequence "'.$sequence_name.'" already exists'); - } - - if (is_array($this->fail_on_invalid_names)) { - $name = strtoupper($sequence_name); - foreach ($this->fail_on_invalid_names as $rdbms) { - if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'sequence name "'.$sequence_name.'" is a reserved word in: '.$rdbms); - } - } - } - - if (empty($sequence['was'])) { - $sequence['was'] = $sequence_name; - } - - if (!empty($sequence['on']) - && (empty($sequence['on']['table']) || empty($sequence['on']['field'])) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'sequence "'.$sequence_name.'" on a table was not properly defined'); - } - return MDB2_OK; - } - - // }}} - // {{{ validateDatabase() - - /** - * Checks whether a parsed database is valid. Modify its structure and - * data when necessary. - * - * @param array &$database multi dimensional array that contains the - * structure and optional data of the database. - * - * @return bool|error object - * - * @access public - */ - function validateDatabase(&$database) - { - /* Have we got a name? */ - if (!is_array($database) || !isset($database['name']) || !$database['name']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'a database has to have a name'); - } - - /* Database name reserved? */ - if (is_array($this->fail_on_invalid_names)) { - $name = strtoupper($database['name']); - foreach ($this->fail_on_invalid_names as $rdbms) { - if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'database name "'.$database['name'].'" is a reserved word in: '.$rdbms); - } - } - } - - /* Create */ - if (isset($database['create']) - && !$this->isBoolean($database['create']) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "create" has to be a boolean value'); - } - - /* Overwrite */ - if (isset($database['overwrite']) - && $database['overwrite'] !== '' - && !$this->isBoolean($database['overwrite']) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "overwrite" has to be a boolean value'); - } - - /* - * This have to be done here otherwise we can't guarantee that all - * tables were already defined in the moment we are parsing constraints - */ - if (isset($database['tables'])) { - foreach ($database['tables'] as $table_name => $table) { - if (!empty($table['constraints'])) { - foreach ($table['constraints'] as $constraint_name => $constraint) { - $referenced_table_name = $constraint['references']['table']; - - if (!isset($database['tables'][$referenced_table_name])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'referenced table "'.$referenced_table_name.'" of foreign key "'.$constraint_name.'" of table "'.$table_name.'" does not exist'); - } - - if (empty($constraint['references']['fields'])) { - $referenced_table = $database['tables'][$referenced_table_name]; - - $primary = false; - - if (!empty($referenced_table['indexes'])) { - foreach ($referenced_table['indexes'] as $index_name => $index) { - if (array_key_exists('primary', $index) - && $index['primary'] - ) { - $primary = array(); - foreach ($index['fields'] as $field_name => $field) { - $primary[$field_name] = ''; - } - break; - } - } - } - - if (!$primary) { - foreach ($referenced_table['fields'] as $field_name => $field) { - if (array_key_exists('autoincrement', $field) - && $field['autoincrement'] - ) { - $primary = array( $field_name => '' ); - break; - } - } - } - - if (!$primary) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'referenced table "'.$referenced_table_name.'" has no primary key and no referenced field was specified for foreign key "'.$constraint_name.'" of table "'.$table_name.'"'); - } - - $constraint['references']['fields'] = $primary; - } - - /* the same number of referencing and referenced fields ? */ - if (count($constraint['fields']) != count($constraint['references']['fields'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'The number of fields in the referenced key must match those of the foreign key "'.$constraint_name.'"'); - } - - $database['tables'][$table_name]['constraints'][$constraint_name]['references']['fields'] = $constraint['references']['fields']; - } - } - } - } - - /* - * This have to be done here otherwise we can't guarantee that all - * tables were already defined in the moment we are parsing sequences - */ - if (isset($database['sequences'])) { - foreach ($database['sequences'] as $seq_name => $seq) { - if (!empty($seq['on']) - && empty($database['tables'][$seq['on']['table']]['fields'][$seq['on']['field']]) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'sequence "'.$seq_name.'" was assigned on unexisting field/table'); - } - } - } - return MDB2_OK; - } - - // }}} - // {{{ validateDataField() - - /* Data Manipulation */ - /** - * Checks whether a parsed DML-field is valid. Modify its structure when - * necessary. This is called when validating INSERT and - * UPDATE. - * - * @param array $table_fields multi dimensional array that contains the - * definition for current table's fields. - * @param array $instruction_fields multi dimensional array that contains the - * parsed fields of the current DML instruction. - * @param string &$field array that contains the parsed instruction field - * - * @return bool|error object - * - * @access public - */ - function validateDataField($table_fields, $instruction_fields, &$field) - { - if (!$field['name']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field-name has to be specified'); - } - - if (is_array($instruction_fields) && isset($instruction_fields[$field['name']])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field "'.$field['name'].'" already initialized'); - } - - if (is_array($table_fields) && !isset($table_fields[$field['name']])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field['name'].'" is not defined'); - } - - if (!isset($field['group']['type'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field['name'].'" has no initial value'); - } - - if (isset($field['group']['data']) - && $field['group']['type'] == 'value' - && $field['group']['data'] !== '' - && PEAR::isError($result = $this->validateDataFieldValue($table_fields[$field['name']], $field['group']['data'], $field['name'])) - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'value of "'.$field['name'].'" is incorrect: '.$result->getUserinfo()); - } - - return MDB2_OK; - } - - // }}} - // {{{ validateDataFieldValue() - - /** - * Checks whether a given value is compatible with a table field. This is - * done when parsing a field for a INSERT or UPDATE instruction. - * - * @param array $field_def multi dimensional array that contains the - * definition for current table's fields. - * @param string &$field_value value to fill the parsed field - * @param string $field_name name of the parsed field - * - * @return bool|error object - * - * @access public - * @see MDB2_Schema_Validate::validateInsertField() - */ - function validateDataFieldValue($field_def, &$field_value, $field_name) - { - switch ($field_def['type']) { - case 'text': - case 'clob': - if (!empty($field_def['length']) && strlen($field_value) > $field_def['length']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is larger than "'.$field_def['length'].'"'); - } - break; - case 'blob': - $field_value = pack('H*', $field_value); - if (!empty($field_def['length']) && strlen($field_value) > $field_def['length']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is larger than "'.$field_def['type'].'"'); - } - break; - case 'integer': - if ($field_value != ((int)$field_value)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - //$field_value = (int)$field_value; - if (!empty($field_def['unsigned']) && $field_def['unsigned'] && $field_value < 0) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" signed instead of unsigned'); - } - break; - case 'boolean': - if (!$this->isBoolean($field_value)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - break; - case 'date': - if (!preg_match('/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/', $field_value) - && $field_value !== 'CURRENT_DATE' - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - break; - case 'timestamp': - if (!preg_match('/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/', $field_value) - && strcasecmp($field_value, 'now()') != 0 - && $field_value !== 'CURRENT_TIMESTAMP' - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - break; - case 'time': - if (!preg_match("/([0-9]{2}):([0-9]{2}):([0-9]{2})/", $field_value) - && $field_value !== 'CURRENT_TIME' - ) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - break; - case 'float': - case 'double': - if ($field_value != (double)$field_value) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - '"'.$field_value.'" is not of type "'.$field_def['type'].'"'); - } - //$field_value = (double)$field_value; - break; - } - return MDB2_OK; - } -} - -?> diff --git a/3rdparty/MDB2/Schema/Writer.php b/3rdparty/MDB2/Schema/Writer.php deleted file mode 100644 index 5ae4918dc1d086af46f6e297a72c7af9d4105b1f..0000000000000000000000000000000000000000 --- a/3rdparty/MDB2/Schema/Writer.php +++ /dev/null @@ -1,581 +0,0 @@ -<?php -/** - * PHP versions 4 and 5 - * - * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, - * Stig. S. Bakken, Lukas Smith, Igor Feghali - * All rights reserved. - * - * MDB2_Schema enables users to maintain RDBMS independant schema files - * in XML that can be used to manipulate both data and database schemas - * 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, Igor Feghali 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> - * Author: Igor Feghali <ifeghali@php.net> - * - * @category Database - * @package MDB2_Schema - * @author Lukas Smith <smith@pooteeweet.org> - * @author Igor Feghali <ifeghali@php.net> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @version CVS: $Id: Writer.php,v 1.40 2008/11/30 03:34:00 clockwerx Exp $ - * @link http://pear.php.net/packages/MDB2_Schema - */ - -/** - * Writes an XML schema file - * - * @category Database - * @package MDB2_Schema - * @author Lukas Smith <smith@pooteeweet.org> - * @license BSD http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/packages/MDB2_Schema - */ -class MDB2_Schema_Writer -{ - // {{{ properties - - var $valid_types = array(); - - // }}} - // {{{ constructor - - function __construct($valid_types = array()) - { - $this->valid_types = $valid_types; - } - - function MDB2_Schema_Writer($valid_types = array()) - { - $this->__construct($valid_types); - } - - // }}} - // {{{ raiseError() - - /** - * This method is used to communicate an error and invoke error - * callbacks etc. Basically a wrapper for PEAR::raiseError - * without the message string. - * - * @param int|PEAR_Error $code integer error code or and PEAR_Error instance - * @param int $mode error mode, see PEAR_Error docs - * 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 $options Extra debug information. Defaults to the last - * query and native error code. - * - * @return object a PEAR error object - * @access public - * @see PEAR_Error - */ - function &raiseError($code = null, $mode = null, $options = null, $userinfo = null) - { - $error =& MDB2_Schema::raiseError($code, $mode, $options, $userinfo); - return $error; - } - - // }}} - // {{{ _escapeSpecialChars() - - /** - * add escapecharacters to all special characters in a string - * - * @param string $string string that should be escaped - * - * @return string escaped string - * @access protected - */ - function _escapeSpecialChars($string) - { - if (!is_string($string)) { - $string = strval($string); - } - - $escaped = ''; - for ($char = 0, $count = strlen($string); $char < $count; $char++) { - switch ($string[$char]) { - case '&': - $escaped .= '&'; - break; - case '>': - $escaped .= '>'; - break; - case '<': - $escaped .= '<'; - break; - case '"': - $escaped .= '"'; - break; - case '\'': - $escaped .= '''; - break; - default: - $code = ord($string[$char]); - if ($code < 32 || $code > 127) { - $escaped .= "&#$code;"; - } else { - $escaped .= $string[$char]; - } - break; - } - } - return $escaped; - } - - // }}} - // {{{ _dumpBoolean() - - /** - * dump the structure of a sequence - * - * @param string $boolean boolean value or variable definition - * - * @return string with xml boolea definition - * @access private - */ - function _dumpBoolean($boolean) - { - if (is_string($boolean)) { - if ($boolean !== 'true' || $boolean !== 'false' - || preg_match('/<variable>.*</variable>/', $boolean) - ) { - return $boolean; - } - } - return $boolean ? 'true' : 'false'; - } - - // }}} - // {{{ dumpSequence() - - /** - * dump the structure of a sequence - * - * @param string $sequence_definition sequence definition - * @param string $sequence_name sequence name - * @param string $eol end of line characters - * @param integer $dump determines what data to dump - * MDB2_SCHEMA_DUMP_ALL : the entire db - * MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db - * MDB2_SCHEMA_DUMP_CONTENT : only the content of the db - * - * @return mixed string xml sequence definition on success, or a error object - * @access public - */ - function dumpSequence($sequence_definition, $sequence_name, $eol, $dump = MDB2_SCHEMA_DUMP_ALL) - { - $buffer = "$eol <sequence>$eol <name>$sequence_name</name>$eol"; - if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT) { - if (!empty($sequence_definition['start'])) { - $start = $sequence_definition['start']; - $buffer .= " <start>$start</start>$eol"; - } - } - - if (!empty($sequence_definition['on'])) { - $buffer .= " <on>$eol"; - $buffer .= " <table>".$sequence_definition['on']['table']; - $buffer .= "</table>$eol <field>".$sequence_definition['on']['field']; - $buffer .= "</field>$eol </on>$eol"; - } - $buffer .= " </sequence>$eol"; - - return $buffer; - } - - // }}} - // {{{ dumpDatabase() - - /** - * Dump a previously parsed database structure in the Metabase schema - * XML based format suitable for the Metabase parser. This function - * may optionally dump the database definition with initialization - * commands that specify the data that is currently present in the tables. - * - * @param array $database_definition unknown - * @param array $arguments associative array that takes pairs of tag - * names and values that define dump options. - * array ( - * 'output_mode' => String - * 'file' : dump into a file - * default: dump using a function - * 'output' => String - * depending on the 'Output_Mode' - * name of the file - * name of the function - * 'end_of_line' => String - * end of line delimiter that should be used - * default: "\n" - * ); - * @param integer $dump determines what data to dump - * MDB2_SCHEMA_DUMP_ALL : the entire db - * MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db - * MDB2_SCHEMA_DUMP_CONTENT : only the content of the db - * - * @return mixed MDB2_OK on success, or a error object - * @access public - */ - function dumpDatabase($database_definition, $arguments, $dump = MDB2_SCHEMA_DUMP_ALL) - { - if (!empty($arguments['output'])) { - if (!empty($arguments['output_mode']) && $arguments['output_mode'] == 'file') { - $fp = fopen($arguments['output'], 'w'); - if ($fp === false) { - return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null, - 'it was not possible to open output file'); - } - - $output = false; - } elseif (is_callable($arguments['output'])) { - $output = $arguments['output']; - } else { - return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null, - 'no valid output function specified'); - } - } else { - return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null, - 'no output method specified'); - } - - $eol = isset($arguments['end_of_line']) ? $arguments['end_of_line'] : "\n"; - - $sequences = array(); - if (!empty($database_definition['sequences']) - && is_array($database_definition['sequences']) - ) { - foreach ($database_definition['sequences'] as $sequence_name => $sequence) { - $table = !empty($sequence['on']) ? $sequence['on']['table'] :''; - - $sequences[$table][] = $sequence_name; - } - } - - $buffer = '<?xml version="1.0" encoding="ISO-8859-1" ?>'.$eol; - $buffer .= "<database>$eol$eol <name>".$database_definition['name']."</name>"; - $buffer .= "$eol <create>".$this->_dumpBoolean($database_definition['create'])."</create>"; - $buffer .= "$eol <overwrite>".$this->_dumpBoolean($database_definition['overwrite'])."</overwrite>$eol"; - $buffer .= "$eol <charset>".$database_definition['charset']."</charset>$eol"; - - if ($output) { - call_user_func($output, $buffer); - } else { - fwrite($fp, $buffer); - } - - if (!empty($database_definition['tables']) && is_array($database_definition['tables'])) { - foreach ($database_definition['tables'] as $table_name => $table) { - $buffer = "$eol <table>$eol$eol <name>$table_name</name>$eol"; - if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_STRUCTURE) { - $buffer .= "$eol <declaration>$eol"; - if (!empty($table['fields']) && is_array($table['fields'])) { - foreach ($table['fields'] as $field_name => $field) { - if (empty($field['type'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null, - 'it was not specified the type of the field "'. - $field_name.'" of the table "'.$table_name.'"'); - } - if (!empty($this->valid_types) && !array_key_exists($field['type'], $this->valid_types)) { - return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null, - 'type "'.$field['type'].'" is not yet supported'); - } - $buffer .= "$eol <field>$eol <name>$field_name</name>$eol <type>"; - $buffer .= $field['type']."</type>$eol"; - if (!empty($field['fixed']) && $field['type'] === 'text') { - $buffer .= " <fixed>".$this->_dumpBoolean($field['fixed'])."</fixed>$eol"; - } - if (array_key_exists('default', $field) - && $field['type'] !== 'clob' && $field['type'] !== 'blob' - ) { - $buffer .= ' <default>'.$this->_escapeSpecialChars($field['default'])."</default>$eol"; - } - if (!empty($field['notnull'])) { - $buffer .= " <notnull>".$this->_dumpBoolean($field['notnull'])."</notnull>$eol"; - } else { - $buffer .= " <notnull>false</notnull>$eol"; - } - if (!empty($field['autoincrement'])) { - $buffer .= " <autoincrement>" . $field['autoincrement'] ."</autoincrement>$eol"; - } - if (!empty($field['unsigned'])) { - $buffer .= " <unsigned>".$this->_dumpBoolean($field['unsigned'])."</unsigned>$eol"; - } - if (!empty($field['length'])) { - $buffer .= ' <length>'.$field['length']."</length>$eol"; - } - $buffer .= " </field>$eol"; - } - } - - if (!empty($table['indexes']) && is_array($table['indexes'])) { - foreach ($table['indexes'] as $index_name => $index) { - if (strtolower($index_name) === 'primary') { - $index_name = $table_name . '_pKey'; - } - $buffer .= "$eol <index>$eol <name>$index_name</name>$eol"; - if (!empty($index['unique'])) { - $buffer .= " <unique>".$this->_dumpBoolean($index['unique'])."</unique>$eol"; - } - - if (!empty($index['primary'])) { - $buffer .= " <primary>".$this->_dumpBoolean($index['primary'])."</primary>$eol"; - } - - foreach ($index['fields'] as $field_name => $field) { - $buffer .= " <field>$eol <name>$field_name</name>$eol"; - if (!empty($field) && is_array($field)) { - $buffer .= ' <sorting>'.$field['sorting']."</sorting>$eol"; - } - $buffer .= " </field>$eol"; - } - $buffer .= " </index>$eol"; - } - } - - if (!empty($table['constraints']) && is_array($table['constraints'])) { - foreach ($table['constraints'] as $constraint_name => $constraint) { - $buffer .= "$eol <foreign>$eol <name>$constraint_name</name>$eol"; - if (empty($constraint['fields']) || !is_array($constraint['fields'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null, - 'it was not specified a field for the foreign key "'. - $constraint_name.'" of the table "'.$table_name.'"'); - } - if (!is_array($constraint['references']) || empty($constraint['references']['table'])) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null, - 'it was not specified the referenced table of the foreign key "'. - $constraint_name.'" of the table "'.$table_name.'"'); - } - if (!empty($constraint['match'])) { - $buffer .= " <match>".$constraint['match']."</match>$eol"; - } - if (!empty($constraint['ondelete'])) { - $buffer .= " <ondelete>".$constraint['ondelete']."</ondelete>$eol"; - } - if (!empty($constraint['onupdate'])) { - $buffer .= " <onupdate>".$constraint['onupdate']."</onupdate>$eol"; - } - if (!empty($constraint['deferrable'])) { - $buffer .= " <deferrable>".$constraint['deferrable']."</deferrable>$eol"; - } - if (!empty($constraint['initiallydeferred'])) { - $buffer .= " <initiallydeferred>".$constraint['initiallydeferred']."</initiallydeferred>$eol"; - } - foreach ($constraint['fields'] as $field_name => $field) { - $buffer .= " <field>$field_name</field>$eol"; - } - $buffer .= " <references>$eol <table>".$constraint['references']['table']."</table>$eol"; - foreach ($constraint['references']['fields'] as $field_name => $field) { - $buffer .= " <field>$field_name</field>$eol"; - } - $buffer .= " </references>$eol"; - - $buffer .= " </foreign>$eol"; - } - } - - $buffer .= "$eol </declaration>$eol"; - } - - if ($output) { - call_user_func($output, $buffer); - } else { - fwrite($fp, $buffer); - } - - $buffer = ''; - if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT) { - if (!empty($table['initialization']) && is_array($table['initialization'])) { - $buffer = "$eol <initialization>$eol"; - foreach ($table['initialization'] as $instruction) { - switch ($instruction['type']) { - case 'insert': - $buffer .= "$eol <insert>$eol"; - foreach ($instruction['data']['field'] as $field) { - $field_name = $field['name']; - - $buffer .= "$eol <field>$eol <name>$field_name</name>$eol"; - $buffer .= $this->writeExpression($field['group'], 5, $arguments); - $buffer .= " </field>$eol"; - } - $buffer .= "$eol </insert>$eol"; - break; - case 'update': - $buffer .= "$eol <update>$eol"; - foreach ($instruction['data']['field'] as $field) { - $field_name = $field['name']; - - $buffer .= "$eol <field>$eol <name>$field_name</name>$eol"; - $buffer .= $this->writeExpression($field['group'], 5, $arguments); - $buffer .= " </field>$eol"; - } - - if (!empty($instruction['data']['where']) - && is_array($instruction['data']['where']) - ) { - $buffer .= " <where>$eol"; - $buffer .= $this->writeExpression($instruction['data']['where'], 5, $arguments); - $buffer .= " </where>$eol"; - } - - $buffer .= "$eol </update>$eol"; - break; - case 'delete': - $buffer .= "$eol <delete>$eol$eol"; - if (!empty($instruction['data']['where']) - && is_array($instruction['data']['where']) - ) { - $buffer .= " <where>$eol"; - $buffer .= $this->writeExpression($instruction['data']['where'], 5, $arguments); - $buffer .= " </where>$eol"; - } - $buffer .= "$eol </delete>$eol"; - break; - } - } - $buffer .= "$eol </initialization>$eol"; - } - } - $buffer .= "$eol </table>$eol"; - if ($output) { - call_user_func($output, $buffer); - } else { - fwrite($fp, $buffer); - } - - if (isset($sequences[$table_name])) { - foreach ($sequences[$table_name] as $sequence) { - $result = $this->dumpSequence($database_definition['sequences'][$sequence], - $sequence, $eol, $dump); - if (PEAR::isError($result)) { - return $result; - } - - if ($output) { - call_user_func($output, $result); - } else { - fwrite($fp, $result); - } - } - } - } - } - - if (isset($sequences[''])) { - foreach ($sequences[''] as $sequence) { - $result = $this->dumpSequence($database_definition['sequences'][$sequence], - $sequence, $eol, $dump); - if (PEAR::isError($result)) { - return $result; - } - - if ($output) { - call_user_func($output, $result); - } else { - fwrite($fp, $result); - } - } - } - - $buffer = "$eol</database>$eol"; - if ($output) { - call_user_func($output, $buffer); - } else { - fwrite($fp, $buffer); - fclose($fp); - } - - return MDB2_OK; - } - - // }}} - // {{{ writeExpression() - - /** - * Dumps the structure of an element. Elements can be value, column, - * function or expression. - * - * @param array $element multi dimensional array that represents the parsed element - * of a DML instruction. - * @param integer $offset base indentation width - * @param array $arguments associative array that takes pairs of tag - * names and values that define dump options. - * - * @return string - * - * @access public - * @see MDB2_Schema_Writer::dumpDatabase() - */ - function writeExpression($element, $offset = 0, $arguments = null) - { - $eol = isset($arguments['end_of_line']) ? $arguments['end_of_line'] : "\n"; - $str = ''; - - $indent = str_repeat(' ', $offset); - $noffset = $offset + 1; - - switch ($element['type']) { - case 'value': - $str .= "$indent<value>".$this->_escapeSpecialChars($element['data'])."</value>$eol"; - break; - case 'column': - $str .= "$indent<column>".$this->_escapeSpecialChars($element['data'])."</column>$eol"; - break; - case 'function': - $str .= "$indent<function>$eol$indent <name>".$this->_escapeSpecialChars($element['data']['name'])."</name>$eol"; - - if (!empty($element['data']['arguments']) - && is_array($element['data']['arguments']) - ) { - foreach ($element['data']['arguments'] as $v) { - $str .= $this->writeExpression($v, $noffset, $arguments); - } - } - - $str .= "$indent</function>$eol"; - break; - case 'expression': - $str .= "$indent<expression>$eol"; - $str .= $this->writeExpression($element['data']['operants'][0], $noffset, $arguments); - $str .= "$indent <operator>".$element['data']['operator']."</operator>$eol"; - $str .= $this->writeExpression($element['data']['operants'][1], $noffset, $arguments); - $str .= "$indent</expression>$eol"; - break; - } - return $str; - } - - // }}} -} -?> diff --git a/3rdparty/PEAR.php b/3rdparty/PEAR.php deleted file mode 100644 index f832c0d49162c40c64ecc9b43762a58561f2c15b..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR.php +++ /dev/null @@ -1,1055 +0,0 @@ -<?php -// -// +--------------------------------------------------------------------+ -// | PEAR, the PHP Extension and Application Repository | -// +--------------------------------------------------------------------+ -// | 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: Sterling Hughes <sterling@php.net> | -// | Stig Bakken <ssb@php.net> | -// | Tomas V.V.Cox <cox@idecnet.com> | -// +--------------------------------------------------------------------+ -// -// $Id: PEAR.php,v 1.82.2.6 2005/01/01 05:24:51 cellog 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 = strtolower(get_class($this)); - if ($this->_debug) { - print "PEAR constructor called, class=$classname\n"; - } - if ($error_class !== null) { - $this->_error_class = $error_class; - } - while ($classname && strcasecmp($classname, "pear")) { - $destructor = "_$classname"; - if (method_exists($this, $destructor)) { - global $_PEAR_destructor_object_list; - $_PEAR_destructor_object_list[] = &$this; - if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) { - register_shutdown_function("_PEAR_call_destructors"); - $GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true; - } - 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", strtolower(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 - */ - static function isError($data, $code = null) - { - if ($data instanceof 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) && $this instanceof 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) && $this instanceof PEAR) { - return $this->raiseError($message, $code, null, null, $userinfo); - } else { - return PEAR::raiseError($message, $code, null, null, $userinfo); - } - } - - // }}} - function staticPushErrorHandling($mode, $options = null) - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - $def_mode = &$GLOBALS['_PEAR_default_error_mode']; - $def_options = &$GLOBALS['_PEAR_default_error_options']; - $stack[] = array($def_mode, $def_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: - $def_mode = $mode; - $def_options = $options; - break; - - case PEAR_ERROR_CALLBACK: - $def_mode = $mode; - // class/object method callback - if (is_callable($options)) { - $def_options = $options; - } else { - trigger_error("invalid error callback", E_USER_WARNING); - } - break; - - default: - trigger_error("invalid error mode", E_USER_WARNING); - break; - } - $stack[] = array($mode, $options); - return true; - } - - function staticPopErrorHandling() - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - $setmode = &$GLOBALS['_PEAR_default_error_mode']; - $setoptions = &$GLOBALS['_PEAR_default_error_options']; - array_pop($stack); - list($mode, $options) = $stack[sizeof($stack) - 1]; - array_pop($stack); - 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; - } - return true; - } - - // {{{ 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) && $this instanceof 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) && $this instanceof 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) && $this instanceof 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); - if (@PEAR::getStaticProperty('PEAR', 'destructlifo')) { - $_PEAR_destructor_object_list = array_reverse($_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")) { - if (@!PEAR::getStaticProperty('PEAR_Error', 'skiptrace')) { - $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 = (is_object($this->callback[0]) ? - strtolower(get_class($this->callback[0])) : - $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"]', - strtolower(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"]', - strtolower(get_class($this)), $this->message, $this->code, - implode("|", $modes), $levels[$this->level], - $this->error_message_prefix, - $this->userinfo); - } - - // }}} -} - -/* - * Local Variables: - * mode: php - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ -?> diff --git a/3rdparty/PEAR/Autoloader.php b/3rdparty/PEAR/Autoloader.php deleted file mode 100644 index de0278d61913c6e62fe8982f3efefc04591de6ed..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Autoloader.php +++ /dev/null @@ -1,208 +0,0 @@ -<?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: Stig Bakken <ssb@php.net> | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Autoloader.php,v 1.11 2004/02/27 02:21:29 cellog Exp $ - -if (!extension_loaded("overload")) { - // die hard without ext/overload - die("Rebuild PHP with the `overload' extension to use PEAR_Autoloader"); -} - -require_once "PEAR.php"; - -/** - * This class is for objects where you want to separate the code for - * some methods into separate classes. This is useful if you have a - * class with not-frequently-used methods that contain lots of code - * that you would like to avoid always parsing. - * - * The PEAR_Autoloader class provides autoloading and aggregation. - * The autoloading lets you set up in which classes the separated - * methods are found. Aggregation is the technique used to import new - * methods, an instance of each class providing separated methods is - * stored and called every time the aggregated method is called. - * - * @author Stig S�ther Bakken <ssb@php.net> - */ -class PEAR_Autoloader extends PEAR -{ - // {{{ properties - - /** - * Map of methods and classes where they are defined - * - * @var array - * - * @access private - */ - var $_autoload_map = array(); - - /** - * Map of methods and aggregate objects - * - * @var array - * - * @access private - */ - var $_method_map = array(); - - // }}} - // {{{ addAutoload() - - /** - * Add one or more autoload entries. - * - * @param string $method which method to autoload - * - * @param string $classname (optional) which class to find the method in. - * If the $method parameter is an array, this - * parameter may be omitted (and will be ignored - * if not), and the $method parameter will be - * treated as an associative array with method - * names as keys and class names as values. - * - * @return void - * - * @access public - */ - function addAutoload($method, $classname = null) - { - if (is_array($method)) { - array_walk($method, create_function('$a,&$b', '$b = strtolower($b);')); - $this->_autoload_map = array_merge($this->_autoload_map, $method); - } else { - $this->_autoload_map[strtolower($method)] = $classname; - } - } - - // }}} - // {{{ removeAutoload() - - /** - * Remove an autoload entry. - * - * @param string $method which method to remove the autoload entry for - * - * @return bool TRUE if an entry was removed, FALSE if not - * - * @access public - */ - function removeAutoload($method) - { - $method = strtolower($method); - $ok = isset($this->_autoload_map[$method]); - unset($this->_autoload_map[$method]); - return $ok; - } - - // }}} - // {{{ addAggregateObject() - - /** - * Add an aggregate object to this object. If the specified class - * is not defined, loading it will be attempted following PEAR's - * file naming scheme. All the methods in the class will be - * aggregated, except private ones (name starting with an - * underscore) and constructors. - * - * @param string $classname what class to instantiate for the object. - * - * @return void - * - * @access public - */ - function addAggregateObject($classname) - { - $classname = strtolower($classname); - if (!class_exists($classname)) { - $include_file = preg_replace('/[^a-z0-9]/i', '_', $classname); - include_once $include_file; - } - $obj =& new $classname; - $methods = get_class_methods($classname); - foreach ($methods as $method) { - // don't import priviate methods and constructors - if ($method{0} != '_' && $method != $classname) { - $this->_method_map[$method] = $obj; - } - } - } - - // }}} - // {{{ removeAggregateObject() - - /** - * Remove an aggregate object. - * - * @param string $classname the class of the object to remove - * - * @return bool TRUE if an object was removed, FALSE if not - * - * @access public - */ - function removeAggregateObject($classname) - { - $ok = false; - $classname = strtolower($classname); - reset($this->_method_map); - while (list($method, $obj) = each($this->_method_map)) { - if (is_a($obj, $classname)) { - unset($this->_method_map[$method]); - $ok = true; - } - } - return $ok; - } - - // }}} - // {{{ __call() - - /** - * Overloaded object call handler, called each time an - * undefined/aggregated method is invoked. This method repeats - * the call in the right aggregate object and passes on the return - * value. - * - * @param string $method which method that was called - * - * @param string $args An array of the parameters passed in the - * original call - * - * @return mixed The return value from the aggregated method, or a PEAR - * error if the called method was unknown. - */ - function __call($method, $args, &$retval) - { - $method = strtolower($method); - if (empty($this->_method_map[$method]) && isset($this->_autoload_map[$method])) { - $this->addAggregateObject($this->_autoload_map[$method]); - } - if (isset($this->_method_map[$method])) { - $retval = call_user_func_array(array($this->_method_map[$method], $method), $args); - return true; - } - return false; - } - - // }}} -} - -overload("PEAR_Autoloader"); - -?> diff --git a/3rdparty/PEAR/Builder.php b/3rdparty/PEAR/Builder.php deleted file mode 100644 index 4f6cc135d1ef825c92a4b89d683a601fdb09e0eb..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Builder.php +++ /dev/null @@ -1,426 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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. | -// +----------------------------------------------------------------------+ -// | Authors: Stig S�ther Bakken <ssb@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Builder.php,v 1.16.2.3 2005/02/17 17:55:01 cellog Exp $ - -require_once 'PEAR/Common.php'; - -/** - * Class to handle building (compiling) extensions. - * - * @author Stig S�ther Bakken <ssb@php.net> - */ -class PEAR_Builder extends PEAR_Common -{ - // {{{ properties - - var $php_api_version = 0; - var $zend_module_api_no = 0; - var $zend_extension_api_no = 0; - - var $extensions_built = array(); - - var $current_callback = null; - - // used for msdev builds - var $_lastline = null; - var $_firstline = null; - // }}} - // {{{ constructor - - /** - * PEAR_Builder constructor. - * - * @param object $ui user interface object (instance of PEAR_Frontend_*) - * - * @access public - */ - function PEAR_Builder(&$ui) - { - parent::PEAR_Common(); - $this->setFrontendObject($ui); - } - - // }}} - - // {{{ _build_win32() - - /** - * Build an extension from source on windows. - * requires msdev - */ - function _build_win32($descfile, $callback = null) - { - if (PEAR::isError($info = $this->infoFromDescriptionFile($descfile))) { - return $info; - } - $dir = dirname($descfile); - $old_cwd = getcwd(); - - if (!@chdir($dir)) { - return $this->raiseError("could not chdir to $dir"); - } - $this->log(2, "building in $dir"); - - $dsp = $info['package'].'.dsp'; - if (!@is_file("$dir/$dsp")) { - return $this->raiseError("The DSP $dsp does not exist."); - } - // XXX TODO: make release build type configurable - $command = 'msdev '.$dsp.' /MAKE "'.$info['package']. ' - Release"'; - - $this->current_callback = $callback; - $err = $this->_runCommand($command, array(&$this, 'msdevCallback')); - if (PEAR::isError($err)) { - return $err; - } - - // figure out the build platform and type - $platform = 'Win32'; - $buildtype = 'Release'; - if (preg_match('/.*?'.$info['package'].'\s-\s(\w+)\s(.*?)-+/i',$this->_firstline,$matches)) { - $platform = $matches[1]; - $buildtype = $matches[2]; - } - - if (preg_match('/(.*)?\s-\s(\d+).*?(\d+)/',$this->_lastline,$matches)) { - if ($matches[2]) { - // there were errors in the build - return $this->raiseError("There were errors during compilation."); - } - $out = $matches[1]; - } else { - return $this->raiseError("Did not understand the completion status returned from msdev.exe."); - } - - // msdev doesn't tell us the output directory :/ - // open the dsp, find /out and use that directory - $dsptext = join(file($dsp),''); - - // this regex depends on the build platform and type having been - // correctly identified above. - $regex ='/.*?!IF\s+"\$\(CFG\)"\s+==\s+("'. - $info['package'].'\s-\s'. - $platform.'\s'. - $buildtype.'").*?'. - '\/out:"(.*?)"/is'; - - if ($dsptext && preg_match($regex,$dsptext,$matches)) { - // what we get back is a relative path to the output file itself. - $outfile = realpath($matches[2]); - } else { - return $this->raiseError("Could not retrieve output information from $dsp."); - } - if (@copy($outfile, "$dir/$out")) { - $outfile = "$dir/$out"; - } - - $built_files[] = array( - 'file' => "$outfile", - 'php_api' => $this->php_api_version, - 'zend_mod_api' => $this->zend_module_api_no, - 'zend_ext_api' => $this->zend_extension_api_no, - ); - - return $built_files; - } - // }}} - - // {{{ msdevCallback() - function msdevCallback($what, $data) - { - if (!$this->_firstline) - $this->_firstline = $data; - $this->_lastline = $data; - } - // }}} - - // {{{ _harventInstDir - /** - * @param string - * @param string - * @param array - * @access private - */ - function _harvestInstDir($dest_prefix, $dirname, &$built_files) - { - $d = opendir($dirname); - if (!$d) - return false; - - $ret = true; - while (($ent = readdir($d)) !== false) { - if ($ent{0} == '.') - continue; - - $full = $dirname . DIRECTORY_SEPARATOR . $ent; - if (is_dir($full)) { - if (!$this->_harvestInstDir( - $dest_prefix . DIRECTORY_SEPARATOR . $ent, - $full, $built_files)) { - $ret = false; - break; - } - } else { - $dest = $dest_prefix . DIRECTORY_SEPARATOR . $ent; - $built_files[] = array( - 'file' => $full, - 'dest' => $dest, - 'php_api' => $this->php_api_version, - 'zend_mod_api' => $this->zend_module_api_no, - 'zend_ext_api' => $this->zend_extension_api_no, - ); - } - } - closedir($d); - return $ret; - } - - // }}} - - // {{{ build() - - /** - * Build an extension from source. Runs "phpize" in the source - * directory, but compiles in a temporary directory - * (/var/tmp/pear-build-USER/PACKAGE-VERSION). - * - * @param string $descfile path to XML package description file - * - * @param mixed $callback callback function used to report output, - * see PEAR_Builder::_runCommand for details - * - * @return array an array of associative arrays with built files, - * format: - * array( array( 'file' => '/path/to/ext.so', - * 'php_api' => YYYYMMDD, - * 'zend_mod_api' => YYYYMMDD, - * 'zend_ext_api' => YYYYMMDD ), - * ... ) - * - * @access public - * - * @see PEAR_Builder::_runCommand - * @see PEAR_Common::infoFromDescriptionFile - */ - function build($descfile, $callback = null) - { - if (PEAR_OS == "Windows") { - return $this->_build_win32($descfile,$callback); - } - if (PEAR_OS != 'Unix') { - return $this->raiseError("building extensions not supported on this platform"); - } - if (PEAR::isError($info = $this->infoFromDescriptionFile($descfile))) { - return $info; - } - $dir = dirname($descfile); - $old_cwd = getcwd(); - if (!@chdir($dir)) { - return $this->raiseError("could not chdir to $dir"); - } - $vdir = "$info[package]-$info[version]"; - if (is_dir($vdir)) { - chdir($vdir); - } - $dir = getcwd(); - $this->log(2, "building in $dir"); - $this->current_callback = $callback; - putenv('PATH=' . $this->config->get('bin_dir') . ':' . getenv('PATH')); - $err = $this->_runCommand("phpize", array(&$this, 'phpizeCallback')); - if (PEAR::isError($err)) { - return $err; - } - if (!$err) { - return $this->raiseError("`phpize' failed"); - } - - // {{{ start of interactive part - $configure_command = "$dir/configure"; - if (isset($info['configure_options'])) { - foreach ($info['configure_options'] as $o) { - list($r) = $this->ui->userDialog('build', - array($o['prompt']), - array('text'), - array(@$o['default'])); - if (substr($o['name'], 0, 5) == 'with-' && - ($r == 'yes' || $r == 'autodetect')) { - $configure_command .= " --$o[name]"; - } else { - $configure_command .= " --$o[name]=".trim($r); - } - } - } - // }}} end of interactive part - - // FIXME make configurable - if(!$user=getenv('USER')){ - $user='defaultuser'; - } - $build_basedir = "/var/tmp/pear-build-$user"; - $build_dir = "$build_basedir/$info[package]-$info[version]"; - $inst_dir = "$build_basedir/install-$info[package]-$info[version]"; - $this->log(1, "building in $build_dir"); - if (is_dir($build_dir)) { - System::rm('-rf', $build_dir); - } - if (!System::mkDir(array('-p', $build_dir))) { - return $this->raiseError("could not create build dir: $build_dir"); - } - $this->addTempFile($build_dir); - if (!System::mkDir(array('-p', $inst_dir))) { - return $this->raiseError("could not create temporary install dir: $inst_dir"); - } - $this->addTempFile($inst_dir); - - if (getenv('MAKE')) { - $make_command = getenv('MAKE'); - } else { - $make_command = 'make'; - } - $to_run = array( - $configure_command, - $make_command, - "$make_command INSTALL_ROOT=\"$inst_dir\" install", - "find \"$inst_dir\" -ls" - ); - if (!@chdir($build_dir)) { - return $this->raiseError("could not chdir to $build_dir"); - } - putenv('PHP_PEAR_VERSION=@PEAR-VER@'); - foreach ($to_run as $cmd) { - $err = $this->_runCommand($cmd, $callback); - if (PEAR::isError($err)) { - chdir($old_cwd); - return $err; - } - if (!$err) { - chdir($old_cwd); - return $this->raiseError("`$cmd' failed"); - } - } - if (!($dp = opendir("modules"))) { - chdir($old_cwd); - return $this->raiseError("no `modules' directory found"); - } - $built_files = array(); - $prefix = exec("php-config --prefix"); - $this->_harvestInstDir($prefix, $inst_dir . DIRECTORY_SEPARATOR . $prefix, $built_files); - chdir($old_cwd); - return $built_files; - } - - // }}} - // {{{ phpizeCallback() - - /** - * Message callback function used when running the "phpize" - * program. Extracts the API numbers used. Ignores other message - * types than "cmdoutput". - * - * @param string $what the type of message - * @param mixed $data the message - * - * @return void - * - * @access public - */ - function phpizeCallback($what, $data) - { - if ($what != 'cmdoutput') { - return; - } - $this->log(1, rtrim($data)); - if (preg_match('/You should update your .aclocal.m4/', $data)) { - return; - } - $matches = array(); - if (preg_match('/^\s+(\S[^:]+):\s+(\d{8})/', $data, $matches)) { - $member = preg_replace('/[^a-z]/', '_', strtolower($matches[1])); - $apino = (int)$matches[2]; - if (isset($this->$member)) { - $this->$member = $apino; - //$msg = sprintf("%-22s : %d", $matches[1], $apino); - //$this->log(1, $msg); - } - } - } - - // }}} - // {{{ _runCommand() - - /** - * Run an external command, using a message callback to report - * output. The command will be run through popen and output is - * reported for every line with a "cmdoutput" message with the - * line string, including newlines, as payload. - * - * @param string $command the command to run - * - * @param mixed $callback (optional) function to use as message - * callback - * - * @return bool whether the command was successful (exit code 0 - * means success, any other means failure) - * - * @access private - */ - function _runCommand($command, $callback = null) - { - $this->log(1, "running: $command"); - $pp = @popen("$command 2>&1", "r"); - if (!$pp) { - return $this->raiseError("failed to run `$command'"); - } - if ($callback && $callback[0]->debug == 1) { - $olddbg = $callback[0]->debug; - $callback[0]->debug = 2; - } - - while ($line = fgets($pp, 1024)) { - if ($callback) { - call_user_func($callback, 'cmdoutput', $line); - } else { - $this->log(2, rtrim($line)); - } - } - if ($callback && isset($olddbg)) { - $callback[0]->debug = $olddbg; - } - $exitcode = @pclose($pp); - return ($exitcode == 0); - } - - // }}} - // {{{ log() - - function log($level, $msg) - { - if ($this->current_callback) { - if ($this->debug >= $level) { - call_user_func($this->current_callback, 'output', $msg); - } - return; - } - return PEAR_Common::log($level, $msg); - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Command.php b/3rdparty/PEAR/Command.php deleted file mode 100644 index 2ea68743d2063e01a60611409efd859e8135ce2c..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Command.php +++ /dev/null @@ -1,398 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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: Stig Bakken <ssb@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Command.php,v 1.24 2004/05/16 15:43:30 pajoye Exp $ - - -require_once "PEAR.php"; - -/** - * List of commands and what classes they are implemented in. - * @var array command => implementing class - */ -$GLOBALS['_PEAR_Command_commandlist'] = array(); - -/** - * List of shortcuts to common commands. - * @var array shortcut => command - */ -$GLOBALS['_PEAR_Command_shortcuts'] = array(); - -/** - * Array of command objects - * @var array class => object - */ -$GLOBALS['_PEAR_Command_objects'] = array(); - -/** - * Which user interface class is being used. - * @var string class name - */ -$GLOBALS['_PEAR_Command_uiclass'] = 'PEAR_Frontend_CLI'; - -/** - * Instance of $_PEAR_Command_uiclass. - * @var object - */ -$GLOBALS['_PEAR_Command_uiobject'] = null; - -/** - * PEAR command class, a simple factory class for administrative - * commands. - * - * How to implement command classes: - * - * - The class must be called PEAR_Command_Nnn, installed in the - * "PEAR/Common" subdir, with a method called getCommands() that - * returns an array of the commands implemented by the class (see - * PEAR/Command/Install.php for an example). - * - * - The class must implement a run() function that is called with three - * params: - * - * (string) command name - * (array) assoc array with options, freely defined by each - * command, for example: - * array('force' => true) - * (array) list of the other parameters - * - * The run() function returns a PEAR_CommandResponse object. Use - * these methods to get information: - * - * int getStatus() Returns PEAR_COMMAND_(SUCCESS|FAILURE|PARTIAL) - * *_PARTIAL means that you need to issue at least - * one more command to complete the operation - * (used for example for validation steps). - * - * string getMessage() Returns a message for the user. Remember, - * no HTML or other interface-specific markup. - * - * If something unexpected happens, run() returns a PEAR error. - * - * - DON'T OUTPUT ANYTHING! Return text for output instead. - * - * - DON'T USE HTML! The text you return will be used from both Gtk, - * web and command-line interfaces, so for now, keep everything to - * plain text. - * - * - DON'T USE EXIT OR DIE! Always use pear errors. From static - * classes do PEAR::raiseError(), from other classes do - * $this->raiseError(). - */ -class PEAR_Command -{ - // {{{ factory() - - /** - * Get the right object for executing a command. - * - * @param string $command The name of the command - * @param object $config Instance of PEAR_Config object - * - * @return object the command object or a PEAR error - * - * @access public - * @static - */ - function factory($command, &$config) - { - if (empty($GLOBALS['_PEAR_Command_commandlist'])) { - PEAR_Command::registerCommands(); - } - if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { - $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; - } - if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { - return PEAR::raiseError("unknown command `$command'"); - } - $class = $GLOBALS['_PEAR_Command_commandlist'][$command]; - if (!class_exists($class)) { - return PEAR::raiseError("unknown command `$command'"); - } - $ui =& PEAR_Command::getFrontendObject(); - $obj = &new $class($ui, $config); - return $obj; - } - - // }}} - // {{{ & getFrontendObject() - - /** - * Get instance of frontend object. - * - * @return object - * @static - */ - function &getFrontendObject() - { - if (empty($GLOBALS['_PEAR_Command_uiobject'])) { - $GLOBALS['_PEAR_Command_uiobject'] = &new $GLOBALS['_PEAR_Command_uiclass']; - } - return $GLOBALS['_PEAR_Command_uiobject']; - } - - // }}} - // {{{ & setFrontendClass() - - /** - * Load current frontend class. - * - * @param string $uiclass Name of class implementing the frontend - * - * @return object the frontend object, or a PEAR error - * @static - */ - function &setFrontendClass($uiclass) - { - if (is_object($GLOBALS['_PEAR_Command_uiobject']) && - is_a($GLOBALS['_PEAR_Command_uiobject'], $uiclass)) { - return $GLOBALS['_PEAR_Command_uiobject']; - } - if (!class_exists($uiclass)) { - $file = str_replace('_', '/', $uiclass) . '.php'; - if (PEAR_Command::isIncludeable($file)) { - include_once $file; - } - } - if (class_exists($uiclass)) { - $obj = &new $uiclass; - // quick test to see if this class implements a few of the most - // important frontend methods - if (method_exists($obj, 'userConfirm')) { - $GLOBALS['_PEAR_Command_uiobject'] = &$obj; - $GLOBALS['_PEAR_Command_uiclass'] = $uiclass; - return $obj; - } else { - $err = PEAR::raiseError("not a frontend class: $uiclass"); - return $err; - } - } - $err = PEAR::raiseError("no such class: $uiclass"); - return $err; - } - - // }}} - // {{{ setFrontendType() - - // }}} - // {{{ isIncludeable() - - /** - * @param string $path relative or absolute include path - * @return boolean - * @static - */ - function isIncludeable($path) - { - if (file_exists($path) && is_readable($path)) { - return true; - } - $ipath = explode(PATH_SEPARATOR, ini_get('include_path')); - foreach ($ipath as $include) { - $test = realpath($include . DIRECTORY_SEPARATOR . $path); - if (file_exists($test) && is_readable($test)) { - return true; - } - } - return false; - } - - /** - * Set current frontend. - * - * @param string $uitype Name of the frontend type (for example "CLI") - * - * @return object the frontend object, or a PEAR error - * @static - */ - function setFrontendType($uitype) - { - $uiclass = 'PEAR_Frontend_' . $uitype; - return PEAR_Command::setFrontendClass($uiclass); - } - - // }}} - // {{{ registerCommands() - - /** - * Scan through the Command directory looking for classes - * and see what commands they implement. - * - * @param bool (optional) if FALSE (default), the new list of - * commands should replace the current one. If TRUE, - * new entries will be merged with old. - * - * @param string (optional) where (what directory) to look for - * classes, defaults to the Command subdirectory of - * the directory from where this file (__FILE__) is - * included. - * - * @return bool TRUE on success, a PEAR error on failure - * - * @access public - * @static - */ - function registerCommands($merge = false, $dir = null) - { - if ($dir === null) { - $dir = dirname(__FILE__) . '/Command'; - } - $dp = @opendir($dir); - if (empty($dp)) { - return PEAR::raiseError("registerCommands: opendir($dir) failed"); - } - if (!$merge) { - $GLOBALS['_PEAR_Command_commandlist'] = array(); - } - while ($entry = readdir($dp)) { - if ($entry{0} == '.' || substr($entry, -4) != '.php' || $entry == 'Common.php') { - continue; - } - $class = "PEAR_Command_".substr($entry, 0, -4); - $file = "$dir/$entry"; - include_once $file; - // List of commands - if (empty($GLOBALS['_PEAR_Command_objects'][$class])) { - $GLOBALS['_PEAR_Command_objects'][$class] = &new $class($ui, $config); - } - $implements = $GLOBALS['_PEAR_Command_objects'][$class]->getCommands(); - foreach ($implements as $command => $desc) { - $GLOBALS['_PEAR_Command_commandlist'][$command] = $class; - $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc; - } - $shortcuts = $GLOBALS['_PEAR_Command_objects'][$class]->getShortcuts(); - foreach ($shortcuts as $shortcut => $command) { - $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command; - } - } - @closedir($dp); - return true; - } - - // }}} - // {{{ getCommands() - - /** - * Get the list of currently supported commands, and what - * classes implement them. - * - * @return array command => implementing class - * - * @access public - * @static - */ - function getCommands() - { - if (empty($GLOBALS['_PEAR_Command_commandlist'])) { - PEAR_Command::registerCommands(); - } - return $GLOBALS['_PEAR_Command_commandlist']; - } - - // }}} - // {{{ getShortcuts() - - /** - * Get the list of command shortcuts. - * - * @return array shortcut => command - * - * @access public - * @static - */ - function getShortcuts() - { - if (empty($GLOBALS['_PEAR_Command_shortcuts'])) { - PEAR_Command::registerCommands(); - } - return $GLOBALS['_PEAR_Command_shortcuts']; - } - - // }}} - // {{{ getGetoptArgs() - - /** - * Compiles arguments for getopt. - * - * @param string $command command to get optstring for - * @param string $short_args (reference) short getopt format - * @param array $long_args (reference) long getopt format - * - * @return void - * - * @access public - * @static - */ - function getGetoptArgs($command, &$short_args, &$long_args) - { - if (empty($GLOBALS['_PEAR_Command_commandlist'])) { - PEAR_Command::registerCommands(); - } - if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { - return null; - } - $class = $GLOBALS['_PEAR_Command_commandlist'][$command]; - $obj = &$GLOBALS['_PEAR_Command_objects'][$class]; - return $obj->getGetoptArgs($command, $short_args, $long_args); - } - - // }}} - // {{{ getDescription() - - /** - * Get description for a command. - * - * @param string $command Name of the command - * - * @return string command description - * - * @access public - * @static - */ - function getDescription($command) - { - if (!isset($GLOBALS['_PEAR_Command_commanddesc'][$command])) { - return null; - } - return $GLOBALS['_PEAR_Command_commanddesc'][$command]; - } - - // }}} - // {{{ getHelp() - - /** - * Get help for command. - * - * @param string $command Name of the command to return help for - * - * @access public - * @static - */ - function getHelp($command) - { - $cmds = PEAR_Command::getCommands(); - if (isset($cmds[$command])) { - $class = $cmds[$command]; - return $GLOBALS['_PEAR_Command_objects'][$class]->getHelp($command); - } - return false; - } - // }}} -} - -?> diff --git a/3rdparty/PEAR/Command/Auth.php b/3rdparty/PEAR/Command/Auth.php deleted file mode 100644 index 0b9d3d3965d46ab1c474794bf6f250fed3e7ea6f..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Command/Auth.php +++ /dev/null @@ -1,155 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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: Stig Bakken <ssb@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Auth.php,v 1.15 2004/01/08 17:33:13 sniper Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Remote.php"; -require_once "PEAR/Config.php"; - -/** - * PEAR commands for managing configuration data. - * - */ -class PEAR_Command_Auth extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'login' => array( - 'summary' => 'Connects and authenticates to remote server', - 'shortcut' => 'li', - 'function' => 'doLogin', - 'options' => array(), - 'doc' => ' -Log in to the remote server. To use remote functions in the installer -that require any kind of privileges, you need to log in first. The -username and password you enter here will be stored in your per-user -PEAR configuration (~/.pearrc on Unix-like systems). After logging -in, your username and password will be sent along in subsequent -operations on the remote server.', - ), - 'logout' => array( - 'summary' => 'Logs out from the remote server', - 'shortcut' => 'lo', - 'function' => 'doLogout', - 'options' => array(), - 'doc' => ' -Logs out from the remote server. This command does not actually -connect to the remote server, it only deletes the stored username and -password from your user configuration.', - ) - - ); - - // }}} - - // {{{ constructor - - /** - * PEAR_Command_Auth constructor. - * - * @access public - */ - function PEAR_Command_Auth(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doLogin() - - /** - * Execute the 'login' command. - * - * @param string $command command name - * - * @param array $options option_name => value - * - * @param array $params list of additional parameters - * - * @return bool TRUE on success, FALSE for unknown commands, or - * a PEAR error on failure - * - * @access public - */ - function doLogin($command, $options, $params) - { - $server = $this->config->get('master_server'); - $remote = new PEAR_Remote($this->config); - $username = $this->config->get('username'); - if (empty($username)) { - $username = @$_ENV['USER']; - } - $this->ui->outputData("Logging in to $server.", $command); - - list($username, $password) = $this->ui->userDialog( - $command, - array('Username', 'Password'), - array('text', 'password'), - array($username, '') - ); - $username = trim($username); - $password = trim($password); - - $this->config->set('username', $username); - $this->config->set('password', $password); - - $remote->expectError(401); - $ok = $remote->call('logintest'); - $remote->popExpect(); - if ($ok === true) { - $this->ui->outputData("Logged in.", $command); - $this->config->store(); - } else { - return $this->raiseError("Login failed!"); - } - - } - - // }}} - // {{{ doLogout() - - /** - * Execute the 'logout' command. - * - * @param string $command command name - * - * @param array $options option_name => value - * - * @param array $params list of additional parameters - * - * @return bool TRUE on success, FALSE for unknown commands, or - * a PEAR error on failure - * - * @access public - */ - function doLogout($command, $options, $params) - { - $server = $this->config->get('master_server'); - $this->ui->outputData("Logging out from $server.", $command); - $this->config->remove('username'); - $this->config->remove('password'); - $this->config->store(); - } - - // }}} -} - -?> \ No newline at end of file diff --git a/3rdparty/PEAR/Command/Build.php b/3rdparty/PEAR/Command/Build.php deleted file mode 100644 index 2ecbbc92f5fe38a3f4f48ac33f9ec5232ea1590f..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Command/Build.php +++ /dev/null @@ -1,89 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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: Stig Bakken <ssb@php.net> | -// | Tomas V.V.Cox <cox@idecnet.com> | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Build.php,v 1.9 2004/01/08 17:33:13 sniper Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Builder.php"; - -/** - * PEAR commands for building extensions. - * - */ -class PEAR_Command_Build extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'build' => array( - 'summary' => 'Build an Extension From C Source', - 'function' => 'doBuild', - 'shortcut' => 'b', - 'options' => array(), - 'doc' => '[package.xml] -Builds one or more extensions contained in a package.' - ), - ); - - // }}} - - // {{{ constructor - - /** - * PEAR_Command_Build constructor. - * - * @access public - */ - function PEAR_Command_Build(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doBuild() - - function doBuild($command, $options, $params) - { - if (sizeof($params) < 1) { - $params[0] = 'package.xml'; - } - $builder = &new PEAR_Builder($this->ui); - $this->debug = $this->config->get('verbose'); - $err = $builder->build($params[0], array(&$this, 'buildCallback')); - if (PEAR::isError($err)) { - return $err; - } - return true; - } - - // }}} - // {{{ buildCallback() - - function buildCallback($what, $data) - { - if (($what == 'cmdoutput' && $this->debug > 1) || - ($what == 'output' && $this->debug > 0)) { - $this->ui->outputData(rtrim($data), 'build'); - } - } - - // }}} -} diff --git a/3rdparty/PEAR/Command/Common.php b/3rdparty/PEAR/Command/Common.php deleted file mode 100644 index c6ace694caf92c625b8bd64647f965c5194d3206..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Command/Common.php +++ /dev/null @@ -1,249 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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: Stig S�ther Bakken <ssb@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php,v 1.24 2004/01/08 17:33:13 sniper Exp $ - -require_once "PEAR.php"; - -class PEAR_Command_Common extends PEAR -{ - // {{{ properties - - /** - * PEAR_Config object used to pass user system and configuration - * on when executing commands - * - * @var object - */ - var $config; - - /** - * User Interface object, for all interaction with the user. - * @var object - */ - var $ui; - - var $_deps_rel_trans = array( - 'lt' => '<', - 'le' => '<=', - 'eq' => '=', - 'ne' => '!=', - 'gt' => '>', - 'ge' => '>=', - 'has' => '==' - ); - - var $_deps_type_trans = array( - 'pkg' => 'package', - 'extension' => 'extension', - 'php' => 'PHP', - 'prog' => 'external program', - 'ldlib' => 'external library for linking', - 'rtlib' => 'external runtime library', - 'os' => 'operating system', - 'websrv' => 'web server', - 'sapi' => 'SAPI backend' - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Common constructor. - * - * @access public - */ - function PEAR_Command_Common(&$ui, &$config) - { - parent::PEAR(); - $this->config = &$config; - $this->ui = &$ui; - } - - // }}} - - // {{{ getCommands() - - /** - * Return a list of all the commands defined by this class. - * @return array list of commands - * @access public - */ - function getCommands() - { - $ret = array(); - foreach (array_keys($this->commands) as $command) { - $ret[$command] = $this->commands[$command]['summary']; - } - return $ret; - } - - // }}} - // {{{ getShortcuts() - - /** - * Return a list of all the command shortcuts defined by this class. - * @return array shortcut => command - * @access public - */ - function getShortcuts() - { - $ret = array(); - foreach (array_keys($this->commands) as $command) { - if (isset($this->commands[$command]['shortcut'])) { - $ret[$this->commands[$command]['shortcut']] = $command; - } - } - return $ret; - } - - // }}} - // {{{ getOptions() - - function getOptions($command) - { - return @$this->commands[$command]['options']; - } - - // }}} - // {{{ getGetoptArgs() - - function getGetoptArgs($command, &$short_args, &$long_args) - { - $short_args = ""; - $long_args = array(); - if (empty($this->commands[$command])) { - return; - } - reset($this->commands[$command]); - while (list($option, $info) = each($this->commands[$command]['options'])) { - $larg = $sarg = ''; - if (isset($info['arg'])) { - if ($info['arg']{0} == '(') { - $larg = '=='; - $sarg = '::'; - $arg = substr($info['arg'], 1, -1); - } else { - $larg = '='; - $sarg = ':'; - $arg = $info['arg']; - } - } - if (isset($info['shortopt'])) { - $short_args .= $info['shortopt'] . $sarg; - } - $long_args[] = $option . $larg; - } - } - - // }}} - // {{{ getHelp() - /** - * Returns the help message for the given command - * - * @param string $command The command - * @return mixed A fail string if the command does not have help or - * a two elements array containing [0]=>help string, - * [1]=> help string for the accepted cmd args - */ - function getHelp($command) - { - $config = &PEAR_Config::singleton(); - $help = @$this->commands[$command]['doc']; - if (empty($help)) { - // XXX (cox) Fallback to summary if there is no doc (show both?) - if (!$help = @$this->commands[$command]['summary']) { - return "No help for command \"$command\""; - } - } - if (preg_match_all('/{config\s+([^\}]+)}/e', $help, $matches)) { - foreach($matches[0] as $k => $v) { - $help = preg_replace("/$v/", $config->get($matches[1][$k]), $help); - } - } - return array($help, $this->getHelpArgs($command)); - } - - // }}} - // {{{ getHelpArgs() - /** - * Returns the help for the accepted arguments of a command - * - * @param string $command - * @return string The help string - */ - function getHelpArgs($command) - { - if (isset($this->commands[$command]['options']) && - count($this->commands[$command]['options'])) - { - $help = "Options:\n"; - foreach ($this->commands[$command]['options'] as $k => $v) { - if (isset($v['arg'])) { - if ($v['arg']{0} == '(') { - $arg = substr($v['arg'], 1, -1); - $sapp = " [$arg]"; - $lapp = "[=$arg]"; - } else { - $sapp = " $v[arg]"; - $lapp = "=$v[arg]"; - } - } else { - $sapp = $lapp = ""; - } - if (isset($v['shortopt'])) { - $s = $v['shortopt']; - @$help .= " -$s$sapp, --$k$lapp\n"; - } else { - @$help .= " --$k$lapp\n"; - } - $p = " "; - $doc = rtrim(str_replace("\n", "\n$p", $v['doc'])); - $help .= " $doc\n"; - } - return $help; - } - return null; - } - - // }}} - // {{{ run() - - function run($command, $options, $params) - { - $func = @$this->commands[$command]['function']; - if (empty($func)) { - // look for shortcuts - foreach (array_keys($this->commands) as $cmd) { - if (@$this->commands[$cmd]['shortcut'] == $command) { - $command = $cmd; - $func = @$this->commands[$command]['function']; - if (empty($func)) { - return $this->raiseError("unknown command `$command'"); - } - break; - } - } - } - return $this->$func($command, $options, $params); - } - - // }}} -} - -?> \ No newline at end of file diff --git a/3rdparty/PEAR/Command/Config.php b/3rdparty/PEAR/Command/Config.php deleted file mode 100644 index 474a2345170c6f217da573e45a33c1e11a88d7d8..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Command/Config.php +++ /dev/null @@ -1,225 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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: Stig Bakken <ssb@php.net> | -// | Tomas V.V.Cox <cox@idecnet.com> | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Config.php,v 1.27 2004/06/15 16:48:49 pajoye Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Config.php"; - -/** - * PEAR commands for managing configuration data. - * - */ -class PEAR_Command_Config extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'config-show' => array( - 'summary' => 'Show All Settings', - 'function' => 'doConfigShow', - 'shortcut' => 'csh', - 'options' => array(), - 'doc' => ' -Displays all configuration values. An optional argument -may be used to tell which configuration layer to display. Valid -configuration layers are "user", "system" and "default". -', - ), - 'config-get' => array( - 'summary' => 'Show One Setting', - 'function' => 'doConfigGet', - 'shortcut' => 'cg', - 'options' => array(), - 'doc' => '<parameter> [layer] -Displays the value of one configuration parameter. The -first argument is the name of the parameter, an optional second argument -may be used to tell which configuration layer to look in. Valid configuration -layers are "user", "system" and "default". If no layer is specified, a value -will be picked from the first layer that defines the parameter, in the order -just specified. -', - ), - 'config-set' => array( - 'summary' => 'Change Setting', - 'function' => 'doConfigSet', - 'shortcut' => 'cs', - 'options' => array(), - 'doc' => '<parameter> <value> [layer] -Sets the value of one configuration parameter. The first argument is -the name of the parameter, the second argument is the new value. Some -parameters are subject to validation, and the command will fail with -an error message if the new value does not make sense. An optional -third argument may be used to specify in which layer to set the -configuration parameter. The default layer is "user". -', - ), - 'config-help' => array( - 'summary' => 'Show Information About Setting', - 'function' => 'doConfigHelp', - 'shortcut' => 'ch', - 'options' => array(), - 'doc' => '[parameter] -Displays help for a configuration parameter. Without arguments it -displays help for all configuration parameters. -', - ), - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Config constructor. - * - * @access public - */ - function PEAR_Command_Config(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doConfigShow() - - function doConfigShow($command, $options, $params) - { - // $params[0] -> the layer - if ($error = $this->_checkLayer(@$params[0])) { - return $this->raiseError($error); - } - $keys = $this->config->getKeys(); - sort($keys); - $data = array('caption' => 'Configuration:'); - foreach ($keys as $key) { - $type = $this->config->getType($key); - $value = $this->config->get($key, @$params[0]); - if ($type == 'password' && $value) { - $value = '********'; - } - if ($value === false) { - $value = 'false'; - } elseif ($value === true) { - $value = 'true'; - } - $data['data'][$this->config->getGroup($key)][] = array($this->config->getPrompt($key) , $key, $value); - } - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doConfigGet() - - function doConfigGet($command, $options, $params) - { - // $params[0] -> the parameter - // $params[1] -> the layer - if ($error = $this->_checkLayer(@$params[1])) { - return $this->raiseError($error); - } - if (sizeof($params) < 1 || sizeof($params) > 2) { - return $this->raiseError("config-get expects 1 or 2 parameters"); - } elseif (sizeof($params) == 1) { - $this->ui->outputData($this->config->get($params[0]), $command); - } else { - $data = $this->config->get($params[0], $params[1]); - $this->ui->outputData($data, $command); - } - return true; - } - - // }}} - // {{{ doConfigSet() - - function doConfigSet($command, $options, $params) - { - // $param[0] -> a parameter to set - // $param[1] -> the value for the parameter - // $param[2] -> the layer - $failmsg = ''; - if (sizeof($params) < 2 || sizeof($params) > 3) { - $failmsg .= "config-set expects 2 or 3 parameters"; - return PEAR::raiseError($failmsg); - } - if ($error = $this->_checkLayer(@$params[2])) { - $failmsg .= $error; - return PEAR::raiseError($failmsg); - } - if (!call_user_func_array(array(&$this->config, 'set'), $params)) - { - $failmsg = "config-set (" . implode(", ", $params) . ") failed"; - } else { - $this->config->store(); - } - if ($failmsg) { - return $this->raiseError($failmsg); - } - return true; - } - - // }}} - // {{{ doConfigHelp() - - function doConfigHelp($command, $options, $params) - { - if (empty($params)) { - $params = $this->config->getKeys(); - } - $data['caption'] = "Config help" . ((count($params) == 1) ? " for $params[0]" : ''); - $data['headline'] = array('Name', 'Type', 'Description'); - $data['border'] = true; - foreach ($params as $name) { - $type = $this->config->getType($name); - $docs = $this->config->getDocs($name); - if ($type == 'set') { - $docs = rtrim($docs) . "\nValid set: " . - implode(' ', $this->config->getSetValues($name)); - } - $data['data'][] = array($name, $type, $docs); - } - $this->ui->outputData($data, $command); - } - - // }}} - // {{{ _checkLayer() - - /** - * Checks if a layer is defined or not - * - * @param string $layer The layer to search for - * @return mixed False on no error or the error message - */ - function _checkLayer($layer = null) - { - if (!empty($layer) && $layer != 'default') { - $layers = $this->config->getLayers(); - if (!in_array($layer, $layers)) { - return " only the layers: \"" . implode('" or "', $layers) . "\" are supported"; - } - } - return false; - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Command/Install.php b/3rdparty/PEAR/Command/Install.php deleted file mode 100644 index dce52f017e2fe0397c55678db37a0ac14e69d1f2..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Command/Install.php +++ /dev/null @@ -1,470 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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: Stig S�ther Bakken <ssb@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Install.php,v 1.53.2.1 2004/10/19 04:08:42 cellog Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Installer.php"; - -/** - * PEAR commands for installation or deinstallation/upgrading of - * packages. - * - */ -class PEAR_Command_Install extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'install' => array( - 'summary' => 'Install Package', - 'function' => 'doInstall', - 'shortcut' => 'i', - 'options' => array( - 'force' => array( - 'shortopt' => 'f', - 'doc' => 'will overwrite newer installed packages', - ), - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, install anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not install files, only register the package as installed', - ), - 'soft' => array( - 'shortopt' => 's', - 'doc' => 'soft install, fail silently, or upgrade if already installed', - ), - 'nobuild' => array( - 'shortopt' => 'B', - 'doc' => 'don\'t build C extensions', - ), - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'request uncompressed files when downloading', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - 'alldeps' => array( - 'shortopt' => 'a', - 'doc' => 'install all required and optional dependencies', - ), - 'onlyreqdeps' => array( - 'shortopt' => 'o', - 'doc' => 'install all required dependencies', - ), - ), - 'doc' => '<package> ... -Installs one or more PEAR packages. You can specify a package to -install in four ways: - -"Package-1.0.tgz" : installs from a local file - -"http://example.com/Package-1.0.tgz" : installs from -anywhere on the net. - -"package.xml" : installs the package described in -package.xml. Useful for testing, or for wrapping a PEAR package in -another package manager such as RPM. - -"Package" : queries your configured server -({config master_server}) and downloads the newest package with -the preferred quality/state ({config preferred_state}). - -More than one package may be specified at once. It is ok to mix these -four ways of specifying packages. -'), - 'upgrade' => array( - 'summary' => 'Upgrade Package', - 'function' => 'doInstall', - 'shortcut' => 'up', - 'options' => array( - 'force' => array( - 'shortopt' => 'f', - 'doc' => 'overwrite newer installed packages', - ), - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, upgrade anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not install files, only register the package as upgraded', - ), - 'nobuild' => array( - 'shortopt' => 'B', - 'doc' => 'don\'t build C extensions', - ), - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'request uncompressed files when downloading', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - 'alldeps' => array( - 'shortopt' => 'a', - 'doc' => 'install all required and optional dependencies', - ), - 'onlyreqdeps' => array( - 'shortopt' => 'o', - 'doc' => 'install all required dependencies', - ), - ), - 'doc' => '<package> ... -Upgrades one or more PEAR packages. See documentation for the -"install" command for ways to specify a package. - -When upgrading, your package will be updated if the provided new -package has a higher version number (use the -f option if you need to -upgrade anyway). - -More than one package may be specified at once. -'), - 'upgrade-all' => array( - 'summary' => 'Upgrade All Packages', - 'function' => 'doInstall', - 'shortcut' => 'ua', - 'options' => array( - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, upgrade anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not install files, only register the package as upgraded', - ), - 'nobuild' => array( - 'shortopt' => 'B', - 'doc' => 'don\'t build C extensions', - ), - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'request uncompressed files when downloading', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - ), - 'doc' => ' -Upgrades all packages that have a newer release available. Upgrades are -done only if there is a release available of the state specified in -"preferred_state" (currently {config preferred_state}), or a state considered -more stable. -'), - 'uninstall' => array( - 'summary' => 'Un-install Package', - 'function' => 'doUninstall', - 'shortcut' => 'un', - 'options' => array( - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, uninstall anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not remove files, only register the packages as not installed', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - ), - 'doc' => '<package> ... -Uninstalls one or more PEAR packages. More than one package may be -specified at once. -'), - 'bundle' => array( - 'summary' => 'Unpacks a Pecl Package', - 'function' => 'doBundle', - 'shortcut' => 'bun', - 'options' => array( - 'destination' => array( - 'shortopt' => 'd', - 'arg' => 'DIR', - 'doc' => 'Optional destination directory for unpacking (defaults to current path or "ext" if exists)', - ), - 'force' => array( - 'shortopt' => 'f', - 'doc' => 'Force the unpacking even if there were errors in the package', - ), - ), - 'doc' => '<package> -Unpacks a Pecl Package into the selected location. It will download the -package if needed. -'), - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Install constructor. - * - * @access public - */ - function PEAR_Command_Install(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doInstall() - - function doInstall($command, $options, $params) - { - require_once 'PEAR/Downloader.php'; - if (empty($this->installer)) { - $this->installer = &new PEAR_Installer($this->ui); - } - if ($command == 'upgrade') { - $options['upgrade'] = true; - } - if ($command == 'upgrade-all') { - include_once "PEAR/Remote.php"; - $options['upgrade'] = true; - $remote = &new PEAR_Remote($this->config); - $state = $this->config->get('preferred_state'); - if (empty($state) || $state == 'any') { - $latest = $remote->call("package.listLatestReleases"); - } else { - $latest = $remote->call("package.listLatestReleases", $state); - } - if (PEAR::isError($latest)) { - return $latest; - } - $reg = new PEAR_Registry($this->config->get('php_dir')); - $installed = array_flip($reg->listPackages()); - $params = array(); - foreach ($latest as $package => $info) { - $package = strtolower($package); - if (!isset($installed[$package])) { - // skip packages we don't have installed - continue; - } - $inst_version = $reg->packageInfo($package, 'version'); - if (version_compare("$info[version]", "$inst_version", "le")) { - // installed version is up-to-date - continue; - } - $params[] = $package; - $this->ui->outputData(array('data' => "Will upgrade $package"), $command); - } - } - $this->downloader = &new PEAR_Downloader($this->ui, $options, $this->config); - $errors = array(); - $downloaded = array(); - $this->downloader->download($params); - $errors = $this->downloader->getErrorMsgs(); - if (count($errors)) { - $err['data'] = array($errors); - $err['headline'] = 'Install Errors'; - $this->ui->outputData($err); - return $this->raiseError("$command failed"); - } - $downloaded = $this->downloader->getDownloadedPackages(); - $this->installer->sortPkgDeps($downloaded); - foreach ($downloaded as $pkg) { - PEAR::pushErrorHandling(PEAR_ERROR_RETURN); - $info = $this->installer->install($pkg['file'], $options, $this->config); - PEAR::popErrorHandling(); - if (PEAR::isError($info)) { - $this->ui->outputData('ERROR: ' .$info->getMessage()); - continue; - } - if (is_array($info)) { - if ($this->config->get('verbose') > 0) { - $label = "$info[package] $info[version]"; - $out = array('data' => "$command ok: $label"); - if (isset($info['release_warnings'])) { - $out['release_warnings'] = $info['release_warnings']; - } - $this->ui->outputData($out, $command); - } - } else { - return $this->raiseError("$command failed"); - } - } - return true; - } - - // }}} - // {{{ doUninstall() - - function doUninstall($command, $options, $params) - { - if (empty($this->installer)) { - $this->installer = &new PEAR_Installer($this->ui); - } - if (sizeof($params) < 1) { - return $this->raiseError("Please supply the package(s) you want to uninstall"); - } - include_once 'PEAR/Registry.php'; - $reg = new PEAR_Registry($this->config->get('php_dir')); - $newparams = array(); - $badparams = array(); - foreach ($params as $pkg) { - $info = $reg->packageInfo($pkg); - if ($info === null) { - $badparams[] = $pkg; - } else { - $newparams[] = $info; - } - } - $this->installer->sortPkgDeps($newparams, true); - $params = array(); - foreach($newparams as $info) { - $params[] = $info['info']['package']; - } - $params = array_merge($params, $badparams); - foreach ($params as $pkg) { - if ($this->installer->uninstall($pkg, $options)) { - if ($this->config->get('verbose') > 0) { - $this->ui->outputData("uninstall ok: $pkg", $command); - } - } else { - return $this->raiseError("uninstall failed: $pkg"); - } - } - return true; - } - - // }}} - - - // }}} - // {{{ doBundle() - /* - (cox) It just downloads and untars the package, does not do - any check that the PEAR_Installer::_installFile() does. - */ - - function doBundle($command, $options, $params) - { - if (empty($this->installer)) { - $this->installer = &new PEAR_Downloader($this->ui); - } - $installer = &$this->installer; - if (sizeof($params) < 1) { - return $this->raiseError("Please supply the package you want to bundle"); - } - $pkgfile = $params[0]; - $need_download = false; - if (preg_match('#^(http|ftp)://#', $pkgfile)) { - $need_download = true; - } elseif (!@is_file($pkgfile)) { - if ($installer->validPackageName($pkgfile)) { - $pkgfile = $installer->getPackageDownloadUrl($pkgfile); - $need_download = true; - } else { - if (strlen($pkgfile)) { - return $this->raiseError("Could not open the package file: $pkgfile"); - } else { - return $this->raiseError("No package file given"); - } - } - } - - // Download package ----------------------------------------------- - if ($need_download) { - $downloaddir = $installer->config->get('download_dir'); - if (empty($downloaddir)) { - if (PEAR::isError($downloaddir = System::mktemp('-d'))) { - return $downloaddir; - } - $installer->log(2, '+ tmp dir created at ' . $downloaddir); - } - $callback = $this->ui ? array(&$installer, '_downloadCallback') : null; - $file = $installer->downloadHttp($pkgfile, $this->ui, $downloaddir, $callback); - if (PEAR::isError($file)) { - return $this->raiseError($file); - } - $pkgfile = $file; - } - - // Parse xml file ----------------------------------------------- - $pkginfo = $installer->infoFromTgzFile($pkgfile); - if (PEAR::isError($pkginfo)) { - return $this->raiseError($pkginfo); - } - $installer->validatePackageInfo($pkginfo, $errors, $warnings); - // XXX We allow warnings, do we have to do it? - if (count($errors)) { - if (empty($options['force'])) { - return $this->raiseError("The following errors where found:\n". - implode("\n", $errors)); - } else { - $this->log(0, "warning : the following errors were found:\n". - implode("\n", $errors)); - } - } - $pkgname = $pkginfo['package']; - - // Unpacking ------------------------------------------------- - - if (isset($options['destination'])) { - if (!is_dir($options['destination'])) { - System::mkdir('-p ' . $options['destination']); - } - $dest = realpath($options['destination']); - } else { - $pwd = getcwd(); - if (is_dir($pwd . DIRECTORY_SEPARATOR . 'ext')) { - $dest = $pwd . DIRECTORY_SEPARATOR . 'ext'; - } else { - $dest = $pwd; - } - } - $dest .= DIRECTORY_SEPARATOR . $pkgname; - $orig = $pkgname . '-' . $pkginfo['version']; - - $tar = new Archive_Tar($pkgfile); - if (!@$tar->extractModify($dest, $orig)) { - return $this->raiseError("unable to unpack $pkgfile"); - } - $this->ui->outputData("Package ready at '$dest'"); - // }}} - } - - // }}} - -} -?> diff --git a/3rdparty/PEAR/Command/Mirror.php b/3rdparty/PEAR/Command/Mirror.php deleted file mode 100644 index bf56c3db640b806ea4b223f93c2a7f29514d3bd3..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Command/Mirror.php +++ /dev/null @@ -1,101 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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: Alexander Merz <alexmerz@php.net> | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Mirror.php,v 1.5 2004/03/18 12:23:57 mj Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Command.php"; -require_once "PEAR/Remote.php"; -require_once "PEAR.php"; - -/** - * PEAR commands for providing file mirrors - * - */ -class PEAR_Command_Mirror extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'download-all' => array( - 'summary' => 'Downloads each available package from master_server', - 'function' => 'doDownloadAll', - 'shortcut' => 'da', - 'options' => array(), - 'doc' => ' - Requests a list of available packages from the package server - (master_server) and downloads them to current working directory' - ), - ); - - // }}} - - // {{{ constructor - - /** - * PEAR_Command_Mirror constructor. - * - * @access public - * @param object PEAR_Frontend a reference to an frontend - * @param object PEAR_Config a reference to the configuration data - */ - function PEAR_Command_Mirror(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doDownloadAll() - /** - * retrieves a list of avaible Packages from master server - * and downloads them - * - * @access public - * @param string $command the command - * @param array $options the command options before the command - * @param array $params the stuff after the command name - * @return bool true if succesful - * @throw PEAR_Error - */ - function doDownloadAll($command, $options, $params) - { - $this->config->set("php_dir", "."); - $remote = &new PEAR_Remote($this->config); - $remoteInfo = $remote->call("package.listAll"); - if (PEAR::isError($remoteInfo)) { - return $remoteInfo; - } - $cmd = &PEAR_Command::factory("download", $this->config); - if (PEAR::isError($cmd)) { - return $cmd; - } - foreach ($remoteInfo as $pkgn => $pkg) { - /** - * Error handling not neccesary, because already done by - * the download command - */ - $cmd->run("download", array(), array($pkgn)); - } - - return true; - } - - // }}} -} diff --git a/3rdparty/PEAR/Command/Package.php b/3rdparty/PEAR/Command/Package.php deleted file mode 100644 index aca8711111802b46eb0aabee901c3596298f8460..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Command/Package.php +++ /dev/null @@ -1,819 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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. | -// +----------------------------------------------------------------------+ -// | Authors: Stig Bakken <ssb@php.net> | -// | Martin Jansen <mj@php.net> | -// | Greg Beaver <cellog@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Package.php,v 1.61.2.7 2005/02/17 17:47:55 cellog Exp $ - -require_once 'PEAR/Common.php'; -require_once 'PEAR/Command/Common.php'; - -class PEAR_Command_Package extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'package' => array( - 'summary' => 'Build Package', - 'function' => 'doPackage', - 'shortcut' => 'p', - 'options' => array( - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'Do not gzip the package file' - ), - 'showname' => array( - 'shortopt' => 'n', - 'doc' => 'Print the name of the packaged file.', - ), - ), - 'doc' => '[descfile] -Creates a PEAR package from its description file (usually called -package.xml). -' - ), - 'package-validate' => array( - 'summary' => 'Validate Package Consistency', - 'function' => 'doPackageValidate', - 'shortcut' => 'pv', - 'options' => array(), - 'doc' => ' -', - ), - 'cvsdiff' => array( - 'summary' => 'Run a "cvs diff" for all files in a package', - 'function' => 'doCvsDiff', - 'shortcut' => 'cd', - 'options' => array( - 'quiet' => array( - 'shortopt' => 'q', - 'doc' => 'Be quiet', - ), - 'reallyquiet' => array( - 'shortopt' => 'Q', - 'doc' => 'Be really quiet', - ), - 'date' => array( - 'shortopt' => 'D', - 'doc' => 'Diff against revision of DATE', - 'arg' => 'DATE', - ), - 'release' => array( - 'shortopt' => 'R', - 'doc' => 'Diff against tag for package release REL', - 'arg' => 'REL', - ), - 'revision' => array( - 'shortopt' => 'r', - 'doc' => 'Diff against revision REV', - 'arg' => 'REV', - ), - 'context' => array( - 'shortopt' => 'c', - 'doc' => 'Generate context diff', - ), - 'unified' => array( - 'shortopt' => 'u', - 'doc' => 'Generate unified diff', - ), - 'ignore-case' => array( - 'shortopt' => 'i', - 'doc' => 'Ignore case, consider upper- and lower-case letters equivalent', - ), - 'ignore-whitespace' => array( - 'shortopt' => 'b', - 'doc' => 'Ignore changes in amount of white space', - ), - 'ignore-blank-lines' => array( - 'shortopt' => 'B', - 'doc' => 'Ignore changes that insert or delete blank lines', - ), - 'brief' => array( - 'doc' => 'Report only whether the files differ, no details', - ), - 'dry-run' => array( - 'shortopt' => 'n', - 'doc' => 'Don\'t do anything, just pretend', - ), - ), - 'doc' => '<package.xml> -Compares all the files in a package. Without any options, this -command will compare the current code with the last checked-in code. -Using the -r or -R option you may compare the current code with that -of a specific release. -', - ), - 'cvstag' => array( - 'summary' => 'Set CVS Release Tag', - 'function' => 'doCvsTag', - 'shortcut' => 'ct', - 'options' => array( - 'quiet' => array( - 'shortopt' => 'q', - 'doc' => 'Be quiet', - ), - 'reallyquiet' => array( - 'shortopt' => 'Q', - 'doc' => 'Be really quiet', - ), - 'slide' => array( - 'shortopt' => 'F', - 'doc' => 'Move (slide) tag if it exists', - ), - 'delete' => array( - 'shortopt' => 'd', - 'doc' => 'Remove tag', - ), - 'dry-run' => array( - 'shortopt' => 'n', - 'doc' => 'Don\'t do anything, just pretend', - ), - ), - 'doc' => '<package.xml> -Sets a CVS tag on all files in a package. Use this command after you have -packaged a distribution tarball with the "package" command to tag what -revisions of what files were in that release. If need to fix something -after running cvstag once, but before the tarball is released to the public, -use the "slide" option to move the release tag. -', - ), - 'run-tests' => array( - 'summary' => 'Run Regression Tests', - 'function' => 'doRunTests', - 'shortcut' => 'rt', - 'options' => array( - 'recur' => array( - 'shortopt' => 'r', - 'doc' => 'Run tests in child directories, recursively. 4 dirs deep maximum', - ), - 'ini' => array( - 'shortopt' => 'i', - 'doc' => 'actual string of settings to pass to php in format " -d setting=blah"', - 'arg' => 'SETTINGS' - ), - 'realtimelog' => array( - 'shortopt' => 'l', - 'doc' => 'Log test runs/results as they are run', - ), - ), - 'doc' => '[testfile|dir ...] -Run regression tests with PHP\'s regression testing script (run-tests.php).', - ), - 'package-dependencies' => array( - 'summary' => 'Show package dependencies', - 'function' => 'doPackageDependencies', - 'shortcut' => 'pd', - 'options' => array(), - 'doc' => ' -List all depencies the package has.' - ), - 'sign' => array( - 'summary' => 'Sign a package distribution file', - 'function' => 'doSign', - 'shortcut' => 'si', - 'options' => array(), - 'doc' => '<package-file> -Signs a package distribution (.tar or .tgz) file with GnuPG.', - ), - 'makerpm' => array( - 'summary' => 'Builds an RPM spec file from a PEAR package', - 'function' => 'doMakeRPM', - 'shortcut' => 'rpm', - 'options' => array( - 'spec-template' => array( - 'shortopt' => 't', - 'arg' => 'FILE', - 'doc' => 'Use FILE as RPM spec file template' - ), - 'rpm-pkgname' => array( - 'shortopt' => 'p', - 'arg' => 'FORMAT', - 'doc' => 'Use FORMAT as format string for RPM package name, %s is replaced -by the PEAR package name, defaults to "PEAR::%s".', - ), - ), - 'doc' => '<package-file> - -Creates an RPM .spec file for wrapping a PEAR package inside an RPM -package. Intended to be used from the SPECS directory, with the PEAR -package tarball in the SOURCES directory: - -$ pear makerpm ../SOURCES/Net_Socket-1.0.tgz -Wrote RPM spec file PEAR::Net_Geo-1.0.spec -$ rpm -bb PEAR::Net_Socket-1.0.spec -... -Wrote: /usr/src/redhat/RPMS/i386/PEAR::Net_Socket-1.0-1.i386.rpm -', - ), - ); - - var $output; - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Package constructor. - * - * @access public - */ - function PEAR_Command_Package(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ _displayValidationResults() - - function _displayValidationResults($err, $warn, $strict = false) - { - foreach ($err as $e) { - $this->output .= "Error: $e\n"; - } - foreach ($warn as $w) { - $this->output .= "Warning: $w\n"; - } - $this->output .= sprintf('Validation: %d error(s), %d warning(s)'."\n", - sizeof($err), sizeof($warn)); - if ($strict && sizeof($err) > 0) { - $this->output .= "Fix these errors and try again."; - return false; - } - return true; - } - - // }}} - // {{{ doPackage() - - function doPackage($command, $options, $params) - { - $this->output = ''; - include_once 'PEAR/Packager.php'; - if (sizeof($params) < 1) { - $params[0] = "package.xml"; - } - $pkginfofile = isset($params[0]) ? $params[0] : 'package.xml'; - $packager =& new PEAR_Packager(); - $err = $warn = array(); - $dir = dirname($pkginfofile); - $compress = empty($options['nocompress']) ? true : false; - $result = $packager->package($pkginfofile, $compress); - if (PEAR::isError($result)) { - $this->ui->outputData($this->output, $command); - return $this->raiseError($result); - } - // Don't want output, only the package file name just created - if (isset($options['showname'])) { - $this->output = $result; - } - if (PEAR::isError($result)) { - $this->output .= "Package failed: ".$result->getMessage(); - } - $this->ui->outputData($this->output, $command); - return true; - } - - // }}} - // {{{ doPackageValidate() - - function doPackageValidate($command, $options, $params) - { - $this->output = ''; - if (sizeof($params) < 1) { - $params[0] = "package.xml"; - } - $obj = new PEAR_Common; - $info = null; - if ($fp = @fopen($params[0], "r")) { - $test = fread($fp, 5); - fclose($fp); - if ($test == "<?xml") { - $info = $obj->infoFromDescriptionFile($params[0]); - } - } - if (empty($info)) { - $info = $obj->infoFromTgzFile($params[0]); - } - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - $obj->validatePackageInfo($info, $err, $warn); - $this->_displayValidationResults($err, $warn); - $this->ui->outputData($this->output, $command); - return true; - } - - // }}} - // {{{ doCvsTag() - - function doCvsTag($command, $options, $params) - { - $this->output = ''; - $_cmd = $command; - if (sizeof($params) < 1) { - $help = $this->getHelp($command); - return $this->raiseError("$command: missing parameter: $help[0]"); - } - $obj = new PEAR_Common; - $info = $obj->infoFromDescriptionFile($params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - $err = $warn = array(); - $obj->validatePackageInfo($info, $err, $warn); - if (!$this->_displayValidationResults($err, $warn, true)) { - $this->ui->outputData($this->output, $command); - break; - } - $version = $info['version']; - $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $version); - $cvstag = "RELEASE_$cvsversion"; - $files = array_keys($info['filelist']); - $command = "cvs"; - if (isset($options['quiet'])) { - $command .= ' -q'; - } - if (isset($options['reallyquiet'])) { - $command .= ' -Q'; - } - $command .= ' tag'; - if (isset($options['slide'])) { - $command .= ' -F'; - } - if (isset($options['delete'])) { - $command .= ' -d'; - } - $command .= ' ' . $cvstag . ' ' . escapeshellarg($params[0]); - foreach ($files as $file) { - $command .= ' ' . escapeshellarg($file); - } - if ($this->config->get('verbose') > 1) { - $this->output .= "+ $command\n"; - } - $this->output .= "+ $command\n"; - if (empty($options['dry-run'])) { - $fp = popen($command, "r"); - while ($line = fgets($fp, 1024)) { - $this->output .= rtrim($line)."\n"; - } - pclose($fp); - } - $this->ui->outputData($this->output, $_cmd); - return true; - } - - // }}} - // {{{ doCvsDiff() - - function doCvsDiff($command, $options, $params) - { - $this->output = ''; - if (sizeof($params) < 1) { - $help = $this->getHelp($command); - return $this->raiseError("$command: missing parameter: $help[0]"); - } - $obj = new PEAR_Common; - $info = $obj->infoFromDescriptionFile($params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - $files = array_keys($info['filelist']); - $cmd = "cvs"; - if (isset($options['quiet'])) { - $cmd .= ' -q'; - unset($options['quiet']); - } - if (isset($options['reallyquiet'])) { - $cmd .= ' -Q'; - unset($options['reallyquiet']); - } - if (isset($options['release'])) { - $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $options['release']); - $cvstag = "RELEASE_$cvsversion"; - $options['revision'] = $cvstag; - unset($options['release']); - } - $execute = true; - if (isset($options['dry-run'])) { - $execute = false; - unset($options['dry-run']); - } - $cmd .= ' diff'; - // the rest of the options are passed right on to "cvs diff" - foreach ($options as $option => $optarg) { - $arg = @$this->commands[$command]['options'][$option]['arg']; - $short = @$this->commands[$command]['options'][$option]['shortopt']; - $cmd .= $short ? " -$short" : " --$option"; - if ($arg && $optarg) { - $cmd .= ($short ? '' : '=') . escapeshellarg($optarg); - } - } - foreach ($files as $file) { - $cmd .= ' ' . escapeshellarg($file); - } - if ($this->config->get('verbose') > 1) { - $this->output .= "+ $cmd\n"; - } - if ($execute) { - $fp = popen($cmd, "r"); - while ($line = fgets($fp, 1024)) { - $this->output .= rtrim($line)."\n"; - } - pclose($fp); - } - $this->ui->outputData($this->output, $command); - return true; - } - - // }}} - // {{{ doRunTests() - - function doRunTests($command, $options, $params) - { - include_once 'PEAR/RunTest.php'; - $log = new PEAR_Common; - $log->ui = &$this->ui; // slightly hacky, but it will work - $run = new PEAR_RunTest($log); - $tests = array(); - if (isset($options['recur'])) { - $depth = 4; - } else { - $depth = 1; - } - if (!count($params)) { - $params[] = '.'; - } - foreach ($params as $p) { - if (is_dir($p)) { - $dir = System::find(array($p, '-type', 'f', - '-maxdepth', $depth, - '-name', '*.phpt')); - $tests = array_merge($tests, $dir); - } else { - if (!@file_exists($p)) { - if (!preg_match('/\.phpt$/', $p)) { - $p .= '.phpt'; - } - $dir = System::find(array(dirname($p), '-type', 'f', - '-maxdepth', $depth, - '-name', $p)); - $tests = array_merge($tests, $dir); - } else { - $tests[] = $p; - } - } - } - $ini_settings = ''; - if (isset($options['ini'])) { - $ini_settings .= $options['ini']; - } - if (isset($_ENV['TEST_PHP_INCLUDE_PATH'])) { - $ini_settings .= " -d include_path={$_ENV['TEST_PHP_INCLUDE_PATH']}"; - } - if ($ini_settings) { - $this->ui->outputData('Using INI settings: "' . $ini_settings . '"'); - } - $skipped = $passed = $failed = array(); - $this->ui->outputData('Running ' . count($tests) . ' tests', $command); - $start = time(); - if (isset($options['realtimelog'])) { - @unlink('run-tests.log'); - } - foreach ($tests as $t) { - if (isset($options['realtimelog'])) { - $fp = @fopen('run-tests.log', 'a'); - if ($fp) { - fwrite($fp, "Running test $t..."); - fclose($fp); - } - } - $result = $run->run($t, $ini_settings); - if (OS_WINDOWS) { - for($i=0;$i<2000;$i++) { - $i = $i; // delay - race conditions on windows - } - } - if (isset($options['realtimelog'])) { - $fp = @fopen('run-tests.log', 'a'); - if ($fp) { - fwrite($fp, "$result\n"); - fclose($fp); - } - } - if ($result == 'FAILED') { - $failed[] = $t; - } - if ($result == 'PASSED') { - $passed[] = $t; - } - if ($result == 'SKIPPED') { - $skipped[] = $t; - } - } - $total = date('i:s', time() - $start); - if (count($failed)) { - $output = "TOTAL TIME: $total\n"; - $output .= count($passed) . " PASSED TESTS\n"; - $output .= count($skipped) . " SKIPPED TESTS\n"; - $output .= count($failed) . " FAILED TESTS:\n"; - foreach ($failed as $failure) { - $output .= $failure . "\n"; - } - if (isset($options['realtimelog'])) { - $fp = @fopen('run-tests.log', 'a'); - } else { - $fp = @fopen('run-tests.log', 'w'); - } - if ($fp) { - fwrite($fp, $output, strlen($output)); - fclose($fp); - $this->ui->outputData('wrote log to "' . realpath('run-tests.log') . '"', $command); - } - } elseif (@file_exists('run-tests.log') && !@is_dir('run-tests.log')) { - @unlink('run-tests.log'); - } - $this->ui->outputData('TOTAL TIME: ' . $total); - $this->ui->outputData(count($passed) . ' PASSED TESTS', $command); - $this->ui->outputData(count($skipped) . ' SKIPPED TESTS', $command); - if (count($failed)) { - $this->ui->outputData(count($failed) . ' FAILED TESTS:', $command); - foreach ($failed as $failure) { - $this->ui->outputData($failure, $command); - } - } - - return true; - } - - // }}} - // {{{ doPackageDependencies() - - function doPackageDependencies($command, $options, $params) - { - // $params[0] -> the PEAR package to list its information - if (sizeof($params) != 1) { - return $this->raiseError("bad parameter(s), try \"help $command\""); - } - - $obj = new PEAR_Common(); - if (PEAR::isError($info = $obj->infoFromAny($params[0]))) { - return $this->raiseError($info); - } - - if (is_array($info['release_deps'])) { - $data = array( - 'caption' => 'Dependencies for ' . $info['package'], - 'border' => true, - 'headline' => array("Type", "Name", "Relation", "Version"), - ); - - foreach ($info['release_deps'] as $d) { - - if (isset($this->_deps_rel_trans[$d['rel']])) { - $rel = $this->_deps_rel_trans[$d['rel']]; - } else { - $rel = $d['rel']; - } - - if (isset($this->_deps_type_trans[$d['type']])) { - $type = ucfirst($this->_deps_type_trans[$d['type']]); - } else { - $type = $d['type']; - } - - if (isset($d['name'])) { - $name = $d['name']; - } else { - $name = ''; - } - - if (isset($d['version'])) { - $version = $d['version']; - } else { - $version = ''; - } - - $data['data'][] = array($type, $name, $rel, $version); - } - - $this->ui->outputData($data, $command); - return true; - } - - // Fallback - $this->ui->outputData("This package does not have any dependencies.", $command); - } - - // }}} - // {{{ doSign() - - function doSign($command, $options, $params) - { - // should move most of this code into PEAR_Packager - // so it'll be easy to implement "pear package --sign" - if (sizeof($params) != 1) { - return $this->raiseError("bad parameter(s), try \"help $command\""); - } - if (!file_exists($params[0])) { - return $this->raiseError("file does not exist: $params[0]"); - } - $obj = new PEAR_Common; - $info = $obj->infoFromTgzFile($params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - include_once "Archive/Tar.php"; - include_once "System.php"; - $tar = new Archive_Tar($params[0]); - $tmpdir = System::mktemp('-d pearsign'); - if (!$tar->extractList('package.xml package.sig', $tmpdir)) { - return $this->raiseError("failed to extract tar file"); - } - if (file_exists("$tmpdir/package.sig")) { - return $this->raiseError("package already signed"); - } - @unlink("$tmpdir/package.sig"); - $input = $this->ui->userDialog($command, - array('GnuPG Passphrase'), - array('password')); - $gpg = popen("gpg --batch --passphrase-fd 0 --armor --detach-sign --output $tmpdir/package.sig $tmpdir/package.xml 2>/dev/null", "w"); - if (!$gpg) { - return $this->raiseError("gpg command failed"); - } - fwrite($gpg, "$input[0]\r"); - if (pclose($gpg) || !file_exists("$tmpdir/package.sig")) { - return $this->raiseError("gpg sign failed"); - } - $tar->addModify("$tmpdir/package.sig", '', $tmpdir); - return true; - } - - // }}} - // {{{ doMakeRPM() - - /* - - (cox) - - TODO: - - - Fill the rpm dependencies in the template file. - - IDEAS: - - - Instead of mapping the role to rpm vars, perhaps it's better - - to use directly the pear cmd to install the files by itself - - in %postrun so: - - pear -d php_dir=%{_libdir}/php/pear -d test_dir=.. <package> - - */ - - function doMakeRPM($command, $options, $params) - { - if (sizeof($params) != 1) { - return $this->raiseError("bad parameter(s), try \"help $command\""); - } - if (!file_exists($params[0])) { - return $this->raiseError("file does not exist: $params[0]"); - } - include_once "Archive/Tar.php"; - include_once "PEAR/Installer.php"; - include_once "System.php"; - $tar = new Archive_Tar($params[0]); - $tmpdir = System::mktemp('-d pear2rpm'); - $instroot = System::mktemp('-d pear2rpm'); - $tmp = $this->config->get('verbose'); - $this->config->set('verbose', 0); - $installer = new PEAR_Installer($this->ui); - $info = $installer->install($params[0], - array('installroot' => $instroot, - 'nodeps' => true)); - $pkgdir = "$info[package]-$info[version]"; - $info['rpm_xml_dir'] = '/var/lib/pear'; - $this->config->set('verbose', $tmp); - if (!$tar->extractList("package.xml", $tmpdir, $pkgdir)) { - return $this->raiseError("failed to extract $params[0]"); - } - if (!file_exists("$tmpdir/package.xml")) { - return $this->raiseError("no package.xml found in $params[0]"); - } - if (isset($options['spec-template'])) { - $spec_template = $options['spec-template']; - } else { - $spec_template = $this->config->get('data_dir') . - '/PEAR/template.spec'; - } - if (isset($options['rpm-pkgname'])) { - $rpm_pkgname_format = $options['rpm-pkgname']; - } else { - $rpm_pkgname_format = "PEAR::%s"; - } - - $info['extra_headers'] = ''; - $info['doc_files'] = ''; - $info['files'] = ''; - $info['rpm_package'] = sprintf($rpm_pkgname_format, $info['package']); - $srcfiles = 0; - foreach ($info['filelist'] as $name => $attr) { - - if (!isset($attr['role'])) { - continue; - } - $name = preg_replace('![/:\\\\]!', '/', $name); - if ($attr['role'] == 'doc') { - $info['doc_files'] .= " $name"; - - // Map role to the rpm vars - } else { - - $c_prefix = '%{_libdir}/php/pear'; - - switch ($attr['role']) { - - case 'php': - - $prefix = $c_prefix; break; - - case 'ext': - - $prefix = '%{_libdir}/php'; break; // XXX good place? - - case 'src': - - $srcfiles++; - - $prefix = '%{_includedir}/php'; break; // XXX good place? - - case 'test': - - $prefix = "$c_prefix/tests/" . $info['package']; break; - - case 'data': - - $prefix = "$c_prefix/data/" . $info['package']; break; - - case 'script': - - $prefix = '%{_bindir}'; break; - - } - - $name = str_replace('\\', '/', $name); - $info['files'] .= "$prefix/$name\n"; - - } - } - if ($srcfiles > 0) { - include_once "OS/Guess.php"; - $os = new OS_Guess; - $arch = $os->getCpu(); - } else { - $arch = 'noarch'; - } - $cfg = array('master_server', 'php_dir', 'ext_dir', 'doc_dir', - 'bin_dir', 'data_dir', 'test_dir'); - foreach ($cfg as $k) { - $info[$k] = $this->config->get($k); - } - $info['arch'] = $arch; - $fp = @fopen($spec_template, "r"); - if (!$fp) { - return $this->raiseError("could not open RPM spec file template $spec_template: $php_errormsg"); - } - $spec_contents = preg_replace('/@([a-z0-9_-]+)@/e', '$info["\1"]', fread($fp, filesize($spec_template))); - fclose($fp); - $spec_file = "$info[rpm_package]-$info[version].spec"; - $wp = fopen($spec_file, "wb"); - if (!$wp) { - return $this->raiseError("could not write RPM spec file $spec_file: $php_errormsg"); - } - fwrite($wp, $spec_contents); - fclose($wp); - $this->ui->outputData("Wrote RPM spec file $spec_file", $command); - - return true; - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Command/Registry.php b/3rdparty/PEAR/Command/Registry.php deleted file mode 100644 index 62cb4b00e28947cd0c3f811387dd69bd99a72218..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Command/Registry.php +++ /dev/null @@ -1,351 +0,0 @@ -<?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: Stig Bakken <ssb@php.net> | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Registry.php,v 1.36 2004/01/08 17:33:13 sniper Exp $ - -require_once 'PEAR/Command/Common.php'; -require_once 'PEAR/Registry.php'; -require_once 'PEAR/Config.php'; - -class PEAR_Command_Registry extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'list' => array( - 'summary' => 'List Installed Packages', - 'function' => 'doList', - 'shortcut' => 'l', - 'options' => array(), - 'doc' => '[package] -If invoked without parameters, this command lists the PEAR packages -installed in your php_dir ({config php_dir)). With a parameter, it -lists the files in that package. -', - ), - 'shell-test' => array( - 'summary' => 'Shell Script Test', - 'function' => 'doShellTest', - 'shortcut' => 'st', - 'options' => array(), - 'doc' => '<package> [[relation] version] -Tests if a package is installed in the system. Will exit(1) if it is not. - <relation> The version comparison operator. One of: - <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne - <version> The version to compare with -'), - 'info' => array( - 'summary' => 'Display information about a package', - 'function' => 'doInfo', - 'shortcut' => 'in', - 'options' => array(), - 'doc' => '<package> -Displays information about a package. The package argument may be a -local package file, an URL to a package file, or the name of an -installed package.' - ) - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Registry constructor. - * - * @access public - */ - function PEAR_Command_Registry(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doList() - - function _sortinfo($a, $b) - { - return strcmp($a['package'], $b['package']); - } - - function doList($command, $options, $params) - { - $reg = new PEAR_Registry($this->config->get('php_dir')); - if (sizeof($params) == 0) { - $installed = $reg->packageInfo(); - usort($installed, array(&$this, '_sortinfo')); - $i = $j = 0; - $data = array( - 'caption' => 'Installed packages:', - 'border' => true, - 'headline' => array('Package', 'Version', 'State') - ); - foreach ($installed as $package) { - $data['data'][] = array($package['package'], - $package['version'], - @$package['release_state']); - } - if (count($installed)==0) { - $data = '(no packages installed)'; - } - $this->ui->outputData($data, $command); - } else { - if (file_exists($params[0]) && !is_dir($params[0])) { - include_once "PEAR/Common.php"; - $obj = &new PEAR_Common; - $info = $obj->infoFromAny($params[0]); - $headings = array('Package File', 'Install Path'); - $installed = false; - } else { - $info = $reg->packageInfo($params[0]); - $headings = array('Type', 'Install Path'); - $installed = true; - } - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - if ($info === null) { - return $this->raiseError("`$params[0]' not installed"); - } - $list = $info['filelist']; - if ($installed) { - $caption = 'Installed Files For ' . $params[0]; - } else { - $caption = 'Contents of ' . basename($params[0]); - } - $data = array( - 'caption' => $caption, - 'border' => true, - 'headline' => $headings); - foreach ($list as $file => $att) { - if ($installed) { - if (empty($att['installed_as'])) { - continue; - } - $data['data'][] = array($att['role'], $att['installed_as']); - } else { - if (isset($att['baseinstalldir'])) { - $dest = $att['baseinstalldir'] . DIRECTORY_SEPARATOR . - $file; - } else { - $dest = $file; - } - switch ($att['role']) { - case 'test': - case 'data': - if ($installed) { - break 2; - } - $dest = '-- will not be installed --'; - break; - case 'doc': - $dest = $this->config->get('doc_dir') . DIRECTORY_SEPARATOR . - $dest; - break; - case 'php': - default: - $dest = $this->config->get('php_dir') . DIRECTORY_SEPARATOR . - $dest; - } - $dest = preg_replace('!/+!', '/', $dest); - $file = preg_replace('!/+!', '/', $file); - $data['data'][] = array($file, $dest); - } - } - $this->ui->outputData($data, $command); - - - } - return true; - } - - // }}} - // {{{ doShellTest() - - function doShellTest($command, $options, $params) - { - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $reg = &new PEAR_Registry($this->config->get('php_dir')); - // "pear shell-test Foo" - if (sizeof($params) == 1) { - if (!$reg->packageExists($params[0])) { - exit(1); - } - // "pear shell-test Foo 1.0" - } elseif (sizeof($params) == 2) { - $v = $reg->packageInfo($params[0], 'version'); - if (!$v || !version_compare("$v", "{$params[1]}", "ge")) { - exit(1); - } - // "pear shell-test Foo ge 1.0" - } elseif (sizeof($params) == 3) { - $v = $reg->packageInfo($params[0], 'version'); - if (!$v || !version_compare("$v", "{$params[2]}", $params[1])) { - exit(1); - } - } else { - $this->popErrorHandling(); - $this->raiseError("$command: expects 1 to 3 parameters"); - exit(1); - } - } - - // }}} - // {{{ doInfo - - function doInfo($command, $options, $params) - { - // $params[0] The package for showing info - if (sizeof($params) != 1) { - return $this->raiseError("This command only accepts one param: ". - "the package you want information"); - } - if (@is_file($params[0])) { - $obj = &new PEAR_Common(); - $info = $obj->infoFromAny($params[0]); - } else { - $reg = &new PEAR_Registry($this->config->get('php_dir')); - $info = $reg->packageInfo($params[0]); - } - if (PEAR::isError($info)) { - return $info; - } - if (empty($info)) { - $this->raiseError("Nothing found for `$params[0]'"); - return; - } - unset($info['filelist']); - unset($info['changelog']); - $keys = array_keys($info); - $longtext = array('description', 'summary'); - foreach ($keys as $key) { - if (is_array($info[$key])) { - switch ($key) { - case 'maintainers': { - $i = 0; - $mstr = ''; - foreach ($info[$key] as $m) { - if ($i++ > 0) { - $mstr .= "\n"; - } - $mstr .= $m['name'] . " <"; - if (isset($m['email'])) { - $mstr .= $m['email']; - } else { - $mstr .= $m['handle'] . '@php.net'; - } - $mstr .= "> ($m[role])"; - } - $info[$key] = $mstr; - break; - } - case 'release_deps': { - $i = 0; - $dstr = ''; - foreach ($info[$key] as $d) { - if (isset($this->_deps_rel_trans[$d['rel']])) { - $rel = $this->_deps_rel_trans[$d['rel']]; - } else { - $rel = $d['rel']; - } - if (isset($this->_deps_type_trans[$d['type']])) { - $type = ucfirst($this->_deps_type_trans[$d['type']]); - } else { - $type = $d['type']; - } - if (isset($d['name'])) { - $name = $d['name'] . ' '; - } else { - $name = ''; - } - if (isset($d['version'])) { - $version = $d['version'] . ' '; - } else { - $version = ''; - } - $dstr .= "$type $name$rel $version\n"; - } - $info[$key] = $dstr; - break; - } - case 'provides' : { - $debug = $this->config->get('verbose'); - if ($debug < 2) { - $pstr = 'Classes: '; - } else { - $pstr = ''; - } - $i = 0; - foreach ($info[$key] as $p) { - if ($debug < 2 && $p['type'] != "class") { - continue; - } - // Only print classes when verbosity mode is < 2 - if ($debug < 2) { - if ($i++ > 0) { - $pstr .= ", "; - } - $pstr .= $p['name']; - } else { - if ($i++ > 0) { - $pstr .= "\n"; - } - $pstr .= ucfirst($p['type']) . " " . $p['name']; - if (isset($p['explicit']) && $p['explicit'] == 1) { - $pstr .= " (explicit)"; - } - } - } - $info[$key] = $pstr; - break; - } - default: { - $info[$key] = implode(", ", $info[$key]); - break; - } - } - } - if ($key == '_lastmodified') { - $hdate = date('Y-m-d', $info[$key]); - unset($info[$key]); - $info['Last Modified'] = $hdate; - } else { - $info[$key] = trim($info[$key]); - if (in_array($key, $longtext)) { - $info[$key] = preg_replace('/ +/', ' ', $info[$key]); - } - } - } - $caption = 'About ' . $info['package'] . '-' . $info['version']; - $data = array( - 'caption' => $caption, - 'border' => true); - foreach ($info as $key => $value) { - $key = ucwords(trim(str_replace('_', ' ', $key))); - $data['data'][] = array($key, $value); - } - $data['raw'] = $info; - - $this->ui->outputData($data, 'package-info'); - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Command/Remote.php b/3rdparty/PEAR/Command/Remote.php deleted file mode 100644 index bbd16093f5d83876aba5686e4b74ab54d01e515f..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Command/Remote.php +++ /dev/null @@ -1,435 +0,0 @@ -<?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: Stig Bakken <ssb@php.net> | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Remote.php,v 1.39 2004/04/03 15:56:00 cellog Exp $ - -require_once 'PEAR/Command/Common.php'; -require_once 'PEAR/Common.php'; -require_once 'PEAR/Remote.php'; -require_once 'PEAR/Registry.php'; - -class PEAR_Command_Remote extends PEAR_Command_Common -{ - // {{{ command definitions - - var $commands = array( - 'remote-info' => array( - 'summary' => 'Information About Remote Packages', - 'function' => 'doRemoteInfo', - 'shortcut' => 'ri', - 'options' => array(), - 'doc' => '<package> -Get details on a package from the server.', - ), - 'list-upgrades' => array( - 'summary' => 'List Available Upgrades', - 'function' => 'doListUpgrades', - 'shortcut' => 'lu', - 'options' => array(), - 'doc' => ' -List releases on the server of packages you have installed where -a newer version is available with the same release state (stable etc.).' - ), - 'remote-list' => array( - 'summary' => 'List Remote Packages', - 'function' => 'doRemoteList', - 'shortcut' => 'rl', - 'options' => array(), - 'doc' => ' -Lists the packages available on the configured server along with the -latest stable release of each package.', - ), - 'search' => array( - 'summary' => 'Search remote package database', - 'function' => 'doSearch', - 'shortcut' => 'sp', - 'options' => array(), - 'doc' => ' -Lists all packages which match the search parameters (first param -is package name, second package info)', - ), - 'list-all' => array( - 'summary' => 'List All Packages', - 'function' => 'doListAll', - 'shortcut' => 'la', - 'options' => array(), - 'doc' => ' -Lists the packages available on the configured server along with the -latest stable release of each package.', - ), - 'download' => array( - 'summary' => 'Download Package', - 'function' => 'doDownload', - 'shortcut' => 'd', - 'options' => array( - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'download an uncompressed (.tar) file', - ), - ), - 'doc' => '{package|package-version} -Download a package tarball. The file will be named as suggested by the -server, for example if you download the DB package and the latest stable -version of DB is 1.2, the downloaded file will be DB-1.2.tgz.', - ), - 'clear-cache' => array( - 'summary' => 'Clear XML-RPC Cache', - 'function' => 'doClearCache', - 'shortcut' => 'cc', - 'options' => array(), - 'doc' => ' -Clear the XML-RPC cache. See also the cache_ttl configuration -parameter. -', - ), - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Remote constructor. - * - * @access public - */ - function PEAR_Command_Remote(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doRemoteInfo() - - function doRemoteInfo($command, $options, $params) - { - if (sizeof($params) != 1) { - return $this->raiseError("$command expects one param: the remote package name"); - } - $r = new PEAR_Remote($this->config); - $info = $r->call('package.info', $params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - - $reg = new PEAR_Registry($this->config->get('php_dir')); - $installed = $reg->packageInfo($info['name']); - $info['installed'] = $installed['version'] ? $installed['version'] : '- no -'; - - $this->ui->outputData($info, $command); - - return true; - } - - // }}} - // {{{ doRemoteList() - - function doRemoteList($command, $options, $params) - { - $r = new PEAR_Remote($this->config); - $list_options = false; - if ($this->config->get('preferred_state') == 'stable') - $list_options = true; - $available = $r->call('package.listAll', $list_options); - if (PEAR::isError($available)) { - return $this->raiseError($available); - } - $i = $j = 0; - $data = array( - 'caption' => 'Available packages:', - 'border' => true, - 'headline' => array('Package', 'Version'), - ); - foreach ($available as $name => $info) { - $data['data'][] = array($name, isset($info['stable']) ? $info['stable'] : '-n/a-'); - } - if (count($available)==0) { - $data = '(no packages installed yet)'; - } - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doListAll() - - function doListAll($command, $options, $params) - { - $r = new PEAR_Remote($this->config); - $reg = new PEAR_Registry($this->config->get('php_dir')); - $list_options = false; - if ($this->config->get('preferred_state') == 'stable') - $list_options = true; - $available = $r->call('package.listAll', $list_options); - if (PEAR::isError($available)) { - return $this->raiseError($available); - } - if (!is_array($available)) { - return $this->raiseError('The package list could not be fetched from the remote server. Please try again. (Debug info: "'.$available.'")'); - } - $data = array( - 'caption' => 'All packages:', - 'border' => true, - 'headline' => array('Package', 'Latest', 'Local'), - ); - $local_pkgs = $reg->listPackages(); - - foreach ($available as $name => $info) { - $installed = $reg->packageInfo($name); - $desc = $info['summary']; - if (isset($params[$name])) - $desc .= "\n\n".$info['description']; - - if (isset($options['mode'])) - { - if ($options['mode'] == 'installed' && !isset($installed['version'])) - continue; - if ($options['mode'] == 'notinstalled' && isset($installed['version'])) - continue; - if ($options['mode'] == 'upgrades' - && (!isset($installed['version']) || $installed['version'] == $info['stable'])) - { - continue; - } - } - $pos = array_search(strtolower($name), $local_pkgs); - if ($pos !== false) { - unset($local_pkgs[$pos]); - } - - $data['data'][$info['category']][] = array( - $name, - @$info['stable'], - @$installed['version'], - @$desc, - @$info['deps'], - ); - } - - foreach ($local_pkgs as $name) { - $info = $reg->packageInfo($name); - $data['data']['Local'][] = array( - $info['package'], - '', - $info['version'], - $info['summary'], - @$info['release_deps'] - ); - } - - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doSearch() - - function doSearch($command, $options, $params) - { - if ((!isset($params[0]) || empty($params[0])) - && (!isset($params[1]) || empty($params[1]))) - { - return $this->raiseError('no valid search string supplied'); - }; - - $r = new PEAR_Remote($this->config); - $reg = new PEAR_Registry($this->config->get('php_dir')); - $available = $r->call('package.listAll', true, false); - if (PEAR::isError($available)) { - return $this->raiseError($available); - } - $data = array( - 'caption' => 'Matched packages:', - 'border' => true, - 'headline' => array('Package', 'Stable/(Latest)', 'Local'), - ); - - foreach ($available as $name => $info) { - $found = (!empty($params[0]) && stristr($name, $params[0]) !== false); - if (!$found && !(isset($params[1]) && !empty($params[1]) - && (stristr($info['summary'], $params[1]) !== false - || stristr($info['description'], $params[1]) !== false))) - { - continue; - }; - - $installed = $reg->packageInfo($name); - $desc = $info['summary']; - if (isset($params[$name])) - $desc .= "\n\n".$info['description']; - - $unstable = ''; - if ($info['unstable']) { - $unstable = '/(' . $info['unstable'] . $info['state'] . ')'; - } - if (!isset($info['stable']) || !$info['stable']) { - $info['stable'] = 'none'; - } - $data['data'][$info['category']][] = array( - $name, - $info['stable'] . $unstable, - $installed['version'], - $desc, - ); - } - if (!isset($data['data'])) { - return $this->raiseError('no packages found'); - } - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doDownload() - - function doDownload($command, $options, $params) - { - //$params[0] -> The package to download - if (count($params) != 1) { - return PEAR::raiseError("download expects one argument: the package to download"); - } - $server = $this->config->get('master_server'); - if (!ereg('^http://', $params[0])) { - $getoption = isset($options['nocompress'])&&$options['nocompress']==1?'?uncompress=on':''; - $pkgfile = "http://$server/get/$params[0]".$getoption; - } else { - $pkgfile = $params[0]; - } - $this->bytes_downloaded = 0; - $saved = PEAR_Common::downloadHttp($pkgfile, $this->ui, '.', - array(&$this, 'downloadCallback')); - if (PEAR::isError($saved)) { - return $this->raiseError($saved); - } - $fname = basename($saved); - $this->ui->outputData("File $fname downloaded ($this->bytes_downloaded bytes)", $command); - return true; - } - - function downloadCallback($msg, $params = null) - { - if ($msg == 'done') { - $this->bytes_downloaded = $params; - } - } - - // }}} - // {{{ doListUpgrades() - - function doListUpgrades($command, $options, $params) - { - include_once "PEAR/Registry.php"; - $remote = new PEAR_Remote($this->config); - if (empty($params[0])) { - $state = $this->config->get('preferred_state'); - } else { - $state = $params[0]; - } - $caption = 'Available Upgrades'; - if (empty($state) || $state == 'any') { - $latest = $remote->call("package.listLatestReleases"); - } else { - $latest = $remote->call("package.listLatestReleases", $state); - $caption .= ' (' . implode(', ', PEAR_Common::betterStates($state, true)) . ')'; - } - $caption .= ':'; - if (PEAR::isError($latest)) { - return $latest; - } - $reg = new PEAR_Registry($this->config->get('php_dir')); - $inst = array_flip($reg->listPackages()); - $data = array( - 'caption' => $caption, - 'border' => 1, - 'headline' => array('Package', 'Local', 'Remote', 'Size'), - ); - foreach ((array)$latest as $pkg => $info) { - $package = strtolower($pkg); - if (!isset($inst[$package])) { - // skip packages we don't have installed - continue; - } - extract($info); - $pkginfo = $reg->packageInfo($package); - $inst_version = $pkginfo['version']; - $inst_state = $pkginfo['release_state']; - if (version_compare("$version", "$inst_version", "le")) { - // installed version is up-to-date - continue; - } - if ($filesize >= 20480) { - $filesize += 1024 - ($filesize % 1024); - $fs = sprintf("%dkB", $filesize / 1024); - } elseif ($filesize > 0) { - $filesize += 103 - ($filesize % 103); - $fs = sprintf("%.1fkB", $filesize / 1024.0); - } else { - $fs = " -"; // XXX center instead - } - $data['data'][] = array($pkg, "$inst_version ($inst_state)", "$version ($state)", $fs); - } - if (empty($data['data'])) { - $this->ui->outputData('No upgrades available'); - } else { - $this->ui->outputData($data, $command); - } - return true; - } - - // }}} - // {{{ doClearCache() - - function doClearCache($command, $options, $params) - { - $cache_dir = $this->config->get('cache_dir'); - $verbose = $this->config->get('verbose'); - $output = ''; - if (!($dp = @opendir($cache_dir))) { - return $this->raiseError("opendir($cache_dir) failed: $php_errormsg"); - } - if ($verbose >= 1) { - $output .= "reading directory $cache_dir\n"; - } - $num = 0; - while ($ent = readdir($dp)) { - if (preg_match('/^xmlrpc_cache_[a-z0-9]{32}$/', $ent)) { - $path = $cache_dir . DIRECTORY_SEPARATOR . $ent; - $ok = @unlink($path); - if ($ok) { - if ($verbose >= 2) { - $output .= "deleted $path\n"; - } - $num++; - } elseif ($verbose >= 1) { - $output .= "failed to delete $path\n"; - } - } - } - closedir($dp); - if ($verbose >= 1) { - $output .= "$num cache entries cleared\n"; - } - $this->ui->outputData(rtrim($output), $command); - return $num; - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Common.php b/3rdparty/PEAR/Common.php deleted file mode 100644 index fba53a377997ab5d70e596cc26d24554ff4e564e..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Common.php +++ /dev/null @@ -1,2094 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | PHP Version 4 | -// +----------------------------------------------------------------------+ -// | Copyright (c) 1997-2003 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: Common.php,v 1.126.2.2 2004/12/27 07:04:19 cellog Exp $ - -require_once 'PEAR.php'; -require_once 'Archive/Tar.php'; -require_once 'System.php'; -require_once 'PEAR/Config.php'; - -// {{{ constants and globals - -/** - * PEAR_Common error when an invalid PHP file is passed to PEAR_Common::analyzeSourceCode() - */ -define('PEAR_COMMON_ERROR_INVALIDPHP', 1); -define('_PEAR_COMMON_PACKAGE_NAME_PREG', '[A-Za-z][a-zA-Z0-9_]+'); -define('PEAR_COMMON_PACKAGE_NAME_PREG', '/^' . _PEAR_COMMON_PACKAGE_NAME_PREG . '$/'); - -// this should allow: 1, 1.0, 1.0RC1, 1.0dev, 1.0dev123234234234, 1.0a1, 1.0b1, 1.0pl1 -define('_PEAR_COMMON_PACKAGE_VERSION_PREG', '\d+(?:\.\d+)*(?:[a-zA-Z]+\d*)?'); -define('PEAR_COMMON_PACKAGE_VERSION_PREG', '/^' . _PEAR_COMMON_PACKAGE_VERSION_PREG . '$/i'); - -// XXX far from perfect :-) -define('PEAR_COMMON_PACKAGE_DOWNLOAD_PREG', '/^(' . _PEAR_COMMON_PACKAGE_NAME_PREG . ')(-([.0-9a-zA-Z]+))?$/'); - -/** - * List of temporary files and directories registered by - * PEAR_Common::addTempFile(). - * @var array - */ -$GLOBALS['_PEAR_Common_tempfiles'] = array(); - -/** - * Valid maintainer roles - * @var array - */ -$GLOBALS['_PEAR_Common_maintainer_roles'] = array('lead','developer','contributor','helper'); - -/** - * Valid release states - * @var array - */ -$GLOBALS['_PEAR_Common_release_states'] = array('alpha','beta','stable','snapshot','devel'); - -/** - * Valid dependency types - * @var array - */ -$GLOBALS['_PEAR_Common_dependency_types'] = array('pkg','ext','php','prog','ldlib','rtlib','os','websrv','sapi'); - -/** - * Valid dependency relations - * @var array - */ -$GLOBALS['_PEAR_Common_dependency_relations'] = array('has','eq','lt','le','gt','ge','not', 'ne'); - -/** - * Valid file roles - * @var array - */ -$GLOBALS['_PEAR_Common_file_roles'] = array('php','ext','test','doc','data','src','script'); - -/** - * Valid replacement types - * @var array - */ -$GLOBALS['_PEAR_Common_replacement_types'] = array('php-const', 'pear-config', 'package-info'); - -/** - * Valid "provide" types - * @var array - */ -$GLOBALS['_PEAR_Common_provide_types'] = array('ext', 'prog', 'class', 'function', 'feature', 'api'); - -/** - * Valid "provide" types - * @var array - */ -$GLOBALS['_PEAR_Common_script_phases'] = array('pre-install', 'post-install', 'pre-uninstall', 'post-uninstall', 'pre-build', 'post-build', 'pre-configure', 'post-configure', 'pre-setup', 'post-setup'); - -// }}} - -/** - * Class providing common functionality for PEAR administration classes. - * @deprecated This class will disappear, and its components will be spread - * into smaller classes, like the AT&T breakup - */ -class PEAR_Common extends PEAR -{ - // {{{ properties - - /** stack of elements, gives some sort of XML context */ - var $element_stack = array(); - - /** name of currently parsed XML element */ - var $current_element; - - /** array of attributes of the currently parsed XML element */ - var $current_attributes = array(); - - /** assoc with information about a package */ - var $pkginfo = array(); - - /** - * User Interface object (PEAR_Frontend_* class). If null, - * the log() method uses print. - * @var object - */ - var $ui = null; - - /** - * Configuration object (PEAR_Config). - * @var object - */ - var $config = null; - - var $current_path = null; - - /** - * PEAR_SourceAnalyzer instance - * @var object - */ - var $source_analyzer = null; - /** - * Flag variable used to mark a valid package file - * @var boolean - * @access private - */ - var $_validPackageFile; - - // }}} - - // {{{ constructor - - /** - * PEAR_Common constructor - * - * @access public - */ - function PEAR_Common() - { - parent::PEAR(); - $this->config = &PEAR_Config::singleton(); - $this->debug = $this->config->get('verbose'); - } - - // }}} - // {{{ destructor - - /** - * PEAR_Common destructor - * - * @access private - */ - function _PEAR_Common() - { - // doesn't work due to bug #14744 - //$tempfiles = $this->_tempfiles; - $tempfiles =& $GLOBALS['_PEAR_Common_tempfiles']; - while ($file = array_shift($tempfiles)) { - if (@is_dir($file)) { - System::rm(array('-rf', $file)); - } elseif (file_exists($file)) { - unlink($file); - } - } - } - - // }}} - // {{{ addTempFile() - - /** - * Register a temporary file or directory. When the destructor is - * executed, all registered temporary files and directories are - * removed. - * - * @param string $file name of file or directory - * - * @return void - * - * @access public - */ - function addTempFile($file) - { - $GLOBALS['_PEAR_Common_tempfiles'][] = $file; - } - - // }}} - // {{{ mkDirHier() - - /** - * Wrapper to System::mkDir(), creates a directory as well as - * any necessary parent directories. - * - * @param string $dir directory name - * - * @return bool TRUE on success, or a PEAR error - * - * @access public - */ - function mkDirHier($dir) - { - $this->log(2, "+ create dir $dir"); - return System::mkDir(array('-p', $dir)); - } - - // }}} - // {{{ log() - - /** - * Logging method. - * - * @param int $level log level (0 is quiet, higher is noisier) - * @param string $msg message to write to the log - * - * @return void - * - * @access public - */ - function log($level, $msg, $append_crlf = true) - { - if ($this->debug >= $level) { - if (is_object($this->ui)) { - $this->ui->log($msg, $append_crlf); - } else { - print "$msg\n"; - } - } - } - - // }}} - // {{{ mkTempDir() - - /** - * Create and register a temporary directory. - * - * @param string $tmpdir (optional) Directory to use as tmpdir. - * Will use system defaults (for example - * /tmp or c:\windows\temp) if not specified - * - * @return string name of created directory - * - * @access public - */ - function mkTempDir($tmpdir = '') - { - if ($tmpdir) { - $topt = array('-t', $tmpdir); - } else { - $topt = array(); - } - $topt = array_merge($topt, array('-d', 'pear')); - if (!$tmpdir = System::mktemp($topt)) { - return false; - } - $this->addTempFile($tmpdir); - return $tmpdir; - } - - // }}} - // {{{ setFrontendObject() - - /** - * Set object that represents the frontend to be used. - * - * @param object Reference of the frontend object - * @return void - * @access public - */ - function setFrontendObject(&$ui) - { - $this->ui = &$ui; - } - - // }}} - - // {{{ _unIndent() - - /** - * Unindent given string (?) - * - * @param string $str The string that has to be unindented. - * @return string - * @access private - */ - function _unIndent($str) - { - // remove leading newlines - $str = preg_replace('/^[\r\n]+/', '', $str); - // find whitespace at the beginning of the first line - $indent_len = strspn($str, " \t"); - $indent = substr($str, 0, $indent_len); - $data = ''; - // remove the same amount of whitespace from following lines - foreach (explode("\n", $str) as $line) { - if (substr($line, 0, $indent_len) == $indent) { - $data .= substr($line, $indent_len) . "\n"; - } - } - return $data; - } - - // }}} - // {{{ _element_start() - - /** - * XML parser callback for starting elements. Used while package - * format version is not yet known. - * - * @param resource $xp XML parser resource - * @param string $name name of starting element - * @param array $attribs element attributes, name => value - * - * @return void - * - * @access private - */ - function _element_start($xp, $name, $attribs) - { - array_push($this->element_stack, $name); - $this->current_element = $name; - $spos = sizeof($this->element_stack) - 2; - $this->prev_element = ($spos >= 0) ? $this->element_stack[$spos] : ''; - $this->current_attributes = $attribs; - switch ($name) { - case 'package': { - $this->_validPackageFile = true; - if (isset($attribs['version'])) { - $vs = preg_replace('/[^0-9a-z]/', '_', $attribs['version']); - } else { - $vs = '1_0'; - } - $elem_start = '_element_start_'. $vs; - $elem_end = '_element_end_'. $vs; - $cdata = '_pkginfo_cdata_'. $vs; - if (!method_exists($this, $elem_start) || - !method_exists($this, $elem_end) || - !method_exists($this, $cdata)) { - $this->raiseError("No handlers for package.xml version $attribs[version]"); - return; - } - xml_set_element_handler($xp, $elem_start, $elem_end); - xml_set_character_data_handler($xp, $cdata); - break; - } - } - } - - // }}} - // {{{ _element_end() - - /** - * XML parser callback for ending elements. Used while package - * format version is not yet known. - * - * @param resource $xp XML parser resource - * @param string $name name of ending element - * - * @return void - * - * @access private - */ - function _element_end($xp, $name) - { - } - - // }}} - - // Support for package DTD v1.0: - // {{{ _element_start_1_0() - - /** - * XML parser callback for ending elements. Used for version 1.0 - * packages. - * - * @param resource $xp XML parser resource - * @param string $name name of ending element - * - * @return void - * - * @access private - */ - function _element_start_1_0($xp, $name, $attribs) - { - array_push($this->element_stack, $name); - $this->current_element = $name; - $spos = sizeof($this->element_stack) - 2; - $this->prev_element = ($spos >= 0) ? $this->element_stack[$spos] : ''; - $this->current_attributes = $attribs; - $this->cdata = ''; - switch ($name) { - case 'dir': - if ($this->in_changelog) { - break; - } - if ($attribs['name'] != '/') { - $this->dir_names[] = $attribs['name']; - } - if (isset($attribs['baseinstalldir'])) { - $this->dir_install = $attribs['baseinstalldir']; - } - if (isset($attribs['role'])) { - $this->dir_role = $attribs['role']; - } - break; - case 'file': - if ($this->in_changelog) { - break; - } - if (isset($attribs['name'])) { - $path = ''; - if (count($this->dir_names)) { - foreach ($this->dir_names as $dir) { - $path .= $dir . DIRECTORY_SEPARATOR; - } - } - $path .= $attribs['name']; - unset($attribs['name']); - $this->current_path = $path; - $this->filelist[$path] = $attribs; - // Set the baseinstalldir only if the file don't have this attrib - if (!isset($this->filelist[$path]['baseinstalldir']) && - isset($this->dir_install)) - { - $this->filelist[$path]['baseinstalldir'] = $this->dir_install; - } - // Set the Role - if (!isset($this->filelist[$path]['role']) && isset($this->dir_role)) { - $this->filelist[$path]['role'] = $this->dir_role; - } - } - break; - case 'replace': - if (!$this->in_changelog) { - $this->filelist[$this->current_path]['replacements'][] = $attribs; - } - break; - case 'maintainers': - $this->pkginfo['maintainers'] = array(); - $this->m_i = 0; // maintainers array index - break; - case 'maintainer': - // compatibility check - if (!isset($this->pkginfo['maintainers'])) { - $this->pkginfo['maintainers'] = array(); - $this->m_i = 0; - } - $this->pkginfo['maintainers'][$this->m_i] = array(); - $this->current_maintainer =& $this->pkginfo['maintainers'][$this->m_i]; - break; - case 'changelog': - $this->pkginfo['changelog'] = array(); - $this->c_i = 0; // changelog array index - $this->in_changelog = true; - break; - case 'release': - if ($this->in_changelog) { - $this->pkginfo['changelog'][$this->c_i] = array(); - $this->current_release = &$this->pkginfo['changelog'][$this->c_i]; - } else { - $this->current_release = &$this->pkginfo; - } - break; - case 'deps': - if (!$this->in_changelog) { - $this->pkginfo['release_deps'] = array(); - } - break; - case 'dep': - // dependencies array index - if (!$this->in_changelog) { - $this->d_i++; - $this->pkginfo['release_deps'][$this->d_i] = $attribs; - } - break; - case 'configureoptions': - if (!$this->in_changelog) { - $this->pkginfo['configure_options'] = array(); - } - break; - case 'configureoption': - if (!$this->in_changelog) { - $this->pkginfo['configure_options'][] = $attribs; - } - break; - case 'provides': - if (empty($attribs['type']) || empty($attribs['name'])) { - break; - } - $attribs['explicit'] = true; - $this->pkginfo['provides']["$attribs[type];$attribs[name]"] = $attribs; - break; - } - } - - // }}} - // {{{ _element_end_1_0() - - /** - * XML parser callback for ending elements. Used for version 1.0 - * packages. - * - * @param resource $xp XML parser resource - * @param string $name name of ending element - * - * @return void - * - * @access private - */ - function _element_end_1_0($xp, $name) - { - $data = trim($this->cdata); - switch ($name) { - case 'name': - switch ($this->prev_element) { - case 'package': - // XXX should we check the package name here? - $this->pkginfo['package'] = ereg_replace('[^a-zA-Z0-9._]', '_', $data); - break; - case 'maintainer': - $this->current_maintainer['name'] = $data; - break; - } - break; - case 'summary': - $this->pkginfo['summary'] = $data; - break; - case 'description': - $data = $this->_unIndent($this->cdata); - $this->pkginfo['description'] = $data; - break; - case 'user': - $this->current_maintainer['handle'] = $data; - break; - case 'email': - $this->current_maintainer['email'] = $data; - break; - case 'role': - $this->current_maintainer['role'] = $data; - break; - case 'version': - $data = ereg_replace ('[^a-zA-Z0-9._\-]', '_', $data); - if ($this->in_changelog) { - $this->current_release['version'] = $data; - } else { - $this->pkginfo['version'] = $data; - } - break; - case 'date': - if ($this->in_changelog) { - $this->current_release['release_date'] = $data; - } else { - $this->pkginfo['release_date'] = $data; - } - break; - case 'notes': - // try to "de-indent" release notes in case someone - // has been over-indenting their xml ;-) - $data = $this->_unIndent($this->cdata); - if ($this->in_changelog) { - $this->current_release['release_notes'] = $data; - } else { - $this->pkginfo['release_notes'] = $data; - } - break; - case 'warnings': - if ($this->in_changelog) { - $this->current_release['release_warnings'] = $data; - } else { - $this->pkginfo['release_warnings'] = $data; - } - break; - case 'state': - if ($this->in_changelog) { - $this->current_release['release_state'] = $data; - } else { - $this->pkginfo['release_state'] = $data; - } - break; - case 'license': - if ($this->in_changelog) { - $this->current_release['release_license'] = $data; - } else { - $this->pkginfo['release_license'] = $data; - } - break; - case 'dep': - if ($data && !$this->in_changelog) { - $this->pkginfo['release_deps'][$this->d_i]['name'] = $data; - } - break; - case 'dir': - if ($this->in_changelog) { - break; - } - array_pop($this->dir_names); - break; - case 'file': - if ($this->in_changelog) { - break; - } - if ($data) { - $path = ''; - if (count($this->dir_names)) { - foreach ($this->dir_names as $dir) { - $path .= $dir . DIRECTORY_SEPARATOR; - } - } - $path .= $data; - $this->filelist[$path] = $this->current_attributes; - // Set the baseinstalldir only if the file don't have this attrib - if (!isset($this->filelist[$path]['baseinstalldir']) && - isset($this->dir_install)) - { - $this->filelist[$path]['baseinstalldir'] = $this->dir_install; - } - // Set the Role - if (!isset($this->filelist[$path]['role']) && isset($this->dir_role)) { - $this->filelist[$path]['role'] = $this->dir_role; - } - } - break; - case 'maintainer': - if (empty($this->pkginfo['maintainers'][$this->m_i]['role'])) { - $this->pkginfo['maintainers'][$this->m_i]['role'] = 'lead'; - } - $this->m_i++; - break; - case 'release': - if ($this->in_changelog) { - $this->c_i++; - } - break; - case 'changelog': - $this->in_changelog = false; - break; - } - array_pop($this->element_stack); - $spos = sizeof($this->element_stack) - 1; - $this->current_element = ($spos > 0) ? $this->element_stack[$spos] : ''; - $this->cdata = ''; - } - - // }}} - // {{{ _pkginfo_cdata_1_0() - - /** - * XML parser callback for character data. Used for version 1.0 - * packages. - * - * @param resource $xp XML parser resource - * @param string $name character data - * - * @return void - * - * @access private - */ - function _pkginfo_cdata_1_0($xp, $data) - { - if (isset($this->cdata)) { - $this->cdata .= $data; - } - } - - // }}} - - // {{{ infoFromTgzFile() - - /** - * Returns information about a package file. Expects the name of - * a gzipped tar file as input. - * - * @param string $file name of .tgz file - * - * @return array array with package information - * - * @access public - * - */ - function infoFromTgzFile($file) - { - if (!@is_file($file)) { - return $this->raiseError("could not open file \"$file\""); - } - $tar = new Archive_Tar($file); - if ($this->debug <= 1) { - $tar->pushErrorHandling(PEAR_ERROR_RETURN); - } - $content = $tar->listContent(); - if ($this->debug <= 1) { - $tar->popErrorHandling(); - } - if (!is_array($content)) { - $file = realpath($file); - return $this->raiseError("Could not get contents of package \"$file\"". - '. Invalid tgz file.'); - } - $xml = null; - foreach ($content as $file) { - $name = $file['filename']; - if ($name == 'package.xml') { - $xml = $name; - break; - } elseif (ereg('package.xml$', $name, $match)) { - $xml = $match[0]; - break; - } - } - $tmpdir = System::mkTemp(array('-d', 'pear')); - $this->addTempFile($tmpdir); - if (!$xml || !$tar->extractList(array($xml), $tmpdir)) { - return $this->raiseError('could not extract the package.xml file'); - } - return $this->infoFromDescriptionFile("$tmpdir/$xml"); - } - - // }}} - // {{{ infoFromDescriptionFile() - - /** - * Returns information about a package file. Expects the name of - * a package xml file as input. - * - * @param string $descfile name of package xml file - * - * @return array array with package information - * - * @access public - * - */ - function infoFromDescriptionFile($descfile) - { - if (!@is_file($descfile) || !is_readable($descfile) || - (!$fp = @fopen($descfile, 'r'))) { - return $this->raiseError("Unable to open $descfile"); - } - - // read the whole thing so we only get one cdata callback - // for each block of cdata - $data = fread($fp, filesize($descfile)); - return $this->infoFromString($data); - } - - // }}} - // {{{ infoFromString() - - /** - * Returns information about a package file. Expects the contents - * of a package xml file as input. - * - * @param string $data name of package xml file - * - * @return array array with package information - * - * @access public - * - */ - function infoFromString($data) - { - require_once('PEAR/Dependency.php'); - if (PEAR_Dependency::checkExtension($error, 'xml')) { - return $this->raiseError($error); - } - $xp = @xml_parser_create(); - if (!$xp) { - return $this->raiseError('Unable to create XML parser'); - } - xml_set_object($xp, $this); - xml_set_element_handler($xp, '_element_start', '_element_end'); - xml_set_character_data_handler($xp, '_pkginfo_cdata'); - xml_parser_set_option($xp, XML_OPTION_CASE_FOLDING, false); - - $this->element_stack = array(); - $this->pkginfo = array('provides' => array()); - $this->current_element = false; - unset($this->dir_install); - $this->pkginfo['filelist'] = array(); - $this->filelist =& $this->pkginfo['filelist']; - $this->dir_names = array(); - $this->in_changelog = false; - $this->d_i = 0; - $this->cdata = ''; - $this->_validPackageFile = false; - - if (!xml_parse($xp, $data, 1)) { - $code = xml_get_error_code($xp); - $msg = sprintf("XML error: %s at line %d", - xml_error_string($code), - xml_get_current_line_number($xp)); - xml_parser_free($xp); - return $this->raiseError($msg, $code); - } - - xml_parser_free($xp); - - if (!$this->_validPackageFile) { - return $this->raiseError('Invalid Package File, no <package> tag'); - } - foreach ($this->pkginfo as $k => $v) { - if (!is_array($v)) { - $this->pkginfo[$k] = trim($v); - } - } - return $this->pkginfo; - } - // }}} - // {{{ infoFromAny() - - /** - * Returns package information from different sources - * - * This method is able to extract information about a package - * from a .tgz archive or from a XML package definition file. - * - * @access public - * @param string Filename of the source ('package.xml', '<package>.tgz') - * @return string - */ - function infoFromAny($info) - { - if (is_string($info) && file_exists($info)) { - $tmp = substr($info, -4); - if ($tmp == '.xml') { - $info = $this->infoFromDescriptionFile($info); - } elseif ($tmp == '.tar' || $tmp == '.tgz') { - $info = $this->infoFromTgzFile($info); - } else { - $fp = fopen($info, "r"); - $test = fread($fp, 5); - fclose($fp); - if ($test == "<?xml") { - $info = $this->infoFromDescriptionFile($info); - } else { - $info = $this->infoFromTgzFile($info); - } - } - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - } - return $info; - } - - // }}} - // {{{ xmlFromInfo() - - /** - * Return an XML document based on the package info (as returned - * by the PEAR_Common::infoFrom* methods). - * - * @param array $pkginfo package info - * - * @return string XML data - * - * @access public - */ - function xmlFromInfo($pkginfo) - { - static $maint_map = array( - "handle" => "user", - "name" => "name", - "email" => "email", - "role" => "role", - ); - $ret = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n"; - $ret .= "<!DOCTYPE package SYSTEM \"http://pear.php.net/dtd/package-1.0\">\n"; - $ret .= "<package version=\"1.0\"> - <name>$pkginfo[package]</name> - <summary>".htmlspecialchars($pkginfo['summary'])."</summary> - <description>".htmlspecialchars($pkginfo['description'])."</description> - <maintainers> -"; - foreach ($pkginfo['maintainers'] as $maint) { - $ret .= " <maintainer>\n"; - foreach ($maint_map as $idx => $elm) { - $ret .= " <$elm>"; - $ret .= htmlspecialchars($maint[$idx]); - $ret .= "</$elm>\n"; - } - $ret .= " </maintainer>\n"; - } - $ret .= " </maintainers>\n"; - $ret .= $this->_makeReleaseXml($pkginfo); - if (@sizeof($pkginfo['changelog']) > 0) { - $ret .= " <changelog>\n"; - foreach ($pkginfo['changelog'] as $oldrelease) { - $ret .= $this->_makeReleaseXml($oldrelease, true); - } - $ret .= " </changelog>\n"; - } - $ret .= "</package>\n"; - return $ret; - } - - // }}} - // {{{ _makeReleaseXml() - - /** - * Generate part of an XML description with release information. - * - * @param array $pkginfo array with release information - * @param bool $changelog whether the result will be in a changelog element - * - * @return string XML data - * - * @access private - */ - function _makeReleaseXml($pkginfo, $changelog = false) - { - // XXX QUOTE ENTITIES IN PCDATA, OR EMBED IN CDATA BLOCKS!! - $indent = $changelog ? " " : ""; - $ret = "$indent <release>\n"; - if (!empty($pkginfo['version'])) { - $ret .= "$indent <version>$pkginfo[version]</version>\n"; - } - if (!empty($pkginfo['release_date'])) { - $ret .= "$indent <date>$pkginfo[release_date]</date>\n"; - } - if (!empty($pkginfo['release_license'])) { - $ret .= "$indent <license>$pkginfo[release_license]</license>\n"; - } - if (!empty($pkginfo['release_state'])) { - $ret .= "$indent <state>$pkginfo[release_state]</state>\n"; - } - if (!empty($pkginfo['release_notes'])) { - $ret .= "$indent <notes>".htmlspecialchars($pkginfo['release_notes'])."</notes>\n"; - } - if (!empty($pkginfo['release_warnings'])) { - $ret .= "$indent <warnings>".htmlspecialchars($pkginfo['release_warnings'])."</warnings>\n"; - } - if (isset($pkginfo['release_deps']) && sizeof($pkginfo['release_deps']) > 0) { - $ret .= "$indent <deps>\n"; - foreach ($pkginfo['release_deps'] as $dep) { - $ret .= "$indent <dep type=\"$dep[type]\" rel=\"$dep[rel]\""; - if (isset($dep['version'])) { - $ret .= " version=\"$dep[version]\""; - } - if (isset($dep['optional'])) { - $ret .= " optional=\"$dep[optional]\""; - } - if (isset($dep['name'])) { - $ret .= ">$dep[name]</dep>\n"; - } else { - $ret .= "/>\n"; - } - } - $ret .= "$indent </deps>\n"; - } - if (isset($pkginfo['configure_options'])) { - $ret .= "$indent <configureoptions>\n"; - foreach ($pkginfo['configure_options'] as $c) { - $ret .= "$indent <configureoption name=\"". - htmlspecialchars($c['name']) . "\""; - if (isset($c['default'])) { - $ret .= " default=\"" . htmlspecialchars($c['default']) . "\""; - } - $ret .= " prompt=\"" . htmlspecialchars($c['prompt']) . "\""; - $ret .= "/>\n"; - } - $ret .= "$indent </configureoptions>\n"; - } - if (isset($pkginfo['provides'])) { - foreach ($pkginfo['provides'] as $key => $what) { - $ret .= "$indent <provides type=\"$what[type]\" "; - $ret .= "name=\"$what[name]\" "; - if (isset($what['extends'])) { - $ret .= "extends=\"$what[extends]\" "; - } - $ret .= "/>\n"; - } - } - if (isset($pkginfo['filelist'])) { - $ret .= "$indent <filelist>\n"; - foreach ($pkginfo['filelist'] as $file => $fa) { - @$ret .= "$indent <file role=\"$fa[role]\""; - if (isset($fa['baseinstalldir'])) { - $ret .= ' baseinstalldir="' . - htmlspecialchars($fa['baseinstalldir']) . '"'; - } - if (isset($fa['md5sum'])) { - $ret .= " md5sum=\"$fa[md5sum]\""; - } - if (isset($fa['platform'])) { - $ret .= " platform=\"$fa[platform]\""; - } - if (!empty($fa['install-as'])) { - $ret .= ' install-as="' . - htmlspecialchars($fa['install-as']) . '"'; - } - $ret .= ' name="' . htmlspecialchars($file) . '"'; - if (empty($fa['replacements'])) { - $ret .= "/>\n"; - } else { - $ret .= ">\n"; - foreach ($fa['replacements'] as $r) { - $ret .= "$indent <replace"; - foreach ($r as $k => $v) { - $ret .= " $k=\"" . htmlspecialchars($v) .'"'; - } - $ret .= "/>\n"; - } - @$ret .= "$indent </file>\n"; - } - } - $ret .= "$indent </filelist>\n"; - } - $ret .= "$indent </release>\n"; - return $ret; - } - - // }}} - // {{{ validatePackageInfo() - - /** - * Validate XML package definition file. - * - * @param string $info Filename of the package archive or of the - * package definition file - * @param array $errors Array that will contain the errors - * @param array $warnings Array that will contain the warnings - * @param string $dir_prefix (optional) directory where source files - * may be found, or empty if they are not available - * @access public - * @return boolean - */ - function validatePackageInfo($info, &$errors, &$warnings, $dir_prefix = '') - { - if (PEAR::isError($info = $this->infoFromAny($info))) { - return $this->raiseError($info); - } - if (!is_array($info)) { - return false; - } - - $errors = array(); - $warnings = array(); - if (!isset($info['package'])) { - $errors[] = 'missing package name'; - } elseif (!$this->validPackageName($info['package'])) { - $errors[] = 'invalid package name'; - } - $this->_packageName = $pn = $info['package']; - - if (empty($info['summary'])) { - $errors[] = 'missing summary'; - } elseif (strpos(trim($info['summary']), "\n") !== false) { - $warnings[] = 'summary should be on a single line'; - } - if (empty($info['description'])) { - $errors[] = 'missing description'; - } - if (empty($info['release_license'])) { - $errors[] = 'missing license'; - } - if (!isset($info['version'])) { - $errors[] = 'missing version'; - } elseif (!$this->validPackageVersion($info['version'])) { - $errors[] = 'invalid package release version'; - } - if (empty($info['release_state'])) { - $errors[] = 'missing release state'; - } elseif (!in_array($info['release_state'], PEAR_Common::getReleaseStates())) { - $errors[] = "invalid release state `$info[release_state]', should be one of: " - . implode(' ', PEAR_Common::getReleaseStates()); - } - if (empty($info['release_date'])) { - $errors[] = 'missing release date'; - } elseif (!preg_match('/^\d{4}-\d\d-\d\d$/', $info['release_date'])) { - $errors[] = "invalid release date `$info[release_date]', format is YYYY-MM-DD"; - } - if (empty($info['release_notes'])) { - $errors[] = "missing release notes"; - } - if (empty($info['maintainers'])) { - $errors[] = 'no maintainer(s)'; - } else { - $i = 1; - foreach ($info['maintainers'] as $m) { - if (empty($m['handle'])) { - $errors[] = "maintainer $i: missing handle"; - } - if (empty($m['role'])) { - $errors[] = "maintainer $i: missing role"; - } elseif (!in_array($m['role'], PEAR_Common::getUserRoles())) { - $errors[] = "maintainer $i: invalid role `$m[role]', should be one of: " - . implode(' ', PEAR_Common::getUserRoles()); - } - if (empty($m['name'])) { - $errors[] = "maintainer $i: missing name"; - } - if (empty($m['email'])) { - $errors[] = "maintainer $i: missing email"; - } - $i++; - } - } - if (!empty($info['release_deps'])) { - $i = 1; - foreach ($info['release_deps'] as $d) { - if (empty($d['type'])) { - $errors[] = "dependency $i: missing type"; - } elseif (!in_array($d['type'], PEAR_Common::getDependencyTypes())) { - $errors[] = "dependency $i: invalid type '$d[type]', should be one of: " . - implode(' ', PEAR_Common::getDependencyTypes()); - } - if (empty($d['rel'])) { - $errors[] = "dependency $i: missing relation"; - } elseif (!in_array($d['rel'], PEAR_Common::getDependencyRelations())) { - $errors[] = "dependency $i: invalid relation '$d[rel]', should be one of: " - . implode(' ', PEAR_Common::getDependencyRelations()); - } - if (!empty($d['optional'])) { - if (!in_array($d['optional'], array('yes', 'no'))) { - $errors[] = "dependency $i: invalid relation optional attribute '$d[optional]', should be one of: yes no"; - } else { - if (($d['rel'] == 'not' || $d['rel'] == 'ne') && $d['optional'] == 'yes') { - $errors[] = "dependency $i: 'not' and 'ne' dependencies cannot be " . - "optional"; - } - } - } - if ($d['rel'] != 'not' && $d['rel'] != 'has' && empty($d['version'])) { - $warnings[] = "dependency $i: missing version"; - } elseif (($d['rel'] == 'not' || $d['rel'] == 'has') && !empty($d['version'])) { - $warnings[] = "dependency $i: version ignored for `$d[rel]' dependencies"; - } - if ($d['rel'] == 'not' && !empty($d['version'])) { - $warnings[] = "dependency $i: 'not' defines a total conflict, to exclude " . - "specific versions, use 'ne'"; - } - if ($d['type'] == 'php' && !empty($d['name'])) { - $warnings[] = "dependency $i: name ignored for php type dependencies"; - } elseif ($d['type'] != 'php' && empty($d['name'])) { - $errors[] = "dependency $i: missing name"; - } - if ($d['type'] == 'php' && $d['rel'] == 'not') { - $errors[] = "dependency $i: PHP dependencies cannot use 'not' " . - "rel, use 'ne' to exclude versions"; - } - $i++; - } - } - if (!empty($info['configure_options'])) { - $i = 1; - foreach ($info['configure_options'] as $c) { - if (empty($c['name'])) { - $errors[] = "configure option $i: missing name"; - } - if (empty($c['prompt'])) { - $errors[] = "configure option $i: missing prompt"; - } - $i++; - } - } - if (empty($info['filelist'])) { - $errors[] = 'no files'; - } else { - foreach ($info['filelist'] as $file => $fa) { - if (empty($fa['role'])) { - $errors[] = "file $file: missing role"; - continue; - } elseif (!in_array($fa['role'], PEAR_Common::getFileRoles())) { - $errors[] = "file $file: invalid role, should be one of: " - . implode(' ', PEAR_Common::getFileRoles()); - } - if ($fa['role'] == 'php' && $dir_prefix) { - $this->log(1, "Analyzing $file"); - $srcinfo = $this->analyzeSourceCode($dir_prefix . DIRECTORY_SEPARATOR . $file); - if ($srcinfo) { - $this->buildProvidesArray($srcinfo); - } - } - - // (ssb) Any checks we can do for baseinstalldir? - // (cox) Perhaps checks that either the target dir and - // baseInstall doesn't cointain "../../" - } - } - $this->_packageName = $pn = $info['package']; - $pnl = strlen($pn); - foreach ((array)$this->pkginfo['provides'] as $key => $what) { - if (isset($what['explicit'])) { - // skip conformance checks if the provides entry is - // specified in the package.xml file - continue; - } - extract($what); - if ($type == 'class') { - if (!strncasecmp($name, $pn, $pnl)) { - continue; - } - $warnings[] = "in $file: class \"$name\" not prefixed with package name \"$pn\""; - } elseif ($type == 'function') { - if (strstr($name, '::') || !strncasecmp($name, $pn, $pnl)) { - continue; - } - $warnings[] = "in $file: function \"$name\" not prefixed with package name \"$pn\""; - } - } - - - return true; - } - - // }}} - // {{{ buildProvidesArray() - - /** - * Build a "provides" array from data returned by - * analyzeSourceCode(). The format of the built array is like - * this: - * - * array( - * 'class;MyClass' => 'array('type' => 'class', 'name' => 'MyClass'), - * ... - * ) - * - * - * @param array $srcinfo array with information about a source file - * as returned by the analyzeSourceCode() method. - * - * @return void - * - * @access public - * - */ - function buildProvidesArray($srcinfo) - { - $file = basename($srcinfo['source_file']); - $pn = ''; - if (isset($this->_packageName)) { - $pn = $this->_packageName; - } - $pnl = strlen($pn); - foreach ($srcinfo['declared_classes'] as $class) { - $key = "class;$class"; - if (isset($this->pkginfo['provides'][$key])) { - continue; - } - $this->pkginfo['provides'][$key] = - array('file'=> $file, 'type' => 'class', 'name' => $class); - if (isset($srcinfo['inheritance'][$class])) { - $this->pkginfo['provides'][$key]['extends'] = - $srcinfo['inheritance'][$class]; - } - } - foreach ($srcinfo['declared_methods'] as $class => $methods) { - foreach ($methods as $method) { - $function = "$class::$method"; - $key = "function;$function"; - if ($method{0} == '_' || !strcasecmp($method, $class) || - isset($this->pkginfo['provides'][$key])) { - continue; - } - $this->pkginfo['provides'][$key] = - array('file'=> $file, 'type' => 'function', 'name' => $function); - } - } - - foreach ($srcinfo['declared_functions'] as $function) { - $key = "function;$function"; - if ($function{0} == '_' || isset($this->pkginfo['provides'][$key])) { - continue; - } - if (!strstr($function, '::') && strncasecmp($function, $pn, $pnl)) { - $warnings[] = "in1 " . $file . ": function \"$function\" not prefixed with package name \"$pn\""; - } - $this->pkginfo['provides'][$key] = - array('file'=> $file, 'type' => 'function', 'name' => $function); - } - } - - // }}} - // {{{ analyzeSourceCode() - - /** - * Analyze the source code of the given PHP file - * - * @param string Filename of the PHP file - * @return mixed - * @access public - */ - function analyzeSourceCode($file) - { - if (!function_exists("token_get_all")) { - return false; - } - if (!defined('T_DOC_COMMENT')) { - define('T_DOC_COMMENT', T_COMMENT); - } - if (!defined('T_INTERFACE')) { - define('T_INTERFACE', -1); - } - if (!defined('T_IMPLEMENTS')) { - define('T_IMPLEMENTS', -1); - } - if (!$fp = @fopen($file, "r")) { - return false; - } - $contents = fread($fp, filesize($file)); - $tokens = token_get_all($contents); -/* - for ($i = 0; $i < sizeof($tokens); $i++) { - @list($token, $data) = $tokens[$i]; - if (is_string($token)) { - var_dump($token); - } else { - print token_name($token) . ' '; - var_dump(rtrim($data)); - } - } -*/ - $look_for = 0; - $paren_level = 0; - $bracket_level = 0; - $brace_level = 0; - $lastphpdoc = ''; - $current_class = ''; - $current_interface = ''; - $current_class_level = -1; - $current_function = ''; - $current_function_level = -1; - $declared_classes = array(); - $declared_interfaces = array(); - $declared_functions = array(); - $declared_methods = array(); - $used_classes = array(); - $used_functions = array(); - $extends = array(); - $implements = array(); - $nodeps = array(); - $inquote = false; - $interface = false; - for ($i = 0; $i < sizeof($tokens); $i++) { - if (is_array($tokens[$i])) { - list($token, $data) = $tokens[$i]; - } else { - $token = $tokens[$i]; - $data = ''; - } - if ($inquote) { - if ($token != '"') { - continue; - } else { - $inquote = false; - } - } - switch ($token) { - case T_WHITESPACE: - continue; - case ';': - if ($interface) { - $current_function = ''; - $current_function_level = -1; - } - break; - case '"': - $inquote = true; - break; - case T_CURLY_OPEN: - case T_DOLLAR_OPEN_CURLY_BRACES: - case '{': $brace_level++; continue 2; - case '}': - $brace_level--; - if ($current_class_level == $brace_level) { - $current_class = ''; - $current_class_level = -1; - } - if ($current_function_level == $brace_level) { - $current_function = ''; - $current_function_level = -1; - } - continue 2; - case '[': $bracket_level++; continue 2; - case ']': $bracket_level--; continue 2; - case '(': $paren_level++; continue 2; - case ')': $paren_level--; continue 2; - case T_INTERFACE: - $interface = true; - case T_CLASS: - if (($current_class_level != -1) || ($current_function_level != -1)) { - PEAR::raiseError("Parser error: Invalid PHP file $file", - PEAR_COMMON_ERROR_INVALIDPHP); - return false; - } - case T_FUNCTION: - case T_NEW: - case T_EXTENDS: - case T_IMPLEMENTS: - $look_for = $token; - continue 2; - case T_STRING: - if (version_compare(zend_version(), '2.0', '<')) { - if (in_array(strtolower($data), - array('public', 'private', 'protected', 'abstract', - 'interface', 'implements', 'clone', 'throw') - )) { - PEAR::raiseError('Error: PHP5 packages must be packaged by php 5 PEAR'); - return false; - } - } - if ($look_for == T_CLASS) { - $current_class = $data; - $current_class_level = $brace_level; - $declared_classes[] = $current_class; - } elseif ($look_for == T_INTERFACE) { - $current_interface = $data; - $current_class_level = $brace_level; - $declared_interfaces[] = $current_interface; - } elseif ($look_for == T_IMPLEMENTS) { - $implements[$current_class] = $data; - } elseif ($look_for == T_EXTENDS) { - $extends[$current_class] = $data; - } elseif ($look_for == T_FUNCTION) { - if ($current_class) { - $current_function = "$current_class::$data"; - $declared_methods[$current_class][] = $data; - } elseif ($current_interface) { - $current_function = "$current_interface::$data"; - $declared_methods[$current_interface][] = $data; - } else { - $current_function = $data; - $declared_functions[] = $current_function; - } - $current_function_level = $brace_level; - $m = array(); - } elseif ($look_for == T_NEW) { - $used_classes[$data] = true; - } - $look_for = 0; - continue 2; - case T_VARIABLE: - $look_for = 0; - continue 2; - case T_DOC_COMMENT: - case T_COMMENT: - if (preg_match('!^/\*\*\s!', $data)) { - $lastphpdoc = $data; - if (preg_match_all('/@nodep\s+(\S+)/', $lastphpdoc, $m)) { - $nodeps = array_merge($nodeps, $m[1]); - } - } - continue 2; - case T_DOUBLE_COLON: - if (!($tokens[$i - 1][0] == T_WHITESPACE || $tokens[$i - 1][0] == T_STRING)) { - PEAR::raiseError("Parser error: Invalid PHP file $file", - PEAR_COMMON_ERROR_INVALIDPHP); - return false; - } - $class = $tokens[$i - 1][1]; - if (strtolower($class) != 'parent') { - $used_classes[$class] = true; - } - continue 2; - } - } - return array( - "source_file" => $file, - "declared_classes" => $declared_classes, - "declared_interfaces" => $declared_interfaces, - "declared_methods" => $declared_methods, - "declared_functions" => $declared_functions, - "used_classes" => array_diff(array_keys($used_classes), $nodeps), - "inheritance" => $extends, - "implements" => $implements, - ); - } - - // }}} - // {{{ betterStates() - - /** - * Return an array containing all of the states that are more stable than - * or equal to the passed in state - * - * @param string Release state - * @param boolean Determines whether to include $state in the list - * @return false|array False if $state is not a valid release state - */ - function betterStates($state, $include = false) - { - static $states = array('snapshot', 'devel', 'alpha', 'beta', 'stable'); - $i = array_search($state, $states); - if ($i === false) { - return false; - } - if ($include) { - $i--; - } - return array_slice($states, $i + 1); - } - - // }}} - // {{{ detectDependencies() - - function detectDependencies($any, $status_callback = null) - { - if (!function_exists("token_get_all")) { - return false; - } - if (PEAR::isError($info = $this->infoFromAny($any))) { - return $this->raiseError($info); - } - if (!is_array($info)) { - return false; - } - $deps = array(); - $used_c = $decl_c = $decl_f = $decl_m = array(); - foreach ($info['filelist'] as $file => $fa) { - $tmp = $this->analyzeSourceCode($file); - $used_c = @array_merge($used_c, $tmp['used_classes']); - $decl_c = @array_merge($decl_c, $tmp['declared_classes']); - $decl_f = @array_merge($decl_f, $tmp['declared_functions']); - $decl_m = @array_merge($decl_m, $tmp['declared_methods']); - $inheri = @array_merge($inheri, $tmp['inheritance']); - } - $used_c = array_unique($used_c); - $decl_c = array_unique($decl_c); - $undecl_c = array_diff($used_c, $decl_c); - return array('used_classes' => $used_c, - 'declared_classes' => $decl_c, - 'declared_methods' => $decl_m, - 'declared_functions' => $decl_f, - 'undeclared_classes' => $undecl_c, - 'inheritance' => $inheri, - ); - } - - // }}} - // {{{ getUserRoles() - - /** - * Get the valid roles for a PEAR package maintainer - * - * @return array - * @static - */ - function getUserRoles() - { - return $GLOBALS['_PEAR_Common_maintainer_roles']; - } - - // }}} - // {{{ getReleaseStates() - - /** - * Get the valid package release states of packages - * - * @return array - * @static - */ - function getReleaseStates() - { - return $GLOBALS['_PEAR_Common_release_states']; - } - - // }}} - // {{{ getDependencyTypes() - - /** - * Get the implemented dependency types (php, ext, pkg etc.) - * - * @return array - * @static - */ - function getDependencyTypes() - { - return $GLOBALS['_PEAR_Common_dependency_types']; - } - - // }}} - // {{{ getDependencyRelations() - - /** - * Get the implemented dependency relations (has, lt, ge etc.) - * - * @return array - * @static - */ - function getDependencyRelations() - { - return $GLOBALS['_PEAR_Common_dependency_relations']; - } - - // }}} - // {{{ getFileRoles() - - /** - * Get the implemented file roles - * - * @return array - * @static - */ - function getFileRoles() - { - return $GLOBALS['_PEAR_Common_file_roles']; - } - - // }}} - // {{{ getReplacementTypes() - - /** - * Get the implemented file replacement types in - * - * @return array - * @static - */ - function getReplacementTypes() - { - return $GLOBALS['_PEAR_Common_replacement_types']; - } - - // }}} - // {{{ getProvideTypes() - - /** - * Get the implemented file replacement types in - * - * @return array - * @static - */ - function getProvideTypes() - { - return $GLOBALS['_PEAR_Common_provide_types']; - } - - // }}} - // {{{ getScriptPhases() - - /** - * Get the implemented file replacement types in - * - * @return array - * @static - */ - function getScriptPhases() - { - return $GLOBALS['_PEAR_Common_script_phases']; - } - - // }}} - // {{{ validPackageName() - - /** - * Test whether a string contains a valid package name. - * - * @param string $name the package name to test - * - * @return bool - * - * @access public - */ - function validPackageName($name) - { - return (bool)preg_match(PEAR_COMMON_PACKAGE_NAME_PREG, $name); - } - - - // }}} - // {{{ validPackageVersion() - - /** - * Test whether a string contains a valid package version. - * - * @param string $ver the package version to test - * - * @return bool - * - * @access public - */ - function validPackageVersion($ver) - { - return (bool)preg_match(PEAR_COMMON_PACKAGE_VERSION_PREG, $ver); - } - - - // }}} - - // {{{ downloadHttp() - - /** - * Download a file through HTTP. Considers suggested file name in - * Content-disposition: header and can run a callback function for - * different events. The callback will be called with two - * parameters: the callback type, and parameters. The implemented - * callback types are: - * - * 'setup' called at the very beginning, parameter is a UI object - * that should be used for all output - * 'message' the parameter is a string with an informational message - * 'saveas' may be used to save with a different file name, the - * parameter is the filename that is about to be used. - * If a 'saveas' callback returns a non-empty string, - * that file name will be used as the filename instead. - * Note that $save_dir will not be affected by this, only - * the basename of the file. - * 'start' download is starting, parameter is number of bytes - * that are expected, or -1 if unknown - * 'bytesread' parameter is the number of bytes read so far - * 'done' download is complete, parameter is the total number - * of bytes read - * 'connfailed' if the TCP connection fails, this callback is called - * with array(host,port,errno,errmsg) - * 'writefailed' if writing to disk fails, this callback is called - * with array(destfile,errmsg) - * - * If an HTTP proxy has been configured (http_proxy PEAR_Config - * setting), the proxy will be used. - * - * @param string $url the URL to download - * @param object $ui PEAR_Frontend_* instance - * @param object $config PEAR_Config instance - * @param string $save_dir (optional) directory to save file in - * @param mixed $callback (optional) function/method to call for status - * updates - * - * @return string Returns the full path of the downloaded file or a PEAR - * error on failure. If the error is caused by - * socket-related errors, the error object will - * have the fsockopen error code available through - * getCode(). - * - * @access public - */ - function downloadHttp($url, &$ui, $save_dir = '.', $callback = null) - { - if ($callback) { - call_user_func($callback, 'setup', array(&$ui)); - } - if (preg_match('!^http://([^/:?#]*)(:(\d+))?(/.*)!', $url, $matches)) { - list(,$host,,$port,$path) = $matches; - } - if (isset($this)) { - $config = &$this->config; - } else { - $config = &PEAR_Config::singleton(); - } - $proxy_host = $proxy_port = $proxy_user = $proxy_pass = ''; - if ($proxy = parse_url($config->get('http_proxy'))) { - $proxy_host = @$proxy['host']; - $proxy_port = @$proxy['port']; - $proxy_user = @$proxy['user']; - $proxy_pass = @$proxy['pass']; - - if ($proxy_port == '') { - $proxy_port = 8080; - } - if ($callback) { - call_user_func($callback, 'message', "Using HTTP proxy $host:$port"); - } - } - if (empty($port)) { - $port = 80; - } - if ($proxy_host != '') { - $fp = @fsockopen($proxy_host, $proxy_port, $errno, $errstr); - if (!$fp) { - if ($callback) { - call_user_func($callback, 'connfailed', array($proxy_host, $proxy_port, - $errno, $errstr)); - } - return PEAR::raiseError("Connection to `$proxy_host:$proxy_port' failed: $errstr", $errno); - } - $request = "GET $url HTTP/1.0\r\n"; - } else { - $fp = @fsockopen($host, $port, $errno, $errstr); - if (!$fp) { - if ($callback) { - call_user_func($callback, 'connfailed', array($host, $port, - $errno, $errstr)); - } - return PEAR::raiseError("Connection to `$host:$port' failed: $errstr", $errno); - } - $request = "GET $path HTTP/1.0\r\n"; - } - $request .= "Host: $host:$port\r\n". - "User-Agent: PHP/".PHP_VERSION."\r\n"; - if ($proxy_host != '' && $proxy_user != '') { - $request .= 'Proxy-Authorization: Basic ' . - base64_encode($proxy_user . ':' . $proxy_pass) . "\r\n"; - } - $request .= "\r\n"; - fwrite($fp, $request); - $headers = array(); - while (trim($line = fgets($fp, 1024))) { - if (preg_match('/^([^:]+):\s+(.*)\s*$/', $line, $matches)) { - $headers[strtolower($matches[1])] = trim($matches[2]); - } elseif (preg_match('|^HTTP/1.[01] ([0-9]{3}) |', $line, $matches)) { - if ($matches[1] != 200) { - return PEAR::raiseError("File http://$host:$port$path not valid (received: $line)"); - } - } - } - if (isset($headers['content-disposition']) && - preg_match('/\sfilename=\"([^;]*\S)\"\s*(;|$)/', $headers['content-disposition'], $matches)) { - $save_as = basename($matches[1]); - } else { - $save_as = basename($url); - } - if ($callback) { - $tmp = call_user_func($callback, 'saveas', $save_as); - if ($tmp) { - $save_as = $tmp; - } - } - $dest_file = $save_dir . DIRECTORY_SEPARATOR . $save_as; - if (!$wp = @fopen($dest_file, 'wb')) { - fclose($fp); - if ($callback) { - call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg)); - } - return PEAR::raiseError("could not open $dest_file for writing"); - } - if (isset($headers['content-length'])) { - $length = $headers['content-length']; - } else { - $length = -1; - } - $bytes = 0; - if ($callback) { - call_user_func($callback, 'start', array(basename($dest_file), $length)); - } - while ($data = @fread($fp, 1024)) { - $bytes += strlen($data); - if ($callback) { - call_user_func($callback, 'bytesread', $bytes); - } - if (!@fwrite($wp, $data)) { - fclose($fp); - if ($callback) { - call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg)); - } - return PEAR::raiseError("$dest_file: write failed ($php_errormsg)"); - } - } - fclose($fp); - fclose($wp); - if ($callback) { - call_user_func($callback, 'done', $bytes); - } - return $dest_file; - } - - // }}} - // {{{ sortPkgDeps() - - /** - * Sort a list of arrays of array(downloaded packagefilename) by dependency. - * - * It also removes duplicate dependencies - * @param array - * @param boolean Sort packages in reverse order if true - * @return array array of array(packagefilename, package.xml contents) - */ - function sortPkgDeps(&$packages, $uninstall = false) - { - $ret = array(); - if ($uninstall) { - foreach($packages as $packageinfo) { - $ret[] = array('info' => $packageinfo); - } - } else { - foreach($packages as $packagefile) { - if (!is_array($packagefile)) { - $ret[] = array('file' => $packagefile, - 'info' => $a = $this->infoFromAny($packagefile), - 'pkg' => $a['package']); - } else { - $ret[] = $packagefile; - } - } - } - $checkdupes = array(); - $newret = array(); - foreach($ret as $i => $p) { - if (!isset($checkdupes[$p['info']['package']])) { - $checkdupes[$p['info']['package']][] = $i; - $newret[] = $p; - } - } - $this->_packageSortTree = $this->_getPkgDepTree($newret); - - $func = $uninstall ? '_sortPkgDepsRev' : '_sortPkgDeps'; - usort($newret, array(&$this, $func)); - $this->_packageSortTree = null; - $packages = $newret; - } - - // }}} - // {{{ _sortPkgDeps() - - /** - * Compare two package's package.xml, and sort - * so that dependencies are installed first - * - * This is a crude compare, real dependency checking is done on install. - * The only purpose this serves is to make the command-line - * order-independent (you can list a dependent package first, and - * installation occurs in the order required) - * @access private - */ - function _sortPkgDeps($p1, $p2) - { - $p1name = $p1['info']['package']; - $p2name = $p2['info']['package']; - $p1deps = $this->_getPkgDeps($p1); - $p2deps = $this->_getPkgDeps($p2); - if (!count($p1deps) && !count($p2deps)) { - return 0; // order makes no difference - } - if (!count($p1deps)) { - return -1; // package 2 has dependencies, package 1 doesn't - } - if (!count($p2deps)) { - return 1; // package 1 has dependencies, package 2 doesn't - } - // both have dependencies - if (in_array($p1name, $p2deps)) { - return -1; // put package 1 first: package 2 depends on package 1 - } - if (in_array($p2name, $p1deps)) { - return 1; // put package 2 first: package 1 depends on package 2 - } - if ($this->_removedDependency($p1name, $p2name)) { - return -1; // put package 1 first: package 2 depends on packages that depend on package 1 - } - if ($this->_removedDependency($p2name, $p1name)) { - return 1; // put package 2 first: package 1 depends on packages that depend on package 2 - } - // doesn't really matter if neither depends on the other - return 0; - } - - // }}} - // {{{ _sortPkgDepsRev() - - /** - * Compare two package's package.xml, and sort - * so that dependencies are uninstalled last - * - * This is a crude compare, real dependency checking is done on uninstall. - * The only purpose this serves is to make the command-line - * order-independent (you can list a dependency first, and - * uninstallation occurs in the order required) - * @access private - */ - function _sortPkgDepsRev($p1, $p2) - { - $p1name = $p1['info']['package']; - $p2name = $p2['info']['package']; - $p1deps = $this->_getRevPkgDeps($p1); - $p2deps = $this->_getRevPkgDeps($p2); - if (!count($p1deps) && !count($p2deps)) { - return 0; // order makes no difference - } - if (!count($p1deps)) { - return 1; // package 2 has dependencies, package 1 doesn't - } - if (!count($p2deps)) { - return -1; // package 2 has dependencies, package 1 doesn't - } - // both have dependencies - if (in_array($p1name, $p2deps)) { - return 1; // put package 1 last - } - if (in_array($p2name, $p1deps)) { - return -1; // put package 2 last - } - if ($this->_removedDependency($p1name, $p2name)) { - return 1; // put package 1 last: package 2 depends on packages that depend on package 1 - } - if ($this->_removedDependency($p2name, $p1name)) { - return -1; // put package 2 last: package 1 depends on packages that depend on package 2 - } - // doesn't really matter if neither depends on the other - return 0; - } - - // }}} - // {{{ _getPkgDeps() - - /** - * get an array of package dependency names - * @param array - * @return array - * @access private - */ - function _getPkgDeps($p) - { - if (!isset($p['info']['releases'])) { - return $this->_getRevPkgDeps($p); - } - $rel = array_shift($p['info']['releases']); - if (!isset($rel['deps'])) { - return array(); - } - $ret = array(); - foreach($rel['deps'] as $dep) { - if ($dep['type'] == 'pkg') { - $ret[] = $dep['name']; - } - } - return $ret; - } - - // }}} - // {{{ _getPkgDeps() - - /** - * get an array representation of the package dependency tree - * @return array - * @access private - */ - function _getPkgDepTree($packages) - { - $tree = array(); - foreach ($packages as $p) { - $package = $p['info']['package']; - $deps = $this->_getPkgDeps($p); - $tree[$package] = $deps; - } - return $tree; - } - - // }}} - // {{{ _removedDependency($p1, $p2) - - /** - * get an array of package dependency names for uninstall - * @param string package 1 name - * @param string package 2 name - * @return bool - * @access private - */ - function _removedDependency($p1, $p2) - { - if (empty($this->_packageSortTree[$p2])) { - return false; - } - if (!in_array($p1, $this->_packageSortTree[$p2])) { - foreach ($this->_packageSortTree[$p2] as $potential) { - if ($this->_removedDependency($p1, $potential)) { - return true; - } - } - return false; - } - return true; - } - - // }}} - // {{{ _getRevPkgDeps() - - /** - * get an array of package dependency names for uninstall - * @param array - * @return array - * @access private - */ - function _getRevPkgDeps($p) - { - if (!isset($p['info']['release_deps'])) { - return array(); - } - $ret = array(); - foreach($p['info']['release_deps'] as $dep) { - if ($dep['type'] == 'pkg') { - $ret[] = $dep['name']; - } - } - return $ret; - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Config.php b/3rdparty/PEAR/Config.php deleted file mode 100644 index ba641735250ddf68878f66ef40178707d5d30a60..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Config.php +++ /dev/null @@ -1,1169 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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: Stig Bakken <ssb@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Config.php,v 1.52 2004/01/08 17:33:12 sniper Exp $ - -require_once 'PEAR.php'; -require_once 'System.php'; - -/** - * Last created PEAR_Config instance. - * @var object - */ -$GLOBALS['_PEAR_Config_instance'] = null; -if (!defined('PEAR_INSTALL_DIR') || !PEAR_INSTALL_DIR) { - $PEAR_INSTALL_DIR = PHP_LIBDIR . DIRECTORY_SEPARATOR . 'pear'; -} else { - $PEAR_INSTALL_DIR = PEAR_INSTALL_DIR; -} - -// Below we define constants with default values for all configuration -// parameters except username/password. All of them can have their -// defaults set through environment variables. The reason we use the -// PHP_ prefix is for some security, PHP protects environment -// variables starting with PHP_*. - -if (getenv('PHP_PEAR_SYSCONF_DIR')) { - define('PEAR_CONFIG_SYSCONFDIR', getenv('PHP_PEAR_SYSCONF_DIR')); -} elseif (getenv('SystemRoot')) { - define('PEAR_CONFIG_SYSCONFDIR', getenv('SystemRoot')); -} else { - define('PEAR_CONFIG_SYSCONFDIR', PHP_SYSCONFDIR); -} - -// Default for master_server -if (getenv('PHP_PEAR_MASTER_SERVER')) { - define('PEAR_CONFIG_DEFAULT_MASTER_SERVER', getenv('PHP_PEAR_MASTER_SERVER')); -} else { - define('PEAR_CONFIG_DEFAULT_MASTER_SERVER', 'pear.php.net'); -} - -// Default for http_proxy -if (getenv('PHP_PEAR_HTTP_PROXY')) { - define('PEAR_CONFIG_DEFAULT_HTTP_PROXY', getenv('PHP_PEAR_HTTP_PROXY')); -} elseif (getenv('http_proxy')) { - define('PEAR_CONFIG_DEFAULT_HTTP_PROXY', getenv('http_proxy')); -} else { - define('PEAR_CONFIG_DEFAULT_HTTP_PROXY', ''); -} - -// Default for php_dir -if (getenv('PHP_PEAR_INSTALL_DIR')) { - define('PEAR_CONFIG_DEFAULT_PHP_DIR', getenv('PHP_PEAR_INSTALL_DIR')); -} else { - if (@is_dir($PEAR_INSTALL_DIR)) { - define('PEAR_CONFIG_DEFAULT_PHP_DIR', - $PEAR_INSTALL_DIR); - } else { - define('PEAR_CONFIG_DEFAULT_PHP_DIR', $PEAR_INSTALL_DIR); - } -} - -// Default for ext_dir -if (getenv('PHP_PEAR_EXTENSION_DIR')) { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', getenv('PHP_PEAR_EXTENSION_DIR')); -} else { - if (ini_get('extension_dir')) { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', ini_get('extension_dir')); - } elseif (defined('PEAR_EXTENSION_DIR') && @is_dir(PEAR_EXTENSION_DIR)) { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', PEAR_EXTENSION_DIR); - } elseif (defined('PHP_EXTENSION_DIR')) { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', PHP_EXTENSION_DIR); - } else { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', '.'); - } -} - -// Default for doc_dir -if (getenv('PHP_PEAR_DOC_DIR')) { - define('PEAR_CONFIG_DEFAULT_DOC_DIR', getenv('PHP_PEAR_DOC_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_DOC_DIR', - $PEAR_INSTALL_DIR.DIRECTORY_SEPARATOR.'docs'); -} - -// Default for bin_dir -if (getenv('PHP_PEAR_BIN_DIR')) { - define('PEAR_CONFIG_DEFAULT_BIN_DIR', getenv('PHP_PEAR_BIN_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_BIN_DIR', PHP_BINDIR); -} - -// Default for data_dir -if (getenv('PHP_PEAR_DATA_DIR')) { - define('PEAR_CONFIG_DEFAULT_DATA_DIR', getenv('PHP_PEAR_DATA_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_DATA_DIR', - $PEAR_INSTALL_DIR.DIRECTORY_SEPARATOR.'data'); -} - -// Default for test_dir -if (getenv('PHP_PEAR_TEST_DIR')) { - define('PEAR_CONFIG_DEFAULT_TEST_DIR', getenv('PHP_PEAR_TEST_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_TEST_DIR', - $PEAR_INSTALL_DIR.DIRECTORY_SEPARATOR.'tests'); -} - -// Default for cache_dir -if (getenv('PHP_PEAR_CACHE_DIR')) { - define('PEAR_CONFIG_DEFAULT_CACHE_DIR', getenv('PHP_PEAR_CACHE_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_CACHE_DIR', - System::tmpdir() . DIRECTORY_SEPARATOR . 'pear' . - DIRECTORY_SEPARATOR . 'cache'); -} - -// Default for php_bin -if (getenv('PHP_PEAR_PHP_BIN')) { - define('PEAR_CONFIG_DEFAULT_PHP_BIN', getenv('PHP_PEAR_PHP_BIN')); -} else { - define('PEAR_CONFIG_DEFAULT_PHP_BIN', PEAR_CONFIG_DEFAULT_BIN_DIR. - DIRECTORY_SEPARATOR.'php'.(OS_WINDOWS ? '.exe' : '')); -} - -// Default for verbose -if (getenv('PHP_PEAR_VERBOSE')) { - define('PEAR_CONFIG_DEFAULT_VERBOSE', getenv('PHP_PEAR_VERBOSE')); -} else { - define('PEAR_CONFIG_DEFAULT_VERBOSE', 1); -} - -// Default for preferred_state -if (getenv('PHP_PEAR_PREFERRED_STATE')) { - define('PEAR_CONFIG_DEFAULT_PREFERRED_STATE', getenv('PHP_PEAR_PREFERRED_STATE')); -} else { - define('PEAR_CONFIG_DEFAULT_PREFERRED_STATE', 'stable'); -} - -// Default for umask -if (getenv('PHP_PEAR_UMASK')) { - define('PEAR_CONFIG_DEFAULT_UMASK', getenv('PHP_PEAR_UMASK')); -} else { - define('PEAR_CONFIG_DEFAULT_UMASK', decoct(umask())); -} - -// Default for cache_ttl -if (getenv('PHP_PEAR_CACHE_TTL')) { - define('PEAR_CONFIG_DEFAULT_CACHE_TTL', getenv('PHP_PEAR_CACHE_TTL')); -} else { - define('PEAR_CONFIG_DEFAULT_CACHE_TTL', 3600); -} - -// Default for sig_type -if (getenv('PHP_PEAR_SIG_TYPE')) { - define('PEAR_CONFIG_DEFAULT_SIG_TYPE', getenv('PHP_PEAR_SIG_TYPE')); -} else { - define('PEAR_CONFIG_DEFAULT_SIG_TYPE', 'gpg'); -} - -// Default for sig_bin -if (getenv('PHP_PEAR_SIG_BIN')) { - define('PEAR_CONFIG_DEFAULT_SIG_BIN', getenv('PHP_PEAR_SIG_BIN')); -} else { - define('PEAR_CONFIG_DEFAULT_SIG_BIN', - System::which( - 'gpg', OS_WINDOWS ? 'c:\gnupg\gpg.exe' : '/usr/local/bin/gpg')); -} - -// Default for sig_keydir -if (getenv('PHP_PEAR_SIG_KEYDIR')) { - define('PEAR_CONFIG_DEFAULT_SIG_KEYDIR', getenv('PHP_PEAR_SIG_KEYDIR')); -} else { - define('PEAR_CONFIG_DEFAULT_SIG_KEYDIR', - PEAR_CONFIG_SYSCONFDIR . DIRECTORY_SEPARATOR . 'pearkeys'); -} - -/** - * This is a class for storing configuration data, keeping track of - * which are system-defined, user-defined or defaulted. - */ -class PEAR_Config extends PEAR -{ - // {{{ properties - - /** - * Array of config files used. - * - * @var array layer => config file - */ - var $files = array( - 'system' => '', - 'user' => '', - ); - - var $layers = array(); - - /** - * Configuration data, two-dimensional array where the first - * dimension is the config layer ('user', 'system' and 'default'), - * and the second dimension is keyname => value. - * - * The order in the first dimension is important! Earlier - * layers will shadow later ones when a config value is - * requested (if a 'user' value exists, it will be returned first, - * then 'system' and finally 'default'). - * - * @var array layer => array(keyname => value, ...) - */ - var $configuration = array( - 'user' => array(), - 'system' => array(), - 'default' => array(), - ); - - /** - * Information about the configuration data. Stores the type, - * default value and a documentation string for each configuration - * value. - * - * @var array layer => array(infotype => value, ...) - */ - var $configuration_info = array( - // Internet Access - 'master_server' => array( - 'type' => 'string', - 'default' => 'pear.php.net', - 'doc' => 'name of the main PEAR server', - 'prompt' => 'PEAR server', - 'group' => 'Internet Access', - ), - 'http_proxy' => array( - 'type' => 'string', - 'default' => PEAR_CONFIG_DEFAULT_HTTP_PROXY, - 'doc' => 'HTTP proxy (host:port) to use when downloading packages', - 'prompt' => 'HTTP Proxy Server Address', - 'group' => 'Internet Access', - ), - // File Locations - 'php_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_PHP_DIR, - 'doc' => 'directory where .php files are installed', - 'prompt' => 'PEAR directory', - 'group' => 'File Locations', - ), - 'ext_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_EXT_DIR, - 'doc' => 'directory where loadable extensions are installed', - 'prompt' => 'PHP extension directory', - 'group' => 'File Locations', - ), - 'doc_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_DOC_DIR, - 'doc' => 'directory where documentation is installed', - 'prompt' => 'PEAR documentation directory', - 'group' => 'File Locations', - ), - 'bin_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_BIN_DIR, - 'doc' => 'directory where executables are installed', - 'prompt' => 'PEAR executables directory', - 'group' => 'File Locations', - ), - 'data_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_DATA_DIR, - 'doc' => 'directory where data files are installed', - 'prompt' => 'PEAR data directory', - 'group' => 'File Locations (Advanced)', - ), - 'test_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_TEST_DIR, - 'doc' => 'directory where regression tests are installed', - 'prompt' => 'PEAR test directory', - 'group' => 'File Locations (Advanced)', - ), - 'cache_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_CACHE_DIR, - 'doc' => 'directory which is used for XMLRPC cache', - 'prompt' => 'PEAR Installer cache directory', - 'group' => 'File Locations (Advanced)', - ), - 'php_bin' => array( - 'type' => 'file', - 'default' => PEAR_CONFIG_DEFAULT_PHP_BIN, - 'doc' => 'PHP CLI/CGI binary for executing scripts', - 'prompt' => 'PHP CLI/CGI binary', - 'group' => 'File Locations (Advanced)', - ), - // Maintainers - 'username' => array( - 'type' => 'string', - 'default' => '', - 'doc' => '(maintainers) your PEAR account name', - 'prompt' => 'PEAR username (for maintainers)', - 'group' => 'Maintainers', - ), - 'password' => array( - 'type' => 'password', - 'default' => '', - 'doc' => '(maintainers) your PEAR account password', - 'prompt' => 'PEAR password (for maintainers)', - 'group' => 'Maintainers', - ), - // Advanced - 'verbose' => array( - 'type' => 'integer', - 'default' => PEAR_CONFIG_DEFAULT_VERBOSE, - 'doc' => 'verbosity level -0: really quiet -1: somewhat quiet -2: verbose -3: debug', - 'prompt' => 'Debug Log Level', - 'group' => 'Advanced', - ), - 'preferred_state' => array( - 'type' => 'set', - 'default' => PEAR_CONFIG_DEFAULT_PREFERRED_STATE, - 'doc' => 'the installer will prefer releases with this state when installing packages without a version or state specified', - 'valid_set' => array( - 'stable', 'beta', 'alpha', 'devel', 'snapshot'), - 'prompt' => 'Preferred Package State', - 'group' => 'Advanced', - ), - 'umask' => array( - 'type' => 'mask', - 'default' => PEAR_CONFIG_DEFAULT_UMASK, - 'doc' => 'umask used when creating files (Unix-like systems only)', - 'prompt' => 'Unix file mask', - 'group' => 'Advanced', - ), - 'cache_ttl' => array( - 'type' => 'integer', - 'default' => PEAR_CONFIG_DEFAULT_CACHE_TTL, - 'doc' => 'amount of secs where the local cache is used and not updated', - 'prompt' => 'Cache TimeToLive', - 'group' => 'Advanced', - ), - 'sig_type' => array( - 'type' => 'set', - 'default' => PEAR_CONFIG_DEFAULT_SIG_TYPE, - 'doc' => 'which package signature mechanism to use', - 'valid_set' => array('gpg'), - 'prompt' => 'Package Signature Type', - 'group' => 'Maintainers', - ), - 'sig_bin' => array( - 'type' => 'string', - 'default' => PEAR_CONFIG_DEFAULT_SIG_BIN, - 'doc' => 'which package signature mechanism to use', - 'prompt' => 'Signature Handling Program', - 'group' => 'Maintainers', - ), - 'sig_keyid' => array( - 'type' => 'string', - 'default' => '', - 'doc' => 'which key to use for signing with', - 'prompt' => 'Signature Key Id', - 'group' => 'Maintainers', - ), - 'sig_keydir' => array( - 'type' => 'string', - 'default' => PEAR_CONFIG_DEFAULT_SIG_KEYDIR, - 'doc' => 'which package signature mechanism to use', - 'prompt' => 'Signature Key Directory', - 'group' => 'Maintainers', - ), - ); - - // }}} - - // {{{ PEAR_Config([file], [defaults_file]) - - /** - * Constructor. - * - * @param string (optional) file to read user-defined options from - * @param string (optional) file to read system-wide defaults from - * - * @access public - * - * @see PEAR_Config::singleton - */ - function PEAR_Config($user_file = '', $system_file = '') - { - $this->PEAR(); - $sl = DIRECTORY_SEPARATOR; - if (empty($user_file)) { - if (OS_WINDOWS) { - $user_file = PEAR_CONFIG_SYSCONFDIR . $sl . 'pear.ini'; - } else { - $user_file = getenv('HOME') . $sl . '.pearrc'; - } - } - if (empty($system_file)) { - if (OS_WINDOWS) { - $system_file = PEAR_CONFIG_SYSCONFDIR . $sl . 'pearsys.ini'; - } else { - $system_file = PEAR_CONFIG_SYSCONFDIR . $sl . 'pear.conf'; - } - } - $this->layers = array_keys($this->configuration); - $this->files['user'] = $user_file; - $this->files['system'] = $system_file; - if ($user_file && file_exists($user_file)) { - $this->readConfigFile($user_file); - } - if ($system_file && file_exists($system_file)) { - $this->mergeConfigFile($system_file, false, 'system'); - } - foreach ($this->configuration_info as $key => $info) { - $this->configuration['default'][$key] = $info['default']; - } - //$GLOBALS['_PEAR_Config_instance'] = &$this; - } - - // }}} - // {{{ singleton([file], [defaults_file]) - - /** - * Static singleton method. If you want to keep only one instance - * of this class in use, this method will give you a reference to - * the last created PEAR_Config object if one exists, or create a - * new object. - * - * @param string (optional) file to read user-defined options from - * @param string (optional) file to read system-wide defaults from - * - * @return object an existing or new PEAR_Config instance - * - * @access public - * - * @see PEAR_Config::PEAR_Config - */ - function &singleton($user_file = '', $system_file = '') - { - if (is_object($GLOBALS['_PEAR_Config_instance'])) { - return $GLOBALS['_PEAR_Config_instance']; - } - $GLOBALS['_PEAR_Config_instance'] = - &new PEAR_Config($user_file, $system_file); - return $GLOBALS['_PEAR_Config_instance']; - } - - // }}} - // {{{ readConfigFile([file], [layer]) - - /** - * Reads configuration data from a file. All existing values in - * the config layer are discarded and replaced with data from the - * file. - * - * @param string (optional) file to read from, if NULL or not - * specified, the last-used file for the same layer (second param) - * is used - * - * @param string (optional) config layer to insert data into - * ('user' or 'system') - * - * @return bool TRUE on success or a PEAR error on failure - * - * @access public - */ - function readConfigFile($file = null, $layer = 'user') - { - if (empty($this->files[$layer])) { - return $this->raiseError("unknown config file type `$layer'"); - } - if ($file === null) { - $file = $this->files[$layer]; - } - $data = $this->_readConfigDataFrom($file); - if (PEAR::isError($data)) { - return $data; - } - $this->_decodeInput($data); - $this->configuration[$layer] = $data; - return true; - } - - // }}} - // {{{ mergeConfigFile(file, [override], [layer]) - - /** - * Merges data into a config layer from a file. Does the same - * thing as readConfigFile, except it does not replace all - * existing values in the config layer. - * - * @param string file to read from - * - * @param bool (optional) whether to overwrite existing data - * (default TRUE) - * - * @param string config layer to insert data into ('user' or - * 'system') - * - * @return bool TRUE on success or a PEAR error on failure - * - * @access public. - */ - function mergeConfigFile($file, $override = true, $layer = 'user') - { - if (empty($this->files[$layer])) { - return $this->raiseError("unknown config file type `$layer'"); - } - if ($file === null) { - $file = $this->files[$layer]; - } - $data = $this->_readConfigDataFrom($file); - if (PEAR::isError($data)) { - return $data; - } - $this->_decodeInput($data); - if ($override) { - $this->configuration[$layer] = array_merge($this->configuration[$layer], $data); - } else { - $this->configuration[$layer] = array_merge($data, $this->configuration[$layer]); - } - return true; - } - - // }}} - // {{{ writeConfigFile([file], [layer]) - - /** - * Writes data into a config layer from a file. - * - * @param string file to read from - * - * @param bool (optional) whether to overwrite existing data - * (default TRUE) - * - * @param string config layer to insert data into ('user' or - * 'system') - * - * @return bool TRUE on success or a PEAR error on failure - * - * @access public. - */ - function writeConfigFile($file = null, $layer = 'user', $data = null) - { - if ($layer == 'both' || $layer == 'all') { - foreach ($this->files as $type => $file) { - $err = $this->writeConfigFile($file, $type, $data); - if (PEAR::isError($err)) { - return $err; - } - } - return true; - } - if (empty($this->files[$layer])) { - return $this->raiseError("unknown config file type `$layer'"); - } - if ($file === null) { - $file = $this->files[$layer]; - } - $data = ($data === null) ? $this->configuration[$layer] : $data; - $this->_encodeOutput($data); - $opt = array('-p', dirname($file)); - if (!@System::mkDir($opt)) { - return $this->raiseError("could not create directory: " . dirname($file)); - } - if (@is_file($file) && !@is_writeable($file)) { - return $this->raiseError("no write access to $file!"); - } - $fp = @fopen($file, "w"); - if (!$fp) { - return $this->raiseError("PEAR_Config::writeConfigFile fopen('$file','w') failed"); - } - $contents = "#PEAR_Config 0.9\n" . serialize($data); - if (!@fwrite($fp, $contents)) { - return $this->raiseError("PEAR_Config::writeConfigFile: fwrite failed"); - } - return true; - } - - // }}} - // {{{ _readConfigDataFrom(file) - - /** - * Reads configuration data from a file and returns the parsed data - * in an array. - * - * @param string file to read from - * - * @return array configuration data or a PEAR error on failure - * - * @access private - */ - function _readConfigDataFrom($file) - { - $fp = @fopen($file, "r"); - if (!$fp) { - return $this->raiseError("PEAR_Config::readConfigFile fopen('$file','r') failed"); - } - $size = filesize($file); - $rt = get_magic_quotes_runtime(); - set_magic_quotes_runtime(0); - $contents = fread($fp, $size); - set_magic_quotes_runtime($rt); - fclose($fp); - $version = '0.1'; - if (preg_match('/^#PEAR_Config\s+(\S+)\s+/si', $contents, $matches)) { - $version = $matches[1]; - $contents = substr($contents, strlen($matches[0])); - } - if (version_compare("$version", '1', '<')) { - $data = unserialize($contents); - if (!is_array($data)) { - if (strlen(trim($contents)) > 0) { - $error = "PEAR_Config: bad data in $file"; -// if (isset($this)) { - return $this->raiseError($error); -// } else { -// return PEAR::raiseError($error); - } else { - $data = array(); - } - } - // add parsing of newer formats here... - } else { - return $this->raiseError("$file: unknown version `$version'"); - } - return $data; - } - - // }}} - // {{{ getConfFile(layer) - /** - * Gets the file used for storing the config for a layer - * - * @param string $layer 'user' or 'system' - */ - - function getConfFile($layer) - { - return $this->files[$layer]; - } - - // }}} - // {{{ _encodeOutput(&data) - - /** - * Encodes/scrambles configuration data before writing to files. - * Currently, 'password' values will be base64-encoded as to avoid - * that people spot cleartext passwords by accident. - * - * @param array (reference) array to encode values in - * - * @return bool TRUE on success - * - * @access private - */ - function _encodeOutput(&$data) - { - foreach ($data as $key => $value) { - if (!isset($this->configuration_info[$key])) { - continue; - } - $type = $this->configuration_info[$key]['type']; - switch ($type) { - // we base64-encode passwords so they are at least - // not shown in plain by accident - case 'password': { - $data[$key] = base64_encode($data[$key]); - break; - } - case 'mask': { - $data[$key] = octdec($data[$key]); - break; - } - } - } - return true; - } - - // }}} - // {{{ _decodeInput(&data) - - /** - * Decodes/unscrambles configuration data after reading from files. - * - * @param array (reference) array to encode values in - * - * @return bool TRUE on success - * - * @access private - * - * @see PEAR_Config::_encodeOutput - */ - function _decodeInput(&$data) - { - if (!is_array($data)) { - return true; - } - foreach ($data as $key => $value) { - if (!isset($this->configuration_info[$key])) { - continue; - } - $type = $this->configuration_info[$key]['type']; - switch ($type) { - case 'password': { - $data[$key] = base64_decode($data[$key]); - break; - } - case 'mask': { - $data[$key] = decoct($data[$key]); - break; - } - } - } - return true; - } - - // }}} - // {{{ get(key, [layer]) - - /** - * Returns a configuration value, prioritizing layers as per the - * layers property. - * - * @param string config key - * - * @return mixed the config value, or NULL if not found - * - * @access public - */ - function get($key, $layer = null) - { - if ($layer === null) { - foreach ($this->layers as $layer) { - if (isset($this->configuration[$layer][$key])) { - return $this->configuration[$layer][$key]; - } - } - } elseif (isset($this->configuration[$layer][$key])) { - return $this->configuration[$layer][$key]; - } - return null; - } - - // }}} - // {{{ set(key, value, [layer]) - - /** - * Set a config value in a specific layer (defaults to 'user'). - * Enforces the types defined in the configuration_info array. An - * integer config variable will be cast to int, and a set config - * variable will be validated against its legal values. - * - * @param string config key - * - * @param string config value - * - * @param string (optional) config layer - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function set($key, $value, $layer = 'user') - { - if (empty($this->configuration_info[$key])) { - return false; - } - extract($this->configuration_info[$key]); - switch ($type) { - case 'integer': - $value = (int)$value; - break; - case 'set': { - // If a valid_set is specified, require the value to - // be in the set. If there is no valid_set, accept - // any value. - if ($valid_set) { - reset($valid_set); - if ((key($valid_set) === 0 && !in_array($value, $valid_set)) || - (key($valid_set) !== 0 && empty($valid_set[$value]))) - { - return false; - } - } - break; - } - } - $this->configuration[$layer][$key] = $value; - return true; - } - - // }}} - // {{{ getType(key) - - /** - * Get the type of a config value. - * - * @param string config key - * - * @return string type, one of "string", "integer", "file", - * "directory", "set" or "password". - * - * @access public - * - */ - function getType($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['type']; - } - return false; - } - - // }}} - // {{{ getDocs(key) - - /** - * Get the documentation for a config value. - * - * @param string config key - * - * @return string documentation string - * - * @access public - * - */ - function getDocs($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['doc']; - } - return false; - } - // }}} - // {{{ getPrompt(key) - - /** - * Get the short documentation for a config value. - * - * @param string config key - * - * @return string short documentation string - * - * @access public - * - */ - function getPrompt($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['prompt']; - } - return false; - } - // }}} - // {{{ getGroup(key) - - /** - * Get the parameter group for a config key. - * - * @param string config key - * - * @return string parameter group - * - * @access public - * - */ - function getGroup($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['group']; - } - return false; - } - - // }}} - // {{{ getGroups() - - /** - * Get the list of parameter groups. - * - * @return array list of parameter groups - * - * @access public - * - */ - function getGroups() - { - $tmp = array(); - foreach ($this->configuration_info as $key => $info) { - $tmp[$info['group']] = 1; - } - return array_keys($tmp); - } - - // }}} - // {{{ getGroupKeys() - - /** - * Get the list of the parameters in a group. - * - * @param string $group parameter group - * - * @return array list of parameters in $group - * - * @access public - * - */ - function getGroupKeys($group) - { - $keys = array(); - foreach ($this->configuration_info as $key => $info) { - if ($info['group'] == $group) { - $keys[] = $key; - } - } - return $keys; - } - - // }}} - // {{{ getSetValues(key) - - /** - * Get the list of allowed set values for a config value. Returns - * NULL for config values that are not sets. - * - * @param string config key - * - * @return array enumerated array of set values, or NULL if the - * config key is unknown or not a set - * - * @access public - * - */ - function getSetValues($key) - { - if (isset($this->configuration_info[$key]) && - isset($this->configuration_info[$key]['type']) && - $this->configuration_info[$key]['type'] == 'set') - { - $valid_set = $this->configuration_info[$key]['valid_set']; - reset($valid_set); - if (key($valid_set) === 0) { - return $valid_set; - } - return array_keys($valid_set); - } - return false; - } - - // }}} - // {{{ getKeys() - - /** - * Get all the current config keys. - * - * @return array simple array of config keys - * - * @access public - */ - function getKeys() - { - $keys = array(); - foreach ($this->layers as $layer) { - $keys = array_merge($keys, $this->configuration[$layer]); - } - return array_keys($keys); - } - - // }}} - // {{{ remove(key, [layer]) - - /** - * Remove the a config key from a specific config layer. - * - * @param string config key - * - * @param string (optional) config layer - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function remove($key, $layer = 'user') - { - if (isset($this->configuration[$layer][$key])) { - unset($this->configuration[$layer][$key]); - return true; - } - return false; - } - - // }}} - // {{{ removeLayer(layer) - - /** - * Temporarily remove an entire config layer. USE WITH CARE! - * - * @param string config key - * - * @param string (optional) config layer - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function removeLayer($layer) - { - if (isset($this->configuration[$layer])) { - $this->configuration[$layer] = array(); - return true; - } - return false; - } - - // }}} - // {{{ store([layer]) - - /** - * Stores configuration data in a layer. - * - * @param string config layer to store - * - * @return bool TRUE on success, or PEAR error on failure - * - * @access public - */ - function store($layer = 'user', $data = null) - { - return $this->writeConfigFile(null, $layer, $data); - } - - // }}} - // {{{ toDefault(key) - - /** - * Unset the user-defined value of a config key, reverting the - * value to the system-defined one. - * - * @param string config key - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function toDefault($key) - { - trigger_error("PEAR_Config::toDefault() deprecated, use PEAR_Config::remove() instead", E_USER_NOTICE); - return $this->remove($key, 'user'); - } - - // }}} - // {{{ definedBy(key) - - /** - * Tells what config layer that gets to define a key. - * - * @param string config key - * - * @return string the config layer, or an empty string if not found - * - * @access public - */ - function definedBy($key) - { - foreach ($this->layers as $layer) { - if (isset($this->configuration[$layer][$key])) { - return $layer; - } - } - return ''; - } - - // }}} - // {{{ isDefaulted(key) - - /** - * Tells whether a config value has a system-defined value. - * - * @param string config key - * - * @return bool - * - * @access public - * - * @deprecated - */ - function isDefaulted($key) - { - trigger_error("PEAR_Config::isDefaulted() deprecated, use PEAR_Config::definedBy() instead", E_USER_NOTICE); - return $this->definedBy($key) == 'system'; - } - - // }}} - // {{{ isDefined(key) - - /** - * Tells whether a given key exists as a config value. - * - * @param string config key - * - * @return bool whether <config key> exists in this object - * - * @access public - */ - function isDefined($key) - { - foreach ($this->layers as $layer) { - if (isset($this->configuration[$layer][$key])) { - return true; - } - } - return false; - } - - // }}} - // {{{ isDefinedLayer(key) - - /** - * Tells whether a given config layer exists. - * - * @param string config layer - * - * @return bool whether <config layer> exists in this object - * - * @access public - */ - function isDefinedLayer($layer) - { - return isset($this->configuration[$layer]); - } - - // }}} - // {{{ getLayers() - - /** - * Returns the layers defined (except the 'default' one) - * - * @return array of the defined layers - */ - function getLayers() - { - $cf = $this->configuration; - unset($cf['default']); - return array_keys($cf); - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Dependency.php b/3rdparty/PEAR/Dependency.php deleted file mode 100644 index 705167aa70fa158d03884b188ccadb3db8eca505..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Dependency.php +++ /dev/null @@ -1,487 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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. | -// +----------------------------------------------------------------------+ -// | Authors: Tomas V.V.Cox <cox@idecnet.com> | -// | Stig Bakken <ssb@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Dependency.php,v 1.36.4.1 2004/12/27 07:04:19 cellog Exp $ - -require_once "PEAR.php"; - -define('PEAR_DEPENDENCY_MISSING', -1); -define('PEAR_DEPENDENCY_CONFLICT', -2); -define('PEAR_DEPENDENCY_UPGRADE_MINOR', -3); -define('PEAR_DEPENDENCY_UPGRADE_MAJOR', -4); -define('PEAR_DEPENDENCY_BAD_DEPENDENCY', -5); -define('PEAR_DEPENDENCY_MISSING_OPTIONAL', -6); -define('PEAR_DEPENDENCY_CONFLICT_OPTIONAL', -7); -define('PEAR_DEPENDENCY_UPGRADE_MINOR_OPTIONAL', -8); -define('PEAR_DEPENDENCY_UPGRADE_MAJOR_OPTIONAL', -9); - -/** - * Dependency check for PEAR packages - * - * The class is based on the dependency RFC that can be found at - * http://cvs.php.net/cvs.php/pearweb/rfc. It requires PHP >= 4.1 - * - * @author Tomas V.V.Vox <cox@idecnet.com> - * @author Stig Bakken <ssb@php.net> - */ -class PEAR_Dependency -{ - // {{{ constructor - /** - * Constructor - * - * @access public - * @param object Registry object - * @return void - */ - function PEAR_Dependency(&$registry) - { - $this->registry = &$registry; - } - - // }}} - // {{{ callCheckMethod() - - /** - * This method maps the XML dependency definition to the - * corresponding one from PEAR_Dependency - * - * <pre> - * $opts => Array - * ( - * [type] => pkg - * [rel] => ge - * [version] => 3.4 - * [name] => HTML_Common - * [optional] => false - * ) - * </pre> - * - * @param string Error message - * @param array Options - * @return boolean - */ - function callCheckMethod(&$errmsg, $opts) - { - $rel = isset($opts['rel']) ? $opts['rel'] : 'has'; - $req = isset($opts['version']) ? $opts['version'] : null; - $name = isset($opts['name']) ? $opts['name'] : null; - $opt = (isset($opts['optional']) && $opts['optional'] == 'yes') ? - $opts['optional'] : null; - $errmsg = ''; - switch ($opts['type']) { - case 'pkg': - return $this->checkPackage($errmsg, $name, $req, $rel, $opt); - break; - case 'ext': - return $this->checkExtension($errmsg, $name, $req, $rel, $opt); - break; - case 'php': - return $this->checkPHP($errmsg, $req, $rel); - break; - case 'prog': - return $this->checkProgram($errmsg, $name); - break; - case 'os': - return $this->checkOS($errmsg, $name); - break; - case 'sapi': - return $this->checkSAPI($errmsg, $name); - break; - case 'zend': - return $this->checkZend($errmsg, $name); - break; - default: - return "'{$opts['type']}' dependency type not supported"; - } - } - - // }}} - // {{{ checkPackage() - - /** - * Package dependencies check method - * - * @param string $errmsg Empty string, it will be populated with an error message, if any - * @param string $name Name of the package to test - * @param string $req The package version required - * @param string $relation How to compare versions with each other - * @param bool $opt Whether the relationship is optional - * - * @return mixed bool false if no error or the error string - */ - function checkPackage(&$errmsg, $name, $req = null, $relation = 'has', - $opt = false) - { - if (is_string($req) && substr($req, 0, 2) == 'v.') { - $req = substr($req, 2); - } - switch ($relation) { - case 'has': - if (!$this->registry->packageExists($name)) { - if ($opt) { - $errmsg = "package `$name' is recommended to utilize some features."; - return PEAR_DEPENDENCY_MISSING_OPTIONAL; - } - $errmsg = "requires package `$name'"; - return PEAR_DEPENDENCY_MISSING; - } - return false; - case 'not': - if ($this->registry->packageExists($name)) { - $errmsg = "conflicts with package `$name'"; - return PEAR_DEPENDENCY_CONFLICT; - } - return false; - case 'lt': - case 'le': - case 'eq': - case 'ne': - case 'ge': - case 'gt': - $version = $this->registry->packageInfo($name, 'version'); - if (!$this->registry->packageExists($name) - || !version_compare("$version", "$req", $relation)) - { - $code = $this->codeFromRelation($relation, $version, $req, $opt); - if ($opt) { - $errmsg = "package `$name' version " . $this->signOperator($relation) . - " $req is recommended to utilize some features."; - if ($version) { - $errmsg .= " Installed version is $version"; - } - return $code; - } - $errmsg = "requires package `$name' " . - $this->signOperator($relation) . " $req"; - return $code; - } - return false; - } - $errmsg = "relation '$relation' with requirement '$req' is not supported (name=$name)"; - return PEAR_DEPENDENCY_BAD_DEPENDENCY; - } - - // }}} - // {{{ checkPackageUninstall() - - /** - * Check package dependencies on uninstall - * - * @param string $error The resultant error string - * @param string $warning The resultant warning string - * @param string $name Name of the package to test - * - * @return bool true if there were errors - */ - function checkPackageUninstall(&$error, &$warning, $package) - { - $error = null; - $packages = $this->registry->listPackages(); - foreach ($packages as $pkg) { - if ($pkg == $package) { - continue; - } - $deps = $this->registry->packageInfo($pkg, 'release_deps'); - if (empty($deps)) { - continue; - } - foreach ($deps as $dep) { - if ($dep['type'] == 'pkg' && strcasecmp($dep['name'], $package) == 0) { - if ($dep['rel'] == 'ne' || $dep['rel'] == 'not') { - continue; - } - if (isset($dep['optional']) && $dep['optional'] == 'yes') { - $warning .= "\nWarning: Package '$pkg' optionally depends on '$package'"; - } else { - $error .= "Package '$pkg' depends on '$package'\n"; - } - } - } - } - return ($error) ? true : false; - } - - // }}} - // {{{ checkExtension() - - /** - * Extension dependencies check method - * - * @param string $name Name of the extension to test - * @param string $req_ext_ver Required extension version to compare with - * @param string $relation How to compare versions with eachother - * @param bool $opt Whether the relationship is optional - * - * @return mixed bool false if no error or the error string - */ - function checkExtension(&$errmsg, $name, $req = null, $relation = 'has', - $opt = false) - { - if ($relation == 'not') { - if (extension_loaded($name)) { - $errmsg = "conflicts with PHP extension '$name'"; - return PEAR_DEPENDENCY_CONFLICT; - } else { - return false; - } - } - - if (!extension_loaded($name)) { - if ($relation == 'not') { - return false; - } - if ($opt) { - $errmsg = "'$name' PHP extension is recommended to utilize some features"; - return PEAR_DEPENDENCY_MISSING_OPTIONAL; - } - $errmsg = "'$name' PHP extension is not installed"; - return PEAR_DEPENDENCY_MISSING; - } - if ($relation == 'has') { - return false; - } - $code = false; - if (is_string($req) && substr($req, 0, 2) == 'v.') { - $req = substr($req, 2); - } - $ext_ver = phpversion($name); - $operator = $relation; - // Force params to be strings, otherwise the comparation will fail (ex. 0.9==0.90) - if (!version_compare("$ext_ver", "$req", $operator)) { - $errmsg = "'$name' PHP extension version " . - $this->signOperator($operator) . " $req is required"; - $code = $this->codeFromRelation($relation, $ext_ver, $req, $opt); - if ($opt) { - $errmsg = "'$name' PHP extension version " . $this->signOperator($operator) . - " $req is recommended to utilize some features"; - return $code; - } - } - return $code; - } - - // }}} - // {{{ checkOS() - - /** - * Operating system dependencies check method - * - * @param string $os Name of the operating system - * - * @return mixed bool false if no error or the error string - */ - function checkOS(&$errmsg, $os) - { - // XXX Fixme: Implement a more flexible way, like - // comma separated values or something similar to PEAR_OS - static $myos; - if (empty($myos)) { - include_once "OS/Guess.php"; - $myos = new OS_Guess(); - } - // only 'has' relation is currently supported - if ($myos->matchSignature($os)) { - return false; - } - $errmsg = "'$os' operating system not supported"; - return PEAR_DEPENDENCY_CONFLICT; - } - - // }}} - // {{{ checkPHP() - - /** - * PHP version check method - * - * @param string $req which version to compare - * @param string $relation how to compare the version - * - * @return mixed bool false if no error or the error string - */ - function checkPHP(&$errmsg, $req, $relation = 'ge') - { - // this would be a bit stupid, but oh well :) - if ($relation == 'has') { - return false; - } - if ($relation == 'not') { - $errmsg = 'Invalid dependency - "not" is not allowed for php dependencies, ' . - 'php cannot conflict with itself'; - return PEAR_DEPENDENCY_BAD_DEPENDENCY; - } - if (substr($req, 0, 2) == 'v.') { - $req = substr($req,2, strlen($req) - 2); - } - $php_ver = phpversion(); - $operator = $relation; - if (!version_compare("$php_ver", "$req", $operator)) { - $errmsg = "PHP version " . $this->signOperator($operator) . - " $req is required"; - return PEAR_DEPENDENCY_CONFLICT; - } - return false; - } - - // }}} - // {{{ checkProgram() - - /** - * External program check method. Looks for executable files in - * directories listed in the PATH environment variable. - * - * @param string $program which program to look for - * - * @return mixed bool false if no error or the error string - */ - function checkProgram(&$errmsg, $program) - { - // XXX FIXME honor safe mode - $exe_suffix = OS_WINDOWS ? '.exe' : ''; - $path_elements = explode(PATH_SEPARATOR, getenv('PATH')); - foreach ($path_elements as $dir) { - $file = $dir . DIRECTORY_SEPARATOR . $program . $exe_suffix; - if (@file_exists($file) && @is_executable($file)) { - return false; - } - } - $errmsg = "'$program' program is not present in the PATH"; - return PEAR_DEPENDENCY_MISSING; - } - - // }}} - // {{{ checkSAPI() - - /** - * SAPI backend check method. Version comparison is not yet - * available here. - * - * @param string $name name of SAPI backend - * @param string $req which version to compare - * @param string $relation how to compare versions (currently - * hardcoded to 'has') - * @return mixed bool false if no error or the error string - */ - function checkSAPI(&$errmsg, $name, $req = null, $relation = 'has') - { - // XXX Fixme: There is no way to know if the user has or - // not other SAPI backends installed than the installer one - - $sapi_backend = php_sapi_name(); - // Version comparisons not supported, sapi backends don't have - // version information yet. - if ($sapi_backend == $name) { - return false; - } - $errmsg = "'$sapi_backend' SAPI backend not supported"; - return PEAR_DEPENDENCY_CONFLICT; - } - - // }}} - // {{{ checkZend() - - /** - * Zend version check method - * - * @param string $req which version to compare - * @param string $relation how to compare the version - * - * @return mixed bool false if no error or the error string - */ - function checkZend(&$errmsg, $req, $relation = 'ge') - { - if (substr($req, 0, 2) == 'v.') { - $req = substr($req,2, strlen($req) - 2); - } - $zend_ver = zend_version(); - $operator = substr($relation,0,2); - if (!version_compare("$zend_ver", "$req", $operator)) { - $errmsg = "Zend version " . $this->signOperator($operator) . - " $req is required"; - return PEAR_DEPENDENCY_CONFLICT; - } - return false; - } - - // }}} - // {{{ signOperator() - - /** - * Converts text comparing operators to them sign equivalents - * - * Example: 'ge' to '>=' - * - * @access public - * @param string Operator - * @return string Sign equivalent - */ - function signOperator($operator) - { - switch($operator) { - case 'lt': return '<'; - case 'le': return '<='; - case 'gt': return '>'; - case 'ge': return '>='; - case 'eq': return '=='; - case 'ne': return '!='; - default: - return $operator; - } - } - - // }}} - // {{{ codeFromRelation() - - /** - * Convert relation into corresponding code - * - * @access public - * @param string Relation - * @param string Version - * @param string Requirement - * @param bool Optional dependency indicator - * @return integer - */ - function codeFromRelation($relation, $version, $req, $opt = false) - { - $code = PEAR_DEPENDENCY_BAD_DEPENDENCY; - switch ($relation) { - case 'gt': case 'ge': case 'eq': - // upgrade - $have_major = preg_replace('/\D.*/', '', $version); - $need_major = preg_replace('/\D.*/', '', $req); - if ($need_major > $have_major) { - $code = $opt ? PEAR_DEPENDENCY_UPGRADE_MAJOR_OPTIONAL : - PEAR_DEPENDENCY_UPGRADE_MAJOR; - } else { - $code = $opt ? PEAR_DEPENDENCY_UPGRADE_MINOR_OPTIONAL : - PEAR_DEPENDENCY_UPGRADE_MINOR; - } - break; - case 'lt': case 'le': case 'ne': - $code = $opt ? PEAR_DEPENDENCY_CONFLICT_OPTIONAL : - PEAR_DEPENDENCY_CONFLICT; - break; - } - return $code; - } - - // }}} -} -?> diff --git a/3rdparty/PEAR/Downloader.php b/3rdparty/PEAR/Downloader.php deleted file mode 100644 index 5e16dc5ffb1b74791687df743b8d850fe3f80157..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Downloader.php +++ /dev/null @@ -1,680 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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. | -// +----------------------------------------------------------------------+ -// | Authors: Stig Bakken <ssb@php.net> | -// | Tomas V.V.Cox <cox@idecnet.com> | -// | Martin Jansen <mj@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Downloader.php,v 1.17.2.1 2004/10/22 22:54:03 cellog Exp $ - -require_once 'PEAR/Common.php'; -require_once 'PEAR/Registry.php'; -require_once 'PEAR/Dependency.php'; -require_once 'PEAR/Remote.php'; -require_once 'System.php'; - - -define('PEAR_INSTALLER_OK', 1); -define('PEAR_INSTALLER_FAILED', 0); -define('PEAR_INSTALLER_SKIPPED', -1); -define('PEAR_INSTALLER_ERROR_NO_PREF_STATE', 2); - -/** - * Administration class used to download PEAR packages and maintain the - * installed package database. - * - * @since PEAR 1.4 - * @author Greg Beaver <cellog@php.net> - */ -class PEAR_Downloader extends PEAR_Common -{ - /** - * @var PEAR_Config - * @access private - */ - var $_config; - - /** - * @var PEAR_Registry - * @access private - */ - var $_registry; - - /** - * @var PEAR_Remote - * @access private - */ - var $_remote; - - /** - * Preferred Installation State (snapshot, devel, alpha, beta, stable) - * @var string|null - * @access private - */ - var $_preferredState; - - /** - * Options from command-line passed to Install. - * - * Recognized options:<br /> - * - onlyreqdeps : install all required dependencies as well - * - alldeps : install all dependencies, including optional - * - installroot : base relative path to install files in - * - force : force a download even if warnings would prevent it - * @see PEAR_Command_Install - * @access private - * @var array - */ - var $_options; - - /** - * Downloaded Packages after a call to download(). - * - * Format of each entry: - * - * <code> - * array('pkg' => 'package_name', 'file' => '/path/to/local/file', - * 'info' => array() // parsed package.xml - * ); - * </code> - * @access private - * @var array - */ - var $_downloadedPackages = array(); - - /** - * Packages slated for download. - * - * This is used to prevent downloading a package more than once should it be a dependency - * for two packages to be installed. - * Format of each entry: - * - * <pre> - * array('package_name1' => parsed package.xml, 'package_name2' => parsed package.xml, - * ); - * </pre> - * @access private - * @var array - */ - var $_toDownload = array(); - - /** - * Array of every package installed, with names lower-cased. - * - * Format: - * <code> - * array('package1' => 0, 'package2' => 1, ); - * </code> - * @var array - */ - var $_installed = array(); - - /** - * @var array - * @access private - */ - var $_errorStack = array(); - - // {{{ PEAR_Downloader() - - function PEAR_Downloader(&$ui, $options, &$config) - { - $this->_options = $options; - $this->_config = &$config; - $this->_preferredState = $this->_config->get('preferred_state'); - $this->ui = &$ui; - if (!$this->_preferredState) { - // don't inadvertantly use a non-set preferred_state - $this->_preferredState = null; - } - - $php_dir = $this->_config->get('php_dir'); - if (isset($this->_options['installroot'])) { - if (substr($this->_options['installroot'], -1) == DIRECTORY_SEPARATOR) { - $this->_options['installroot'] = substr($this->_options['installroot'], 0, -1); - } - $php_dir = $this->_prependPath($php_dir, $this->_options['installroot']); - } - $this->_registry = &new PEAR_Registry($php_dir); - $this->_remote = &new PEAR_Remote($config); - - if (isset($this->_options['alldeps']) || isset($this->_options['onlyreqdeps'])) { - $this->_installed = $this->_registry->listPackages(); - array_walk($this->_installed, create_function('&$v,$k','$v = strtolower($v);')); - $this->_installed = array_flip($this->_installed); - } - parent::PEAR_Common(); - } - - // }}} - // {{{ configSet() - function configSet($key, $value, $layer = 'user') - { - $this->_config->set($key, $value, $layer); - $this->_preferredState = $this->_config->get('preferred_state'); - if (!$this->_preferredState) { - // don't inadvertantly use a non-set preferred_state - $this->_preferredState = null; - } - } - - // }}} - // {{{ setOptions() - function setOptions($options) - { - $this->_options = $options; - } - - // }}} - // {{{ _downloadFile() - /** - * @param string filename to download - * @param string version/state - * @param string original value passed to command-line - * @param string|null preferred state (snapshot/devel/alpha/beta/stable) - * Defaults to configuration preferred state - * @return null|PEAR_Error|string - * @access private - */ - function _downloadFile($pkgfile, $version, $origpkgfile, $state = null) - { - if (is_null($state)) { - $state = $this->_preferredState; - } - // {{{ check the package filename, and whether it's already installed - $need_download = false; - if (preg_match('#^(http|ftp)://#', $pkgfile)) { - $need_download = true; - } elseif (!@is_file($pkgfile)) { - if ($this->validPackageName($pkgfile)) { - if ($this->_registry->packageExists($pkgfile)) { - if (empty($this->_options['upgrade']) && empty($this->_options['force'])) { - $errors[] = "$pkgfile already installed"; - return; - } - } - $pkgfile = $this->getPackageDownloadUrl($pkgfile, $version); - $need_download = true; - } else { - if (strlen($pkgfile)) { - $errors[] = "Could not open the package file: $pkgfile"; - } else { - $errors[] = "No package file given"; - } - return; - } - } - // }}} - - // {{{ Download package ----------------------------------------------- - if ($need_download) { - $downloaddir = $this->_config->get('download_dir'); - if (empty($downloaddir)) { - if (PEAR::isError($downloaddir = System::mktemp('-d'))) { - return $downloaddir; - } - $this->log(3, '+ tmp dir created at ' . $downloaddir); - } - $callback = $this->ui ? array(&$this, '_downloadCallback') : null; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $file = $this->downloadHttp($pkgfile, $this->ui, $downloaddir, $callback); - $this->popErrorHandling(); - if (PEAR::isError($file)) { - if ($this->validPackageName($origpkgfile)) { - if (!PEAR::isError($info = $this->_remote->call('package.info', - $origpkgfile))) { - if (!count($info['releases'])) { - return $this->raiseError('Package ' . $origpkgfile . - ' has no releases'); - } else { - return $this->raiseError('No releases of preferred state "' - . $state . '" exist for package ' . $origpkgfile . - '. Use ' . $origpkgfile . '-state to install another' . - ' state (like ' . $origpkgfile .'-beta)', - PEAR_INSTALLER_ERROR_NO_PREF_STATE); - } - } else { - return $pkgfile; - } - } else { - return $this->raiseError($file); - } - } - $pkgfile = $file; - } - // }}} - return $pkgfile; - } - // }}} - // {{{ getPackageDownloadUrl() - - function getPackageDownloadUrl($package, $version = null) - { - if ($version) { - $package .= "-$version"; - } - if ($this === null || $this->_config === null) { - $package = "http://pear.php.net/get/$package"; - } else { - $package = "http://" . $this->_config->get('master_server') . - "/get/$package"; - } - if (!extension_loaded("zlib")) { - $package .= '?uncompress=yes'; - } - return $package; - } - - // }}} - // {{{ extractDownloadFileName($pkgfile, &$version) - - function extractDownloadFileName($pkgfile, &$version) - { - if (@is_file($pkgfile)) { - return $pkgfile; - } - // regex defined in Common.php - if (preg_match(PEAR_COMMON_PACKAGE_DOWNLOAD_PREG, $pkgfile, $m)) { - $version = (isset($m[3])) ? $m[3] : null; - return $m[1]; - } - $version = null; - return $pkgfile; - } - - // }}} - - // }}} - // {{{ getDownloadedPackages() - - /** - * Retrieve a list of downloaded packages after a call to {@link download()}. - * - * Also resets the list of downloaded packages. - * @return array - */ - function getDownloadedPackages() - { - $ret = $this->_downloadedPackages; - $this->_downloadedPackages = array(); - $this->_toDownload = array(); - return $ret; - } - - // }}} - // {{{ download() - - /** - * Download any files and their dependencies, if necessary - * - * BC-compatible method name - * @param array a mixed list of package names, local files, or package.xml - */ - function download($packages) - { - return $this->doDownload($packages); - } - - // }}} - // {{{ doDownload() - - /** - * Download any files and their dependencies, if necessary - * - * @param array a mixed list of package names, local files, or package.xml - */ - function doDownload($packages) - { - $mywillinstall = array(); - $state = $this->_preferredState; - - // {{{ download files in this list if necessary - foreach($packages as $pkgfile) { - $need_download = false; - if (!is_file($pkgfile)) { - if (preg_match('#^(http|ftp)://#', $pkgfile)) { - $need_download = true; - } - $pkgfile = $this->_downloadNonFile($pkgfile); - if (PEAR::isError($pkgfile)) { - return $pkgfile; - } - if ($pkgfile === false) { - continue; - } - } // end is_file() - - $tempinfo = $this->infoFromAny($pkgfile); - if ($need_download) { - $this->_toDownload[] = $tempinfo['package']; - } - if (isset($this->_options['alldeps']) || isset($this->_options['onlyreqdeps'])) { - // ignore dependencies if there are any errors - if (!PEAR::isError($tempinfo)) { - $mywillinstall[strtolower($tempinfo['package'])] = @$tempinfo['release_deps']; - } - } - $this->_downloadedPackages[] = array('pkg' => $tempinfo['package'], - 'file' => $pkgfile, 'info' => $tempinfo); - } // end foreach($packages) - // }}} - - // {{{ extract dependencies from downloaded files and then download - // them if necessary - if (isset($this->_options['alldeps']) || isset($this->_options['onlyreqdeps'])) { - $deppackages = array(); - foreach ($mywillinstall as $package => $alldeps) { - if (!is_array($alldeps)) { - // there are no dependencies - continue; - } - $fail = false; - foreach ($alldeps as $info) { - if ($info['type'] != 'pkg') { - continue; - } - $ret = $this->_processDependency($package, $info, $mywillinstall); - if ($ret === false) { - continue; - } - if ($ret === 0) { - $fail = true; - continue; - } - if (PEAR::isError($ret)) { - return $ret; - } - $deppackages[] = $ret; - } // foreach($alldeps - if ($fail) { - $deppackages = array(); - } - } - - if (count($deppackages)) { - $this->doDownload($deppackages); - } - } // }}} if --alldeps or --onlyreqdeps - } - - // }}} - // {{{ _downloadNonFile($pkgfile) - - /** - * @return false|PEAR_Error|string false if loop should be broken out of, - * string if the file was downloaded, - * PEAR_Error on exception - * @access private - */ - function _downloadNonFile($pkgfile) - { - $origpkgfile = $pkgfile; - $state = null; - $pkgfile = $this->extractDownloadFileName($pkgfile, $version); - if (preg_match('#^(http|ftp)://#', $pkgfile)) { - return $this->_downloadFile($pkgfile, $version, $origpkgfile); - } - if (!$this->validPackageName($pkgfile)) { - return $this->raiseError("Package name '$pkgfile' not valid"); - } - // ignore packages that are installed unless we are upgrading - $curinfo = $this->_registry->packageInfo($pkgfile); - if ($this->_registry->packageExists($pkgfile) - && empty($this->_options['upgrade']) && empty($this->_options['force'])) { - $this->log(0, "Package '{$curinfo['package']}' already installed, skipping"); - return false; - } - if (in_array($pkgfile, $this->_toDownload)) { - return false; - } - $releases = $this->_remote->call('package.info', $pkgfile, 'releases', true); - if (!count($releases)) { - return $this->raiseError("No releases found for package '$pkgfile'"); - } - // Want a specific version/state - if ($version !== null) { - // Passed Foo-1.2 - if ($this->validPackageVersion($version)) { - if (!isset($releases[$version])) { - return $this->raiseError("No release with version '$version' found for '$pkgfile'"); - } - // Passed Foo-alpha - } elseif (in_array($version, $this->getReleaseStates())) { - $state = $version; - $version = 0; - foreach ($releases as $ver => $inf) { - if ($inf['state'] == $state && version_compare("$version", "$ver") < 0) { - $version = $ver; - break; - } - } - if ($version == 0) { - return $this->raiseError("No release with state '$state' found for '$pkgfile'"); - } - // invalid suffix passed - } else { - return $this->raiseError("Invalid suffix '-$version', be sure to pass a valid PEAR ". - "version number or release state"); - } - // Guess what to download - } else { - $states = $this->betterStates($this->_preferredState, true); - $possible = false; - $version = 0; - $higher_version = 0; - $prev_hi_ver = 0; - foreach ($releases as $ver => $inf) { - if (in_array($inf['state'], $states) && version_compare("$version", "$ver") < 0) { - $version = $ver; - break; - } else { - $ver = (string)$ver; - if (version_compare($prev_hi_ver, $ver) < 0) { - $prev_hi_ver = $higher_version = $ver; - } - } - } - if ($version === 0 && !isset($this->_options['force'])) { - return $this->raiseError('No release with state equal to: \'' . implode(', ', $states) . - "' found for '$pkgfile'"); - } elseif ($version === 0) { - $this->log(0, "Warning: $pkgfile is state '" . $releases[$higher_version]['state'] . "' which is less stable " . - "than state '$this->_preferredState'"); - } - } - // Check if we haven't already the version - if (empty($this->_options['force']) && !is_null($curinfo)) { - if ($curinfo['version'] == $version) { - $this->log(0, "Package '{$curinfo['package']}-{$curinfo['version']}' already installed, skipping"); - return false; - } elseif (version_compare("$version", "{$curinfo['version']}") < 0) { - $this->log(0, "Package '{$curinfo['package']}' version '{$curinfo['version']}' " . - " is installed and {$curinfo['version']} is > requested '$version', skipping"); - return false; - } - } - $this->_toDownload[] = $pkgfile; - return $this->_downloadFile($pkgfile, $version, $origpkgfile, $state); - } - - // }}} - // {{{ _processDependency($package, $info, $mywillinstall) - - /** - * Process a dependency, download if necessary - * @param array dependency information from PEAR_Remote call - * @param array packages that will be installed in this iteration - * @return false|string|PEAR_Error - * @access private - * @todo Add test for relation 'lt'/'le' -> make sure that the dependency requested is - * in fact lower than the required value. This will be very important for BC dependencies - */ - function _processDependency($package, $info, $mywillinstall) - { - $state = $this->_preferredState; - if (!isset($this->_options['alldeps']) && isset($info['optional']) && - $info['optional'] == 'yes') { - // skip optional deps - $this->log(0, "skipping Package '$package' optional dependency '$info[name]'"); - return false; - } - // {{{ get releases - $releases = $this->_remote->call('package.info', $info['name'], 'releases', true); - if (PEAR::isError($releases)) { - return $releases; - } - if (!count($releases)) { - if (!isset($this->_installed[strtolower($info['name'])])) { - $this->pushError("Package '$package' dependency '$info[name]' ". - "has no releases"); - } - return false; - } - $found = false; - $save = $releases; - while(count($releases) && !$found) { - if (!empty($state) && $state != 'any') { - list($release_version, $release) = each($releases); - if ($state != $release['state'] && - !in_array($release['state'], $this->betterStates($state))) - { - // drop this release - it ain't stable enough - array_shift($releases); - } else { - $found = true; - } - } else { - $found = true; - } - } - if (!count($releases) && !$found) { - $get = array(); - foreach($save as $release) { - $get = array_merge($get, - $this->betterStates($release['state'], true)); - } - $savestate = array_shift($get); - $this->pushError( "Release for '$package' dependency '$info[name]' " . - "has state '$savestate', requires '$state'"); - return 0; - } - if (in_array(strtolower($info['name']), $this->_toDownload) || - isset($mywillinstall[strtolower($info['name'])])) { - // skip upgrade check for packages we will install - return false; - } - if (!isset($this->_installed[strtolower($info['name'])])) { - // check to see if we can install the specific version required - if ($info['rel'] == 'eq') { - return $info['name'] . '-' . $info['version']; - } - // skip upgrade check for packages we don't have installed - return $info['name']; - } - // }}} - - // {{{ see if a dependency must be upgraded - $inst_version = $this->_registry->packageInfo($info['name'], 'version'); - if (!isset($info['version'])) { - // this is a rel='has' dependency, check against latest - if (version_compare($release_version, $inst_version, 'le')) { - return false; - } else { - return $info['name']; - } - } - if (version_compare($info['version'], $inst_version, 'le')) { - // installed version is up-to-date - return false; - } - return $info['name']; - } - - // }}} - // {{{ _downloadCallback() - - function _downloadCallback($msg, $params = null) - { - switch ($msg) { - case 'saveas': - $this->log(1, "downloading $params ..."); - break; - case 'done': - $this->log(1, '...done: ' . number_format($params, 0, '', ',') . ' bytes'); - break; - case 'bytesread': - static $bytes; - if (empty($bytes)) { - $bytes = 0; - } - if (!($bytes % 10240)) { - $this->log(1, '.', false); - } - $bytes += $params; - break; - case 'start': - $this->log(1, "Starting to download {$params[0]} (".number_format($params[1], 0, '', ',')." bytes)"); - break; - } - if (method_exists($this->ui, '_downloadCallback')) - $this->ui->_downloadCallback($msg, $params); - } - - // }}} - // {{{ _prependPath($path, $prepend) - - function _prependPath($path, $prepend) - { - if (strlen($prepend) > 0) { - if (OS_WINDOWS && preg_match('/^[a-z]:/i', $path)) { - $path = $prepend . substr($path, 2); - } else { - $path = $prepend . $path; - } - } - return $path; - } - // }}} - // {{{ pushError($errmsg, $code) - - /** - * @param string - * @param integer - */ - function pushError($errmsg, $code = -1) - { - array_push($this->_errorStack, array($errmsg, $code)); - } - - // }}} - // {{{ getErrorMsgs() - - function getErrorMsgs() - { - $msgs = array(); - $errs = $this->_errorStack; - foreach ($errs as $err) { - $msgs[] = $err[0]; - } - $this->_errorStack = array(); - return $msgs; - } - - // }}} -} -// }}} - -?> diff --git a/3rdparty/PEAR/ErrorStack.php b/3rdparty/PEAR/ErrorStack.php deleted file mode 100644 index da52f08d34543667a5716319e84873fbd7f665c5..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/ErrorStack.php +++ /dev/null @@ -1,981 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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: Gregory Beaver <cellog@php.net> | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: ErrorStack.php,v 1.7.2.5 2005/01/01 21:26:51 cellog Exp $ - -/** - * Error Stack Implementation - * - * This is an incredibly simple implementation of a very complex error handling - * facility. It contains the ability - * to track multiple errors from multiple packages simultaneously. In addition, - * it can track errors of many levels, save data along with the error, context - * information such as the exact file, line number, class and function that - * generated the error, and if necessary, it can raise a traditional PEAR_Error. - * It has built-in support for PEAR::Log, to log errors as they occur - * - * Since version 0.2alpha, it is also possible to selectively ignore errors, - * through the use of an error callback, see {@link pushCallback()} - * - * Since version 0.3alpha, it is possible to specify the exception class - * returned from {@link push()} - * - * Since version PEAR1.3.2, ErrorStack no longer instantiates an exception class. This can - * still be done quite handily in an error callback or by manipulating the returned array - * @author Greg Beaver <cellog@php.net> - * @version PEAR1.3.2 (beta) - * @package PEAR_ErrorStack - * @category Debugging - * @license http://www.php.net/license/3_0.txt PHP License v3.0 - */ - -/** - * Singleton storage - * - * Format: - * <pre> - * array( - * 'package1' => PEAR_ErrorStack object, - * 'package2' => PEAR_ErrorStack object, - * ... - * ) - * </pre> - * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] - */ -$GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] = array(); - -/** - * Global error callback (default) - * - * This is only used if set to non-false. * is the default callback for - * all packages, whereas specific packages may set a default callback - * for all instances, regardless of whether they are a singleton or not. - * - * To exclude non-singletons, only set the local callback for the singleton - * @see PEAR_ErrorStack::setDefaultCallback() - * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'] - */ -$GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'] = array( - '*' => false, -); - -/** - * Global Log object (default) - * - * This is only used if set to non-false. Use to set a default log object for - * all stacks, regardless of instantiation order or location - * @see PEAR_ErrorStack::setDefaultLogger() - * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] - */ -$GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = false; - -/** - * Global Overriding Callback - * - * This callback will override any error callbacks that specific loggers have set. - * Use with EXTREME caution - * @see PEAR_ErrorStack::staticPushCallback() - * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] - */ -$GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array(); - -/**#@+ - * One of four possible return values from the error Callback - * @see PEAR_ErrorStack::_errorCallback() - */ -/** - * If this is returned, then the error will be both pushed onto the stack - * and logged. - */ -define('PEAR_ERRORSTACK_PUSHANDLOG', 1); -/** - * If this is returned, then the error will only be pushed onto the stack, - * and not logged. - */ -define('PEAR_ERRORSTACK_PUSH', 2); -/** - * If this is returned, then the error will only be logged, but not pushed - * onto the error stack. - */ -define('PEAR_ERRORSTACK_LOG', 3); -/** - * If this is returned, then the error is completely ignored. - */ -define('PEAR_ERRORSTACK_IGNORE', 4); -/** - * If this is returned, then the error is logged and die() is called. - */ -define('PEAR_ERRORSTACK_DIE', 5); -/**#@-*/ - -/** - * Error code for an attempt to instantiate a non-class as a PEAR_ErrorStack in - * the singleton method. - */ -define('PEAR_ERRORSTACK_ERR_NONCLASS', 1); - -/** - * Error code for an attempt to pass an object into {@link PEAR_ErrorStack::getMessage()} - * that has no __toString() method - */ -define('PEAR_ERRORSTACK_ERR_OBJTOSTRING', 2); -/** - * Error Stack Implementation - * - * Usage: - * <code> - * // global error stack - * $global_stack = &PEAR_ErrorStack::singleton('MyPackage'); - * // local error stack - * $local_stack = new PEAR_ErrorStack('MyPackage'); - * </code> - * @copyright 2004 Gregory Beaver - * @package PEAR_ErrorStack - * @license http://www.php.net/license/3_0.txt PHP License - */ -class PEAR_ErrorStack { - /** - * Errors are stored in the order that they are pushed on the stack. - * @since 0.4alpha Errors are no longer organized by error level. - * This renders pop() nearly unusable, and levels could be more easily - * handled in a callback anyway - * @var array - * @access private - */ - var $_errors = array(); - - /** - * Storage of errors by level. - * - * Allows easy retrieval and deletion of only errors from a particular level - * @since PEAR 1.4.0dev - * @var array - * @access private - */ - var $_errorsByLevel = array(); - - /** - * Package name this error stack represents - * @var string - * @access protected - */ - var $_package; - - /** - * Determines whether a PEAR_Error is thrown upon every error addition - * @var boolean - * @access private - */ - var $_compat = false; - - /** - * If set to a valid callback, this will be used to generate the error - * message from the error code, otherwise the message passed in will be - * used - * @var false|string|array - * @access private - */ - var $_msgCallback = false; - - /** - * If set to a valid callback, this will be used to generate the error - * context for an error. For PHP-related errors, this will be a file - * and line number as retrieved from debug_backtrace(), but can be - * customized for other purposes. The error might actually be in a separate - * configuration file, or in a database query. - * @var false|string|array - * @access protected - */ - var $_contextCallback = false; - - /** - * If set to a valid callback, this will be called every time an error - * is pushed onto the stack. The return value will be used to determine - * whether to allow an error to be pushed or logged. - * - * The return value must be one an PEAR_ERRORSTACK_* constant - * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG - * @var false|string|array - * @access protected - */ - var $_errorCallback = array(); - - /** - * PEAR::Log object for logging errors - * @var false|Log - * @access protected - */ - var $_logger = false; - - /** - * Error messages - designed to be overridden - * @var array - * @abstract - */ - var $_errorMsgs = array(); - - /** - * Set up a new error stack - * - * @param string $package name of the package this error stack represents - * @param callback $msgCallback callback used for error message generation - * @param callback $contextCallback callback used for context generation, - * defaults to {@link getFileLine()} - * @param boolean $throwPEAR_Error - */ - function PEAR_ErrorStack($package, $msgCallback = false, $contextCallback = false, - $throwPEAR_Error = false) - { - $this->_package = $package; - $this->setMessageCallback($msgCallback); - $this->setContextCallback($contextCallback); - $this->_compat = $throwPEAR_Error; - } - - /** - * Return a single error stack for this package. - * - * Note that all parameters are ignored if the stack for package $package - * has already been instantiated - * @param string $package name of the package this error stack represents - * @param callback $msgCallback callback used for error message generation - * @param callback $contextCallback callback used for context generation, - * defaults to {@link getFileLine()} - * @param boolean $throwPEAR_Error - * @param string $stackClass class to instantiate - * @static - * @return PEAR_ErrorStack - */ - function &singleton($package, $msgCallback = false, $contextCallback = false, - $throwPEAR_Error = false, $stackClass = 'PEAR_ErrorStack') - { - if (isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) { - return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]; - } - if (!class_exists($stackClass)) { - if (function_exists('debug_backtrace')) { - $trace = debug_backtrace(); - } - PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_NONCLASS, - 'exception', array('stackclass' => $stackClass), - 'stack class "%stackclass%" is not a valid class name (should be like PEAR_ErrorStack)', - false, $trace); - } - return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package] = - &new $stackClass($package, $msgCallback, $contextCallback, $throwPEAR_Error); - } - - /** - * Internal error handler for PEAR_ErrorStack class - * - * Dies if the error is an exception (and would have died anyway) - * @access private - */ - function _handleError($err) - { - if ($err['level'] == 'exception') { - $message = $err['message']; - if (isset($_SERVER['REQUEST_URI'])) { - echo '<br />'; - } else { - echo "\n"; - } - var_dump($err['context']); - die($message); - } - } - - /** - * Set up a PEAR::Log object for all error stacks that don't have one - * @param Log $log - * @static - */ - function setDefaultLogger(&$log) - { - if (is_object($log) && method_exists($log, 'log') ) { - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = &$log; - } elseif (is_callable($log)) { - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = &$log; - } - } - - /** - * Set up a PEAR::Log object for this error stack - * @param Log $log - */ - function setLogger(&$log) - { - if (is_object($log) && method_exists($log, 'log') ) { - $this->_logger = &$log; - } elseif (is_callable($log)) { - $this->_logger = &$log; - } - } - - /** - * Set an error code => error message mapping callback - * - * This method sets the callback that can be used to generate error - * messages for any instance - * @param array|string Callback function/method - */ - function setMessageCallback($msgCallback) - { - if (!$msgCallback) { - $this->_msgCallback = array(&$this, 'getErrorMessage'); - } else { - if (is_callable($msgCallback)) { - $this->_msgCallback = $msgCallback; - } - } - } - - /** - * Get an error code => error message mapping callback - * - * This method returns the current callback that can be used to generate error - * messages - * @return array|string|false Callback function/method or false if none - */ - function getMessageCallback() - { - return $this->_msgCallback; - } - - /** - * Sets a default callback to be used by all error stacks - * - * This method sets the callback that can be used to generate error - * messages for a singleton - * @param array|string Callback function/method - * @param string Package name, or false for all packages - * @static - */ - function setDefaultCallback($callback = false, $package = false) - { - if (!is_callable($callback)) { - $callback = false; - } - $package = $package ? $package : '*'; - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$package] = $callback; - } - - /** - * Set a callback that generates context information (location of error) for an error stack - * - * This method sets the callback that can be used to generate context - * information for an error. Passing in NULL will disable context generation - * and remove the expensive call to debug_backtrace() - * @param array|string|null Callback function/method - */ - function setContextCallback($contextCallback) - { - if ($contextCallback === null) { - return $this->_contextCallback = false; - } - if (!$contextCallback) { - $this->_contextCallback = array(&$this, 'getFileLine'); - } else { - if (is_callable($contextCallback)) { - $this->_contextCallback = $contextCallback; - } - } - } - - /** - * Set an error Callback - * If set to a valid callback, this will be called every time an error - * is pushed onto the stack. The return value will be used to determine - * whether to allow an error to be pushed or logged. - * - * The return value must be one of the ERRORSTACK_* constants. - * - * This functionality can be used to emulate PEAR's pushErrorHandling, and - * the PEAR_ERROR_CALLBACK mode, without affecting the integrity of - * the error stack or logging - * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG - * @see popCallback() - * @param string|array $cb - */ - function pushCallback($cb) - { - array_push($this->_errorCallback, $cb); - } - - /** - * Remove a callback from the error callback stack - * @see pushCallback() - * @return array|string|false - */ - function popCallback() - { - if (!count($this->_errorCallback)) { - return false; - } - return array_pop($this->_errorCallback); - } - - /** - * Set a temporary overriding error callback for every package error stack - * - * Use this to temporarily disable all existing callbacks (can be used - * to emulate the @ operator, for instance) - * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG - * @see staticPopCallback(), pushCallback() - * @param string|array $cb - * @static - */ - function staticPushCallback($cb) - { - array_push($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'], $cb); - } - - /** - * Remove a temporary overriding error callback - * @see staticPushCallback() - * @return array|string|false - * @static - */ - function staticPopCallback() - { - $ret = array_pop($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK']); - if (!is_array($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'])) { - $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array(); - } - return $ret; - } - - /** - * Add an error to the stack - * - * If the message generator exists, it is called with 2 parameters. - * - the current Error Stack object - * - an array that is in the same format as an error. Available indices - * are 'code', 'package', 'time', 'params', 'level', and 'context' - * - * Next, if the error should contain context information, this is - * handled by the context grabbing method. - * Finally, the error is pushed onto the proper error stack - * @param int $code Package-specific error code - * @param string $level Error level. This is NOT spell-checked - * @param array $params associative array of error parameters - * @param string $msg Error message, or a portion of it if the message - * is to be generated - * @param array $repackage If this error re-packages an error pushed by - * another package, place the array returned from - * {@link pop()} in this parameter - * @param array $backtrace Protected parameter: use this to pass in the - * {@link debug_backtrace()} that should be used - * to find error context - * @return PEAR_Error|array|Exception - * if compatibility mode is on, a PEAR_Error is also - * thrown. If the class Exception exists, then one - * is returned to allow code like: - * <code> - * throw ($stack->push(MY_ERROR_CODE, 'error', array('username' => 'grob'))); - * </code> - * - * The errorData property of the exception class will be set to the array - * that would normally be returned. If a PEAR_Error is returned, the userinfo - * property is set to the array - * - * Otherwise, an array is returned in this format: - * <code> - * array( - * 'code' => $code, - * 'params' => $params, - * 'package' => $this->_package, - * 'level' => $level, - * 'time' => time(), - * 'context' => $context, - * 'message' => $msg, - * //['repackage' => $err] repackaged error array/Exception class - * ); - * </code> - */ - function push($code, $level = 'error', $params = array(), $msg = false, - $repackage = false, $backtrace = false) - { - $context = false; - // grab error context - if ($this->_contextCallback) { - if (!$backtrace) { - $backtrace = debug_backtrace(); - } - $context = call_user_func($this->_contextCallback, $code, $params, $backtrace); - } - - // save error - $time = explode(' ', microtime()); - $time = $time[1] + $time[0]; - $err = array( - 'code' => $code, - 'params' => $params, - 'package' => $this->_package, - 'level' => $level, - 'time' => $time, - 'context' => $context, - 'message' => $msg, - ); - - // set up the error message, if necessary - if ($this->_msgCallback) { - $msg = call_user_func_array($this->_msgCallback, - array(&$this, $err)); - $err['message'] = $msg; - } - - if ($repackage) { - $err['repackage'] = $repackage; - } - $push = $log = true; - $die = false; - // try the overriding callback first - $callback = $this->staticPopCallback(); - if ($callback) { - $this->staticPushCallback($callback); - } - if (!is_callable($callback)) { - // try the local callback next - $callback = $this->popCallback(); - if (is_callable($callback)) { - $this->pushCallback($callback); - } else { - // try the default callback - $callback = isset($GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$this->_package]) ? - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$this->_package] : - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK']['*']; - } - } - if (is_callable($callback)) { - switch(call_user_func($callback, $err)){ - case PEAR_ERRORSTACK_IGNORE: - return $err; - break; - case PEAR_ERRORSTACK_PUSH: - $log = false; - break; - case PEAR_ERRORSTACK_LOG: - $push = false; - break; - case PEAR_ERRORSTACK_DIE: - $die = true; - break; - // anything else returned has the same effect as pushandlog - } - } - if ($push) { - array_unshift($this->_errors, $err); - $this->_errorsByLevel[$err['level']][] = &$this->_errors[0]; - } - if ($log) { - if ($this->_logger || $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER']) { - $this->_log($err); - } - } - if ($die) { - die(); - } - if ($this->_compat && $push) { - return $this->raiseError($msg, $code, null, null, $err); - } - return $err; - } - - /** - * Static version of {@link push()} - * - * @param string $package Package name this error belongs to - * @param int $code Package-specific error code - * @param string $level Error level. This is NOT spell-checked - * @param array $params associative array of error parameters - * @param string $msg Error message, or a portion of it if the message - * is to be generated - * @param array $repackage If this error re-packages an error pushed by - * another package, place the array returned from - * {@link pop()} in this parameter - * @param array $backtrace Protected parameter: use this to pass in the - * {@link debug_backtrace()} that should be used - * to find error context - * @return PEAR_Error|null|Exception - * if compatibility mode is on, a PEAR_Error is also - * thrown. If the class Exception exists, then one - * is returned to allow code like: - * <code> - * throw ($stack->push(MY_ERROR_CODE, 'error', array('username' => 'grob'))); - * </code> - * @static - */ - function staticPush($package, $code, $level = 'error', $params = array(), - $msg = false, $repackage = false, $backtrace = false) - { - $s = &PEAR_ErrorStack::singleton($package); - if ($s->_contextCallback) { - if (!$backtrace) { - if (function_exists('debug_backtrace')) { - $backtrace = debug_backtrace(); - } - } - } - return $s->push($code, $level, $params, $msg, $repackage, $backtrace); - } - - /** - * Log an error using PEAR::Log - * @param array $err Error array - * @param array $levels Error level => Log constant map - * @access protected - */ - function _log($err) - { - if ($this->_logger) { - $logger = &$this->_logger; - } else { - $logger = &$GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER']; - } - if (is_a($logger, 'Log')) { - $levels = array( - 'exception' => PEAR_LOG_CRIT, - '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); - if (isset($levels[$err['level']])) { - $level = $levels[$err['level']]; - } else { - $level = PEAR_LOG_INFO; - } - $logger->log($err['message'], $level, $err); - } else { // support non-standard logs - call_user_func($logger, $err); - } - } - - - /** - * Pop an error off of the error stack - * - * @return false|array - * @since 0.4alpha it is no longer possible to specify a specific error - * level to return - the last error pushed will be returned, instead - */ - function pop() - { - return @array_shift($this->_errors); - } - - /** - * Determine whether there are any errors on the stack - * @param string|array Level name. Use to determine if any errors - * of level (string), or levels (array) have been pushed - * @return boolean - */ - function hasErrors($level = false) - { - if ($level) { - return isset($this->_errorsByLevel[$level]); - } - return count($this->_errors); - } - - /** - * Retrieve all errors since last purge - * - * @param boolean set in order to empty the error stack - * @param string level name, to return only errors of a particular severity - * @return array - */ - function getErrors($purge = false, $level = false) - { - if (!$purge) { - if ($level) { - if (!isset($this->_errorsByLevel[$level])) { - return array(); - } else { - return $this->_errorsByLevel[$level]; - } - } else { - return $this->_errors; - } - } - if ($level) { - $ret = $this->_errorsByLevel[$level]; - foreach ($this->_errorsByLevel[$level] as $i => $unused) { - // entries are references to the $_errors array - $this->_errorsByLevel[$level][$i] = false; - } - // array_filter removes all entries === false - $this->_errors = array_filter($this->_errors); - unset($this->_errorsByLevel[$level]); - return $ret; - } - $ret = $this->_errors; - $this->_errors = array(); - $this->_errorsByLevel = array(); - return $ret; - } - - /** - * Determine whether there are any errors on a single error stack, or on any error stack - * - * The optional parameter can be used to test the existence of any errors without the need of - * singleton instantiation - * @param string|false Package name to check for errors - * @param string Level name to check for a particular severity - * @return boolean - * @static - */ - function staticHasErrors($package = false, $level = false) - { - if ($package) { - if (!isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) { - return false; - } - return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->hasErrors($level); - } - foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) { - if ($obj->hasErrors($level)) { - return true; - } - } - return false; - } - - /** - * Get a list of all errors since last purge, organized by package - * @since PEAR 1.4.0dev BC break! $level is now in the place $merge used to be - * @param boolean $purge Set to purge the error stack of existing errors - * @param string $level Set to a level name in order to retrieve only errors of a particular level - * @param boolean $merge Set to return a flat array, not organized by package - * @param array $sortfunc Function used to sort a merged array - default - * sorts by time, and should be good for most cases - * @static - * @return array - */ - function staticGetErrors($purge = false, $level = false, $merge = false, - $sortfunc = array('PEAR_ErrorStack', '_sortErrors')) - { - $ret = array(); - if (!is_callable($sortfunc)) { - $sortfunc = array('PEAR_ErrorStack', '_sortErrors'); - } - foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) { - $test = $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->getErrors($purge, $level); - if ($test) { - if ($merge) { - $ret = array_merge($ret, $test); - } else { - $ret[$package] = $test; - } - } - } - if ($merge) { - usort($ret, $sortfunc); - } - return $ret; - } - - /** - * Error sorting function, sorts by time - * @access private - */ - function _sortErrors($a, $b) - { - if ($a['time'] == $b['time']) { - return 0; - } - if ($a['time'] < $b['time']) { - return 1; - } - return -1; - } - - /** - * Standard file/line number/function/class context callback - * - * This function uses a backtrace generated from {@link debug_backtrace()} - * and so will not work at all in PHP < 4.3.0. The frame should - * reference the frame that contains the source of the error. - * @return array|false either array('file' => file, 'line' => line, - * 'function' => function name, 'class' => class name) or - * if this doesn't work, then false - * @param unused - * @param integer backtrace frame. - * @param array Results of debug_backtrace() - * @static - */ - function getFileLine($code, $params, $backtrace = null) - { - if ($backtrace === null) { - return false; - } - $frame = 0; - $functionframe = 1; - if (!isset($backtrace[1])) { - $functionframe = 0; - } else { - while (isset($backtrace[$functionframe]['function']) && - $backtrace[$functionframe]['function'] == 'eval' && - isset($backtrace[$functionframe + 1])) { - $functionframe++; - } - } - if (isset($backtrace[$frame])) { - if (!isset($backtrace[$frame]['file'])) { - $frame++; - } - $funcbacktrace = $backtrace[$functionframe]; - $filebacktrace = $backtrace[$frame]; - $ret = array('file' => $filebacktrace['file'], - 'line' => $filebacktrace['line']); - // rearrange for eval'd code or create function errors - if (strpos($filebacktrace['file'], '(') && - preg_match(';^(.*?)\((\d+)\) : (.*?)$;', $filebacktrace['file'], - $matches)) { - $ret['file'] = $matches[1]; - $ret['line'] = $matches[2] + 0; - } - if (isset($funcbacktrace['function']) && isset($backtrace[1])) { - if ($funcbacktrace['function'] != 'eval') { - if ($funcbacktrace['function'] == '__lambda_func') { - $ret['function'] = 'create_function() code'; - } else { - $ret['function'] = $funcbacktrace['function']; - } - } - } - if (isset($funcbacktrace['class']) && isset($backtrace[1])) { - $ret['class'] = $funcbacktrace['class']; - } - return $ret; - } - return false; - } - - /** - * Standard error message generation callback - * - * This method may also be called by a custom error message generator - * to fill in template values from the params array, simply - * set the third parameter to the error message template string to use - * - * The special variable %__msg% is reserved: use it only to specify - * where a message passed in by the user should be placed in the template, - * like so: - * - * Error message: %msg% - internal error - * - * If the message passed like so: - * - * <code> - * $stack->push(ERROR_CODE, 'error', array(), 'server error 500'); - * </code> - * - * The returned error message will be "Error message: server error 500 - - * internal error" - * @param PEAR_ErrorStack - * @param array - * @param string|false Pre-generated error message template - * @static - * @return string - */ - function getErrorMessage(&$stack, $err, $template = false) - { - if ($template) { - $mainmsg = $template; - } else { - $mainmsg = $stack->getErrorMessageTemplate($err['code']); - } - $mainmsg = str_replace('%__msg%', $err['message'], $mainmsg); - if (count($err['params'])) { - foreach ($err['params'] as $name => $val) { - if (is_array($val)) { - // @ is needed in case $val is a multi-dimensional array - $val = @implode(', ', $val); - } - if (is_object($val)) { - if (method_exists($val, '__toString')) { - $val = $val->__toString(); - } else { - PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_OBJTOSTRING, - 'warning', array('obj' => get_class($val)), - 'object %obj% passed into getErrorMessage, but has no __toString() method'); - $val = 'Object'; - } - } - $mainmsg = str_replace('%' . $name . '%', $val, $mainmsg); - } - } - return $mainmsg; - } - - /** - * Standard Error Message Template generator from code - * @return string - */ - function getErrorMessageTemplate($code) - { - if (!isset($this->_errorMsgs[$code])) { - return '%__msg%'; - } - return $this->_errorMsgs[$code]; - } - - /** - * Set the Error Message Template array - * - * The array format must be: - * <pre> - * array(error code => 'message template',...) - * </pre> - * - * Error message parameters passed into {@link push()} will be used as input - * for the error message. If the template is 'message %foo% was %bar%', and the - * parameters are array('foo' => 'one', 'bar' => 'six'), the error message returned will - * be 'message one was six' - * @return string - */ - function setErrorMessageTemplate($template) - { - $this->_errorMsgs = $template; - } - - - /** - * emulate PEAR::raiseError() - * - * @return PEAR_Error - */ - function raiseError() - { - require_once 'PEAR.php'; - $args = func_get_args(); - return call_user_func_array(array('PEAR', 'raiseError'), $args); - } -} -$stack = &PEAR_ErrorStack::singleton('PEAR_ErrorStack'); -$stack->pushCallback(array('PEAR_ErrorStack', '_handleError')); -?> \ No newline at end of file diff --git a/3rdparty/PEAR/Exception.php b/3rdparty/PEAR/Exception.php deleted file mode 100644 index c735c16b3983f6dd2baba28271b976e0436623d7..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Exception.php +++ /dev/null @@ -1,359 +0,0 @@ -<?php -/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */ -// +----------------------------------------------------------------------+ -// | PEAR_Exception | -// +----------------------------------------------------------------------+ -// | Copyright (c) 2004 The PEAR 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: Tomas V.V.Cox <cox@idecnet.com> | -// | Hans Lellelid <hans@velum.net> | -// | Bertrand Mansion <bmansion@mamasam.com> | -// | Greg Beaver <cellog@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Exception.php,v 1.4.2.2 2004/12/31 19:01:52 cellog Exp $ - - -/** - * Base PEAR_Exception Class - * - * WARNING: This code should be considered stable, but the API is - * subject to immediate and drastic change, so API stability is - * at best alpha - * - * 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> - * - * @since PHP 5 - * @package PEAR - * @version $Revision: 1.4.2.2 $ - * @author Tomas V.V.Cox <cox@idecnet.com> - * @author Hans Lellelid <hans@velum.net> - * @author Bertrand Mansion <bmansion@mamasam.com> - * - */ -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, array $causes); - * PEAR_Exception(string $message, array $causes, int $code); - */ - public function __construct($message, $p2 = null, $p3 = null) - { - if (is_int($p2)) { - $code = $p2; - $this->cause = null; - } elseif ($p2 instanceof Exception || is_array($p2)) { - $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']; - } - } - if ($this->cause instanceof PEAR_Exception) { - $this->cause->getCauseMessage($causes); - } - if (is_array($this->cause)) { - foreach ($this->cause as $cause) { - if ($cause instanceof PEAR_Exception) { - $cause->getCauseMessage($causes); - } 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>' . $v['file'] . ':' . $v['line'] . '</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 diff --git a/3rdparty/PEAR/Frontend/CLI.php b/3rdparty/PEAR/Frontend/CLI.php deleted file mode 100644 index 832ddf09b3fb9939db70c752dba0c72da804ba68..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Frontend/CLI.php +++ /dev/null @@ -1,509 +0,0 @@ -<?php -/* - +----------------------------------------------------------------------+ - | 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: Stig S�ther Bakken <ssb@php.net> | - +----------------------------------------------------------------------+ - - $Id: CLI.php,v 1.41 2004/02/17 05:49:16 ssb Exp $ -*/ - -require_once "PEAR.php"; - -class PEAR_Frontend_CLI extends PEAR -{ - // {{{ properties - - /** - * What type of user interface this frontend is for. - * @var string - * @access public - */ - var $type = 'CLI'; - var $lp = ''; // line prefix - - var $params = array(); - var $term = array( - 'bold' => '', - 'normal' => '', - ); - - // }}} - - // {{{ constructor - - function PEAR_Frontend_CLI() - { - parent::PEAR(); - $term = getenv('TERM'); //(cox) $_ENV is empty for me in 4.1.1 - if (function_exists('posix_isatty') && !posix_isatty(1)) { - // output is being redirected to a file or through a pipe - } elseif ($term) { - // XXX can use ncurses extension here, if available - if (preg_match('/^(xterm|vt220|linux)/', $term)) { - $this->term['bold'] = sprintf("%c%c%c%c", 27, 91, 49, 109); - $this->term['normal']=sprintf("%c%c%c", 27, 91, 109); - } elseif (preg_match('/^vt100/', $term)) { - $this->term['bold'] = sprintf("%c%c%c%c%c%c", 27, 91, 49, 109, 0, 0); - $this->term['normal']=sprintf("%c%c%c%c%c", 27, 91, 109, 0, 0); - } - } elseif (OS_WINDOWS) { - // XXX add ANSI codes here - } - } - - // }}} - - // {{{ displayLine(text) - - function displayLine($text) - { - trigger_error("PEAR_Frontend_CLI::displayLine deprecated", E_USER_ERROR); - } - - function _displayLine($text) - { - print "$this->lp$text\n"; - } - - // }}} - // {{{ display(text) - - function display($text) - { - trigger_error("PEAR_Frontend_CLI::display deprecated", E_USER_ERROR); - } - - function _display($text) - { - print $text; - } - - // }}} - // {{{ displayError(eobj) - - /** - * @param object PEAR_Error object - */ - function displayError($eobj) - { - return $this->_displayLine($eobj->getMessage()); - } - - // }}} - // {{{ displayFatalError(eobj) - - /** - * @param object PEAR_Error object - */ - function displayFatalError($eobj) - { - $this->displayError($eobj); - exit(1); - } - - // }}} - // {{{ displayHeading(title) - - function displayHeading($title) - { - trigger_error("PEAR_Frontend_CLI::displayHeading deprecated", E_USER_ERROR); - } - - function _displayHeading($title) - { - print $this->lp.$this->bold($title)."\n"; - print $this->lp.str_repeat("=", strlen($title))."\n"; - } - - // }}} - // {{{ userDialog(prompt, [type], [default]) - - function userDialog($command, $prompts, $types = array(), $defaults = array()) - { - $result = array(); - if (is_array($prompts)) { - $fp = fopen("php://stdin", "r"); - foreach ($prompts as $key => $prompt) { - $type = $types[$key]; - $default = @$defaults[$key]; - if ($type == 'password') { - system('stty -echo'); - } - print "$this->lp$prompt "; - if ($default) { - print "[$default] "; - } - print ": "; - $line = fgets($fp, 2048); - if ($type == 'password') { - system('stty echo'); - print "\n"; - } - if ($default && trim($line) == "") { - $result[$key] = $default; - } else { - $result[$key] = $line; - } - } - fclose($fp); - } - return $result; - } - - // }}} - // {{{ userConfirm(prompt, [default]) - - function userConfirm($prompt, $default = 'yes') - { - trigger_error("PEAR_Frontend_CLI::userConfirm not yet converted", E_USER_ERROR); - static $positives = array('y', 'yes', 'on', '1'); - static $negatives = array('n', 'no', 'off', '0'); - print "$this->lp$prompt [$default] : "; - $fp = fopen("php://stdin", "r"); - $line = fgets($fp, 2048); - fclose($fp); - $answer = strtolower(trim($line)); - if (empty($answer)) { - $answer = $default; - } - if (in_array($answer, $positives)) { - return true; - } - if (in_array($answer, $negatives)) { - return false; - } - if (in_array($default, $positives)) { - return true; - } - return false; - } - - // }}} - // {{{ startTable([params]) - - function startTable($params = array()) - { - trigger_error("PEAR_Frontend_CLI::startTable deprecated", E_USER_ERROR); - } - - function _startTable($params = array()) - { - $params['table_data'] = array(); - $params['widest'] = array(); // indexed by column - $params['highest'] = array(); // indexed by row - $params['ncols'] = 0; - $this->params = $params; - } - - // }}} - // {{{ tableRow(columns, [rowparams], [colparams]) - - function tableRow($columns, $rowparams = array(), $colparams = array()) - { - trigger_error("PEAR_Frontend_CLI::tableRow deprecated", E_USER_ERROR); - } - - function _tableRow($columns, $rowparams = array(), $colparams = array()) - { - $highest = 1; - for ($i = 0; $i < sizeof($columns); $i++) { - $col = &$columns[$i]; - if (isset($colparams[$i]) && !empty($colparams[$i]['wrap'])) { - $col = wordwrap($col, $colparams[$i]['wrap'], "\n", 0); - } - if (strpos($col, "\n") !== false) { - $multiline = explode("\n", $col); - $w = 0; - foreach ($multiline as $n => $line) { - if (strlen($line) > $w) { - $w = strlen($line); - } - } - $lines = sizeof($multiline); - } else { - $w = strlen($col); - } - if ($w > @$this->params['widest'][$i]) { - $this->params['widest'][$i] = $w; - } - $tmp = count_chars($columns[$i], 1); - // handle unix, mac and windows formats - $lines = (isset($tmp[10]) ? $tmp[10] : @$tmp[13]) + 1; - if ($lines > $highest) { - $highest = $lines; - } - } - if (sizeof($columns) > $this->params['ncols']) { - $this->params['ncols'] = sizeof($columns); - } - $new_row = array( - 'data' => $columns, - 'height' => $highest, - 'rowparams' => $rowparams, - 'colparams' => $colparams, - ); - $this->params['table_data'][] = $new_row; - } - - // }}} - // {{{ endTable() - - function endTable() - { - trigger_error("PEAR_Frontend_CLI::endTable deprecated", E_USER_ERROR); - } - - function _endTable() - { - extract($this->params); - if (!empty($caption)) { - $this->_displayHeading($caption); - } - if (count($table_data) == 0) { - return; - } - if (!isset($width)) { - $width = $widest; - } else { - for ($i = 0; $i < $ncols; $i++) { - if (!isset($width[$i])) { - $width[$i] = $widest[$i]; - } - } - } - $border = false; - if (empty($border)) { - $cellstart = ''; - $cellend = ' '; - $rowend = ''; - $padrowend = false; - $borderline = ''; - } else { - $cellstart = '| '; - $cellend = ' '; - $rowend = '|'; - $padrowend = true; - $borderline = '+'; - foreach ($width as $w) { - $borderline .= str_repeat('-', $w + strlen($cellstart) + strlen($cellend) - 1); - $borderline .= '+'; - } - } - if ($borderline) { - $this->_displayLine($borderline); - } - for ($i = 0; $i < sizeof($table_data); $i++) { - extract($table_data[$i]); - if (!is_array($rowparams)) { - $rowparams = array(); - } - if (!is_array($colparams)) { - $colparams = array(); - } - $rowlines = array(); - if ($height > 1) { - for ($c = 0; $c < sizeof($data); $c++) { - $rowlines[$c] = preg_split('/(\r?\n|\r)/', $data[$c]); - if (sizeof($rowlines[$c]) < $height) { - $rowlines[$c] = array_pad($rowlines[$c], $height, ''); - } - } - } else { - for ($c = 0; $c < sizeof($data); $c++) { - $rowlines[$c] = array($data[$c]); - } - } - for ($r = 0; $r < $height; $r++) { - $rowtext = ''; - for ($c = 0; $c < sizeof($data); $c++) { - if (isset($colparams[$c])) { - $attribs = array_merge($rowparams, $colparams); - } else { - $attribs = $rowparams; - } - $w = isset($width[$c]) ? $width[$c] : 0; - //$cell = $data[$c]; - $cell = $rowlines[$c][$r]; - $l = strlen($cell); - if ($l > $w) { - $cell = substr($cell, 0, $w); - } - if (isset($attribs['bold'])) { - $cell = $this->bold($cell); - } - if ($l < $w) { - // not using str_pad here because we may - // add bold escape characters to $cell - $cell .= str_repeat(' ', $w - $l); - } - - $rowtext .= $cellstart . $cell . $cellend; - } - if (!$border) { - $rowtext = rtrim($rowtext); - } - $rowtext .= $rowend; - $this->_displayLine($rowtext); - } - } - if ($borderline) { - $this->_displayLine($borderline); - } - } - - // }}} - // {{{ outputData() - - function outputData($data, $command = '_default') - { - switch ($command) { - case 'install': - case 'upgrade': - case 'upgrade-all': - if (isset($data['release_warnings'])) { - $this->_displayLine(''); - $this->_startTable(array( - 'border' => false, - 'caption' => 'Release Warnings' - )); - $this->_tableRow(array($data['release_warnings']), null, array(1 => array('wrap' => 55))); - $this->_endTable(); - $this->_displayLine(''); - } - $this->_displayLine($data['data']); - break; - case 'search': - $this->_startTable($data); - if (isset($data['headline']) && is_array($data['headline'])) { - $this->_tableRow($data['headline'], array('bold' => true), array(1 => array('wrap' => 55))); - } - - foreach($data['data'] as $category) { - foreach($category as $pkg) { - $this->_tableRow($pkg, null, array(1 => array('wrap' => 55))); - } - }; - $this->_endTable(); - break; - case 'list-all': - $this->_startTable($data); - if (isset($data['headline']) && is_array($data['headline'])) { - $this->_tableRow($data['headline'], array('bold' => true), array(1 => array('wrap' => 55))); - } - - foreach($data['data'] as $category) { - foreach($category as $pkg) { - unset($pkg[3]); - unset($pkg[4]); - $this->_tableRow($pkg, null, array(1 => array('wrap' => 55))); - } - }; - $this->_endTable(); - break; - case 'config-show': - $data['border'] = false; - $opts = array(0 => array('wrap' => 30), - 1 => array('wrap' => 20), - 2 => array('wrap' => 35)); - $this->_startTable($data); - if (isset($data['headline']) && is_array($data['headline'])) { - $this->_tableRow($data['headline'], - array('bold' => true), - $opts); - } - foreach($data['data'] as $group) { - foreach($group as $value) { - if ($value[2] == '') { - $value[2] = "<not set>"; - } - $this->_tableRow($value, null, $opts); - } - } - $this->_endTable(); - break; - case 'remote-info': - $data = array( - 'caption' => 'Package details:', - 'border' => false, - 'data' => array( - array("Latest", $data['stable']), - array("Installed", $data['installed']), - array("Package", $data['name']), - array("License", $data['license']), - array("Category", $data['category']), - array("Summary", $data['summary']), - array("Description", $data['description']), - ), - ); - default: { - if (is_array($data)) { - $this->_startTable($data); - $count = count($data['data'][0]); - if ($count == 2) { - $opts = array(0 => array('wrap' => 25), - 1 => array('wrap' => 48) - ); - } elseif ($count == 3) { - $opts = array(0 => array('wrap' => 30), - 1 => array('wrap' => 20), - 2 => array('wrap' => 35) - ); - } else { - $opts = null; - } - if (isset($data['headline']) && is_array($data['headline'])) { - $this->_tableRow($data['headline'], - array('bold' => true), - $opts); - } - foreach($data['data'] as $row) { - $this->_tableRow($row, null, $opts); - } - $this->_endTable(); - } else { - $this->_displayLine($data); - } - } - } - } - - // }}} - // {{{ log(text) - - - function log($text, $append_crlf = true) - { - if ($append_crlf) { - return $this->_displayLine($text); - } - return $this->_display($text); - } - - - // }}} - // {{{ bold($text) - - function bold($text) - { - if (empty($this->term['bold'])) { - return strtoupper($text); - } - return $this->term['bold'] . $text . $this->term['normal']; - } - - // }}} -} - -?> diff --git a/3rdparty/PEAR/Installer.php b/3rdparty/PEAR/Installer.php deleted file mode 100644 index 31e2cff81ee6be9e367e6e0f524a7346ce4ac58c..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Installer.php +++ /dev/null @@ -1,1068 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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. | -// +----------------------------------------------------------------------+ -// | Authors: Stig Bakken <ssb@php.net> | -// | Tomas V.V.Cox <cox@idecnet.com> | -// | Martin Jansen <mj@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Installer.php,v 1.150.2.2 2005/02/17 17:47:55 cellog Exp $ - -require_once 'PEAR/Downloader.php'; - -/** - * Administration class used to install PEAR packages and maintain the - * installed package database. - * - * TODO: - * - Check dependencies break on package uninstall (when no force given) - * - add a guessInstallDest() method with the code from _installFile() and - * use that method in Registry::_rebuildFileMap() & Command_Registry::doList(), - * others.. - * - * @since PHP 4.0.2 - * @author Stig Bakken <ssb@php.net> - * @author Martin Jansen <mj@php.net> - * @author Greg Beaver <cellog@php.net> - */ -class PEAR_Installer extends PEAR_Downloader -{ - // {{{ properties - - /** name of the package directory, for example Foo-1.0 - * @var string - */ - var $pkgdir; - - /** directory where PHP code files go - * @var string - */ - var $phpdir; - - /** directory where PHP extension files go - * @var string - */ - var $extdir; - - /** directory where documentation goes - * @var string - */ - var $docdir; - - /** installation root directory (ala PHP's INSTALL_ROOT or - * automake's DESTDIR - * @var string - */ - var $installroot = ''; - - /** debug level - * @var int - */ - var $debug = 1; - - /** temporary directory - * @var string - */ - var $tmpdir; - - /** PEAR_Registry object used by the installer - * @var object - */ - var $registry; - - /** List of file transactions queued for an install/upgrade/uninstall. - * - * Format: - * array( - * 0 => array("rename => array("from-file", "to-file")), - * 1 => array("delete" => array("file-to-delete")), - * ... - * ) - * - * @var array - */ - var $file_operations = array(); - - // }}} - - // {{{ constructor - - /** - * PEAR_Installer constructor. - * - * @param object $ui user interface object (instance of PEAR_Frontend_*) - * - * @access public - */ - function PEAR_Installer(&$ui) - { - parent::PEAR_Common(); - $this->setFrontendObject($ui); - $this->debug = $this->config->get('verbose'); - //$this->registry = &new PEAR_Registry($this->config->get('php_dir')); - } - - // }}} - - // {{{ _deletePackageFiles() - - /** - * Delete a package's installed files, does not remove empty directories. - * - * @param string $package package name - * - * @return bool TRUE on success, or a PEAR error on failure - * - * @access private - */ - function _deletePackageFiles($package) - { - if (!strlen($package)) { - return $this->raiseError("No package to uninstall given"); - } - $filelist = $this->registry->packageInfo($package, 'filelist'); - if ($filelist == null) { - return $this->raiseError("$package not installed"); - } - foreach ($filelist as $file => $props) { - if (empty($props['installed_as'])) { - continue; - } - $path = $this->_prependPath($props['installed_as'], $this->installroot); - $this->addFileOperation('delete', array($path)); - } - return true; - } - - // }}} - // {{{ _installFile() - - /** - * @param string filename - * @param array attributes from <file> tag in package.xml - * @param string path to install the file in - * @param array options from command-line - * @access private - */ - function _installFile($file, $atts, $tmp_path, $options) - { - // {{{ return if this file is meant for another platform - static $os; - if (isset($atts['platform'])) { - if (empty($os)) { - include_once "OS/Guess.php"; - $os = new OS_Guess(); - } - if (strlen($atts['platform']) && $atts['platform']{0} == '!') { - $negate = true; - $platform = substr($atts['platform'], 1); - } else { - $negate = false; - $platform = $atts['platform']; - } - if ((bool) $os->matchSignature($platform) === $negate) { - $this->log(3, "skipped $file (meant for $atts[platform], we are ".$os->getSignature().")"); - return PEAR_INSTALLER_SKIPPED; - } - } - // }}} - - // {{{ assemble the destination paths - switch ($atts['role']) { - case 'doc': - case 'data': - case 'test': - $dest_dir = $this->config->get($atts['role'] . '_dir') . - DIRECTORY_SEPARATOR . $this->pkginfo['package']; - unset($atts['baseinstalldir']); - break; - case 'ext': - case 'php': - $dest_dir = $this->config->get($atts['role'] . '_dir'); - break; - case 'script': - $dest_dir = $this->config->get('bin_dir'); - break; - case 'src': - case 'extsrc': - $this->source_files++; - return; - default: - return $this->raiseError("Invalid role `$atts[role]' for file $file"); - } - $save_destdir = $dest_dir; - if (!empty($atts['baseinstalldir'])) { - $dest_dir .= DIRECTORY_SEPARATOR . $atts['baseinstalldir']; - } - if (dirname($file) != '.' && empty($atts['install-as'])) { - $dest_dir .= DIRECTORY_SEPARATOR . dirname($file); - } - if (empty($atts['install-as'])) { - $dest_file = $dest_dir . DIRECTORY_SEPARATOR . basename($file); - } else { - $dest_file = $dest_dir . DIRECTORY_SEPARATOR . $atts['install-as']; - } - $orig_file = $tmp_path . DIRECTORY_SEPARATOR . $file; - - // Clean up the DIRECTORY_SEPARATOR mess - $ds2 = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR; - list($dest_file, $orig_file) = preg_replace(array('!\\\\+!', '!/!', "!$ds2+!"), - DIRECTORY_SEPARATOR, - array($dest_file, $orig_file)); - $installed_as = $dest_file; - $final_dest_file = $this->_prependPath($dest_file, $this->installroot); - $dest_dir = dirname($final_dest_file); - $dest_file = $dest_dir . DIRECTORY_SEPARATOR . '.tmp' . basename($final_dest_file); - // }}} - - if (!@is_dir($dest_dir)) { - if (!$this->mkDirHier($dest_dir)) { - return $this->raiseError("failed to mkdir $dest_dir", - PEAR_INSTALLER_FAILED); - } - $this->log(3, "+ mkdir $dest_dir"); - } - if (empty($atts['replacements'])) { - if (!file_exists($orig_file)) { - return $this->raiseError("file does not exist", - PEAR_INSTALLER_FAILED); - } - if (!@copy($orig_file, $dest_file)) { - return $this->raiseError("failed to write $dest_file", - PEAR_INSTALLER_FAILED); - } - $this->log(3, "+ cp $orig_file $dest_file"); - if (isset($atts['md5sum'])) { - $md5sum = md5_file($dest_file); - } - } else { - // {{{ file with replacements - if (!file_exists($orig_file)) { - return $this->raiseError("file does not exist", - PEAR_INSTALLER_FAILED); - } - $fp = fopen($orig_file, "r"); - $contents = fread($fp, filesize($orig_file)); - fclose($fp); - if (isset($atts['md5sum'])) { - $md5sum = md5($contents); - } - $subst_from = $subst_to = array(); - foreach ($atts['replacements'] as $a) { - $to = ''; - if ($a['type'] == 'php-const') { - if (preg_match('/^[a-z0-9_]+$/i', $a['to'])) { - eval("\$to = $a[to];"); - } else { - $this->log(0, "invalid php-const replacement: $a[to]"); - continue; - } - } elseif ($a['type'] == 'pear-config') { - $to = $this->config->get($a['to']); - if (is_null($to)) { - $this->log(0, "invalid pear-config replacement: $a[to]"); - continue; - } - } elseif ($a['type'] == 'package-info') { - if (isset($this->pkginfo[$a['to']]) && is_string($this->pkginfo[$a['to']])) { - $to = $this->pkginfo[$a['to']]; - } else { - $this->log(0, "invalid package-info replacement: $a[to]"); - continue; - } - } - if (!is_null($to)) { - $subst_from[] = $a['from']; - $subst_to[] = $to; - } - } - $this->log(3, "doing ".sizeof($subst_from)." substitution(s) for $final_dest_file"); - if (sizeof($subst_from)) { - $contents = str_replace($subst_from, $subst_to, $contents); - } - $wp = @fopen($dest_file, "wb"); - if (!is_resource($wp)) { - return $this->raiseError("failed to create $dest_file: $php_errormsg", - PEAR_INSTALLER_FAILED); - } - if (!fwrite($wp, $contents)) { - return $this->raiseError("failed writing to $dest_file: $php_errormsg", - PEAR_INSTALLER_FAILED); - } - fclose($wp); - // }}} - } - // {{{ check the md5 - if (isset($md5sum)) { - if (strtolower($md5sum) == strtolower($atts['md5sum'])) { - $this->log(2, "md5sum ok: $final_dest_file"); - } else { - if (empty($options['force'])) { - // delete the file - @unlink($dest_file); - return $this->raiseError("bad md5sum for file $final_dest_file", - PEAR_INSTALLER_FAILED); - } else { - $this->log(0, "warning : bad md5sum for file $final_dest_file"); - } - } - } - // }}} - // {{{ set file permissions - if (!OS_WINDOWS) { - if ($atts['role'] == 'script') { - $mode = 0777 & ~(int)octdec($this->config->get('umask')); - $this->log(3, "+ chmod +x $dest_file"); - } else { - $mode = 0666 & ~(int)octdec($this->config->get('umask')); - } - $this->addFileOperation("chmod", array($mode, $dest_file)); - if (!@chmod($dest_file, $mode)) { - $this->log(0, "failed to change mode of $dest_file"); - } - } - // }}} - $this->addFileOperation("rename", array($dest_file, $final_dest_file)); - // Store the full path where the file was installed for easy unistall - $this->addFileOperation("installed_as", array($file, $installed_as, - $save_destdir, dirname(substr($dest_file, strlen($save_destdir))))); - - //$this->log(2, "installed: $dest_file"); - return PEAR_INSTALLER_OK; - } - - // }}} - // {{{ addFileOperation() - - /** - * Add a file operation to the current file transaction. - * - * @see startFileTransaction() - * @var string $type This can be one of: - * - rename: rename a file ($data has 2 values) - * - chmod: change permissions on a file ($data has 2 values) - * - delete: delete a file ($data has 1 value) - * - rmdir: delete a directory if empty ($data has 1 value) - * - installed_as: mark a file as installed ($data has 4 values). - * @var array $data For all file operations, this array must contain the - * full path to the file or directory that is being operated on. For - * the rename command, the first parameter must be the file to rename, - * the second its new name. - * - * The installed_as operation contains 4 elements in this order: - * 1. Filename as listed in the filelist element from package.xml - * 2. Full path to the installed file - * 3. Full path from the php_dir configuration variable used in this - * installation - * 4. Relative path from the php_dir that this file is installed in - */ - function addFileOperation($type, $data) - { - if (!is_array($data)) { - return $this->raiseError('Internal Error: $data in addFileOperation' - . ' must be an array, was ' . gettype($data)); - } - if ($type == 'chmod') { - $octmode = decoct($data[0]); - $this->log(3, "adding to transaction: $type $octmode $data[1]"); - } else { - $this->log(3, "adding to transaction: $type " . implode(" ", $data)); - } - $this->file_operations[] = array($type, $data); - } - - // }}} - // {{{ startFileTransaction() - - function startFileTransaction($rollback_in_case = false) - { - if (count($this->file_operations) && $rollback_in_case) { - $this->rollbackFileTransaction(); - } - $this->file_operations = array(); - } - - // }}} - // {{{ commitFileTransaction() - - function commitFileTransaction() - { - $n = count($this->file_operations); - $this->log(2, "about to commit $n file operations"); - // {{{ first, check permissions and such manually - $errors = array(); - foreach ($this->file_operations as $tr) { - list($type, $data) = $tr; - switch ($type) { - case 'rename': - if (!file_exists($data[0])) { - $errors[] = "cannot rename file $data[0], doesn't exist"; - } - // check that dest dir. is writable - if (!is_writable(dirname($data[1]))) { - $errors[] = "permission denied ($type): $data[1]"; - } - break; - case 'chmod': - // check that file is writable - if (!is_writable($data[1])) { - $errors[] = "permission denied ($type): $data[1] " . decoct($data[0]); - } - break; - case 'delete': - if (!file_exists($data[0])) { - $this->log(2, "warning: file $data[0] doesn't exist, can't be deleted"); - } - // check that directory is writable - if (file_exists($data[0]) && !is_writable(dirname($data[0]))) { - $errors[] = "permission denied ($type): $data[0]"; - } - break; - } - - } - // }}} - $m = sizeof($errors); - if ($m > 0) { - foreach ($errors as $error) { - $this->log(1, $error); - } - return false; - } - // {{{ really commit the transaction - foreach ($this->file_operations as $tr) { - list($type, $data) = $tr; - switch ($type) { - case 'rename': - @unlink($data[1]); - @rename($data[0], $data[1]); - $this->log(3, "+ mv $data[0] $data[1]"); - break; - case 'chmod': - @chmod($data[1], $data[0]); - $octmode = decoct($data[0]); - $this->log(3, "+ chmod $octmode $data[1]"); - break; - case 'delete': - @unlink($data[0]); - $this->log(3, "+ rm $data[0]"); - break; - case 'rmdir': - @rmdir($data[0]); - $this->log(3, "+ rmdir $data[0]"); - break; - case 'installed_as': - $this->pkginfo['filelist'][$data[0]]['installed_as'] = $data[1]; - if (!isset($this->pkginfo['filelist']['dirtree'][dirname($data[1])])) { - $this->pkginfo['filelist']['dirtree'][dirname($data[1])] = true; - while(!empty($data[3]) && $data[3] != '/' && $data[3] != '\\' - && $data[3] != '.') { - $this->pkginfo['filelist']['dirtree'] - [$this->_prependPath($data[3], $data[2])] = true; - $data[3] = dirname($data[3]); - } - } - break; - } - } - // }}} - $this->log(2, "successfully committed $n file operations"); - $this->file_operations = array(); - return true; - } - - // }}} - // {{{ rollbackFileTransaction() - - function rollbackFileTransaction() - { - $n = count($this->file_operations); - $this->log(2, "rolling back $n file operations"); - foreach ($this->file_operations as $tr) { - list($type, $data) = $tr; - switch ($type) { - case 'rename': - @unlink($data[0]); - $this->log(3, "+ rm $data[0]"); - break; - case 'mkdir': - @rmdir($data[0]); - $this->log(3, "+ rmdir $data[0]"); - break; - case 'chmod': - break; - case 'delete': - break; - case 'installed_as': - if (isset($this->pkginfo['filelist'])) { - unset($this->pkginfo['filelist'][$data[0]]['installed_as']); - } - if (isset($this->pkginfo['filelist']['dirtree'][dirname($data[1])])) { - unset($this->pkginfo['filelist']['dirtree'][dirname($data[1])]); - while(!empty($data[3]) && $data[3] != '/' && $data[3] != '\\' - && $data[3] != '.') { - unset($this->pkginfo['filelist']['dirtree'] - [$this->_prependPath($data[3], $data[2])]); - $data[3] = dirname($data[3]); - } - } - if (isset($this->pkginfo['filelist']['dirtree']) - && !count($this->pkginfo['filelist']['dirtree'])) { - unset($this->pkginfo['filelist']['dirtree']); - } - break; - } - } - $this->file_operations = array(); - } - - // }}} - // {{{ mkDirHier($dir) - - function mkDirHier($dir) - { - $this->addFileOperation('mkdir', array($dir)); - return parent::mkDirHier($dir); - } - - // }}} - // {{{ download() - - /** - * Download any files and their dependencies, if necessary - * - * @param array a mixed list of package names, local files, or package.xml - * @param PEAR_Config - * @param array options from the command line - * @param array this is the array that will be populated with packages to - * install. Format of each entry: - * - * <code> - * array('pkg' => 'package_name', 'file' => '/path/to/local/file', - * 'info' => array() // parsed package.xml - * ); - * </code> - * @param array this will be populated with any error messages - * @param false private recursion variable - * @param false private recursion variable - * @param false private recursion variable - * @deprecated in favor of PEAR_Downloader - */ - function download($packages, $options, &$config, &$installpackages, - &$errors, $installed = false, $willinstall = false, $state = false) - { - // trickiness: initialize here - parent::PEAR_Downloader($this->ui, $options, $config); - $ret = parent::download($packages); - $errors = $this->getErrorMsgs(); - $installpackages = $this->getDownloadedPackages(); - trigger_error("PEAR Warning: PEAR_Installer::download() is deprecated " . - "in favor of PEAR_Downloader class", E_USER_WARNING); - return $ret; - } - - // }}} - // {{{ install() - - /** - * Installs the files within the package file specified. - * - * @param string $pkgfile path to the package file - * @param array $options - * recognized options: - * - installroot : optional prefix directory for installation - * - force : force installation - * - register-only : update registry but don't install files - * - upgrade : upgrade existing install - * - soft : fail silently - * - nodeps : ignore dependency conflicts/missing dependencies - * - alldeps : install all dependencies - * - onlyreqdeps : install only required dependencies - * - * @return array|PEAR_Error package info if successful - */ - - function install($pkgfile, $options = array()) - { - $php_dir = $this->config->get('php_dir'); - if (isset($options['installroot'])) { - if (substr($options['installroot'], -1) == DIRECTORY_SEPARATOR) { - $options['installroot'] = substr($options['installroot'], 0, -1); - } - $php_dir = $this->_prependPath($php_dir, $options['installroot']); - $this->installroot = $options['installroot']; - } else { - $this->installroot = ''; - } - $this->registry = &new PEAR_Registry($php_dir); - // ==> XXX should be removed later on - $flag_old_format = false; - - if (substr($pkgfile, -4) == '.xml') { - $descfile = $pkgfile; - } else { - // {{{ Decompress pack in tmp dir ------------------------------------- - - // To allow relative package file names - $pkgfile = realpath($pkgfile); - - if (PEAR::isError($tmpdir = System::mktemp('-d'))) { - return $tmpdir; - } - $this->log(3, '+ tmp dir created at ' . $tmpdir); - - $tar = new Archive_Tar($pkgfile); - if (!@$tar->extract($tmpdir)) { - return $this->raiseError("unable to unpack $pkgfile"); - } - - // {{{ Look for existing package file - $descfile = $tmpdir . DIRECTORY_SEPARATOR . 'package.xml'; - - if (!is_file($descfile)) { - // ----- Look for old package archive format - // In this format the package.xml file was inside the - // Package-n.n directory - $dp = opendir($tmpdir); - do { - $pkgdir = readdir($dp); - } while ($pkgdir{0} == '.'); - - $descfile = $tmpdir . DIRECTORY_SEPARATOR . $pkgdir . DIRECTORY_SEPARATOR . 'package.xml'; - $flag_old_format = true; - $this->log(0, "warning : you are using an archive with an old format"); - } - // }}} - // <== XXX This part should be removed later on - // }}} - } - - if (!is_file($descfile)) { - return $this->raiseError("no package.xml file after extracting the archive"); - } - - // Parse xml file ----------------------------------------------- - $pkginfo = $this->infoFromDescriptionFile($descfile); - if (PEAR::isError($pkginfo)) { - return $pkginfo; - } - $this->validatePackageInfo($pkginfo, $errors, $warnings); - // XXX We allow warnings, do we have to do it? - if (count($errors)) { - if (empty($options['force'])) { - return $this->raiseError("The following errors where found (use force option to install anyway):\n". - implode("\n", $errors)); - } else { - $this->log(0, "warning : the following errors were found:\n". - implode("\n", $errors)); - } - } - - $pkgname = $pkginfo['package']; - - // {{{ Check dependencies ------------------------------------------- - if (isset($pkginfo['release_deps']) && empty($options['nodeps'])) { - $dep_errors = ''; - $error = $this->checkDeps($pkginfo, $dep_errors); - if ($error == true) { - if (empty($options['soft'])) { - $this->log(0, substr($dep_errors, 1)); - } - return $this->raiseError("$pkgname: Dependencies failed"); - } else if (!empty($dep_errors)) { - // Print optional dependencies - if (empty($options['soft'])) { - $this->log(0, $dep_errors); - } - } - } - // }}} - - // {{{ checks to do when not in "force" mode - if (empty($options['force'])) { - $test = $this->registry->checkFileMap($pkginfo); - if (sizeof($test)) { - $tmp = $test; - foreach ($tmp as $file => $pkg) { - if ($pkg == $pkgname) { - unset($test[$file]); - } - } - if (sizeof($test)) { - $msg = "$pkgname: conflicting files found:\n"; - $longest = max(array_map("strlen", array_keys($test))); - $fmt = "%${longest}s (%s)\n"; - foreach ($test as $file => $pkg) { - $msg .= sprintf($fmt, $file, $pkg); - } - return $this->raiseError($msg); - } - } - } - // }}} - - $this->startFileTransaction(); - - if (empty($options['upgrade'])) { - // checks to do only when installing new packages - if (empty($options['force']) && $this->registry->packageExists($pkgname)) { - return $this->raiseError("$pkgname already installed"); - } - } else { - if ($this->registry->packageExists($pkgname)) { - $v1 = $this->registry->packageInfo($pkgname, 'version'); - $v2 = $pkginfo['version']; - $cmp = version_compare("$v1", "$v2", 'gt'); - if (empty($options['force']) && !version_compare("$v2", "$v1", 'gt')) { - return $this->raiseError("upgrade to a newer version ($v2 is not newer than $v1)"); - } - if (empty($options['register-only'])) { - // when upgrading, remove old release's files first: - if (PEAR::isError($err = $this->_deletePackageFiles($pkgname))) { - return $this->raiseError($err); - } - } - } - } - - // {{{ Copy files to dest dir --------------------------------------- - - // info from the package it self we want to access from _installFile - $this->pkginfo = &$pkginfo; - // used to determine whether we should build any C code - $this->source_files = 0; - - if (empty($options['register-only'])) { - if (!is_dir($php_dir)) { - return $this->raiseError("no script destination directory\n", - null, PEAR_ERROR_DIE); - } - - $tmp_path = dirname($descfile); - if (substr($pkgfile, -4) != '.xml') { - $tmp_path .= DIRECTORY_SEPARATOR . $pkgname . '-' . $pkginfo['version']; - } - - // ==> XXX This part should be removed later on - if ($flag_old_format) { - $tmp_path = dirname($descfile); - } - // <== XXX This part should be removed later on - - // {{{ install files - foreach ($pkginfo['filelist'] as $file => $atts) { - $this->expectError(PEAR_INSTALLER_FAILED); - $res = $this->_installFile($file, $atts, $tmp_path, $options); - $this->popExpect(); - if (PEAR::isError($res)) { - if (empty($options['ignore-errors'])) { - $this->rollbackFileTransaction(); - if ($res->getMessage() == "file does not exist") { - $this->raiseError("file $file in package.xml does not exist"); - } - return $this->raiseError($res); - } else { - $this->log(0, "Warning: " . $res->getMessage()); - } - } - if ($res != PEAR_INSTALLER_OK) { - // Do not register files that were not installed - unset($pkginfo['filelist'][$file]); - } - } - // }}} - - // {{{ compile and install source files - if ($this->source_files > 0 && empty($options['nobuild'])) { - $this->log(1, "$this->source_files source files, building"); - $bob = &new PEAR_Builder($this->ui); - $bob->debug = $this->debug; - $built = $bob->build($descfile, array(&$this, '_buildCallback')); - if (PEAR::isError($built)) { - $this->rollbackFileTransaction(); - return $built; - } - $this->log(1, "\nBuild process completed successfully"); - foreach ($built as $ext) { - $bn = basename($ext['file']); - list($_ext_name, $_ext_suff) = explode('.', $bn); - if ($_ext_suff == '.so' || $_ext_suff == '.dll') { - if (extension_loaded($_ext_name)) { - $this->raiseError("Extension '$_ext_name' already loaded. " . - 'Please unload it in your php.ini file ' . - 'prior to install or upgrade'); - } - $role = 'ext'; - } else { - $role = 'src'; - } - $dest = $ext['dest']; - $this->log(1, "Installing '$ext[file]'"); - $copyto = $this->_prependPath($dest, $this->installroot); - $copydir = dirname($copyto); - if (!@is_dir($copydir)) { - if (!$this->mkDirHier($copydir)) { - return $this->raiseError("failed to mkdir $copydir", - PEAR_INSTALLER_FAILED); - } - $this->log(3, "+ mkdir $copydir"); - } - if (!@copy($ext['file'], $copyto)) { - return $this->raiseError("failed to write $copyto", PEAR_INSTALLER_FAILED); - } - $this->log(3, "+ cp $ext[file] $copyto"); - if (!OS_WINDOWS) { - $mode = 0666 & ~(int)octdec($this->config->get('umask')); - $this->addFileOperation('chmod', array($mode, $copyto)); - if (!@chmod($copyto, $mode)) { - $this->log(0, "failed to change mode of $copyto"); - } - } - $this->addFileOperation('rename', array($ext['file'], $copyto)); - - $pkginfo['filelist'][$bn] = array( - 'role' => $role, - 'installed_as' => $dest, - 'php_api' => $ext['php_api'], - 'zend_mod_api' => $ext['zend_mod_api'], - 'zend_ext_api' => $ext['zend_ext_api'], - ); - } - } - // }}} - } - - if (!$this->commitFileTransaction()) { - $this->rollbackFileTransaction(); - return $this->raiseError("commit failed", PEAR_INSTALLER_FAILED); - } - // }}} - - $ret = false; - // {{{ Register that the package is installed ----------------------- - if (empty($options['upgrade'])) { - // if 'force' is used, replace the info in registry - if (!empty($options['force']) && $this->registry->packageExists($pkgname)) { - $this->registry->deletePackage($pkgname); - } - $ret = $this->registry->addPackage($pkgname, $pkginfo); - } else { - // new: upgrade installs a package if it isn't installed - if (!$this->registry->packageExists($pkgname)) { - $ret = $this->registry->addPackage($pkgname, $pkginfo); - } else { - $ret = $this->registry->updatePackage($pkgname, $pkginfo, false); - } - } - if (!$ret) { - return $this->raiseError("Adding package $pkgname to registry failed"); - } - // }}} - return $pkginfo; - } - - // }}} - // {{{ uninstall() - - /** - * Uninstall a package - * - * This method removes all files installed by the application, and then - * removes any empty directories. - * @param string package name - * @param array Command-line options. Possibilities include: - * - * - installroot: base installation dir, if not the default - * - nodeps: do not process dependencies of other packages to ensure - * uninstallation does not break things - */ - function uninstall($package, $options = array()) - { - $php_dir = $this->config->get('php_dir'); - if (isset($options['installroot'])) { - if (substr($options['installroot'], -1) == DIRECTORY_SEPARATOR) { - $options['installroot'] = substr($options['installroot'], 0, -1); - } - $this->installroot = $options['installroot']; - $php_dir = $this->_prependPath($php_dir, $this->installroot); - } else { - $this->installroot = ''; - } - $this->registry = &new PEAR_Registry($php_dir); - $filelist = $this->registry->packageInfo($package, 'filelist'); - if ($filelist == null) { - return $this->raiseError("$package not installed"); - } - if (empty($options['nodeps'])) { - $depchecker = &new PEAR_Dependency($this->registry); - $error = $depchecker->checkPackageUninstall($errors, $warning, $package); - if ($error) { - return $this->raiseError($errors . 'uninstall failed'); - } - if ($warning) { - $this->log(0, $warning); - } - } - // {{{ Delete the files - $this->startFileTransaction(); - if (PEAR::isError($err = $this->_deletePackageFiles($package))) { - $this->rollbackFileTransaction(); - return $this->raiseError($err); - } - if (!$this->commitFileTransaction()) { - $this->rollbackFileTransaction(); - return $this->raiseError("uninstall failed"); - } else { - $this->startFileTransaction(); - if (!isset($filelist['dirtree']) || !count($filelist['dirtree'])) { - return $this->registry->deletePackage($package); - } - // attempt to delete empty directories - uksort($filelist['dirtree'], array($this, '_sortDirs')); - foreach($filelist['dirtree'] as $dir => $notused) { - $this->addFileOperation('rmdir', array($dir)); - } - if (!$this->commitFileTransaction()) { - $this->rollbackFileTransaction(); - } - } - // }}} - - // Register that the package is no longer installed - return $this->registry->deletePackage($package); - } - - // }}} - // {{{ _sortDirs() - function _sortDirs($a, $b) - { - if (strnatcmp($a, $b) == -1) return 1; - if (strnatcmp($a, $b) == 1) return -1; - return 0; - } - - // }}} - // {{{ checkDeps() - - /** - * Check if the package meets all dependencies - * - * @param array Package information (passed by reference) - * @param string Error message (passed by reference) - * @return boolean False when no error occured, otherwise true - */ - function checkDeps(&$pkginfo, &$errors) - { - if (empty($this->registry)) { - $this->registry = &new PEAR_Registry($this->config->get('php_dir')); - } - $depchecker = &new PEAR_Dependency($this->registry); - $error = $errors = ''; - $failed_deps = $optional_deps = array(); - if (is_array($pkginfo['release_deps'])) { - foreach($pkginfo['release_deps'] as $dep) { - $code = $depchecker->callCheckMethod($error, $dep); - if ($code) { - if (isset($dep['optional']) && $dep['optional'] == 'yes') { - $optional_deps[] = array($dep, $code, $error); - } else { - $failed_deps[] = array($dep, $code, $error); - } - } - } - // {{{ failed dependencies - $n = count($failed_deps); - if ($n > 0) { - for ($i = 0; $i < $n; $i++) { - if (isset($failed_deps[$i]['type'])) { - $type = $failed_deps[$i]['type']; - } else { - $type = 'pkg'; - } - switch ($failed_deps[$i][1]) { - case PEAR_DEPENDENCY_MISSING: - if ($type == 'pkg') { - // install - } - $errors .= "\n" . $failed_deps[$i][2]; - break; - case PEAR_DEPENDENCY_UPGRADE_MINOR: - if ($type == 'pkg') { - // upgrade - } - $errors .= "\n" . $failed_deps[$i][2]; - break; - default: - $errors .= "\n" . $failed_deps[$i][2]; - break; - } - } - return true; - } - // }}} - - // {{{ optional dependencies - $count_optional = count($optional_deps); - if ($count_optional > 0) { - $errors = "Optional dependencies:"; - - for ($i = 0; $i < $count_optional; $i++) { - if (isset($optional_deps[$i]['type'])) { - $type = $optional_deps[$i]['type']; - } else { - $type = 'pkg'; - } - switch ($optional_deps[$i][1]) { - case PEAR_DEPENDENCY_MISSING: - case PEAR_DEPENDENCY_UPGRADE_MINOR: - default: - $errors .= "\n" . $optional_deps[$i][2]; - break; - } - } - return false; - } - // }}} - } - return false; - } - - // }}} - // {{{ _buildCallback() - - function _buildCallback($what, $data) - { - if (($what == 'cmdoutput' && $this->debug > 1) || - ($what == 'output' && $this->debug > 0)) { - $this->ui->outputData(rtrim($data), 'build'); - } - } - - // }}} -} - -// {{{ md5_file() utility function -if (!function_exists("md5_file")) { - function md5_file($filename) { - $fp = fopen($filename, "r"); - if (!$fp) return null; - $contents = fread($fp, filesize($filename)); - fclose($fp); - return md5($contents); - } -} -// }}} - -?> diff --git a/3rdparty/PEAR/Packager.php b/3rdparty/PEAR/Packager.php deleted file mode 100644 index 3ed209be8b28c1da639558c4b41bacdc69bc1b98..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Packager.php +++ /dev/null @@ -1,165 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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. | -// +----------------------------------------------------------------------+ -// | Authors: Stig Bakken <ssb@php.net> | -// | Tomas V.V.Cox <cox@idecnet.com> | -// +----------------------------------------------------------------------+ -// -// $Id: Packager.php,v 1.53 2004/06/13 14:06:01 pajoye Exp $ - -require_once 'PEAR/Common.php'; -require_once 'System.php'; - -/** - * Administration class used to make a PEAR release tarball. - * - * TODO: - * - add an extra param the dir where to place the created package - * - * @since PHP 4.0.2 - * @author Stig Bakken <ssb@php.net> - */ -class PEAR_Packager extends PEAR_Common -{ - // {{{ constructor - - function PEAR_Packager() - { - parent::PEAR_Common(); - } - - // }}} - // {{{ destructor - - function _PEAR_Packager() - { - parent::_PEAR_Common(); - } - - // }}} - - // {{{ package() - - function package($pkgfile = null, $compress = true) - { - // {{{ validate supplied package.xml file - if (empty($pkgfile)) { - $pkgfile = 'package.xml'; - } - // $this->pkginfo gets populated inside - $pkginfo = $this->infoFromDescriptionFile($pkgfile); - if (PEAR::isError($pkginfo)) { - return $this->raiseError($pkginfo); - } - - $pkgdir = dirname(realpath($pkgfile)); - $pkgfile = basename($pkgfile); - - $errors = $warnings = array(); - $this->validatePackageInfo($pkginfo, $errors, $warnings, $pkgdir); - foreach ($warnings as $w) { - $this->log(1, "Warning: $w"); - } - foreach ($errors as $e) { - $this->log(0, "Error: $e"); - } - if (sizeof($errors) > 0) { - return $this->raiseError('Errors in package'); - } - // }}} - - $pkgver = $pkginfo['package'] . '-' . $pkginfo['version']; - - // {{{ Create the package file list - $filelist = array(); - $i = 0; - - foreach ($pkginfo['filelist'] as $fname => $atts) { - $file = $pkgdir . DIRECTORY_SEPARATOR . $fname; - if (!file_exists($file)) { - return $this->raiseError("File does not exist: $fname"); - } else { - $filelist[$i++] = $file; - if (empty($pkginfo['filelist'][$fname]['md5sum'])) { - $md5sum = md5_file($file); - $pkginfo['filelist'][$fname]['md5sum'] = $md5sum; - } - $this->log(2, "Adding file $fname"); - } - } - // }}} - - // {{{ regenerate package.xml - $new_xml = $this->xmlFromInfo($pkginfo); - if (PEAR::isError($new_xml)) { - return $this->raiseError($new_xml); - } - if (!($tmpdir = System::mktemp(array('-d')))) { - return $this->raiseError("PEAR_Packager: mktemp failed"); - } - $newpkgfile = $tmpdir . DIRECTORY_SEPARATOR . 'package.xml'; - $np = @fopen($newpkgfile, 'wb'); - if (!$np) { - return $this->raiseError("PEAR_Packager: unable to rewrite $pkgfile as $newpkgfile"); - } - fwrite($np, $new_xml); - fclose($np); - // }}} - - // {{{ TAR the Package ------------------------------------------- - $ext = $compress ? '.tgz' : '.tar'; - $dest_package = getcwd() . DIRECTORY_SEPARATOR . $pkgver . $ext; - $tar =& new Archive_Tar($dest_package, $compress); - $tar->setErrorHandling(PEAR_ERROR_RETURN); // XXX Don't print errors - // ----- Creates with the package.xml file - $ok = $tar->createModify(array($newpkgfile), '', $tmpdir); - if (PEAR::isError($ok)) { - return $this->raiseError($ok); - } elseif (!$ok) { - return $this->raiseError('PEAR_Packager: tarball creation failed'); - } - // ----- Add the content of the package - if (!$tar->addModify($filelist, $pkgver, $pkgdir)) { - return $this->raiseError('PEAR_Packager: tarball creation failed'); - } - $this->log(1, "Package $dest_package done"); - if (file_exists("$pkgdir/CVS/Root")) { - $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $pkginfo['version']); - $cvstag = "RELEASE_$cvsversion"; - $this->log(1, "Tag the released code with `pear cvstag $pkgfile'"); - $this->log(1, "(or set the CVS tag $cvstag by hand)"); - } - // }}} - - return $dest_package; - } - - // }}} -} - -// {{{ md5_file() utility function -if (!function_exists('md5_file')) { - function md5_file($file) { - if (!$fd = @fopen($file, 'r')) { - return false; - } - $md5 = md5(fread($fd, filesize($file))); - fclose($fd); - return $md5; - } -} -// }}} - -?> diff --git a/3rdparty/PEAR/Registry.php b/3rdparty/PEAR/Registry.php deleted file mode 100644 index f2510a38f15c0243b5a261fe00aef897eadc661d..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Registry.php +++ /dev/null @@ -1,538 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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: Stig Bakken <ssb@php.net> | -// | Tomas V.V.Cox <cox@idecnet.com> | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Registry.php,v 1.50.4.3 2004/10/26 19:19:56 cellog Exp $ - -/* -TODO: - - Transform into singleton() - - Add application level lock (avoid change the registry from the cmdline - while using the GTK interface, for ex.) -*/ -require_once "System.php"; -require_once "PEAR.php"; - -define('PEAR_REGISTRY_ERROR_LOCK', -2); -define('PEAR_REGISTRY_ERROR_FORMAT', -3); -define('PEAR_REGISTRY_ERROR_FILE', -4); - -/** - * Administration class used to maintain the installed package database. - */ -class PEAR_Registry extends PEAR -{ - // {{{ properties - - /** Directory where registry files are stored. - * @var string - */ - var $statedir = ''; - - /** File where the file map is stored - * @var string - */ - var $filemap = ''; - - /** Name of file used for locking the registry - * @var string - */ - var $lockfile = ''; - - /** File descriptor used during locking - * @var resource - */ - var $lock_fp = null; - - /** Mode used during locking - * @var int - */ - var $lock_mode = 0; // XXX UNUSED - - /** Cache of package information. Structure: - * array( - * 'package' => array('id' => ... ), - * ... ) - * @var array - */ - var $pkginfo_cache = array(); - - /** Cache of file map. Structure: - * array( '/path/to/file' => 'package', ... ) - * @var array - */ - var $filemap_cache = array(); - - // }}} - - // {{{ constructor - - /** - * PEAR_Registry constructor. - * - * @param string (optional) PEAR install directory (for .php files) - * - * @access public - */ - function PEAR_Registry($pear_install_dir = PEAR_INSTALL_DIR) - { - parent::PEAR(); - $ds = DIRECTORY_SEPARATOR; - $this->install_dir = $pear_install_dir; - $this->statedir = $pear_install_dir.$ds.'.registry'; - $this->filemap = $pear_install_dir.$ds.'.filemap'; - $this->lockfile = $pear_install_dir.$ds.'.lock'; - - // XXX Compatibility code should be removed in the future - // rename all registry files if any to lowercase - if (!OS_WINDOWS && $handle = @opendir($this->statedir)) { - $dest = $this->statedir . DIRECTORY_SEPARATOR; - while (false !== ($file = readdir($handle))) { - if (preg_match('/^.*[A-Z].*\.reg$/', $file)) { - rename($dest . $file, $dest . strtolower($file)); - } - } - closedir($handle); - } - if (!file_exists($this->filemap)) { - $this->rebuildFileMap(); - } - } - - // }}} - // {{{ destructor - - /** - * PEAR_Registry destructor. Makes sure no locks are forgotten. - * - * @access private - */ - function _PEAR_Registry() - { - parent::_PEAR(); - if (is_resource($this->lock_fp)) { - $this->_unlock(); - } - } - - // }}} - - // {{{ _assertStateDir() - - /** - * Make sure the directory where we keep registry files exists. - * - * @return bool TRUE if directory exists, FALSE if it could not be - * created - * - * @access private - */ - function _assertStateDir() - { - if (!@is_dir($this->statedir)) { - if (!System::mkdir(array('-p', $this->statedir))) { - return $this->raiseError("could not create directory '{$this->statedir}'"); - } - } - return true; - } - - // }}} - // {{{ _packageFileName() - - /** - * Get the name of the file where data for a given package is stored. - * - * @param string package name - * - * @return string registry file name - * - * @access public - */ - function _packageFileName($package) - { - return $this->statedir . DIRECTORY_SEPARATOR . strtolower($package) . '.reg'; - } - - // }}} - // {{{ _openPackageFile() - - function _openPackageFile($package, $mode) - { - $this->_assertStateDir(); - $file = $this->_packageFileName($package); - $fp = @fopen($file, $mode); - if (!$fp) { - return null; - } - return $fp; - } - - // }}} - // {{{ _closePackageFile() - - function _closePackageFile($fp) - { - fclose($fp); - } - - // }}} - // {{{ rebuildFileMap() - - function rebuildFileMap() - { - $packages = $this->listPackages(); - $files = array(); - foreach ($packages as $package) { - $version = $this->packageInfo($package, 'version'); - $filelist = $this->packageInfo($package, 'filelist'); - if (!is_array($filelist)) { - continue; - } - foreach ($filelist as $name => $attrs) { - if (isset($attrs['role']) && $attrs['role'] != 'php') { - continue; - } - if (isset($attrs['baseinstalldir'])) { - $file = $attrs['baseinstalldir'].DIRECTORY_SEPARATOR.$name; - } else { - $file = $name; - } - $file = preg_replace(',^/+,', '', $file); - $files[$file] = $package; - } - } - $this->_assertStateDir(); - $fp = @fopen($this->filemap, 'wb'); - if (!$fp) { - return false; - } - $this->filemap_cache = $files; - fwrite($fp, serialize($files)); - fclose($fp); - return true; - } - - // }}} - // {{{ readFileMap() - - function readFileMap() - { - $fp = @fopen($this->filemap, 'r'); - if (!$fp) { - return $this->raiseError('PEAR_Registry: could not open filemap', PEAR_REGISTRY_ERROR_FILE, null, null, $php_errormsg); - } - $fsize = filesize($this->filemap); - $rt = get_magic_quotes_runtime(); - set_magic_quotes_runtime(0); - $data = fread($fp, $fsize); - set_magic_quotes_runtime($rt); - fclose($fp); - $tmp = unserialize($data); - if (!$tmp && $fsize > 7) { - return $this->raiseError('PEAR_Registry: invalid filemap data', PEAR_REGISTRY_ERROR_FORMAT, null, null, $data); - } - $this->filemap_cache = $tmp; - return true; - } - - // }}} - // {{{ _lock() - - /** - * Lock the registry. - * - * @param integer lock mode, one of LOCK_EX, LOCK_SH or LOCK_UN. - * See flock manual for more information. - * - * @return bool TRUE on success, FALSE if locking failed, or a - * PEAR error if some other error occurs (such as the - * lock file not being writable). - * - * @access private - */ - function _lock($mode = LOCK_EX) - { - if (!eregi('Windows 9', php_uname())) { - if ($mode != LOCK_UN && is_resource($this->lock_fp)) { - // XXX does not check type of lock (LOCK_SH/LOCK_EX) - return true; - } - if (PEAR::isError($err = $this->_assertStateDir())) { - return $err; - } - $open_mode = 'w'; - // XXX People reported problems with LOCK_SH and 'w' - if ($mode === LOCK_SH || $mode === LOCK_UN) { - if (@!is_file($this->lockfile)) { - touch($this->lockfile); - } - $open_mode = 'r'; - } - - if (!is_resource($this->lock_fp)) { - $this->lock_fp = @fopen($this->lockfile, $open_mode); - } - - if (!is_resource($this->lock_fp)) { - return $this->raiseError("could not create lock file" . - (isset($php_errormsg) ? ": " . $php_errormsg : "")); - } - if (!(int)flock($this->lock_fp, $mode)) { - switch ($mode) { - case LOCK_SH: $str = 'shared'; break; - case LOCK_EX: $str = 'exclusive'; break; - case LOCK_UN: $str = 'unlock'; break; - default: $str = 'unknown'; break; - } - return $this->raiseError("could not acquire $str lock ($this->lockfile)", - PEAR_REGISTRY_ERROR_LOCK); - } - } - return true; - } - - // }}} - // {{{ _unlock() - - function _unlock() - { - $ret = $this->_lock(LOCK_UN); - if (is_resource($this->lock_fp)) { - fclose($this->lock_fp); - } - $this->lock_fp = null; - return $ret; - } - - // }}} - // {{{ _packageExists() - - function _packageExists($package) - { - return file_exists($this->_packageFileName($package)); - } - - // }}} - // {{{ _packageInfo() - - function _packageInfo($package = null, $key = null) - { - if ($package === null) { - return array_map(array($this, '_packageInfo'), - $this->_listPackages()); - } - $fp = $this->_openPackageFile($package, 'r'); - if ($fp === null) { - return null; - } - $rt = get_magic_quotes_runtime(); - set_magic_quotes_runtime(0); - $data = fread($fp, filesize($this->_packageFileName($package))); - set_magic_quotes_runtime($rt); - $this->_closePackageFile($fp); - $data = unserialize($data); - if ($key === null) { - return $data; - } - if (isset($data[$key])) { - return $data[$key]; - } - return null; - } - - // }}} - // {{{ _listPackages() - - function _listPackages() - { - $pkglist = array(); - $dp = @opendir($this->statedir); - if (!$dp) { - return $pkglist; - } - while ($ent = readdir($dp)) { - if ($ent{0} == '.' || substr($ent, -4) != '.reg') { - continue; - } - $pkglist[] = substr($ent, 0, -4); - } - return $pkglist; - } - - // }}} - - // {{{ packageExists() - - function packageExists($package) - { - if (PEAR::isError($e = $this->_lock(LOCK_SH))) { - return $e; - } - $ret = $this->_packageExists($package); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ packageInfo() - - function packageInfo($package = null, $key = null) - { - if (PEAR::isError($e = $this->_lock(LOCK_SH))) { - return $e; - } - $ret = $this->_packageInfo($package, $key); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ listPackages() - - function listPackages() - { - if (PEAR::isError($e = $this->_lock(LOCK_SH))) { - return $e; - } - $ret = $this->_listPackages(); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ addPackage() - - function addPackage($package, $info) - { - if ($this->packageExists($package)) { - return false; - } - if (PEAR::isError($e = $this->_lock(LOCK_EX))) { - return $e; - } - $fp = $this->_openPackageFile($package, 'wb'); - if ($fp === null) { - $this->_unlock(); - return false; - } - $info['_lastmodified'] = time(); - fwrite($fp, serialize($info)); - $this->_closePackageFile($fp); - $this->_unlock(); - return true; - } - - // }}} - // {{{ deletePackage() - - function deletePackage($package) - { - if (PEAR::isError($e = $this->_lock(LOCK_EX))) { - return $e; - } - $file = $this->_packageFileName($package); - $ret = @unlink($file); - $this->rebuildFileMap(); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ updatePackage() - - function updatePackage($package, $info, $merge = true) - { - $oldinfo = $this->packageInfo($package); - if (empty($oldinfo)) { - return false; - } - if (PEAR::isError($e = $this->_lock(LOCK_EX))) { - return $e; - } - $fp = $this->_openPackageFile($package, 'w'); - if ($fp === null) { - $this->_unlock(); - return false; - } - $info['_lastmodified'] = time(); - if ($merge) { - fwrite($fp, serialize(array_merge($oldinfo, $info))); - } else { - fwrite($fp, serialize($info)); - } - $this->_closePackageFile($fp); - if (isset($info['filelist'])) { - $this->rebuildFileMap(); - } - $this->_unlock(); - return true; - } - - // }}} - // {{{ checkFileMap() - - /** - * Test whether a file belongs to a package. - * - * @param string $path file path, absolute or relative to the pear - * install dir - * - * @return string which package the file belongs to, or an empty - * string if the file does not belong to an installed package - * - * @access public - */ - function checkFileMap($path) - { - if (is_array($path)) { - static $notempty; - if (empty($notempty)) { - $notempty = create_function('$a','return !empty($a);'); - } - $pkgs = array(); - foreach ($path as $name => $attrs) { - if (is_array($attrs) && isset($attrs['baseinstalldir'])) { - $name = $attrs['baseinstalldir'].DIRECTORY_SEPARATOR.$name; - } - $pkgs[$name] = $this->checkFileMap($name); - } - return array_filter($pkgs, $notempty); - } - if (empty($this->filemap_cache) && PEAR::isError($this->readFileMap())) { - return $err; - } - if (isset($this->filemap_cache[$path])) { - return $this->filemap_cache[$path]; - } - $l = strlen($this->install_dir); - if (substr($path, 0, $l) == $this->install_dir) { - $path = preg_replace('!^'.DIRECTORY_SEPARATOR.'+!', '', substr($path, $l)); - } - if (isset($this->filemap_cache[$path])) { - return $this->filemap_cache[$path]; - } - return ''; - } - - // }}} - -} - -?> diff --git a/3rdparty/PEAR/Remote.php b/3rdparty/PEAR/Remote.php deleted file mode 100644 index 7b1e314f903af685e4481fdd8289ede22ccdb8f9..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/Remote.php +++ /dev/null @@ -1,394 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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: Stig Bakken <ssb@php.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Remote.php,v 1.50 2004/06/08 18:03:46 cellog Exp $ - -require_once 'PEAR.php'; -require_once 'PEAR/Config.php'; - -/** - * This is a class for doing remote operations against the central - * PEAR database. - * - * @nodep XML_RPC_Value - * @nodep XML_RPC_Message - * @nodep XML_RPC_Client - */ -class PEAR_Remote extends PEAR -{ - // {{{ properties - - var $config = null; - var $cache = null; - - // }}} - - // {{{ PEAR_Remote(config_object) - - function PEAR_Remote(&$config) - { - $this->PEAR(); - $this->config = &$config; - } - - // }}} - - // {{{ getCache() - - - function getCache($args) - { - $id = md5(serialize($args)); - $cachedir = $this->config->get('cache_dir'); - $filename = $cachedir . DIRECTORY_SEPARATOR . 'xmlrpc_cache_' . $id; - if (!file_exists($filename)) { - return null; - }; - - $fp = fopen($filename, 'rb'); - if (!$fp) { - return null; - } - $content = fread($fp, filesize($filename)); - fclose($fp); - $result = array( - 'age' => time() - filemtime($filename), - 'lastChange' => filemtime($filename), - 'content' => unserialize($content), - ); - return $result; - } - - // }}} - - // {{{ saveCache() - - function saveCache($args, $data) - { - $id = md5(serialize($args)); - $cachedir = $this->config->get('cache_dir'); - if (!file_exists($cachedir)) { - System::mkdir(array('-p', $cachedir)); - } - $filename = $cachedir.'/xmlrpc_cache_'.$id; - - $fp = @fopen($filename, "wb"); - if ($fp) { - fwrite($fp, serialize($data)); - fclose($fp); - }; - } - - // }}} - - // {{{ call(method, [args...]) - - function call($method) - { - $_args = $args = func_get_args(); - - $this->cache = $this->getCache($args); - $cachettl = $this->config->get('cache_ttl'); - // If cache is newer than $cachettl seconds, we use the cache! - if ($this->cache !== null && $this->cache['age'] < $cachettl) { - return $this->cache['content']; - }; - - if (extension_loaded("xmlrpc")) { - $result = call_user_func_array(array(&$this, 'call_epi'), $args); - if (!PEAR::isError($result)) { - $this->saveCache($_args, $result); - }; - return $result; - } - if (!@include_once("XML/RPC.php")) { - return $this->raiseError("For this remote PEAR operation you need to install the XML_RPC package"); - } - array_shift($args); - $server_host = $this->config->get('master_server'); - $username = $this->config->get('username'); - $password = $this->config->get('password'); - $eargs = array(); - foreach($args as $arg) $eargs[] = $this->_encode($arg); - $f = new XML_RPC_Message($method, $eargs); - if ($this->cache !== null) { - $maxAge = '?maxAge='.$this->cache['lastChange']; - } else { - $maxAge = ''; - }; - $proxy_host = $proxy_port = $proxy_user = $proxy_pass = ''; - if ($proxy = parse_url($this->config->get('http_proxy'))) { - $proxy_host = @$proxy['host']; - $proxy_port = @$proxy['port']; - $proxy_user = @urldecode(@$proxy['user']); - $proxy_pass = @urldecode(@$proxy['pass']); - } - $c = new XML_RPC_Client('/xmlrpc.php'.$maxAge, $server_host, 80, $proxy_host, $proxy_port, $proxy_user, $proxy_pass); - if ($username && $password) { - $c->setCredentials($username, $password); - } - if ($this->config->get('verbose') >= 3) { - $c->setDebug(1); - } - $r = $c->send($f); - if (!$r) { - return $this->raiseError("XML_RPC send failed"); - } - $v = $r->value(); - if ($e = $r->faultCode()) { - if ($e == $GLOBALS['XML_RPC_err']['http_error'] && strstr($r->faultString(), '304 Not Modified') !== false) { - return $this->cache['content']; - } - return $this->raiseError($r->faultString(), $e); - } - - $result = XML_RPC_decode($v); - $this->saveCache($_args, $result); - return $result; - } - - // }}} - - // {{{ call_epi(method, [args...]) - - function call_epi($method) - { - do { - if (extension_loaded("xmlrpc")) { - break; - } - if (OS_WINDOWS) { - $ext = 'dll'; - } elseif (PHP_OS == 'HP-UX') { - $ext = 'sl'; - } elseif (PHP_OS == 'AIX') { - $ext = 'a'; - } else { - $ext = 'so'; - } - $ext = OS_WINDOWS ? 'dll' : 'so'; - @dl("xmlrpc-epi.$ext"); - if (extension_loaded("xmlrpc")) { - break; - } - @dl("xmlrpc.$ext"); - if (extension_loaded("xmlrpc")) { - break; - } - return $this->raiseError("unable to load xmlrpc extension"); - } while (false); - $params = func_get_args(); - array_shift($params); - $method = str_replace("_", ".", $method); - $request = xmlrpc_encode_request($method, $params); - $server_host = $this->config->get("master_server"); - if (empty($server_host)) { - return $this->raiseError("PEAR_Remote::call: no master_server configured"); - } - $server_port = 80; - if ($http_proxy = $this->config->get('http_proxy')) { - $proxy = parse_url($http_proxy); - $proxy_host = $proxy_port = $proxy_user = $proxy_pass = ''; - $proxy_host = @$proxy['host']; - $proxy_port = @$proxy['port']; - $proxy_user = @urldecode(@$proxy['user']); - $proxy_pass = @urldecode(@$proxy['pass']); - $fp = @fsockopen($proxy_host, $proxy_port); - $use_proxy = true; - } else { - $use_proxy = false; - $fp = @fsockopen($server_host, $server_port); - } - if (!$fp && $http_proxy) { - return $this->raiseError("PEAR_Remote::call: fsockopen(`$proxy_host', $proxy_port) failed"); - } elseif (!$fp) { - return $this->raiseError("PEAR_Remote::call: fsockopen(`$server_host', $server_port) failed"); - } - $len = strlen($request); - $req_headers = "Host: $server_host:$server_port\r\n" . - "Content-type: text/xml\r\n" . - "Content-length: $len\r\n"; - $username = $this->config->get('username'); - $password = $this->config->get('password'); - if ($username && $password) { - $req_headers .= "Cookie: PEAR_USER=$username; PEAR_PW=$password\r\n"; - $tmp = base64_encode("$username:$password"); - $req_headers .= "Authorization: Basic $tmp\r\n"; - } - if ($this->cache !== null) { - $maxAge = '?maxAge='.$this->cache['lastChange']; - } else { - $maxAge = ''; - }; - - if ($use_proxy && $proxy_host != '' && $proxy_user != '') { - $req_headers .= 'Proxy-Authorization: Basic ' - .base64_encode($proxy_user.':'.$proxy_pass) - ."\r\n"; - } - - if ($this->config->get('verbose') > 3) { - print "XMLRPC REQUEST HEADERS:\n"; - var_dump($req_headers); - print "XMLRPC REQUEST BODY:\n"; - var_dump($request); - } - - if ($use_proxy && $proxy_host != '') { - $post_string = "POST http://".$server_host; - if ($proxy_port > '') { - $post_string .= ':'.$server_port; - } - } else { - $post_string = "POST "; - } - - fwrite($fp, ($post_string."/xmlrpc.php$maxAge HTTP/1.0\r\n$req_headers\r\n$request")); - $response = ''; - $line1 = fgets($fp, 2048); - if (!preg_match('!^HTTP/[0-9\.]+ (\d+) (.*)!', $line1, $matches)) { - return $this->raiseError("PEAR_Remote: invalid HTTP response from XML-RPC server"); - } - switch ($matches[1]) { - case "200": // OK - break; - case "304": // Not Modified - return $this->cache['content']; - case "401": // Unauthorized - if ($username && $password) { - return $this->raiseError("PEAR_Remote: authorization failed", 401); - } else { - return $this->raiseError("PEAR_Remote: authorization required, please log in first", 401); - } - default: - return $this->raiseError("PEAR_Remote: unexpected HTTP response", (int)$matches[1], null, null, "$matches[1] $matches[2]"); - } - while (trim(fgets($fp, 2048)) != ''); // skip rest of headers - while ($chunk = fread($fp, 10240)) { - $response .= $chunk; - } - fclose($fp); - if ($this->config->get('verbose') > 3) { - print "XMLRPC RESPONSE:\n"; - var_dump($response); - } - $ret = xmlrpc_decode($response); - if (is_array($ret) && isset($ret['__PEAR_TYPE__'])) { - if ($ret['__PEAR_TYPE__'] == 'error') { - if (isset($ret['__PEAR_CLASS__'])) { - $class = $ret['__PEAR_CLASS__']; - } else { - $class = "PEAR_Error"; - } - if ($ret['code'] === '') $ret['code'] = null; - if ($ret['message'] === '') $ret['message'] = null; - if ($ret['userinfo'] === '') $ret['userinfo'] = null; - if (strtolower($class) == 'db_error') { - $ret = $this->raiseError(PEAR::errorMessage($ret['code']), - $ret['code'], null, null, - $ret['userinfo']); - } else { - $ret = $this->raiseError($ret['message'], $ret['code'], - null, null, $ret['userinfo']); - } - } - } elseif (is_array($ret) && sizeof($ret) == 1 && isset($ret[0]) - && is_array($ret[0]) && - !empty($ret[0]['faultString']) && - !empty($ret[0]['faultCode'])) { - extract($ret[0]); - $faultString = "XML-RPC Server Fault: " . - str_replace("\n", " ", $faultString); - return $this->raiseError($faultString, $faultCode); - } - return $ret; - } - - // }}} - - // {{{ _encode - - // a slightly extended version of XML_RPC_encode - function _encode($php_val) - { - global $XML_RPC_Boolean, $XML_RPC_Int, $XML_RPC_Double; - global $XML_RPC_String, $XML_RPC_Array, $XML_RPC_Struct; - - $type = gettype($php_val); - $xmlrpcval = new XML_RPC_Value; - - switch($type) { - case "array": - reset($php_val); - $firstkey = key($php_val); - end($php_val); - $lastkey = key($php_val); - if ($firstkey === 0 && is_int($lastkey) && - ($lastkey + 1) == count($php_val)) { - $is_continuous = true; - reset($php_val); - $size = count($php_val); - for ($expect = 0; $expect < $size; $expect++, next($php_val)) { - if (key($php_val) !== $expect) { - $is_continuous = false; - break; - } - } - if ($is_continuous) { - reset($php_val); - $arr = array(); - while (list($k, $v) = each($php_val)) { - $arr[$k] = $this->_encode($v); - } - $xmlrpcval->addArray($arr); - break; - } - } - // fall though if not numerical and continuous - case "object": - $arr = array(); - while (list($k, $v) = each($php_val)) { - $arr[$k] = $this->_encode($v); - } - $xmlrpcval->addStruct($arr); - break; - case "integer": - $xmlrpcval->addScalar($php_val, $XML_RPC_Int); - break; - case "double": - $xmlrpcval->addScalar($php_val, $XML_RPC_Double); - break; - case "string": - case "NULL": - $xmlrpcval->addScalar($php_val, $XML_RPC_String); - break; - case "boolean": - $xmlrpcval->addScalar($php_val, $XML_RPC_Boolean); - break; - case "unknown type": - default: - return null; - } - return $xmlrpcval; - } - - // }}} - -} - -?> diff --git a/3rdparty/PEAR/RunTest.php b/3rdparty/PEAR/RunTest.php deleted file mode 100644 index 1aa02aab9dfd44de3f891c4fa64a34bb2c1419dd..0000000000000000000000000000000000000000 --- a/3rdparty/PEAR/RunTest.php +++ /dev/null @@ -1,363 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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. | -// +----------------------------------------------------------------------+ -// | Authors: Tomas V.V.Cox <cox@idecnet.com> | -// | Greg Beaver <cellog@php.net> | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: RunTest.php,v 1.3.2.4 2005/02/17 17:47:55 cellog Exp $ -// - -/** - * Simplified version of PHP's test suite - * -- EXPERIMENTAL -- - - Try it with: - - $ php -r 'include "../PEAR/RunTest.php"; $t=new PEAR_RunTest; $o=$t->run("./pear_system.phpt");print_r($o);' - - -TODO: - -Actually finish the development and testing - - */ - -require_once 'PEAR.php'; -require_once 'PEAR/Config.php'; - -define('DETAILED', 1); -putenv("PHP_PEAR_RUNTESTS=1"); - -class PEAR_RunTest -{ - var $_logger; - - /** - * An object that supports the PEAR_Common->log() signature, or null - * @param PEAR_Common|null - */ - function PEAR_RunTest($logger = null) - { - $this->_logger = $logger; - } - - // - // Run an individual test case. - // - - function run($file, $ini_settings = '') - { - $cwd = getcwd(); - $conf = &PEAR_Config::singleton(); - $php = $conf->get('php_bin'); - //var_dump($php);exit; - global $log_format, $info_params, $ini_overwrites; - - $info_params = ''; - $log_format = 'LEOD'; - - // Load the sections of the test file. - $section_text = array( - 'TEST' => '(unnamed test)', - 'SKIPIF' => '', - 'GET' => '', - 'ARGS' => '', - ); - - if (!is_file($file) || !$fp = fopen($file, "r")) { - return PEAR::raiseError("Cannot open test file: $file"); - } - - $section = ''; - while (!feof($fp)) { - $line = fgets($fp); - - // Match the beginning of a section. - if (ereg('^--([A-Z]+)--',$line,$r)) { - $section = $r[1]; - $section_text[$section] = ''; - continue; - } - - // Add to the section text. - $section_text[$section] .= $line; - } - fclose($fp); - - $shortname = str_replace($cwd.'/', '', $file); - $tested = trim($section_text['TEST'])." [$shortname]"; - - $tmp = realpath(dirname($file)); - $tmp_skipif = $tmp . uniqid('/phpt.'); - $tmp_file = ereg_replace('\.phpt$','.php',$file); - $tmp_post = $tmp . uniqid('/phpt.'); - - @unlink($tmp_skipif); - @unlink($tmp_file); - @unlink($tmp_post); - - // unlink old test results - @unlink(ereg_replace('\.phpt$','.diff',$file)); - @unlink(ereg_replace('\.phpt$','.log',$file)); - @unlink(ereg_replace('\.phpt$','.exp',$file)); - @unlink(ereg_replace('\.phpt$','.out',$file)); - - // Check if test should be skipped. - $info = ''; - $warn = false; - if (array_key_exists('SKIPIF', $section_text)) { - if (trim($section_text['SKIPIF'])) { - $this->save_text($tmp_skipif, $section_text['SKIPIF']); - //$extra = substr(PHP_OS, 0, 3) !== "WIN" ? - // "unset REQUEST_METHOD;": ""; - - //$output = `$extra $php $info_params -f $tmp_skipif`; - $output = `$php $info_params -f $tmp_skipif`; - unlink($tmp_skipif); - if (eregi("^skip", trim($output))) { - $skipreason = "SKIP $tested"; - $reason = (eregi("^skip[[:space:]]*(.+)\$", trim($output))) ? eregi_replace("^skip[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE; - if ($reason) { - $skipreason .= " (reason: $reason)"; - } - $this->_logger->log(0, $skipreason); - if (isset($old_php)) { - $php = $old_php; - } - return 'SKIPPED'; - } - if (eregi("^info", trim($output))) { - $reason = (ereg("^info[[:space:]]*(.+)\$", trim($output))) ? ereg_replace("^info[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE; - if ($reason) { - $info = " (info: $reason)"; - } - } - if (eregi("^warn", trim($output))) { - $reason = (ereg("^warn[[:space:]]*(.+)\$", trim($output))) ? ereg_replace("^warn[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE; - if ($reason) { - $warn = true; /* only if there is a reason */ - $info = " (warn: $reason)"; - } - } - } - } - - // We've satisfied the preconditions - run the test! - $this->save_text($tmp_file,$section_text['FILE']); - - $args = $section_text['ARGS'] ? ' -- '.$section_text['ARGS'] : ''; - - $cmd = "$php$ini_settings -f $tmp_file$args 2>&1"; - if (isset($this->_logger)) { - $this->_logger->log(2, 'Running command "' . $cmd . '"'); - } - - $savedir = getcwd(); // in case the test moves us around - if (isset($section_text['RETURNS'])) { - ob_start(); - system($cmd, $return_value); - $out = ob_get_contents(); - ob_end_clean(); - @unlink($tmp_post); - $section_text['RETURNS'] = (int) trim($section_text['RETURNS']); - $returnfail = ($return_value != $section_text['RETURNS']); - } else { - $out = `$cmd`; - $returnfail = false; - } - chdir($savedir); - // Does the output match what is expected? - $output = trim($out); - $output = preg_replace('/\r\n/', "\n", $output); - - if (isset($section_text['EXPECTF']) || isset($section_text['EXPECTREGEX'])) { - if (isset($section_text['EXPECTF'])) { - $wanted = trim($section_text['EXPECTF']); - } else { - $wanted = trim($section_text['EXPECTREGEX']); - } - $wanted_re = preg_replace('/\r\n/',"\n",$wanted); - if (isset($section_text['EXPECTF'])) { - $wanted_re = preg_quote($wanted_re, '/'); - // Stick to basics - $wanted_re = str_replace("%s", ".+?", $wanted_re); //not greedy - $wanted_re = str_replace("%i", "[+\-]?[0-9]+", $wanted_re); - $wanted_re = str_replace("%d", "[0-9]+", $wanted_re); - $wanted_re = str_replace("%x", "[0-9a-fA-F]+", $wanted_re); - $wanted_re = str_replace("%f", "[+\-]?\.?[0-9]+\.?[0-9]*(E-?[0-9]+)?", $wanted_re); - $wanted_re = str_replace("%c", ".", $wanted_re); - // %f allows two points "-.0.0" but that is the best *simple* expression - } - /* DEBUG YOUR REGEX HERE - var_dump($wanted_re); - print(str_repeat('=', 80) . "\n"); - var_dump($output); - */ - if (!$returnfail && preg_match("/^$wanted_re\$/s", $output)) { - @unlink($tmp_file); - $this->_logger->log(0, "PASS $tested$info"); - if (isset($old_php)) { - $php = $old_php; - } - return 'PASSED'; - } - - } else { - $wanted = trim($section_text['EXPECT']); - $wanted = preg_replace('/\r\n/',"\n",$wanted); - // compare and leave on success - $ok = (0 == strcmp($output,$wanted)); - if (!$returnfail && $ok) { - @unlink($tmp_file); - $this->_logger->log(0, "PASS $tested$info"); - if (isset($old_php)) { - $php = $old_php; - } - return 'PASSED'; - } - } - - // Test failed so we need to report details. - if ($warn) { - $this->_logger->log(0, "WARN $tested$info"); - } else { - $this->_logger->log(0, "FAIL $tested$info"); - } - - if (isset($section_text['RETURNS'])) { - $GLOBALS['__PHP_FAILED_TESTS__'][] = array( - 'name' => $file, - 'test_name' => $tested, - 'output' => ereg_replace('\.phpt$','.log', $file), - 'diff' => ereg_replace('\.phpt$','.diff', $file), - 'info' => $info, - 'return' => $return_value - ); - } else { - $GLOBALS['__PHP_FAILED_TESTS__'][] = array( - 'name' => $file, - 'test_name' => $tested, - 'output' => ereg_replace('\.phpt$','.log', $file), - 'diff' => ereg_replace('\.phpt$','.diff', $file), - 'info' => $info, - ); - } - - // write .exp - if (strpos($log_format,'E') !== FALSE) { - $logname = ereg_replace('\.phpt$','.exp',$file); - if (!$log = fopen($logname,'w')) { - return PEAR::raiseError("Cannot create test log - $logname"); - } - fwrite($log,$wanted); - fclose($log); - } - - // write .out - if (strpos($log_format,'O') !== FALSE) { - $logname = ereg_replace('\.phpt$','.out',$file); - if (!$log = fopen($logname,'w')) { - return PEAR::raiseError("Cannot create test log - $logname"); - } - fwrite($log,$output); - fclose($log); - } - - // write .diff - if (strpos($log_format,'D') !== FALSE) { - $logname = ereg_replace('\.phpt$','.diff',$file); - if (!$log = fopen($logname,'w')) { - return PEAR::raiseError("Cannot create test log - $logname"); - } - fwrite($log, $this->generate_diff($wanted, $output, - isset($section_text['RETURNS']) ? array(trim($section_text['RETURNS']), - $return_value) : null)); - fclose($log); - } - - // write .log - if (strpos($log_format,'L') !== FALSE) { - $logname = ereg_replace('\.phpt$','.log',$file); - if (!$log = fopen($logname,'w')) { - return PEAR::raiseError("Cannot create test log - $logname"); - } - fwrite($log," ----- EXPECTED OUTPUT -$wanted ----- ACTUAL OUTPUT -$output ----- FAILED -"); - if ($returnfail) { - fwrite($log," ----- EXPECTED RETURN -$section_text[RETURNS] ----- ACTUAL RETURN -$return_value -"); - } - fclose($log); - //error_report($file,$logname,$tested); - } - - if (isset($old_php)) { - $php = $old_php; - } - - return $warn ? 'WARNED' : 'FAILED'; - } - - function generate_diff($wanted, $output, $return_value) - { - $w = explode("\n", $wanted); - $o = explode("\n", $output); - $w1 = array_diff_assoc($w,$o); - $o1 = array_diff_assoc($o,$w); - $w2 = array(); - $o2 = array(); - foreach($w1 as $idx => $val) $w2[sprintf("%03d<",$idx)] = sprintf("%03d- ", $idx+1).$val; - foreach($o1 as $idx => $val) $o2[sprintf("%03d>",$idx)] = sprintf("%03d+ ", $idx+1).$val; - $diff = array_merge($w2, $o2); - ksort($diff); - if ($return_value) { - $extra = "##EXPECTED: $return_value[0]\r\n##RETURNED: $return_value[1]"; - } else { - $extra = ''; - } - return implode("\r\n", $diff) . $extra; - } - - // - // Write the given text to a temporary file, and return the filename. - // - - function save_text($filename, $text) - { - if (!$fp = fopen($filename, 'w')) { - return PEAR::raiseError("Cannot open file '" . $filename . "' (save_text)"); - } - fwrite($fp,$text); - fclose($fp); - if (1 < DETAILED) echo " -FILE $filename {{{ -$text -}}} -"; - } - -} -?> \ No newline at end of file diff --git a/3rdparty/README b/3rdparty/README new file mode 100644 index 0000000000000000000000000000000000000000..e577d414adaa46798ae04d385ee0ad6bac040d19 --- /dev/null +++ b/3rdparty/README @@ -0,0 +1,2 @@ +the 3rdparty libraries are now located in a seperate repository. just copy https://gitorious.org/owncloud/3rdparty into this directory and everything will work + diff --git a/3rdparty/Sabre.includes.php b/3rdparty/Sabre.includes.php deleted file mode 100644 index d41b287b77db5ea8f1ad7b4be78ab68046a803d5..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre.includes.php +++ /dev/null @@ -1,127 +0,0 @@ -<?php - -/** - * Library include file - * - * This file contains all includes to the rest of the SabreDAV library - * Make sure the lib/ directory is in PHP's include_path - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ - -/* Utilities */ -include 'Sabre/HTTP/Util.php'; -include 'Sabre/HTTP/Response.php'; -include 'Sabre/HTTP/Request.php'; -include 'Sabre/HTTP/AbstractAuth.php'; -include 'Sabre/HTTP/BasicAuth.php'; -include 'Sabre/HTTP/DigestAuth.php'; -include 'Sabre/HTTP/AWSAuth.php'; - -/* Version */ -include 'Sabre/DAV/Version.php'; -include 'Sabre/HTTP/Version.php'; - -/* Exceptions */ -include 'Sabre/DAV/Exception.php'; -include 'Sabre/DAV/Exception/BadRequest.php'; -include 'Sabre/DAV/Exception/Conflict.php'; -include 'Sabre/DAV/Exception/FileNotFound.php'; -include 'Sabre/DAV/Exception/InsufficientStorage.php'; -include 'Sabre/DAV/Exception/Locked.php'; -include 'Sabre/DAV/Exception/LockTokenMatchesRequestUri.php'; -include 'Sabre/DAV/Exception/MethodNotAllowed.php'; -include 'Sabre/DAV/Exception/NotImplemented.php'; -include 'Sabre/DAV/Exception/Forbidden.php'; -include 'Sabre/DAV/Exception/PreconditionFailed.php'; -include 'Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php'; -include 'Sabre/DAV/Exception/UnsupportedMediaType.php'; -include 'Sabre/DAV/Exception/NotAuthenticated.php'; - -include 'Sabre/DAV/Exception/ConflictingLock.php'; -include 'Sabre/DAV/Exception/ReportNotImplemented.php'; -include 'Sabre/DAV/Exception/InvalidResourceType.php'; - -/* Properties */ -include 'Sabre/DAV/Property.php'; -include 'Sabre/DAV/Property/GetLastModified.php'; -include 'Sabre/DAV/Property/ResourceType.php'; -include 'Sabre/DAV/Property/SupportedLock.php'; -include 'Sabre/DAV/Property/LockDiscovery.php'; -include 'Sabre/DAV/Property/IHref.php'; -include 'Sabre/DAV/Property/Href.php'; -include 'Sabre/DAV/Property/HrefList.php'; -include 'Sabre/DAV/Property/SupportedReportSet.php'; -include 'Sabre/DAV/Property/Response.php'; -include 'Sabre/DAV/Property/ResponseList.php'; - -/* Node interfaces */ -include 'Sabre/DAV/INode.php'; -include 'Sabre/DAV/IFile.php'; -include 'Sabre/DAV/ICollection.php'; -include 'Sabre/DAV/IProperties.php'; -include 'Sabre/DAV/ILockable.php'; -include 'Sabre/DAV/IQuota.php'; -include 'Sabre/DAV/IExtendedCollection.php'; - -/* Node abstract implementations */ -include 'Sabre/DAV/Node.php'; -include 'Sabre/DAV/File.php'; -include 'Sabre/DAV/Collection.php'; -include 'Sabre/DAV/Directory.php'; - -/* Utilities */ -include 'Sabre/DAV/SimpleCollection.php'; -include 'Sabre/DAV/SimpleDirectory.php'; -include 'Sabre/DAV/XMLUtil.php'; -include 'Sabre/DAV/URLUtil.php'; - -/* Filesystem implementation */ -include 'Sabre/DAV/FS/Node.php'; -include 'Sabre/DAV/FS/File.php'; -include 'Sabre/DAV/FS/Directory.php'; - -/* Advanced filesystem implementation */ -include 'Sabre/DAV/FSExt/Node.php'; -include 'Sabre/DAV/FSExt/File.php'; -include 'Sabre/DAV/FSExt/Directory.php'; - -/* Trees */ -include 'Sabre/DAV/Tree.php'; -include 'Sabre/DAV/ObjectTree.php'; -include 'Sabre/DAV/Tree/Filesystem.php'; - -/* Server */ -include 'Sabre/DAV/Server.php'; -include 'Sabre/DAV/ServerPlugin.php'; - -/* Browser */ -include 'Sabre/DAV/Browser/Plugin.php'; -include 'Sabre/DAV/Browser/MapGetToPropFind.php'; -include 'Sabre/DAV/Browser/GuessContentType.php'; - -/* Locks */ -include 'Sabre/DAV/Locks/LockInfo.php'; -include 'Sabre/DAV/Locks/Plugin.php'; -include 'Sabre/DAV/Locks/Backend/Abstract.php'; -include 'Sabre/DAV/Locks/Backend/FS.php'; -include 'Sabre/DAV/Locks/Backend/PDO.php'; - -/* Temporary File Filter plugin */ -include 'Sabre/DAV/TemporaryFileFilterPlugin.php'; - -/* Authentication plugin */ -include 'Sabre/DAV/Auth/Plugin.php'; -include 'Sabre/DAV/Auth/IBackend.php'; -include 'Sabre/DAV/Auth/Backend/AbstractDigest.php'; -include 'Sabre/DAV/Auth/Backend/AbstractBasic.php'; -include 'Sabre/DAV/Auth/Backend/File.php'; -include 'Sabre/DAV/Auth/Backend/PDO.php'; - -/* DavMount plugin */ -include 'Sabre/DAV/Mount/Plugin.php'; - diff --git a/3rdparty/Sabre/CalDAV/Backend/Abstract.php b/3rdparty/Sabre/CalDAV/Backend/Abstract.php deleted file mode 100644 index b694eef49e4696aa470cf56bc126c2bd1b273378..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Backend/Abstract.php +++ /dev/null @@ -1,163 +0,0 @@ -<?php - -/** - * Abstract Calendaring backend. Extend this class to create your own backends. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_CalDAV_Backend_Abstract { - - /** - * Returns a list of calendars for a principal. - * - * Every project is an array with the following keys: - * * id, a unique id that will be used by other functions to modify the - * calendar. This can be the same as the uri or a database key. - * * uri, which the basename of the uri with which the calendar is - * accessed. - * * principalUri. The owner of the calendar. Almost always the same as - * principalUri passed to this method. - * - * Furthermore it can contain webdav properties in clark notation. A very - * common one is '{DAV:}displayname'. - * - * @param string $principalUri - * @return array - */ - abstract function getCalendarsForUser($principalUri); - - /** - * Creates a new calendar for a principal. - * - * If the creation was a success, an id must be returned that can be used to reference - * this calendar in other methods, such as updateCalendar. - * - * @param string $principalUri - * @param string $calendarUri - * @param array $properties - * @return void - */ - abstract function createCalendar($principalUri,$calendarUri,array $properties); - - /** - * Updates properties for a calendar. - * - * The mutations array uses the propertyName in clark-notation as key, - * and the array value for the property value. In the case a property - * should be deleted, the property value will be null. - * - * This method must be atomic. If one property cannot be changed, the - * entire operation must fail. - * - * If the operation was successful, true can be returned. - * If the operation failed, false can be returned. - * - * Deletion of a non-existant property is always succesful. - * - * Lastly, it is optional to return detailed information about any - * failures. In this case an array should be returned with the following - * structure: - * - * array( - * 403 => array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param string $calendarId - * @param array $mutations - * @return bool|array - */ - public function updateCalendar($calendarId, array $mutations) { - - return false; - - } - - /** - * Delete a calendar and all it's objects - * - * @param string $calendarId - * @return void - */ - abstract function deleteCalendar($calendarId); - - /** - * Returns all calendar objects within a calendar. - * - * Every item contains an array with the following keys: - * * id - unique identifier which will be used for subsequent updates - * * calendardata - The iCalendar-compatible calnedar data - * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string. - * * lastmodified - a timestamp of the last modification time - * * etag - An arbitrary string, surrounded by double-quotes. (e.g.: - * ' "abcdef"') - * * calendarid - The calendarid as it was passed to this function. - * - * Note that the etag is optional, but it's highly encouraged to return for - * speed reasons. - * - * The calendardata is also optional. If it's not returned - * 'getCalendarObject' will be called later, which *is* expected to return - * calendardata. - * - * @param string $calendarId - * @return array - */ - abstract function getCalendarObjects($calendarId); - - /** - * Returns information from a single calendar object, based on it's object - * uri. - * - * The returned array must have the same keys as getCalendarObjects. The - * 'calendardata' object is required here though, while it's not required - * for getCalendarObjects. - * - * @param string $calendarId - * @param string $objectUri - * @return array - */ - abstract function getCalendarObject($calendarId,$objectUri); - - /** - * Creates a new calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - abstract function createCalendarObject($calendarId,$objectUri,$calendarData); - - /** - * Updates an existing calendarobject, based on it's uri. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - abstract function updateCalendarObject($calendarId,$objectUri,$calendarData); - - /** - * Deletes an existing calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @return void - */ - abstract function deleteCalendarObject($calendarId,$objectUri); - -} diff --git a/3rdparty/Sabre/CalDAV/Backend/PDO.php b/3rdparty/Sabre/CalDAV/Backend/PDO.php deleted file mode 100644 index 7b1b33b912ee53a4fd4a94febccbcb6b4c871141..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Backend/PDO.php +++ /dev/null @@ -1,386 +0,0 @@ -<?php - -/** - * PDO CalDAV backend - * - * This backend is used to store calendar-data in a PDO database, such as - * sqlite or MySQL - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { - - /** - * pdo - * - * @var PDO - */ - protected $pdo; - - /** - * The table name that will be used for calendars - * - * @var string - */ - protected $calendarTableName; - - /** - * The table name that will be used for calendar objects - * - * @var string - */ - protected $calendarObjectTableName; - - /** - * List of CalDAV properties, and how they map to database fieldnames - * - * Add your own properties by simply adding on to this array - * - * @var array - */ - public $propertyMap = array( - '{DAV:}displayname' => 'displayname', - '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description', - '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone', - '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder', - '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor', - ); - - /** - * Creates the backend - * - * @param PDO $pdo - */ - public function __construct(PDO $pdo, $calendarTableName = 'calendars', $calendarObjectTableName = 'calendarobjects') { - - $this->pdo = $pdo; - $this->calendarTableName = $calendarTableName; - $this->calendarObjectTableName = $calendarObjectTableName; - - } - - /** - * Returns a list of calendars for a principal. - * - * Every project is an array with the following keys: - * * id, a unique id that will be used by other functions to modify the - * calendar. This can be the same as the uri or a database key. - * * uri, which the basename of the uri with which the calendar is - * accessed. - * * principalUri. The owner of the calendar. Almost always the same as - * principalUri passed to this method. - * - * Furthermore it can contain webdav properties in clark notation. A very - * common one is '{DAV:}displayname'. - * - * @param string $principalUri - * @return array - */ - public function getCalendarsForUser($principalUri) { - - $fields = array_values($this->propertyMap); - $fields[] = 'id'; - $fields[] = 'uri'; - $fields[] = 'ctag'; - $fields[] = 'components'; - $fields[] = 'principaluri'; - - // Making fields a comma-delimited list - $fields = implode(', ', $fields); - $stmt = $this->pdo->prepare("SELECT " . $fields . " FROM `".$this->calendarTableName."` WHERE principaluri = ?"); - $stmt->execute(array($principalUri)); - - $calendars = array(); - while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - - $components = explode(',',$row['components']); - - $calendar = array( - 'id' => $row['id'], - 'uri' => $row['uri'], - 'principaluri' => $row['principaluri'], - '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $row['ctag']?$row['ctag']:'0', - '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components), - ); - - - foreach($this->propertyMap as $xmlName=>$dbName) { - $calendar[$xmlName] = $row[$dbName]; - } - - $calendars[] = $calendar; - - } - - return $calendars; - - } - - /** - * Creates a new calendar for a principal. - * - * If the creation was a success, an id must be returned that can be used to reference - * this calendar in other methods, such as updateCalendar - * - * @param string $principalUri - * @param string $calendarUri - * @param array $properties - */ - public function createCalendar($principalUri,$calendarUri, array $properties) { - - $fieldNames = array( - 'principaluri', - 'uri', - 'ctag', - ); - $values = array( - ':principaluri' => $principalUri, - ':uri' => $calendarUri, - ':ctag' => 1, - ); - - // Default value - $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set'; - $fieldNames[] = 'components'; - if (!isset($properties[$sccs])) { - $values[':components'] = 'VEVENT,VTODO'; - } else { - if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) { - throw new Sabre_DAV_Exception('The ' . $sccs . ' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet'); - } - $values[':components'] = implode(',',$properties[$sccs]->getValue()); - } - - foreach($this->propertyMap as $xmlName=>$dbName) { - if (isset($properties[$xmlName])) { - - $myValue = $properties[$xmlName]; - $values[':' . $dbName] = $properties[$xmlName]; - $fieldNames[] = $dbName; - } - } - - $stmt = $this->pdo->prepare("INSERT INTO `".$this->calendarTableName."` (".implode(', ', $fieldNames).") VALUES (".implode(', ',array_keys($values)).")"); - $stmt->execute($values); - - return $this->pdo->lastInsertId(); - - } - - /** - * Updates properties for a calendar. - * - * The mutations array uses the propertyName in clark-notation as key, - * and the array value for the property value. In the case a property - * should be deleted, the property value will be null. - * - * This method must be atomic. If one property cannot be changed, the - * entire operation must fail. - * - * If the operation was successful, true can be returned. - * If the operation failed, false can be returned. - * - * Deletion of a non-existant property is always succesful. - * - * Lastly, it is optional to return detailed information about any - * failures. In this case an array should be returned with the following - * structure: - * - * array( - * 403 => array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param string $calendarId - * @param array $mutations - * @return bool|array - */ - public function updateCalendar($calendarId, array $mutations) { - - $newValues = array(); - $result = array( - 200 => array(), // Ok - 403 => array(), // Forbidden - 424 => array(), // Failed Dependency - ); - - $hasError = false; - - foreach($mutations as $propertyName=>$propertyValue) { - - // We don't know about this property. - if (!isset($this->propertyMap[$propertyName])) { - $hasError = true; - $result[403][$propertyName] = null; - unset($mutations[$propertyName]); - continue; - } - - $fieldName = $this->propertyMap[$propertyName]; - $newValues[$fieldName] = $propertyValue; - - } - - // If there were any errors we need to fail the request - if ($hasError) { - // Properties has the remaining properties - foreach($mutations as $propertyName=>$propertyValue) { - $result[424][$propertyName] = null; - } - - // Removing unused statuscodes for cleanliness - foreach($result as $status=>$properties) { - if (is_array($properties) && count($properties)===0) unset($result[$status]); - } - - return $result; - - } - - // Success - - // Now we're generating the sql query. - $valuesSql = array(); - foreach($newValues as $fieldName=>$value) { - $valuesSql[] = $fieldName . ' = ?'; - } - $valuesSql[] = 'ctag = ctag + 1'; - - $stmt = $this->pdo->prepare("UPDATE `" . $this->calendarTableName . "` SET " . implode(', ',$valuesSql) . " WHERE id = ?"); - $newValues['id'] = $calendarId; - $stmt->execute(array_values($newValues)); - - return true; - - } - - /** - * Delete a calendar and all it's objects - * - * @param string $calendarId - * @return void - */ - public function deleteCalendar($calendarId) { - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ?'); - $stmt->execute(array($calendarId)); - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->calendarTableName.'` WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - /** - * Returns all calendar objects within a calendar. - * - * Every item contains an array with the following keys: - * * id - unique identifier which will be used for subsequent updates - * * calendardata - The iCalendar-compatible calnedar data - * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string. - * * lastmodified - a timestamp of the last modification time - * * etag - An arbitrary string, surrounded by double-quotes. (e.g.: - * ' "abcdef"') - * * calendarid - The calendarid as it was passed to this function. - * - * Note that the etag is optional, but it's highly encouraged to return for - * speed reasons. - * - * The calendardata is also optional. If it's not returned - * 'getCalendarObject' will be called later, which *is* expected to return - * calendardata. - * - * @param string $calendarId - * @return array - */ - public function getCalendarObjects($calendarId) { - - $stmt = $this->pdo->prepare('SELECT * FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ?'); - $stmt->execute(array($calendarId)); - return $stmt->fetchAll(); - - } - - /** - * Returns information from a single calendar object, based on it's object - * uri. - * - * The returned array must have the same keys as getCalendarObjects. The - * 'calendardata' object is required here though, while it's not required - * for getCalendarObjects. - * - * @param string $calendarId - * @param string $objectUri - * @return array - */ - public function getCalendarObject($calendarId,$objectUri) { - - $stmt = $this->pdo->prepare('SELECT * FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ? AND uri = ?'); - $stmt->execute(array($calendarId, $objectUri)); - return $stmt->fetch(); - - } - - /** - * Creates a new calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - public function createCalendarObject($calendarId,$objectUri,$calendarData) { - - $stmt = $this->pdo->prepare('INSERT INTO `'.$this->calendarObjectTableName.'` (calendarid, uri, calendardata, lastmodified) VALUES (?,?,?,?)'); - $stmt->execute(array($calendarId,$objectUri,$calendarData,time())); - $stmt = $this->pdo->prepare('UPDATE `'.$this->calendarTableName.'` SET ctag = ctag + 1 WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - /** - * Updates an existing calendarobject, based on it's uri. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @return void - */ - public function updateCalendarObject($calendarId,$objectUri,$calendarData) { - - $stmt = $this->pdo->prepare('UPDATE `'.$this->calendarObjectTableName.'` SET calendardata = ?, lastmodified = ? WHERE calendarid = ? AND uri = ?'); - $stmt->execute(array($calendarData,time(),$calendarId,$objectUri)); - $stmt = $this->pdo->prepare('UPDATE `'.$this->calendarTableName.'` SET ctag = ctag + 1 WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - /** - * Deletes an existing calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @return void - */ - public function deleteCalendarObject($calendarId,$objectUri) { - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->calendarObjectTableName.'` WHERE calendarid = ? AND uri = ?'); - $stmt->execute(array($calendarId,$objectUri)); - $stmt = $this->pdo->prepare('UPDATE `'. $this->calendarTableName .'` SET ctag = ctag + 1 WHERE id = ?'); - $stmt->execute(array($calendarId)); - - } - - -} diff --git a/3rdparty/Sabre/CalDAV/Calendar.php b/3rdparty/Sabre/CalDAV/Calendar.php deleted file mode 100644 index 0d2b3875771729f323e8f19cc86a2376eb77b6d6..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Calendar.php +++ /dev/null @@ -1,318 +0,0 @@ -<?php - -/** - * This object represents a CalDAV calendar. - * - * A calendar can contain multiple TODO and or Events. These are represented - * as Sabre_CalDAV_CalendarObject objects. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Calendar implements Sabre_CalDAV_ICalendar, Sabre_DAV_IProperties, Sabre_DAVACL_IACL { - - /** - * This is an array with calendar information - * - * @var array - */ - protected $calendarInfo; - - /** - * CalDAV backend - * - * @var Sabre_CalDAV_Backend_Abstract - */ - protected $caldavBackend; - - /** - * Principal backend - * - * @var Sabre_DAVACL_IPrincipalBackend - */ - protected $principalBackend; - - /** - * Constructor - * - * @param Sabre_CalDAV_Backend_Abstract $caldavBackend - * @param array $calendarInfo - * @return void - */ - public function __construct(Sabre_DAVACL_IPrincipalBackend $principalBackend, Sabre_CalDAV_Backend_Abstract $caldavBackend, $calendarInfo) { - - $this->caldavBackend = $caldavBackend; - $this->principalBackend = $principalBackend; - $this->calendarInfo = $calendarInfo; - - - } - - /** - * Returns the name of the calendar - * - * @return string - */ - public function getName() { - - return $this->calendarInfo['uri']; - - } - - /** - * Updates properties such as the display name and description - * - * @param array $mutations - * @return array - */ - public function updateProperties($mutations) { - - return $this->caldavBackend->updateCalendar($this->calendarInfo['id'],$mutations); - - } - - /** - * Returns the list of properties - * - * @param array $properties - * @return array - */ - public function getProperties($requestedProperties) { - - $response = array(); - - foreach($requestedProperties as $prop) switch($prop) { - - case '{urn:ietf:params:xml:ns:caldav}supported-calendar-data' : - $response[$prop] = new Sabre_CalDAV_Property_SupportedCalendarData(); - break; - case '{urn:ietf:params:xml:ns:caldav}supported-collation-set' : - $response[$prop] = new Sabre_CalDAV_Property_SupportedCollationSet(); - break; - case '{DAV:}owner' : - $response[$prop] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF,$this->calendarInfo['principaluri']); - break; - default : - if (isset($this->calendarInfo[$prop])) $response[$prop] = $this->calendarInfo[$prop]; - break; - - } - return $response; - - } - - /** - * Returns a calendar object - * - * The contained calendar objects are for example Events or Todo's. - * - * @param string $name - * @return Sabre_DAV_ICalendarObject - */ - public function getChild($name) { - - $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'],$name); - if (!$obj) throw new Sabre_DAV_Exception_FileNotFound('Calendar object not found'); - return new Sabre_CalDAV_CalendarObject($this->caldavBackend,$this->calendarInfo,$obj); - - } - - /** - * Returns the full list of calendar objects - * - * @return array - */ - public function getChildren() { - - $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']); - $children = array(); - foreach($objs as $obj) { - $children[] = new Sabre_CalDAV_CalendarObject($this->caldavBackend,$this->calendarInfo,$obj); - } - return $children; - - } - - /** - * Checks if a child-node exists. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'],$name); - if (!$obj) - return false; - else - return true; - - } - - /** - * Creates a new directory - * - * We actually block this, as subdirectories are not allowed in calendars. - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating collections in calendar objects is not allowed'); - - } - - /** - * Creates a new file - * - * The contents of the new file must be a valid ICalendar string. - * - * @param string $name - * @param resource $calendarData - * @return void - */ - public function createFile($name,$calendarData = null) { - - $calendarData = stream_get_contents($calendarData); - // Converting to UTF-8, if needed - $calendarData = Sabre_DAV_StringUtil::ensureUTF8($calendarData); - - $supportedComponents = $this->calendarInfo['{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set']; - if ($supportedComponents) { - $supportedComponents = $supportedComponents->getValue(); - } else { - $supportedComponents = null; - } - Sabre_CalDAV_ICalendarUtil::validateICalendarObject($calendarData, $supportedComponents); - - $this->caldavBackend->createCalendarObject($this->calendarInfo['id'],$name,$calendarData); - - } - - /** - * Deletes the calendar. - * - * @return void - */ - public function delete() { - - $this->caldavBackend->deleteCalendar($this->calendarInfo['id']); - - } - - /** - * Renames the calendar. Note that most calendars use the - * {DAV:}displayname to display a name to display a name. - * - * @param string $newName - * @return void - */ - public function setName($newName) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Renaming calendars is not yet supported'); - - } - - /** - * Returns the last modification date as a unix timestamp. - * - * @return void - */ - public function getLastModified() { - - return null; - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->calendarInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - - -} diff --git a/3rdparty/Sabre/CalDAV/CalendarObject.php b/3rdparty/Sabre/CalDAV/CalendarObject.php deleted file mode 100644 index 0c99f18deb72cca5233bd50ffdce28bd3037fc86..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/CalendarObject.php +++ /dev/null @@ -1,260 +0,0 @@ -<?php - -/** - * The CalendarObject represents a single VEVENT or VTODO within a Calendar. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_CalendarObject extends Sabre_DAV_File implements Sabre_CalDAV_ICalendarObject, Sabre_DAVACL_IACL { - - /** - * Sabre_CalDAV_Backend_Abstract - * - * @var array - */ - protected $caldavBackend; - - /** - * Array with information about this CalendarObject - * - * @var array - */ - protected $objectData; - - /** - * Array with information about the containing calendar - * - * @var array - */ - protected $calendarInfo; - - /** - * Constructor - * - * @param Sabre_CalDAV_Backend_Abstract $caldavBackend - * @param array $calendarInfo - * @param array $objectData - */ - public function __construct(Sabre_CalDAV_Backend_Abstract $caldavBackend,array $calendarInfo,array $objectData) { - - $this->caldavBackend = $caldavBackend; - - if (!isset($objectData['calendarid'])) { - throw new InvalidArgumentException('The objectData argument must contain a \'calendarid\' property'); - } - if (!isset($objectData['uri'])) { - throw new InvalidArgumentException('The objectData argument must contain an \'uri\' property'); - } - - $this->calendarInfo = $calendarInfo; - $this->objectData = $objectData; - - } - - /** - * Returns the uri for this object - * - * @return string - */ - public function getName() { - - return $this->objectData['uri']; - - } - - /** - * Returns the ICalendar-formatted object - * - * @return string - */ - public function get() { - - // Pre-populating the 'calendardata' is optional, if we don't have it - // already we fetch it from the backend. - if (!isset($this->objectData['calendardata'])) { - $this->objectData = $this->caldavBackend->getCalendarObject($this->objectData['calendarid'], $this->objectData['uri']); - } - return $this->objectData['calendardata']; - - } - - /** - * Updates the ICalendar-formatted object - * - * @param string $calendarData - * @return void - */ - public function put($calendarData) { - - if (is_resource($calendarData)) - $calendarData = stream_get_contents($calendarData); - - // Converting to UTF-8, if needed - $calendarData = Sabre_DAV_StringUtil::ensureUTF8($calendarData); - - $supportedComponents = $this->calendarInfo['{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set']; - if ($supportedComponents) { - $supportedComponents = $supportedComponents->getValue(); - } else { - $supportedComponents = null; - } - Sabre_CalDAV_ICalendarUtil::validateICalendarObject($calendarData, $supportedComponents); - - $this->caldavBackend->updateCalendarObject($this->calendarInfo['id'],$this->objectData['uri'],$calendarData); - $this->objectData['calendardata'] = $calendarData; - - } - - /** - * Deletes the calendar object - * - * @return void - */ - public function delete() { - - $this->caldavBackend->deleteCalendarObject($this->calendarInfo['id'],$this->objectData['uri']); - - } - - /** - * Returns the mime content-type - * - * @return string - */ - public function getContentType() { - - return 'text/calendar'; - - } - - /** - * Returns an ETag for this object. - * - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * @return string - */ - public function getETag() { - - if (isset($this->objectData['etag'])) { - return $this->objectData['etag']; - } else { - return '"' . md5($this->get()). '"'; - } - - } - - /** - * Returns the last modification date as a unix timestamp - * - * @return time - */ - public function getLastModified() { - - return $this->objectData['lastmodified']; - - } - - /** - * Returns the size of this object in bytes - * - * @return int - */ - public function getSize() { - - return strlen($this->objectData['calendardata']); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->calendarInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - -} - diff --git a/3rdparty/Sabre/CalDAV/CalendarRootNode.php b/3rdparty/Sabre/CalDAV/CalendarRootNode.php deleted file mode 100644 index 69669a9d7fd96a5612661cf463621f242c8fcd3e..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/CalendarRootNode.php +++ /dev/null @@ -1,75 +0,0 @@ -<?php - -/** - * Users collection - * - * This object is responsible for generating a collection of users. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_CalendarRootNode extends Sabre_DAVACL_AbstractPrincipalCollection { - - /** - * CalDAV backend - * - * @var Sabre_CalDAV_Backend_Abstract - */ - protected $caldavBackend; - - /** - * Constructor - * - * This constructor needs both an authentication and a caldav backend. - * - * By default this class will show a list of calendar collections for - * principals in the 'principals' collection. If your main principals are - * actually located in a different path, use the $principalPrefix argument - * to override this. - * - * - * @param Sabre_DAVACL_IPrincipalBackend $principalBackend - * @param Sabre_CalDAV_Backend_Abstract $caldavBackend - * @param string $principalPrefix - */ - public function __construct(Sabre_DAVACL_IPrincipalBackend $principalBackend,Sabre_CalDAV_Backend_Abstract $caldavBackend, $principalPrefix = 'principals') { - - parent::__construct($principalBackend, $principalPrefix); - $this->caldavBackend = $caldavBackend; - - } - - /** - * Returns the nodename - * - * We're overriding this, because the default will be the 'principalPrefix', - * and we want it to be Sabre_CalDAV_Plugin::CALENDAR_ROOT - * - * @return void - */ - public function getName() { - - return Sabre_CalDAV_Plugin::CALENDAR_ROOT; - - } - - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principal - * @return Sabre_DAV_INode - */ - public function getChildForPrincipal(array $principal) { - - return new Sabre_CalDAV_UserCalendars($this->principalBackend, $this->caldavBackend, $principal['uri']); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Exception/InvalidICalendarObject.php b/3rdparty/Sabre/CalDAV/Exception/InvalidICalendarObject.php deleted file mode 100644 index 656b7286a66538dbeb487983a226384705e7c6b9..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Exception/InvalidICalendarObject.php +++ /dev/null @@ -1,18 +0,0 @@ -<?php - -/** - * InvalidICalendarObject - * - * This exception is thrown when an attempt is made to create or update - * an invalid ICalendar object - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Exception_InvalidICalendarObject extends Sabre_DAV_Exception_PreconditionFailed { - - -} diff --git a/3rdparty/Sabre/CalDAV/ICSExportPlugin.php b/3rdparty/Sabre/CalDAV/ICSExportPlugin.php deleted file mode 100644 index 4e2c6eb93d286da842e1ecb9035d031b0cb885c2..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/ICSExportPlugin.php +++ /dev/null @@ -1,124 +0,0 @@ -<?php - -/** - * ICS Exporter - * - * This plugin adds the ability to export entire calendars as .ics files. - * This is useful for clients that don't support CalDAV yet. They often do - * support ics files. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_ICSExportPlugin extends Sabre_DAV_ServerPlugin { - - /** - * Reference to Server class - * - * @var Sabre_DAV_Server - */ - private $server; - - /** - * Initializes the plugin and registers event handlers - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'), 90); - - } - - /** - * 'beforeMethod' event handles. This event handles intercepts GET requests ending - * with ?export - * - * @param string $method - * @param string $uri - * @return void - */ - public function beforeMethod($method, $uri) { - - if ($method!='GET') return; - if ($this->server->httpRequest->getQueryString()!='export') return; - - // splitting uri - list($uri) = explode('?',$uri,2); - - $node = $this->server->tree->getNodeForPath($uri); - - if (!($node instanceof Sabre_CalDAV_Calendar)) return; - - $this->server->httpResponse->setHeader('Content-Type','text/calendar'); - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->sendBody($this->generateICS($this->server->tree->getChildren($uri))); - - // Returning false to break the event chain - return false; - - } - - /** - * Merges all calendar objects, and builds one big ics export - * - * @param array $nodes - * @return void - */ - public function generateICS(array $nodes) { - - $calendar = new Sabre_VObject_Component('vcalendar'); - $calendar->version = '2.0'; - $calendar->prodid = '-//SabreDAV//SabreDAV ' . Sabre_DAV_Version::VERSION . '//EN'; - $calendar->calscale = 'GREGORIAN'; - - $collectedTimezones = array(); - - $timezones = array(); - $objects = array(); - - foreach($nodes as $node) { - - $nodeData = $node->get(); - $nodeComp = Sabre_VObject_Reader::read($nodeData); - - foreach($nodeComp->children() as $child) { - - switch($child->name) { - case 'VEVENT' : - case 'VTODO' : - case 'VJOURNAL' : - $objects[] = $child; - break; - - // VTIMEZONE is special, because we need to filter out the duplicates - case 'VTIMEZONE' : - // Naively just checking tzid. - if (in_array((string)$child->TZID, $collectedTimezones)) continue; - - $timezones[] = $child; - $collectedTimezones[] = $child->TZID; - break; - - - } - - - } - - - } - - foreach($timezones as $tz) $calendar->add($tz); - foreach($objects as $obj) $calendar->add($obj); - - return $calendar->serialize(); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/ICalendar.php b/3rdparty/Sabre/CalDAV/ICalendar.php deleted file mode 100644 index 8193dff3a8393debda39bb09cf1df42a1f642763..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/ICalendar.php +++ /dev/null @@ -1,18 +0,0 @@ -<?php - -/** - * Calendar interface - * - * Implement this interface to allow a node to be recognized as an calendar. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_CalDAV_ICalendar extends Sabre_DAV_ICollection { - - - -} diff --git a/3rdparty/Sabre/CalDAV/ICalendarObject.php b/3rdparty/Sabre/CalDAV/ICalendarObject.php deleted file mode 100644 index 708300ad7bd83f731c6e0933ebaeaf31789aa876..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/ICalendarObject.php +++ /dev/null @@ -1,20 +0,0 @@ -<?php - -/** - * CalendarObject interface -/** - * Extend the ICalendarObject interface to allow your custom nodes to be picked up as - * CalendarObjects. - * - * Calendar objects are resources such as Events, Todo's or Journals. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_CalDAV_ICalendarObject extends Sabre_DAV_IFile { - -} - diff --git a/3rdparty/Sabre/CalDAV/ICalendarUtil.php b/3rdparty/Sabre/CalDAV/ICalendarUtil.php deleted file mode 100644 index 699abfdd6f5e0726701664a849405df4b422fe32..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/ICalendarUtil.php +++ /dev/null @@ -1,157 +0,0 @@ -<?php - -/** - * This class contains several utilities related to the ICalendar (rfc2445) format - * - * This class is now deprecated, and won't be further maintained. Please use - * the Sabre_VObject package for your ics parsing needs. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - * @deprecated Use Sabre_VObject instead. - */ -class Sabre_CalDAV_ICalendarUtil { - - /** - * Validates an ICalendar object - * - * This method makes sure this ICalendar object is properly formatted. - * If we can't parse it, we'll throw exceptions. - * - * @param string $icalData - * @param array $allowedComponents - * @return bool - */ - static function validateICalendarObject($icalData, array $allowedComponents = null) { - - $xcal = simplexml_load_string(self::toXCal($icalData)); - if (!$xcal) throw new Sabre_CalDAV_Exception_InvalidICalendarObject('Invalid calendarobject format'); - - $xcal->registerXPathNameSpace('cal','urn:ietf:params:xml:ns:xcal'); - - // Check if there's only 1 component - $components = array('vevent','vtodo','vjournal','vfreebusy'); - $componentsFound = array(); - - foreach($components as $component) { - $test = $xcal->xpath('/cal:iCalendar/cal:vcalendar/cal:' . $component); - if (is_array($test)) $componentsFound = array_merge($componentsFound, $test); - } - if (count($componentsFound)<1) { - throw new Sabre_CalDAV_Exception_InvalidICalendarObject('One VEVENT, VTODO, VJOURNAL or VFREEBUSY must be specified. 0 found.'); - } - $component = $componentsFound[0]; - - if (is_null($allowedComponents)) return true; - - // Check if the component is allowed - $name = $component->getName(); - if (!in_array(strtoupper($name),$allowedComponents)) { - throw new Sabre_CalDAV_Exception_InvalidICalendarObject(strtoupper($name) . ' is not allowed in this calendar.'); - } - - if (count($xcal->xpath('/cal:iCalendar/cal:vcalendar/cal:method'))>0) { - throw new Sabre_CalDAV_Exception_InvalidICalendarObject('The METHOD property is not allowed in calendar objects'); - } - - return true; - - } - - /** - * Converts ICalendar data to XML. - * - * Properties are converted to lowercase xml elements. Parameters are; - * converted to attributes. BEGIN:VEVENT is converted to <vevent> and - * END:VEVENT </vevent> as well as other components. - * - * It's a very loose parser. If any line does not conform to the spec, it - * will simply be ignored. It will try to detect if \r\n or \n line endings - * are used. - * - * @todo Currently quoted attributes are not parsed correctly. - * @see http://tools.ietf.org/html/draft-royer-calsch-xcal-03 - * @param string $icalData - * @return string. - */ - static function toXCAL($icalData) { - - // Detecting line endings - $lb="\r\n"; - if (strpos($icalData,"\r\n")!==false) $lb = "\r\n"; - elseif (strpos($icalData,"\n")!==false) $lb = "\n"; - - // Splitting up items per line - $lines = explode($lb,$icalData); - - // Properties can be folded over 2 lines. In this case the second - // line will be preceeded by a space or tab. - $lines2 = array(); - foreach($lines as $line) { - - if (!$line) continue; - if ($line[0]===" " || $line[0]==="\t") { - $lines2[count($lines2)-1].=substr($line,1); - continue; - } - - $lines2[]=$line; - - } - - $xml = '<?xml version="1.0"?>' . "\n"; - $xml.= "<iCalendar xmlns=\"urn:ietf:params:xml:ns:xcal\">\n"; - - $spaces = 2; - foreach($lines2 as $line) { - - $matches = array(); - // This matches PROPERTYNAME;ATTRIBUTES:VALUE - if (!preg_match('/^([^:^;]*)(?:;([^:]*))?:(.*)$/',$line,$matches)) - continue; - - $propertyName = strtolower($matches[1]); - $attributes = $matches[2]; - $value = $matches[3]; - - // If the line was in the format BEGIN:COMPONENT or END:COMPONENT, we need to special case it. - if ($propertyName === 'begin') { - $xml.=str_repeat(" ",$spaces); - $xml.='<' . strtolower($value) . ">\n"; - $spaces+=2; - continue; - } elseif ($propertyName === 'end') { - $spaces-=2; - $xml.=str_repeat(" ",$spaces); - $xml.='</' . strtolower($value) . ">\n"; - continue; - } - - $xml.=str_repeat(" ",$spaces); - $xml.='<' . $propertyName; - if ($attributes) { - // There can be multiple attributes - $attributes = explode(';',$attributes); - foreach($attributes as $att) { - - list($attName,$attValue) = explode('=',$att,2); - $attName = strtolower($attName); - if ($attName === 'language') $attName='xml:lang'; - $xml.=' ' . $attName . '="' . htmlspecialchars($attValue) . '"'; - - } - } - - $xml.='>'. htmlspecialchars(trim($value)) . '</' . $propertyName . ">\n"; - - } - $xml.="</iCalendar>"; - return $xml; - - } - -} - diff --git a/3rdparty/Sabre/CalDAV/Plugin.php b/3rdparty/Sabre/CalDAV/Plugin.php deleted file mode 100644 index 02747c8395e3a2b6d0f32183074d598d707ffff6..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Plugin.php +++ /dev/null @@ -1,788 +0,0 @@ -<?php - -/** - * CalDAV plugin - * - * This plugin provides functionality added by CalDAV (RFC 4791) - * It implements new reports, and the MKCALENDAR method. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { - - /** - * This is the official CalDAV namespace - */ - const NS_CALDAV = 'urn:ietf:params:xml:ns:caldav'; - - /** - * This is the namespace for the proprietary calendarserver extensions - */ - const NS_CALENDARSERVER = 'http://calendarserver.org/ns/'; - - /** - * The following constants are used to differentiate - * the various filters for the calendar-query report - */ - const FILTER_COMPFILTER = 1; - const FILTER_TIMERANGE = 3; - const FILTER_PROPFILTER = 4; - const FILTER_PARAMFILTER = 5; - const FILTER_TEXTMATCH = 6; - - /** - * The hardcoded root for calendar objects. It is unfortunate - * that we're stuck with it, but it will have to do for now - */ - const CALENDAR_ROOT = 'calendars'; - - /** - * Reference to server object - * - * @var Sabre_DAV_Server - */ - private $server; - - /** - * Use this method to tell the server this plugin defines additional - * HTTP methods. - * - * This method is passed a uri. It should only return HTTP methods that are - * available for the specified uri. - * - * @param string $uri - * @return array - */ - public function getHTTPMethods($uri) { - - // The MKCALENDAR is only available on unmapped uri's, whose - // parents extend IExtendedCollection - list($parent, $name) = Sabre_DAV_URLUtil::splitPath($uri); - - $node = $this->server->tree->getNodeForPath($parent); - - if ($node instanceof Sabre_DAV_IExtendedCollection) { - try { - $node->getChild($name); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - return array('MKCALENDAR'); - } - } - return array(); - - } - - /** - * Returns a list of features for the DAV: HTTP header. - * - * @return array - */ - public function getFeatures() { - - return array('calendar-access', 'calendar-proxy'); - - } - - /** - * Returns a plugin name. - * - * Using this name other plugins will be able to access other plugins - * using Sabre_DAV_Server::getPlugin - * - * @return string - */ - public function getPluginName() { - - return 'caldav'; - - } - - /** - * Returns a list of reports this plugin supports. - * - * This will be used in the {DAV:}supported-report-set property. - * Note that you still need to subscribe to the 'report' event to actually - * implement them - * - * @param string $uri - * @return array - */ - public function getSupportedReportSet($uri) { - - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_CalDAV_ICalendar || $node instanceof Sabre_CalDAV_ICalendarObject) { - return array( - '{' . self::NS_CALDAV . '}calendar-multiget', - '{' . self::NS_CALDAV . '}calendar-query', - ); - } - return array(); - - } - - /** - * Initializes the plugin - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('unknownMethod',array($this,'unknownMethod')); - //$server->subscribeEvent('unknownMethod',array($this,'unknownMethod2'),1000); - $server->subscribeEvent('report',array($this,'report')); - $server->subscribeEvent('beforeGetProperties',array($this,'beforeGetProperties')); - - $server->xmlNamespaces[self::NS_CALDAV] = 'cal'; - $server->xmlNamespaces[self::NS_CALENDARSERVER] = 'cs'; - - $server->propertyMap['{' . self::NS_CALDAV . '}supported-calendar-component-set'] = 'Sabre_CalDAV_Property_SupportedCalendarComponentSet'; - - $server->resourceTypeMapping['Sabre_CalDAV_ICalendar'] = '{urn:ietf:params:xml:ns:caldav}calendar'; - $server->resourceTypeMapping['Sabre_CalDAV_Principal_ProxyRead'] = '{http://calendarserver.org/ns/}calendar-proxy-read'; - $server->resourceTypeMapping['Sabre_CalDAV_Principal_ProxyWrite'] = '{http://calendarserver.org/ns/}calendar-proxy-write'; - - array_push($server->protectedProperties, - - '{' . self::NS_CALDAV . '}supported-calendar-component-set', - '{' . self::NS_CALDAV . '}supported-calendar-data', - '{' . self::NS_CALDAV . '}max-resource-size', - '{' . self::NS_CALDAV . '}min-date-time', - '{' . self::NS_CALDAV . '}max-date-time', - '{' . self::NS_CALDAV . '}max-instances', - '{' . self::NS_CALDAV . '}max-attendees-per-instance', - '{' . self::NS_CALDAV . '}calendar-home-set', - '{' . self::NS_CALDAV . '}supported-collation-set', - '{' . self::NS_CALDAV . '}calendar-data', - - // scheduling extension - '{' . self::NS_CALDAV . '}calendar-user-address-set', - - // CalendarServer extensions - '{' . self::NS_CALENDARSERVER . '}getctag', - '{' . self::NS_CALENDARSERVER . '}calendar-proxy-read-for', - '{' . self::NS_CALENDARSERVER . '}calendar-proxy-write-for' - - ); - } - - /** - * This function handles support for the MKCALENDAR method - * - * @param string $method - * @return bool - */ - public function unknownMethod($method, $uri) { - - if ($method!=='MKCALENDAR') return; - - $this->httpMkCalendar($uri); - // false is returned to stop the unknownMethod event - return false; - - } - - /** - * This functions handles REPORT requests specific to CalDAV - * - * @param string $reportName - * @param DOMNode $dom - * @return bool - */ - public function report($reportName,$dom) { - - switch($reportName) { - case '{'.self::NS_CALDAV.'}calendar-multiget' : - $this->calendarMultiGetReport($dom); - return false; - case '{'.self::NS_CALDAV.'}calendar-query' : - $this->calendarQueryReport($dom); - return false; - - } - - - } - - /** - * This function handles the MKCALENDAR HTTP method, which creates - * a new calendar. - * - * @param string $uri - * @return void - */ - public function httpMkCalendar($uri) { - - // Due to unforgivable bugs in iCal, we're completely disabling MKCALENDAR support - // for clients matching iCal in the user agent - //$ua = $this->server->httpRequest->getHeader('User-Agent'); - //if (strpos($ua,'iCal/')!==false) { - // throw new Sabre_DAV_Exception_Forbidden('iCal has major bugs in it\'s RFC3744 support. Therefore we are left with no other choice but disabling this feature.'); - //} - - $body = $this->server->httpRequest->getBody(true); - $properties = array(); - - if ($body) { - - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - foreach($dom->firstChild->childNodes as $child) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($child)!=='{DAV:}set') continue; - foreach(Sabre_DAV_XMLUtil::parseProperties($child,$this->server->propertyMap) as $k=>$prop) { - $properties[$k] = $prop; - } - - } - } - - $resourceType = array('{DAV:}collection','{urn:ietf:params:xml:ns:caldav}calendar'); - - $this->server->createCollection($uri,$resourceType,$properties); - - $this->server->httpResponse->sendStatus(201); - $this->server->httpResponse->setHeader('Content-Length',0); - } - - /** - * beforeGetProperties - * - * This method handler is invoked before any after properties for a - * resource are fetched. This allows us to add in any CalDAV specific - * properties. - * - * @param string $path - * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties - * @return void - */ - public function beforeGetProperties($path, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) { - - if ($node instanceof Sabre_DAVACL_IPrincipal) { - - // calendar-home-set property - $calHome = '{' . self::NS_CALDAV . '}calendar-home-set'; - if (in_array($calHome,$requestedProperties)) { - $principalId = $node->getName(); - $calendarHomePath = self::CALENDAR_ROOT . '/' . $principalId . '/'; - unset($requestedProperties[$calHome]); - $returnedProperties[200][$calHome] = new Sabre_DAV_Property_Href($calendarHomePath); - } - - // calendar-user-address-set property - $calProp = '{' . self::NS_CALDAV . '}calendar-user-address-set'; - if (in_array($calProp,$requestedProperties)) { - - $addresses = $node->getAlternateUriSet(); - $addresses[] = $this->server->getBaseUri() . $node->getPrincipalUrl(); - unset($requestedProperties[$calProp]); - $returnedProperties[200][$calProp] = new Sabre_DAV_Property_HrefList($addresses, false); - - } - - // These two properties are shortcuts for ical to easily find - // other principals this principal has access to. - $propRead = '{' . self::NS_CALENDARSERVER . '}calendar-proxy-read-for'; - $propWrite = '{' . self::NS_CALENDARSERVER . '}calendar-proxy-write-for'; - if (in_array($propRead,$requestedProperties) || in_array($propWrite,$requestedProperties)) { - - $membership = $node->getGroupMembership(); - $readList = array(); - $writeList = array(); - - foreach($membership as $group) { - - $groupNode = $this->server->tree->getNodeForPath($group); - - // If the node is either ap proxy-read or proxy-write - // group, we grab the parent principal and add it to the - // list. - if ($groupNode instanceof Sabre_CalDAV_Principal_ProxyRead) { - list($readList[]) = Sabre_DAV_URLUtil::splitPath($group); - } - if ($groupNode instanceof Sabre_CalDAV_Principal_ProxyWrite) { - list($writeList[]) = Sabre_DAV_URLUtil::splitPath($group); - } - - } - if (in_array($propRead,$requestedProperties)) { - unset($requestedProperties[$propRead]); - $returnedProperties[200][$propRead] = new Sabre_DAV_Property_HrefList($readList); - } - if (in_array($propWrite,$requestedProperties)) { - unset($requestedProperties[$propWrite]); - $returnedProperties[200][$propWrite] = new Sabre_DAV_Property_HrefList($writeList); - } - - } - - } // instanceof IPrincipal - - - if ($node instanceof Sabre_CalDAV_ICalendarObject) { - // The calendar-data property is not supposed to be a 'real' - // property, but in large chunks of the spec it does act as such. - // Therefore we simply expose it as a property. - $calDataProp = '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data'; - if (in_array($calDataProp, $requestedProperties)) { - unset($requestedProperties[$calDataProp]); - $val = $node->get(); - if (is_resource($val)) - $val = stream_get_contents($val); - - // Taking out \r to not screw up the xml output - $returnedProperties[200][$calDataProp] = str_replace("\r","", $val); - - } - } - - } - - /** - * This function handles the calendar-multiget REPORT. - * - * This report is used by the client to fetch the content of a series - * of urls. Effectively avoiding a lot of redundant requests. - * - * @param DOMNode $dom - * @return void - */ - public function calendarMultiGetReport($dom) { - - $properties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); - - $hrefElems = $dom->getElementsByTagNameNS('urn:DAV','href'); - foreach($hrefElems as $elem) { - $uri = $this->server->calculateUri($elem->nodeValue); - list($objProps) = $this->server->getPropertiesForPath($uri,$properties); - $propertyList[]=$objProps; - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList)); - - } - - /** - * This function handles the calendar-query REPORT - * - * This report is used by clients to request calendar objects based on - * complex conditions. - * - * @param DOMNode $dom - * @return void - */ - public function calendarQueryReport($dom) { - - $requestedProperties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); - - $filterNode = $dom->getElementsByTagNameNS('urn:ietf:params:xml:ns:caldav','filter'); - if ($filterNode->length!==1) { - throw new Sabre_DAV_Exception_BadRequest('The calendar-query report must have a filter element'); - } - $filters = Sabre_CalDAV_XMLUtil::parseCalendarQueryFilters($filterNode->item(0)); - - $requestedCalendarData = true; - - if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar-data', $requestedProperties)) { - // We always retrieve calendar-data, as we need it for filtering. - $requestedProperties[] = '{urn:ietf:params:xml:ns:caldav}calendar-data'; - - // If calendar-data wasn't explicitly requested, we need to remove - // it after processing. - $requestedCalendarData = false; - } - - // These are the list of nodes that potentially match the requirement - $candidateNodes = $this->server->getPropertiesForPath($this->server->getRequestUri(),$requestedProperties,$this->server->getHTTPDepth(0)); - - $verifiedNodes = array(); - - foreach($candidateNodes as $node) { - - // If the node didn't have a calendar-data property, it must not be a calendar object - if (!isset($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data'])) continue; - - if ($this->validateFilters($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data'],$filters)) { - - if (!$requestedCalendarData) { - unset($node[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']); - } - $verifiedNodes[] = $node; - } - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($verifiedNodes)); - - } - - - /** - * Verify if a list of filters applies to the calendar data object - * - * The calendarData object must be a valid iCalendar blob. The list of - * filters must be formatted as parsed by Sabre_CalDAV_Plugin::parseCalendarQueryFilters - * - * @param string $calendarData - * @param array $filters - * @return bool - */ - public function validateFilters($calendarData,$filters) { - - // We are converting the calendar object to an XML structure - // This makes it far easier to parse - $xCalendarData = Sabre_CalDAV_ICalendarUtil::toXCal($calendarData); - $xml = simplexml_load_string($xCalendarData); - $xml->registerXPathNamespace('c','urn:ietf:params:xml:ns:xcal'); - - foreach($filters as $xpath=>$filter) { - - // if-not-defined comes first - if (isset($filter['is-not-defined'])) { - if (!$xml->xpath($xpath)) - continue; - else - return false; - - } - - $elem = $xml->xpath($xpath); - - if (!$elem) return false; - $elem = $elem[0]; - - if (isset($filter['time-range'])) { - - switch($elem->getName()) { - case 'vevent' : - $result = $this->validateTimeRangeFilterForEvent($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'vtodo' : - $result = $this->validateTimeRangeFilterForTodo($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'vjournal' : - case 'vfreebusy' : - case 'valarm' : - // TODO: not implemented - break; - - /* - - case 'vjournal' : - $result = $this->validateTimeRangeFilterForJournal($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'vfreebusy' : - $result = $this->validateTimeRangeFilterForFreeBusy($xml,$xpath,$filter); - if ($result===false) return false; - break; - case 'valarm' : - $result = $this->validateTimeRangeFilterForAlarm($xml,$xpath,$filter); - if ($result===false) return false; - break; - - */ - - } - - } - - if (isset($filter['text-match'])) { - $currentString = (string)$elem; - - $isMatching = Sabre_DAV_StringUtil::textMatch($currentString, $filter['text-match']['value'], $filter['text-match']['collation']); - if ($filter['text-match']['negate-condition'] && $isMatching) return false; - if (!$filter['text-match']['negate-condition'] && !$isMatching) return false; - - } - - } - return true; - - } - - /** - * Checks whether a time-range filter matches an event. - * - * @param SimpleXMLElement $xml Event as xml object - * @param string $currentXPath XPath to check - * @param array $currentFilter Filter information - * @return void - */ - private function validateTimeRangeFilterForEvent(SimpleXMLElement $xml,$currentXPath,array $currentFilter) { - - // Grabbing the DTSTART property - $xdtstart = $xml->xpath($currentXPath.'/c:dtstart'); - if (!count($xdtstart)) { - throw new Sabre_DAV_Exception_BadRequest('DTSTART property missing from calendar object'); - } - - // The dtstart can be both a date, or datetime property - if ((string)$xdtstart[0]['value']==='DATE' || strlen((string)$xdtstart[0])===8) { - $isDateTime = false; - } else { - $isDateTime = true; - } - - // Determining the timezone - if ($tzid = (string)$xdtstart[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - if ($isDateTime) { - $dtstart = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdtstart[0],$tz); - } else { - $dtstart = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdtstart[0]); - } - - - // Grabbing the DTEND property - $xdtend = $xml->xpath($currentXPath.'/c:dtend'); - $dtend = null; - - if (count($xdtend)) { - // Determining the timezone - if ($tzid = (string)$xdtend[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - - // Since the VALUE prameter of both DTSTART and DTEND must be the same - // we can assume we don't need to check the VALUE paramter of DTEND. - if ($isDateTime) { - $dtend = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdtend[0],$tz); - } else { - $dtend = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdtend[0],$tz); - } - - } - - if (is_null($dtend)) { - // The DTEND property was not found. We will first see if the event has a duration - // property - - $xduration = $xml->xpath($currentXPath.'/c:duration'); - if (count($xduration)) { - $duration = Sabre_CalDAV_XMLUtil::parseICalendarDuration((string)$xduration[0]); - - // Making sure that the duration is bigger than 0 seconds. - $tempDT = clone $dtstart; - $tempDT->modify($duration); - if ($tempDT > $dtstart) { - - // use DTEND = DTSTART + DURATION - $dtend = $tempDT; - } else { - // use DTEND = DTSTART - $dtend = $dtstart; - } - - } - } - - if (is_null($dtend)) { - if ($isDateTime) { - // DTEND = DTSTART - $dtend = $dtstart; - } else { - // DTEND = DTSTART + 1 DAY - $dtend = clone $dtstart; - $dtend->modify('+1 day'); - } - } - // TODO: we need to properly parse RRULE's, but it's very difficult. - // For now, we're always returning events if they have an RRULE at all. - $rrule = $xml->xpath($currentXPath.'/c:rrule'); - $hasRrule = (count($rrule))>0; - - if (!is_null($currentFilter['time-range']['start']) && $currentFilter['time-range']['start'] >= $dtend) return false; - if (!is_null($currentFilter['time-range']['end']) && $currentFilter['time-range']['end'] <= $dtstart && !$hasRrule) return false; - return true; - - } - - private function validateTimeRangeFilterForTodo(SimpleXMLElement $xml,$currentXPath,array $filter) { - - // Gathering all relevant elements - - $dtStart = null; - $duration = null; - $due = null; - $completed = null; - $created = null; - - $xdt = $xml->xpath($currentXPath.'/c:dtstart'); - if (count($xdt)) { - // The dtstart can be both a date, or datetime property - if ((string)$xdt[0]['value']==='DATE') { - $isDateTime = false; - } else { - $isDateTime = true; - } - - // Determining the timezone - if ($tzid = (string)$xdt[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - if ($isDateTime) { - $dtStart = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0],$tz); - } else { - $dtStart = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdt[0]); - } - } - - // Only need to grab duration if dtStart is set - if (!is_null($dtStart)) { - - $xduration = $xml->xpath($currentXPath.'/c:duration'); - if (count($xduration)) { - $duration = Sabre_CalDAV_XMLUtil::parseICalendarDuration((string)$xduration[0]); - } - - } - - if (!is_null($dtStart) && !is_null($duration)) { - - // Comparision from RFC 4791: - // (start <= DTSTART+DURATION) AND ((end > DTSTART) OR (end >= DTSTART+DURATION)) - - $end = clone $dtStart; - $end->modify($duration); - - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $end) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] > $dtStart || $filter['time-range']['end'] >= $end) ) { - return true; - } else { - return false; - } - - } - - // Need to grab the DUE property - $xdt = $xml->xpath($currentXPath.'/c:due'); - if (count($xdt)) { - // The due property can be both a date, or datetime property - if ((string)$xdt[0]['value']==='DATE') { - $isDateTime = false; - } else { - $isDateTime = true; - } - // Determining the timezone - if ($tzid = (string)$xdt[0]['tzid']) { - $tz = new DateTimeZone($tzid); - } else { - $tz = null; - } - if ($isDateTime) { - $due = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0],$tz); - } else { - $due = Sabre_CalDAV_XMLUtil::parseICalendarDate((string)$xdt[0]); - } - } - - if (!is_null($dtStart) && !is_null($due)) { - - // Comparision from RFC 4791: - // ((start < DUE) OR (start <= DTSTART)) AND ((end > DTSTART) OR (end >= DUE)) - - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] < $due || $filter['time-range']['start'] < $dtstart) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $due) ) { - return true; - } else { - return false; - } - - } - - if (!is_null($dtStart)) { - - // Comparision from RFC 4791 - // (start <= DTSTART) AND (end > DTSTART) - if ( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $dtStart) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] > $dtStart) ) { - return true; - } else { - return false; - } - - } - - if (!is_null($due)) { - - // Comparison from RFC 4791 - // (start < DUE) AND (end >= DUE) - if ( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] < $due) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $due) ) { - return true; - } else { - return false; - } - - } - // Need to grab the COMPLETED property - $xdt = $xml->xpath($currentXPath.'/c:completed'); - if (count($xdt)) { - $completed = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0]); - } - // Need to grab the CREATED property - $xdt = $xml->xpath($currentXPath.'/c:created'); - if (count($xdt)) { - $created = Sabre_CalDAV_XMLUtil::parseICalendarDateTime((string)$xdt[0]); - } - - if (!is_null($completed) && !is_null($created)) { - // Comparison from RFC 4791 - // ((start <= CREATED) OR (start <= COMPLETED)) AND ((end >= CREATED) OR (end >= COMPLETED)) - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $created || $filter['time-range']['start'] <= $completed) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $created || $filter['time-range']['end'] >= $completed)) { - return true; - } else { - return false; - } - } - - if (!is_null($completed)) { - // Comparison from RFC 4791 - // (start <= COMPLETED) AND (end >= COMPLETED) - if( (is_null($filter['time-range']['start']) || $filter['time-range']['start'] <= $completed) && - (is_null($filter['time-range']['end']) || $filter['time-range']['end'] >= $completed)) { - return true; - } else { - return false; - } - } - - if (!is_null($created)) { - // Comparison from RFC 4791 - // (end > CREATED) - if( (is_null($filter['time-range']['end']) || $filter['time-range']['end'] > $created) ) { - return true; - } else { - return false; - } - } - - // Everything else is TRUE - return true; - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/Collection.php b/3rdparty/Sabre/CalDAV/Principal/Collection.php deleted file mode 100644 index 13435b2448efc55a0f7b8439e6a8727174d2cfd7..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Principal/Collection.php +++ /dev/null @@ -1,31 +0,0 @@ -<?php - -/** - * Principal collection - * - * This is an alternative collection to the standard ACL principal collection. - * This collection adds support for the calendar-proxy-read and - * calendar-proxy-write sub-principals, as defined by the caldav-proxy - * specification. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Principal_Collection extends Sabre_DAVACL_AbstractPrincipalCollection { - - /** - * Returns a child object based on principal information - * - * @param array $principalInfo - * @return Sabre_CalDAV_Principal_User - */ - public function getChildForPrincipal(array $principalInfo) { - - return new Sabre_CalDAV_Principal_User($this->principalBackend, $principalInfo); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php b/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php deleted file mode 100644 index f531d85d1ffffacb2bf00101c942e0bb2b0953f3..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Principal/ProxyRead.php +++ /dev/null @@ -1,178 +0,0 @@ -<?php - -/** - * ProxyRead principal - * - * This class represents a principal group, hosted under the main principal. - * This is needed to implement 'Calendar delegation' support. This class is - * instantiated by Sabre_CalDAV_Principal_User. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Principal_ProxyRead implements Sabre_DAVACL_IPrincipal { - - /** - * Principal information from the parent principal. - * - * @var array - */ - protected $principalInfo; - - /** - * Principal backend - * - * @var Sabre_DAVACL_IPrincipalBackend - */ - protected $principalBackend; - - /** - * Creates the object. - * - * Note that you MUST supply the parent principal information. - * - * @param Sabre_DAVACL_IPrincipalBackend $principalBackend - * @param array $principalInfo - */ - public function __construct(Sabre_DAVACL_IPrincipalBackend $principalBackend, array $principalInfo) { - - $this->principalInfo = $principalInfo; - $this->principalBackend = $principalBackend; - - } - - /** - * Returns this principals name. - * - * @return string - */ - public function getName() { - - return 'calendar-proxy-read'; - - } - - /** - * Returns the last modification time - * - * @return null - */ - public function getLastModified() { - - return null; - - } - - /** - * Deletes the current node - * - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to delete node'); - - } - - /** - * Renames the node - * - * @throws Sabre_DAV_Exception_Forbidden - * @param string $name The new name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to rename file'); - - } - - - /** - * Returns a list of altenative urls for a principal - * - * This can for example be an email address, or ldap url. - * - * @return array - */ - public function getAlternateUriSet() { - - return array(); - - } - - /** - * Returns the full principal url - * - * @return string - */ - public function getPrincipalUrl() { - - return $this->principalInfo['uri'] . '/' . $this->getName(); - - } - - /** - * Returns the list of group members - * - * If this principal is a group, this function should return - * all member principal uri's for the group. - * - * @return array - */ - public function getGroupMemberSet() { - - return $this->principalBackend->getGroupMemberSet($this->getPrincipalUrl()); - - } - - /** - * Returns the list of groups this principal is member of - * - * If this principal is a member of a (list of) groups, this function - * should return a list of principal uri's for it's members. - * - * @return array - */ - public function getGroupMembership() { - - return $this->principalBackend->getGroupMembership($this->getPrincipalUrl()); - - } - - /** - * Sets a list of group members - * - * If this principal is a group, this method sets all the group members. - * The list of members is always overwritten, never appended to. - * - * This method should throw an exception if the members could not be set. - * - * @param array $principals - * @return void - */ - public function setGroupMemberSet(array $principals) { - - $this->principalBackend->setGroupMemberSet($this->getPrincipalUrl(), $principals); - - } - - /** - * Returns the displayname - * - * This should be a human readable name for the principal. - * If none is available, return the nodename. - * - * @return string - */ - public function getDisplayName() { - - return $this->getName(); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php b/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php deleted file mode 100644 index 4d8face20607f51a3f81e449143bdace2708aff7..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php +++ /dev/null @@ -1,178 +0,0 @@ -<?php - -/** - * ProxyWrite principal - * - * This class represents a principal group, hosted under the main principal. - * This is needed to implement 'Calendar delegation' support. This class is - * instantiated by Sabre_CalDAV_Principal_User. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Principal_ProxyWrite implements Sabre_DAVACL_IPrincipal { - - /** - * Parent principal information - * - * @var array - */ - protected $principalInfo; - - /** - * Principal Backend - * - * @var Sabre_DAVACL_IPrincipalBackend - */ - protected $principalBackend; - - /** - * Creates the object - * - * Note that you MUST supply the parent principal information. - * - * @param Sabre_DAVACL_IPrincipalBackend $principalBackend - * @param array $principalInfo - */ - public function __construct(Sabre_DAVACL_IPrincipalBackend $principalBackend, array $principalInfo) { - - $this->principalInfo = $principalInfo; - $this->principalBackend = $principalBackend; - - } - - /** - * Returns this principals name. - * - * @return string - */ - public function getName() { - - return 'calendar-proxy-write'; - - } - - /** - * Returns the last modification time - * - * @return null - */ - public function getLastModified() { - - return null; - - } - - /** - * Deletes the current node - * - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to delete node'); - - } - - /** - * Renames the node - * - * @throws Sabre_DAV_Exception_Forbidden - * @param string $name The new name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to rename file'); - - } - - - /** - * Returns a list of altenative urls for a principal - * - * This can for example be an email address, or ldap url. - * - * @return array - */ - public function getAlternateUriSet() { - - return array(); - - } - - /** - * Returns the full principal url - * - * @return string - */ - public function getPrincipalUrl() { - - return $this->principalInfo['uri'] . '/' . $this->getName(); - - } - - /** - * Returns the list of group members - * - * If this principal is a group, this function should return - * all member principal uri's for the group. - * - * @return array - */ - public function getGroupMemberSet() { - - return $this->principalBackend->getGroupMemberSet($this->getPrincipalUrl()); - - } - - /** - * Returns the list of groups this principal is member of - * - * If this principal is a member of a (list of) groups, this function - * should return a list of principal uri's for it's members. - * - * @return array - */ - public function getGroupMembership() { - - return $this->principalBackend->getGroupMembership($this->getPrincipalUrl()); - - } - - /** - * Sets a list of group members - * - * If this principal is a group, this method sets all the group members. - * The list of members is always overwritten, never appended to. - * - * This method should throw an exception if the members could not be set. - * - * @param array $principals - * @return void - */ - public function setGroupMemberSet(array $principals) { - - $this->principalBackend->setGroupMemberSet($this->getPrincipalUrl(), $principals); - - } - - /** - * Returns the displayname - * - * This should be a human readable name for the principal. - * If none is available, return the nodename. - * - * @return string - */ - public function getDisplayName() { - - return $this->getName(); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Principal/User.php b/3rdparty/Sabre/CalDAV/Principal/User.php deleted file mode 100644 index 034629b89b3154006e4756d3ffe614df8ca850b6..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Principal/User.php +++ /dev/null @@ -1,122 +0,0 @@ -<?php - -/** - * CalDAV principal - * - * This is a standard user-principal for CalDAV. This principal is also a - * collection and returns the caldav-proxy-read and caldav-proxy-write child - * principals. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Principal_User extends Sabre_DAVACL_Principal implements Sabre_DAV_ICollection { - - /** - * Creates a new file in the directory - * - * @param string $name Name of the file - * @param resource $data Initial payload, passed as a readable stream resource. - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function createFile($name, $data = null) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to create file (filename ' . $name . ')'); - - } - - /** - * Creates a new subdirectory - * - * @param string $name - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function createDirectory($name) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to create directory'); - - } - - /** - * Returns a specific child node, referenced by its name - * - * @param string $name - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - if ($name === 'calendar-proxy-read') - return new Sabre_CalDAV_Principal_ProxyRead($this->principalBackend, $this->principalProperties); - - if ($name === 'calendar-proxy-write') - return new Sabre_CalDAV_Principal_ProxyWrite($this->principalBackend, $this->principalProperties); - - throw new Sabre_DAV_Exception_FileNotFound('Node with name ' . $name . ' was not found'); - - } - - /** - * Returns an array with all the child nodes - * - * @return Sabre_DAV_INode[] - */ - public function getChildren() { - - return array( - new Sabre_CalDAV_Principal_ProxyRead($this->principalBackend, $this->principalProperties), - new Sabre_CalDAV_Principal_ProxyWrite($this->principalBackend, $this->principalProperties), - ); - - } - - /** - * Checks if a child-node with the specified name exists - * - * @return bool - */ - public function childExists($name) { - - return $name === 'calendar-proxy-read' || $name === 'calendar-proxy-write'; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'] . '/calendar-proxy-read', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'] . '/calendar-proxy-write', - 'protected' => true, - ), - ); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php b/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php deleted file mode 100644 index 1bbaca6b8a75b2c57aafbc6ddf1f461af95b4f9e..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php +++ /dev/null @@ -1,85 +0,0 @@ -<?php - -/** - * Supported component set property - * - * This property is a representation of the supported-calendar_component-set - * property in the CalDAV namespace. It simply requires an array of components, - * such as VEVENT, VTODO - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Property_SupportedCalendarComponentSet extends Sabre_DAV_Property { - - /** - * List of supported components, such as "VEVENT, VTODO" - * - * @var array - */ - private $components; - - /** - * Creates the property - * - * @param array $components - */ - public function __construct(array $components) { - - $this->components = $components; - - } - - /** - * Returns the list of supported components - * - * @return array - */ - public function getValue() { - - return $this->components; - - } - - /** - * Serializes the property in a DOMDocument - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - foreach($this->components as $component) { - - $xcomp = $doc->createElement('cal:comp'); - $xcomp->setAttribute('name',$component); - $node->appendChild($xcomp); - - } - - } - - /** - * Unserializes the DOMElement back into a Property class. - * - * @param DOMElement $node - * @return void - */ - static function unserialize(DOMElement $node) { - - $components = array(); - foreach($node->childNodes as $childNode) { - if (Sabre_DAV_XMLUtil::toClarkNotation($childNode)==='{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}comp') { - $components[] = $childNode->getAttribute('name'); - } - } - return new self($components); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php b/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php deleted file mode 100644 index 5010ee6d5257ad3085b646e95157d3870506279a..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php +++ /dev/null @@ -1,38 +0,0 @@ -<?php - -/** - * Supported-calendar-data property - * - * This property is a representation of the supported-calendar-data property - * in the CalDAV namespace. SabreDAV only has support for text/calendar;2.0 - * so the value is currently hardcoded. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Property_SupportedCalendarData extends Sabre_DAV_Property { - - /** - * Serializes the property in a DOMDocument - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - - $prefix = isset($server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV])?$server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV]:'cal'; - - $caldata = $doc->createElement($prefix . ':calendar-data'); - $caldata->setAttribute('content-type','text/calendar'); - $caldata->setAttribute('version','2.0'); - - $node->appendChild($caldata); - } - -} diff --git a/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php b/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php deleted file mode 100644 index e585e9db3d877b5dc8e1d67ff7961791ac98800d..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php +++ /dev/null @@ -1,44 +0,0 @@ -<?php - -/** - * supported-collation-set property - * - * This property is a representation of the supported-collation-set property - * in the CalDAV namespace. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Property_SupportedCollationSet extends Sabre_DAV_Property { - - /** - * Serializes the property in a DOM document - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - - $prefix = $node->lookupPrefix('urn:ietf:params:xml:ns:caldav'); - if (!$prefix) $prefix = 'cal'; - - $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;ascii-casemap') - ); - $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;octet') - ); - $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;unicode-casemap') - ); - - - } - -} diff --git a/3rdparty/Sabre/CalDAV/Server.php b/3rdparty/Sabre/CalDAV/Server.php deleted file mode 100644 index 969d69c6279a262286d1453d960a8da8aefbb29d..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Server.php +++ /dev/null @@ -1,65 +0,0 @@ -<?php - -/** - * CalDAV server - * - * This script is a convenience script. It quickly sets up a WebDAV server - * with caldav and ACL support, and it creates the root 'principals' and - * 'calendars' collections. - * - * Note that if you plan to do anything moderately complex, you are advised to - * not subclass this server, but use Sabre_DAV_Server directly instead. This - * class is nothing more than an 'easy setup'. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Server extends Sabre_DAV_Server { - - /** - * The authentication realm - * - * Note that if this changes, the hashes in the auth backend must also - * be recalculated. - * - * @var string - */ - public $authRealm = 'SabreDAV'; - - /** - * Sets up the object. A PDO object must be passed to setup all the backends. - * - * @param PDO $pdo - */ - public function __construct(PDO $pdo) { - - /* Backends */ - $authBackend = new Sabre_DAV_Auth_Backend_PDO($pdo); - $calendarBackend = new Sabre_CalDAV_Backend_PDO($pdo); - $principalBackend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); - - /* Directory structure */ - $tree = array( - new Sabre_CalDAV_Principal_Collection($principalBackend), - new Sabre_CalDAV_CalendarRootNode($principalBackend, $calendarBackend), - ); - - /* Initializing server */ - parent::__construct($tree); - - /* Server Plugins */ - $authPlugin = new Sabre_DAV_Auth_Plugin($authBackend,$this->authRealm); - $this->addPlugin($authPlugin); - - $aclPlugin = new Sabre_DAVACL_Plugin(); - $this->addPlugin($aclPlugin); - - $caldavPlugin = new Sabre_CalDAV_Plugin(); - $this->addPlugin($caldavPlugin); - - } - -} diff --git a/3rdparty/Sabre/CalDAV/UserCalendars.php b/3rdparty/Sabre/CalDAV/UserCalendars.php deleted file mode 100644 index f52d65e9a73f222e325ec7695374ae4a0f93ffcb..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/UserCalendars.php +++ /dev/null @@ -1,280 +0,0 @@ -<?php - -/** - * The UserCalenders class contains all calendars associated to one user - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_UserCalendars implements Sabre_DAV_IExtendedCollection, Sabre_DAVACL_IACL { - - /** - * Principal backend - * - * @var Sabre_DAVACL_IPrincipalBackend - */ - protected $principalBackend; - - /** - * CalDAV backend - * - * @var Sabre_CalDAV_Backend_Abstract - */ - protected $caldavBackend; - - /** - * Principal information - * - * @var array - */ - protected $principalInfo; - - /** - * Constructor - * - * @param Sabre_DAVACL_IPrincipalBackend $principalBackend - * @param Sabre_CalDAV_Backend_Abstract $caldavBackend - * @param mixed $userUri - */ - public function __construct(Sabre_DAVACL_IPrincipalBackend $principalBackend, Sabre_CalDAV_Backend_Abstract $caldavBackend, $userUri) { - - $this->principalBackend = $principalBackend; - $this->caldavBackend = $caldavBackend; - $this->principalInfo = $principalBackend->getPrincipalByPath($userUri); - - } - - /** - * Returns the name of this object - * - * @return string - */ - public function getName() { - - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalInfo['uri']); - return $name; - - } - - /** - * Updates the name of this object - * - * @param string $name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_Forbidden(); - - } - - /** - * Deletes this object - * - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_Forbidden(); - - } - - /** - * Returns the last modification date - * - * @return int - */ - public function getLastModified() { - - return null; - - } - - /** - * Creates a new file under this object. - * - * This is currently not allowed - * - * @param string $filename - * @param resource $data - * @return void - */ - public function createFile($filename, $data=null) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); - - } - - /** - * Creates a new directory under this object. - * - * This is currently not allowed. - * - * @param string $filename - * @return void - */ - public function createDirectory($filename) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); - - } - - /** - * Returns a single calendar, by name - * - * @param string $name - * @todo needs optimizing - * @return Sabre_CalDAV_Calendar - */ - public function getChild($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) - return $child; - - } - throw new Sabre_DAV_Exception_FileNotFound('Calendar with name \'' . $name . '\' could not be found'); - - } - - /** - * Checks if a calendar exists. - * - * @param string $name - * @todo needs optimizing - * @return bool - */ - public function childExists($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) - return true; - - } - return false; - - } - - /** - * Returns a list of calendars - * - * @return array - */ - public function getChildren() { - - $calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']); - $objs = array(); - foreach($calendars as $calendar) { - $objs[] = new Sabre_CalDAV_Calendar($this->principalBackend, $this->caldavBackend, $calendar); - } - return $objs; - - } - - /** - * Creates a new calendar - * - * @param string $name - * @param string $properties - * @return void - */ - public function createExtendedCollection($name, array $resourceType, array $properties) { - - if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar',$resourceType) || count($resourceType)!==2) { - throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); - } - $this->caldavBackend->createCalendar($this->principalInfo['uri'], $name, $properties); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->principalInfo['uri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->principalInfo['uri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-read', - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - - -} diff --git a/3rdparty/Sabre/CalDAV/Version.php b/3rdparty/Sabre/CalDAV/Version.php deleted file mode 100644 index df8fe1f6bd6fba8d724939a0ed3d9fe18014fac4..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/Version.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php - -/** - * This class contains the Sabre_CalDAV version constants. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_Version { - - /** - * Full version number - */ - const VERSION = '1.5.3'; - - /** - * Stability : alpha, beta, stable - */ - const STABILITY = 'stable'; - -} diff --git a/3rdparty/Sabre/CalDAV/XMLUtil.php b/3rdparty/Sabre/CalDAV/XMLUtil.php deleted file mode 100644 index bf349a36aae6f13418dd7f25fd1710bcc3975750..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CalDAV/XMLUtil.php +++ /dev/null @@ -1,208 +0,0 @@ -<?php - -/** - * XML utilities for CalDAV - * - * This class contains a few static methods used for parsing certain CalDAV - * requests. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CalDAV_XMLUtil { - - /** - * This function parses the calendar-query report request body - * - * The body is quite complicated, so we're turning it into a PHP - * array. - * - * The resulting associative array has xpath expressions as keys. - * By default the xpath expressions should simply be checked for existance - * The xpath expressions can point to elements or attributes. - * - * The array values can contain a number of items, which alters the query - * filter. - * - * * time-range. Must also check if the todo or event falls within the - * specified timerange. How this is interpreted depends on - * the type of object (VTODO, VEVENT, VJOURNAL, etc) - * * is-not-defined - * Instead of checking if the attribute or element exist, - * we must check if it doesn't. - * * text-match - * Checks if the value of the attribute or element matches - * the specified value. This is actually another array with - * the 'collation', 'value' and 'negate-condition' items. - * - * Refer to the CalDAV spec for more information. - * - * @param DOMNode $domNode - * @param string $basePath used for recursive calls. - * @param array $filters used for recursive calls. - * @return array - */ - static public function parseCalendarQueryFilters($domNode,$basePath = '/c:iCalendar', &$filters = array()) { - - foreach($domNode->childNodes as $child) { - - switch(Sabre_DAV_XMLUtil::toClarkNotation($child)) { - - case '{urn:ietf:params:xml:ns:caldav}comp-filter' : - case '{urn:ietf:params:xml:ns:caldav}prop-filter' : - - $filterName = $basePath . '/' . 'c:' . strtolower($child->getAttribute('name')); - $filters[$filterName] = array(); - - self::parseCalendarQueryFilters($child, $filterName,$filters); - break; - - case '{urn:ietf:params:xml:ns:caldav}time-range' : - - if ($start = $child->getAttribute('start')) { - $start = self::parseICalendarDateTime($start); - } else { - $start = null; - } - if ($end = $child->getAttribute('end')) { - $end = self::parseICalendarDateTime($end); - } else { - $end = null; - } - - if (!is_null($start) && !is_null($end) && $end <= $start) { - throw new Sabre_DAV_Exception_BadRequest('The end-date must be larger than the start-date in the time-range filter'); - } - - $filters[$basePath]['time-range'] = array( - 'start' => $start, - 'end' => $end - ); - break; - - case '{urn:ietf:params:xml:ns:caldav}is-not-defined' : - $filters[$basePath]['is-not-defined'] = true; - break; - - case '{urn:ietf:params:xml:ns:caldav}param-filter' : - - $filterName = $basePath . '/@' . strtolower($child->getAttribute('name')); - $filters[$filterName] = array(); - self::parseCalendarQueryFilters($child, $filterName, $filters); - break; - - case '{urn:ietf:params:xml:ns:caldav}text-match' : - - $collation = $child->getAttribute('collation'); - if (!$collation) $collation = 'i;ascii-casemap'; - - $filters[$basePath]['text-match'] = array( - 'collation' => ($collation == 'default'?'i;ascii-casemap':$collation), - 'negate-condition' => $child->getAttribute('negate-condition')==='yes', - 'value' => $child->nodeValue, - ); - break; - - } - - } - - return $filters; - - } - - /** - * Parses an iCalendar (rfc5545) formatted datetime and returns a DateTime object - * - * Specifying a reference timezone is optional. It will only be used - * if the non-UTC format is used. The argument is used as a reference, the - * returned DateTime object will still be in the UTC timezone. - * - * @param string $dt - * @param DateTimeZone $tz - * @return DateTime - */ - static public function parseICalendarDateTime($dt,DateTimeZone $tz = null) { - - // Format is YYYYMMDD + "T" + hhmmss - $result = preg_match('/^([1-3][0-9]{3})([0-1][0-9])([0-3][0-9])T([0-2][0-9])([0-5][0-9])([0-5][0-9])([Z]?)$/',$dt,$matches); - - if (!$result) { - throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar datetime value is incorrect: ' . $dt); - } - - if ($matches[7]==='Z' || is_null($tz)) { - $tz = new DateTimeZone('UTC'); - } - $date = new DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3] . ' ' . $matches[4] . ':' . $matches[5] .':' . $matches[6], $tz); - - // Still resetting the timezone, to normalize everything to UTC - $date->setTimeZone(new DateTimeZone('UTC')); - return $date; - - } - - /** - * Parses an iCalendar (rfc5545) formatted datetime and returns a DateTime object - * - * @param string $date - * @param DateTimeZone $tz - * @return DateTime - */ - static public function parseICalendarDate($date) { - - // Format is YYYYMMDD - $result = preg_match('/^([1-3][0-9]{3})([0-1][0-9])([0-3][0-9])$/',$date,$matches); - - if (!$result) { - throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar date value is incorrect: ' . $date); - } - - $date = new DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3], new DateTimeZone('UTC')); - return $date; - - } - - /** - * Parses an iCalendar (RFC5545) formatted duration and returns a string suitable - * for strtotime or DateTime::modify. - * - * NOTE: When we require PHP 5.3 this can be replaced by the DateTimeInterval object, which - * supports ISO 8601 Intervals, which is a superset of ICalendar durations. - * - * For now though, we're just gonna live with this messy system - * - * @param string $duration - * @return string - */ - static public function parseICalendarDuration($duration) { - - $result = preg_match('/^(?P<plusminus>\+|-)?P((?P<week>\d+)W)?((?P<day>\d+)D)?(T((?P<hour>\d+)H)?((?P<minute>\d+)M)?((?P<second>\d+)S)?)?$/', $duration, $matches); - if (!$result) { - throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar duration value is incorrect: ' . $duration); - } - - $parts = array( - 'week', - 'day', - 'hour', - 'minute', - 'second', - ); - - $newDur = ''; - foreach($parts as $part) { - if (isset($matches[$part]) && $matches[$part]) { - $newDur.=' '.$matches[$part] . ' ' . $part . 's'; - } - } - - $newDur = ($matches['plusminus']==='-'?'-':'+') . trim($newDur); - return $newDur; - - } - -} diff --git a/3rdparty/Sabre/CardDAV/AddressBook.php b/3rdparty/Sabre/CardDAV/AddressBook.php deleted file mode 100644 index 471ca7b338a7734e392ddfd92fcb0c4db8bcf729..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/AddressBook.php +++ /dev/null @@ -1,293 +0,0 @@ -<?php - -/** - * The AddressBook class represents a CardDAV addressbook, owned by a specific user - * - * The AddressBook can contain multiple vcards - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CardDAV_AddressBook extends Sabre_DAV_Collection implements Sabre_CardDAV_IAddressBook, Sabre_DAV_IProperties, Sabre_DAVACL_IACL { - - /** - * This is an array with addressbook information - * - * @var array - */ - private $addressBookInfo; - - /** - * CardDAV backend - * - * @var Sabre_CardDAV_Backend_Abstract - */ - private $carddavBackend; - - /** - * Constructor - * - * @param Sabre_CardDAV_Backend_Abstract $carddavBackend - * @param array $addressBookInfo - * @return void - */ - public function __construct(Sabre_CardDAV_Backend_Abstract $carddavBackend,array $addressBookInfo) { - - $this->carddavBackend = $carddavBackend; - $this->addressBookInfo = $addressBookInfo; - - } - - /** - * Returns the name of the addressbook - * - * @return string - */ - public function getName() { - - return $this->addressBookInfo['uri']; - - } - - /** - * Returns a card - * - * @param string $name - * @return Sabre_DAV_Card - */ - public function getChild($name) { - - $obj = $this->carddavBackend->getCard($this->addressBookInfo['id'],$name); - if (!$obj) throw new Sabre_DAV_Exception_FileNotFound('Card not found'); - return new Sabre_CardDAV_Card($this->carddavBackend,$this->addressBookInfo,$obj); - - } - - /** - * Returns the full list of cards - * - * @return array - */ - public function getChildren() { - - $objs = $this->carddavBackend->getCards($this->addressBookInfo['id']); - $children = array(); - foreach($objs as $obj) { - $children[] = new Sabre_CardDAV_Card($this->carddavBackend,$this->addressBookInfo,$obj); - } - return $children; - - } - - /** - * Creates a new directory - * - * We actually block this, as subdirectories are not allowed in addressbooks. - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating collections in addressbooks is not allowed'); - - } - - /** - * Creates a new file - * - * The contents of the new file must be a valid VCARD - * - * @param string $name - * @param resource $vcardData - * @return void - */ - public function createFile($name,$vcardData = null) { - - $vcardData = stream_get_contents($vcardData); - // Converting to UTF-8, if needed - $vcardData = Sabre_DAV_StringUtil::ensureUTF8($vcardData); - - $this->carddavBackend->createCard($this->addressBookInfo['id'],$name,$vcardData); - - } - - /** - * Deletes the entire addressbook. - * - * @return void - */ - public function delete() { - - $this->carddavBackend->deleteAddressBook($this->addressBookInfo['id']); - - } - - /** - * Renames the addressbook - * - * @param string $newName - * @return void - */ - public function setName($newName) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Renaming addressbooks is not yet supported'); - - } - - /** - * Returns the last modification date as a unix timestamp. - * - * @return void - */ - public function getLastModified() { - - return null; - - } - - /** - * Updates properties on this node, - * - * The properties array uses the propertyName in clark-notation as key, - * and the array value for the property value. In the case a property - * should be deleted, the property value will be null. - * - * This method must be atomic. If one property cannot be changed, the - * entire operation must fail. - * - * If the operation was successful, true can be returned. - * If the operation failed, false can be returned. - * - * Deletion of a non-existant property is always succesful. - * - * Lastly, it is optional to return detailed information about any - * failures. In this case an array should be returned with the following - * structure: - * - * array( - * 403 => array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param array $mutations - * @return bool|array - */ - public function updateProperties($mutations) { - - return $this->carddavBackend->updateAddressBook($this->addressBookInfo['id'], $mutations); - - } - - /** - * Returns a list of properties for this nodes. - * - * The properties list is a list of propertynames the client requested, - * encoded in clark-notation {xmlnamespace}tagname - * - * If the array is empty, it means 'all properties' were requested. - * - * @param array $properties - * @return void - */ - public function getProperties($properties) { - - $response = array(); - foreach($properties as $propertyName) { - - if (isset($this->addressBookInfo[$propertyName])) { - - $response[$propertyName] = $this->addressBookInfo[$propertyName]; - - } - - } - - return $response; - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->addressBookInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - - -} diff --git a/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php b/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php deleted file mode 100644 index 08adc3b8157ecf72d8bb7508a8e3819384ce9c1b..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/AddressBookQueryParser.php +++ /dev/null @@ -1,211 +0,0 @@ -<?php - -/** - * Parses the addressbook-query report request body. - * - * Whoever designed this format, and the CalDAV equavalent even more so, - * has no feel for design. - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CardDAV_AddressBookQueryParser { - - const TEST_ANYOF = 'anyof'; - const TEST_ALLOF = 'allof'; - - /** - * List of requested properties the client wanted - * - * @var array - */ - public $requestedProperties; - - /** - * The number of results the client wants - * - * null means it wasn't specified, which in most cases means 'all results'. - * - * @var int|null - */ - public $limit; - - /** - * List of property filters. - * - * @var array - */ - public $filters; - - /** - * Either TEST_ANYOF or TEST_ALLOF - * - * @var string - */ - public $test; - - /** - * DOM Document - * - * @var DOMDocument - */ - protected $dom; - - /** - * DOM XPath object - * - * @var DOMXPath - */ - protected $xpath; - - /** - * Creates the parser - * - * @param DOMNode $dom - * @return void - */ - public function __construct(DOMDocument $dom) { - - $this->dom = $dom; - - $this->xpath = new DOMXPath($dom); - $this->xpath->registerNameSpace('card',Sabre_CardDAV_Plugin::NS_CARDDAV); - - } - - /** - * Parses the request. - * - * @param DOMNode $dom - * @return void - */ - public function parse() { - - $filterNode = null; - - $limit = $this->xpath->evaluate('number(/card:addressbook-query/card:limit/card:nresults)'); - if (is_nan($limit)) $limit = null; - - $filter = $this->xpath->query('/card:addressbook-query/card:filter'); - if ($filter->length !== 1) { - throw new Sabre_DAV_Exception_BadRequest('Only one filter element is allowed'); - } - - $filter = $filter->item(0); - $test = $this->xpath->evaluate('string(@test)', $filter); - if (!$test) $test = self::TEST_ANYOF; - if ($test !== self::TEST_ANYOF && $test !== self::TEST_ALLOF) { - throw new Sabre_DAV_Exception_BadRequest('The test attribute must either hold "anyof" or "allof"'); - } - - $propFilters = array(); - - $propFilterNodes = $this->xpath->query('card:prop-filter', $filter); - for($ii=0; $ii < $propFilterNodes->length; $ii++) { - - $propFilters[] = $this->parsePropFilterNode($propFilterNodes->item($ii)); - - - } - - $this->filters = $propFilters; - $this->limit = $limit; - $this->requestedProperties = array_keys(Sabre_DAV_XMLUtil::parseProperties($this->dom->firstChild)); - $this->test = $test; - - } - - /** - * Parses the prop-filter xml element - * - * @param DOMElement $propFilterNode - * @return array - */ - protected function parsePropFilterNode(DOMElement $propFilterNode) { - - $propFilter = array(); - $propFilter['name'] = $propFilterNode->getAttribute('name'); - $propFilter['test'] = $propFilterNode->getAttribute('test'); - if (!$propFilter['test']) $propFilter['test'] = 'anyof'; - - $propFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $propFilterNode)->length>0; - - $paramFilterNodes = $this->xpath->query('card:param-filter', $propFilterNode); - - $propFilter['param-filters'] = array(); - - - for($ii=0;$ii<$paramFilterNodes->length;$ii++) { - - $propFilter['param-filters'][] = $this->parseParamFilterNode($paramFilterNodes->item($ii)); - - } - $propFilter['text-matches'] = array(); - $textMatchNodes = $this->xpath->query('card:text-match', $propFilterNode); - - for($ii=0;$ii<$textMatchNodes->length;$ii++) { - - $propFilter['text-matches'][] = $this->parseTextMatchNode($textMatchNodes->item($ii)); - - } - - return $propFilter; - - } - - /** - * Parses the param-filter element - * - * @param DOMElement $paramFilterNode - * @return array - */ - public function parseParamFilterNode(DOMElement $paramFilterNode) { - - $paramFilter = array(); - $paramFilter['name'] = $paramFilterNode->getAttribute('name'); - $paramFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $paramFilterNode)->length>0; - $paramFilter['text-match'] = null; - - $textMatch = $this->xpath->query('card:text-match', $paramFilterNode); - if ($textMatch->length>0) { - $paramFilter['text-match'] = $this->parseTextMatchNode($textMatch->item(0)); - } - - return $paramFilter; - - } - - /** - * Text match - * - * @param DOMElement $textMatchNode - * @return void - */ - public function parseTextMatchNode(DOMElement $textMatchNode) { - - $matchType = $textMatchNode->getAttribute('match-type'); - if (!$matchType) $matchType = 'contains'; - - if (!in_array($matchType, array('contains', 'equals', 'starts-with', 'ends-with'))) { - throw new Sabre_DAV_Exception_BadRequest('Unknown match-type: ' . $matchType); - } - - $negateCondition = $textMatchNode->getAttribute('negate-condition'); - $negateCondition = $negateCondition==='yes'; - $collation = $textMatchNode->getAttribute('collation'); - if (!$collation) $collation = 'i;unicode-casemap'; - - return array( - 'negate-condition' => $negateCondition, - 'collation' => $collation, - 'match-type' => $matchType, - 'value' => $textMatchNode->nodeValue - ); - - - } - -} diff --git a/3rdparty/Sabre/CardDAV/AddressBookRoot.php b/3rdparty/Sabre/CardDAV/AddressBookRoot.php deleted file mode 100644 index 1a80efba35e38e58251f0b13e815843f5e4d8f06..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/AddressBookRoot.php +++ /dev/null @@ -1,78 +0,0 @@ -<?php - -/** - * AddressBook rootnode - * - * This object lists a collection of users, which can contain addressbooks. - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CardDAV_AddressBookRoot extends Sabre_DAVACL_AbstractPrincipalCollection { - - /** - * Principal Backend - * - * @var Sabre_DAVACL_IPrincipalBackend - */ - protected $principalBackend; - - /** - * CardDAV backend - * - * @var Sabre_CardDAV_Backend_Abstract - */ - protected $carddavBackend; - - /** - * Constructor - * - * This constructor needs both a principal and a carddav backend. - * - * By default this class will show a list of addressbook collections for - * principals in the 'principals' collection. If your main principals are - * actually located in a different path, use the $principalPrefix argument - * to override this. - * - * @param Sabre_DAVACL_IPrincipalBackend $principalBackend - * @param Sabre_CardDAV_Backend_Abstract $carddavBackend - * @param string $principalPrefix - */ - public function __construct(Sabre_DAVACL_IPrincipalBackend $principalBackend,Sabre_CardDAV_Backend_Abstract $carddavBackend, $principalPrefix = 'principals') { - - $this->carddavBackend = $carddavBackend; - parent::__construct($principalBackend, $principalPrefix); - - } - - /** - * Returns the name of the node - * - * @return string - */ - public function getName() { - - return Sabre_CardDAV_Plugin::ADDRESSBOOK_ROOT; - - } - - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principal - * @return Sabre_DAV_INode - */ - public function getChildForPrincipal(array $principal) { - - return new Sabre_CardDAV_UserAddressBooks($this->carddavBackend, $principal['uri']); - - } - -} diff --git a/3rdparty/Sabre/CardDAV/Backend/Abstract.php b/3rdparty/Sabre/CardDAV/Backend/Abstract.php deleted file mode 100644 index 1f0253ddab802d28fbdbe121311fcb88f28af02c..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/Backend/Abstract.php +++ /dev/null @@ -1,121 +0,0 @@ -<?php - -/** - * Abstract Backend class - * - * This class serves as a base-class for addressbook backends - * - * Note that there are references to 'addressBookId' scattered throughout the - * class. The value of the addressBookId is completely up to you, it can be any - * arbitrary value you can use as an unique identifier. - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_CardDAV_Backend_Abstract { - - /** - * Returns the list of addressbooks for a specific user. - * - * Every addressbook should have the following properties: - * id - an arbitrary unique id - * uri - the 'basename' part of the url - * principaluri - Same as the passed parameter - * - * Any additional clark-notation property may be passed besides this. Some - * common ones are : - * {DAV:}displayname - * {urn:ietf:params:xml:ns:carddav}addressbook-description - * {http://calendarserver.org/ns/}getctag - * - * @param string $principalUri - * @return array - */ - public abstract function getAddressBooksForUser($principalUri); - - /** - * Updates an addressbook's properties - * - * See Sabre_DAV_IProperties for a description of the mutations array, as - * well as the return value. - * - * @param mixed $addressBookId - * @param array $mutations - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public abstract function updateAddressBook($addressBookId, array $mutations); - - /** - * Creates a new address book - * - * @param string $principalUri - * @param string $url Just the 'basename' of the url. - * @param array $properties - * @return void - */ - abstract public function createAddressBook($principalUri, $url, array $properties); - - /** - * Deletes an entire addressbook and all its contents - * - * @param mixed $addressBookId - * @return void - */ - abstract public function deleteAddressBook($addressBookId); - - /** - * Returns all cards for a specific addressbook id. - * - * This method should return the following properties for each card: - * * carddata - raw vcard data - * * uri - Some unique url - * * lastmodified - A unix timestamp - - * @param mixed $addressbookId - * @return array - */ - public abstract function getCards($addressbookId); - - /** - * Returns a specfic card - * - * @param mixed $addressBookId - * @param string $cardUri - * @return void - */ - public abstract function getCard($addressBookId, $cardUri); - - /** - * Creates a new card - * - * @param mixed $addressBookId - * @param string $cardUri - * @param string $cardData - * @return bool - */ - abstract public function createCard($addressBookId, $cardUri, $cardData); - - /** - * Updates a card - * - * @param mixed $addressBookId - * @param string $cardUri - * @param string $cardData - * @return bool - */ - abstract public function updateCard($addressBookId, $cardUri, $cardData); - - /** - * Deletes a card - * - * @param mixed $addressBookId - * @param string $cardUri - * @return bool - */ - abstract public function deleteCard($addressBookId, $cardUri); - -} diff --git a/3rdparty/Sabre/CardDAV/Backend/PDO.php b/3rdparty/Sabre/CardDAV/Backend/PDO.php deleted file mode 100644 index f4e44610ccf1146bc3acf3548f23a78d91797977..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/Backend/PDO.php +++ /dev/null @@ -1,277 +0,0 @@ -<?php - -/** - * PDO CardDAV backend - * - * This CardDAV backend uses PDO to store addressbooks - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CardDAV_Backend_PDO extends Sabre_CardDAV_Backend_Abstract { - - /** - * PDO connection - * - * @var PDO - */ - protected $pdo; - - /** - * The PDO table name used to store addressbooks - */ - protected $addressBooksTableName; - - /** - * The PDO table name used to store cards - */ - protected $cardsTableName; - - /** - * Sets up the object - * - * @param PDO $pdo - */ - public function __construct(PDO $pdo, $addressBooksTableName = 'addressbooks', $cardsTableName = 'cards') { - - $this->pdo = $pdo; - $this->addressBooksTableName = $addressBooksTableName; - $this->cardsTableName = $cardsTableName; - - } - - /** - * Returns the list of addressbooks for a specific user. - * - * @param string $principalUri - * @return array - */ - public function getAddressBooksForUser($principalUri) { - - $stmt = $this->pdo->prepare('SELECT id, uri, displayname, principaluri, description, ctag FROM `'.$this->addressBooksTableName.'` WHERE principaluri = ?'); - $result = $stmt->execute(array($principalUri)); - - $addressBooks = array(); - - foreach($stmt->fetchAll() as $row) { - - $addressBooks[] = array( - 'id' => $row['id'], - 'uri' => $row['uri'], - 'principaluri' => $row['principaluri'], - '{DAV:}displayname' => $row['displayname'], - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'], - '{http://calendarserver.org/ns/}getctag' => $row['ctag'], - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => - new Sabre_CardDAV_Property_SupportedAddressData(), - ); - - } - - return $addressBooks; - - } - - - /** - * Updates an addressbook's properties - * - * See Sabre_DAV_IProperties for a description of the mutations array, as - * well as the return value. - * - * @param mixed $addressBookId - * @param array $mutations - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public function updateAddressBook($addressBookId, array $mutations) { - - $updates = array(); - - foreach($mutations as $property=>$newValue) { - - switch($property) { - case '{DAV:}displayname' : - $updates['displayname'] = $newValue; - break; - case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : - $updates['description'] = $newValue; - break; - default : - // If any unsupported values were being updated, we must - // let the entire request fail. - return false; - } - - } - - // No values are being updated? - if (!$updates) { - return false; - } - - $query = 'UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 '; - foreach($updates as $key=>$value) { - $query.=', `' . $key . '` = :' . $key . ' '; - } - $query.=' WHERE id = :addressbookid'; - - $stmt = $this->pdo->prepare($query); - $updates['addressbookid'] = $addressBookId; - - $stmt->execute($updates); - - return true; - - } - - /** - * Creates a new address book - * - * @param string $principalUri - * @param string $url Just the 'basename' of the url. - * @param array $properties - * @return void - */ - public function createAddressBook($principalUri, $url, array $properties) { - - $values = array( - 'displayname' => null, - 'description' => null, - 'principaluri' => $principalUri, - 'uri' => $url, - ); - - foreach($properties as $property=>$newValue) { - - switch($property) { - case '{DAV:}displayname' : - $values['displayname'] = $newValue; - break; - case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : - $values['description'] = $newValue; - break; - default : - throw new Sabre_DAV_Exception_BadRequest('Unknown property: ' . $property); - } - - } - - $query = 'INSERT INTO `' . $this->addressBooksTableName . '` (uri, displayname, description, principaluri, ctag) VALUES (:uri, :displayname, :description, :principaluri, 1)'; - $stmt = $this->pdo->prepare($query); - $stmt->execute($values); - - } - - /** - * Deletes an entire addressbook and all its contents - * - * @param int $addressBookId - * @return void - */ - public function deleteAddressBook($addressBookId) { - - $stmt = $this->pdo->prepare('DELETE FROM `' . $this->cardsTableName . '` WHERE addressbookid = ?'); - $stmt->execute(array($addressBookId)); - - $stmt = $this->pdo->prepare('DELETE FROM `' . $this->addressBooksTableName . '` WHERE id = ?'); - $stmt->execute(array($addressBookId)); - - } - - /** - * Returns all cards for a specific addressbook id. - * - * @param mixed $addressbookId - * @return array - */ - public function getCards($addressbookId) { - - $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM `' . $this->cardsTableName . '` WHERE addressbookid = ?'); - $stmt->execute(array($addressbookId)); - - return $stmt->fetchAll(PDO::FETCH_ASSOC); - - - } - /** - * Returns a specfic card - * - * @param mixed $addressBookId - * @param string $cardUri - * @return array - */ - public function getCard($addressBookId, $cardUri) { - - $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM `' . $this->cardsTableName . '` WHERE addressbookid = ? AND uri = ? LIMIT 1'); - $stmt->execute(array($addressBookId, $cardUri)); - - $result = $stmt->fetchAll(PDO::FETCH_ASSOC); - - return (count($result)>0?$result[0]:false); - - } - - /** - * Creates a new card - * - * @param mixed $addressBookId - * @param string $cardUri - * @param string $cardData - * @return bool - */ - public function createCard($addressBookId, $cardUri, $cardData) { - - $stmt = $this->pdo->prepare('INSERT INTO `' . $this->cardsTableName . '` (carddata, uri, lastmodified, addressbookid) VALUES (?, ?, ?, ?)'); - - $result = $stmt->execute(array($cardData, $cardUri, time(), $addressBookId)); - - $stmt2 = $this->pdo->prepare('UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 WHERE id = ?'); - $stmt2->execute(array($addressBookId)); - - return $result; - - } - - /** - * Updates a card - * - * @param mixed $addressBookId - * @param string $cardUri - * @param string $cardData - * @return bool - */ - public function updateCard($addressBookId, $cardUri, $cardData) { - - $stmt = $this->pdo->prepare('UPDATE `' . $this->cardsTableName . '` SET carddata = ?, lastmodified = ? WHERE uri = ? AND addressbookid =?'); - $result = $stmt->execute(array($cardData, time(), $cardUri, $addressBookId)); - - $stmt2 = $this->pdo->prepare('UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 WHERE id = ?'); - $stmt2->execute(array($addressBookId)); - - return $stmt->rowCount()===1; - - } - - /** - * Deletes a card - * - * @param mixed $addressBookId - * @param string $cardUri - * @return bool - */ - public function deleteCard($addressBookId, $cardUri) { - - $stmt = $this->pdo->prepare('DELETE FROM `' . $this->cardsTableName . '` WHERE addressbookid = ? AND uri = ?'); - $stmt->execute(array($addressBookId, $cardUri)); - - $stmt2 = $this->pdo->prepare('UPDATE `' . $this->addressBooksTableName . '` SET ctag = ctag + 1 WHERE id = ?'); - $stmt2->execute(array($addressBookId)); - - return $stmt->rowCount()===1; - - } -} diff --git a/3rdparty/Sabre/CardDAV/Card.php b/3rdparty/Sabre/CardDAV/Card.php deleted file mode 100644 index 2844eaf7ed6b06f06f3a6fbea2c609a544cc16dd..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/Card.php +++ /dev/null @@ -1,220 +0,0 @@ -<?php - -/** - * The Card object represents a single Card from an addressbook - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CardDAV_Card extends Sabre_DAV_File implements Sabre_CardDAV_ICard, Sabre_DAVACL_IACL { - - /** - * CardDAV backend - * - * @var Sabre_CardDAV_Backend_Abstract - */ - private $carddavBackend; - - /** - * Array with information about this Card - * - * @var array - */ - private $cardData; - - /** - * Array with information about the containing addressbook - * - * @var array - */ - private $addressBookInfo; - - /** - * Constructor - * - * @param Sabre_CardDAV_Backend_Abstract $carddavBackend - * @param array $addressBookInfo - * @param array $cardData - */ - public function __construct(Sabre_CardDAV_Backend_Abstract $carddavBackend,array $addressBookInfo,array $cardData) { - - $this->carddavBackend = $carddavBackend; - $this->addressBookInfo = $addressBookInfo; - $this->cardData = $cardData; - - } - - /** - * Returns the uri for this object - * - * @return string - */ - public function getName() { - - return $this->cardData['uri']; - - } - - /** - * Returns the VCard-formatted object - * - * @return string - */ - public function get() { - - $cardData = $this->cardData['carddata']; - $s = fopen('php://temp','r+'); - fwrite($s, $cardData); - rewind($s); - return $s; - - } - - /** - * Updates the VCard-formatted object - * - * @param string $cardData - * @return void - */ - public function put($cardData) { - - if (is_resource($cardData)) - $cardData = stream_get_contents($cardData); - - // Converting to UTF-8, if needed - $cardData = Sabre_DAV_StringUtil::ensureUTF8($cardData); - - $this->carddavBackend->updateCard($this->addressBookInfo['id'],$this->cardData['uri'],$cardData); - $this->cardData['carddata'] = $cardData; - - } - - /** - * Deletes the card - * - * @return void - */ - public function delete() { - - $this->carddavBackend->deleteCard($this->addressBookInfo['id'],$this->cardData['uri']); - - } - - /** - * Returns the mime content-type - * - * @return string - */ - public function getContentType() { - - return 'text/x-vcard'; - - } - - /** - * Returns an ETag for this object - * - * @return string - */ - public function getETag() { - - return '"' . md5($this->cardData['carddata']) . '"'; - - } - - /** - * Returns the last modification date as a unix timestamp - * - * @return time - */ - public function getLastModified() { - - return isset($this->cardData['lastmodified'])?$this->cardData['lastmodified']:null; - - } - - /** - * Returns the size of this object in bytes - * - * @return int - */ - public function getSize() { - - return strlen($this->cardData['carddata']); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->addressBookInfo['principaluri']; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->addressBookInfo['principaluri'], - 'protected' => true, - ), - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - -} - diff --git a/3rdparty/Sabre/CardDAV/IAddressBook.php b/3rdparty/Sabre/CardDAV/IAddressBook.php deleted file mode 100644 index a0dffb30aea5c11cda8c04731c1068cc3c776089..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/IAddressBook.php +++ /dev/null @@ -1,18 +0,0 @@ -<?php - -/** - * AddressBook interface - * - * Implement this interface to allow a node to be recognized as an addressbook. - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_CardDAV_IAddressBook extends Sabre_DAV_ICollection { - - - -} diff --git a/3rdparty/Sabre/CardDAV/ICard.php b/3rdparty/Sabre/CardDAV/ICard.php deleted file mode 100644 index 25bcc551b73d98994a9c5c4d4d13eec939768e15..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/ICard.php +++ /dev/null @@ -1,18 +0,0 @@ -<?php - -/** - * Card interface - * - * Extend the ICard interface to allow your custom nodes to be picked up as - * 'Cards'. - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_CardDAV_ICard extends Sabre_DAV_IFile { - -} - diff --git a/3rdparty/Sabre/CardDAV/IDirectory.php b/3rdparty/Sabre/CardDAV/IDirectory.php deleted file mode 100644 index e0d0797d285bb8e1dae530513c51d6d47e78856e..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/IDirectory.php +++ /dev/null @@ -1,21 +0,0 @@ -<?php - -/** - * IDirectory interface - * - * Implement this interface to have an addressbook marked as a 'directory'. A - * directory is an (often) global addressbook. - * - * A full description can be found in the IETF draft: - * - draft-daboo-carddav-directory-gateway - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_CardDAV_IDirectory extends Sabre_CardDAV_IAddressBook { - - -} diff --git a/3rdparty/Sabre/CardDAV/Plugin.php b/3rdparty/Sabre/CardDAV/Plugin.php deleted file mode 100644 index 14c9c72b0d532e5d009135547b9136396c15ab4e..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/Plugin.php +++ /dev/null @@ -1,463 +0,0 @@ -<?php - -/** - * CardDAV plugin - * - * The CardDAV plugin adds CardDAV functionality to the WebDAV server - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { - - /** - * Url to the addressbooks - */ - const ADDRESSBOOK_ROOT = 'addressbooks'; - - /** - * xml namespace for CardDAV elements - */ - const NS_CARDDAV = 'urn:ietf:params:xml:ns:carddav'; - - /** - * Add urls to this property to have them automatically exposed as - * 'directories' to the user. - * - * @var array - */ - public $directories = array(); - - /** - * Server class - * - * @var Sabre_DAV_Server - */ - protected $server; - - /** - * Initializes the plugin - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - /* Events */ - $server->subscribeEvent('beforeGetProperties', array($this, 'beforeGetProperties')); - $server->subscribeEvent('report', array($this,'report')); - - /* Namespaces */ - $server->xmlNamespaces[self::NS_CARDDAV] = 'card'; - - /* Mapping Interfaces to {DAV:}resourcetype values */ - $server->resourceTypeMapping['Sabre_CardDAV_IAddressBook'] = '{' . self::NS_CARDDAV . '}addressbook'; - $server->resourceTypeMapping['Sabre_CardDAV_IDirectory'] = '{' . self::NS_CARDDAV . '}directory'; - - /* Adding properties that may never be changed */ - $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}supported-address-data'; - $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}max-resource-size'; - - - $this->server = $server; - - } - - /** - * Returns a list of supported features. - * - * This is used in the DAV: header in the OPTIONS and PROPFIND requests. - * - * @return array - */ - public function getFeatures() { - - return array('addressbook'); - - } - - /** - * Returns a list of reports this plugin supports. - * - * This will be used in the {DAV:}supported-report-set property. - * Note that you still need to subscribe to the 'report' event to actually - * implement them - * - * @param string $uri - * @return array - */ - public function getSupportedReportSet($uri) { - - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_CardDAV_IAddressBook || $node instanceof Sabre_CardDAV_ICard) { - return array( - '{' . self::NS_CARDDAV . '}addressbook-multiget', - '{' . self::NS_CARDDAV . '}addressbook-query', - ); - } - return array(); - - } - - - /** - * Adds all CardDAV-specific properties - * - * @param string $path - * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties - * @return void - */ - public function beforeGetProperties($path, Sabre_DAV_INode $node, array &$requestedProperties, array &$returnedProperties) { - - if ($node instanceof Sabre_DAVACL_IPrincipal) { - - // calendar-home-set property - $addHome = '{' . self::NS_CARDDAV . '}addressbook-home-set'; - if (in_array($addHome,$requestedProperties)) { - $principalId = $node->getName(); - $addressbookHomePath = self::ADDRESSBOOK_ROOT . '/' . $principalId . '/'; - unset($requestedProperties[array_search($addHome, $requestedProperties)]); - $returnedProperties[200][$addHome] = new Sabre_DAV_Property_Href($addressbookHomePath); - } - - $directories = '{' . self::NS_CARDDAV . '}directory-gateway'; - if ($this->directories && in_array($directories, $requestedProperties)) { - unset($requestedProperties[array_search($directories, $requestedProperties)]); - $returnedProperties[200][$directories] = new Sabre_DAV_Property_HrefList($this->directories); - } - - } - - if ($node instanceof Sabre_CardDAV_ICard) { - - // The address-data property is not supposed to be a 'real' - // property, but in large chunks of the spec it does act as such. - // Therefore we simply expose it as a property. - $addressDataProp = '{' . self::NS_CARDDAV . '}address-data'; - if (in_array($addressDataProp, $requestedProperties)) { - unset($requestedProperties[$addressDataProp]); - $val = $node->get(); - if (is_resource($val)) - $val = stream_get_contents($val); - - // Taking out \r to not screw up the xml output - $returnedProperties[200][$addressDataProp] = str_replace("\r","", $val); - - } - } - - } - - /** - * This functions handles REPORT requests specific to CardDAV - * - * @param string $reportName - * @param DOMNode $dom - * @return bool - */ - public function report($reportName,$dom) { - - switch($reportName) { - case '{'.self::NS_CARDDAV.'}addressbook-multiget' : - $this->addressbookMultiGetReport($dom); - return false; - case '{'.self::NS_CARDDAV.'}addressbook-query' : - $this->addressBookQueryReport($dom); - return false; - default : - return; - - } - - - } - - /** - * This function handles the addressbook-multiget REPORT. - * - * This report is used by the client to fetch the content of a series - * of urls. Effectively avoiding a lot of redundant requests. - * - * @param DOMNode $dom - * @return void - */ - public function addressbookMultiGetReport($dom) { - - $properties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); - - $hrefElems = $dom->getElementsByTagNameNS('urn:DAV','href'); - $propertyList = array(); - - foreach($hrefElems as $elem) { - - $uri = $this->server->calculateUri($elem->nodeValue); - list($propertyList[]) = $this->server->getPropertiesForPath($uri,$properties); - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList)); - - } - - /** - * This function handles the addressbook-query REPORT - * - * This report is used by the client to filter an addressbook based on a - * complex query. - * - * @param DOMNode $dom - * @return void - */ - protected function addressbookQueryReport($dom) { - - $query = new Sabre_CardDAV_AddressBookQueryParser($dom); - $query->parse(); - - $depth = $this->server->getHTTPDepth(0); - - if ($depth==0) { - $candidateNodes = array( - $this->server->tree->getNodeForPath($this->server->getRequestUri()) - ); - } else { - $candidateNodes = $this->server->tree->getChildren($this->server->getRequestUri()); - } - - $validNodes = array(); - foreach($candidateNodes as $node) { - - if (!$node instanceof Sabre_CardDAV_ICard) - continue; - - $blob = $node->get(); - if (is_resource($blob)) { - $blob = stream_get_contents($blob); - } - - if (!$this->validateFilters($blob, $query->filters, $query->test)) { - continue; - } - - $validNodes[] = $node; - - if ($query->limit && $query->limit <= count($validNodes)) { - // We hit the maximum number of items, we can stop now. - break; - } - - } - - $result = array(); - foreach($validNodes as $validNode) { - if ($depth==0) { - $href = $this->server->getRequestUri(); - } else { - $href = $this->server->getRequestUri() . '/' . $validNode->getName(); - } - - list($result[]) = $this->server->getPropertiesForPath($href, $query->requestedProperties, 0); - - } - - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendBody($this->server->generateMultiStatus($result)); - - } - - /** - * Validates if a vcard makes it throught a list of filters. - * - * @param string $vcardData - * @param array $filters - * @param string $test anyof or allof (which means OR or AND) - * @return bool - */ - public function validateFilters($vcardData, array $filters, $test) { - - $vcard = Sabre_VObject_Reader::read($vcardData); - - $success = true; - - foreach($filters as $filter) { - - $isDefined = isset($vcard->{$filter['name']}); - if ($filter['is-not-defined']) { - if ($isDefined) { - $success = false; - } else { - $success = true; - } - } elseif ((!$filter['param-filters'] && !$filter['text-matches']) || !$isDefined) { - - // We only need to check for existence - $success = $isDefined; - - } else { - - $vProperties = $vcard->select($filter['name']); - - $results = array(); - if ($filter['param-filters']) { - $results[] = $this->validateParamFilters($vProperties, $filter['param-filters'], $filter['test']); - } - if ($filter['text-matches']) { - $texts = array(); - foreach($vProperties as $vProperty) - $texts[] = $vProperty->value; - - $results[] = $this->validateTextMatches($texts, $filter['text-matches'], $filter['test']); - } - - if (count($results)===1) { - $success = $results[0]; - } else { - if ($filter['test'] === 'anyof') { - $success = $results[0] || $results[1]; - } else { - $success = $results[0] && $results[1]; - } - } - - } // else - - // There are two conditions where we can already determine wether - // or not this filter succeeds. - if ($test==='anyof' && $success) { - return true; - } - if ($test==='allof' && !$success) { - return false; - } - - } // foreach - - // If we got all the way here, it means we haven't been able to - // determine early if the test failed or not. - // - // This implies for 'anyof' that the test failed, and for 'allof' that - // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - - } - - /** - * Validates if a param-filter can be applied to a specific property. - * - * @todo currently we're only validating the first parameter of the passed - * property. Any subsequence parameters with the same name are - * ignored. - * @param Sabre_VObject_Property $vProperty - * @param array $filters - * @param string $test - * @return bool - */ - protected function validateParamFilters(array $vProperties, array $filters, $test) { - - $success = false; - foreach($filters as $filter) { - - $isDefined = false; - foreach($vProperties as $vProperty) { - $isDefined = isset($vProperty[$filter['name']]); - if ($isDefined) break; - } - - if ($filter['is-not-defined']) { - if ($isDefined) { - $success = false; - } else { - $success = true; - } - - // If there's no text-match, we can just check for existence - } elseif (!$filter['text-match'] || !$isDefined) { - - $success = $isDefined; - - } else { - - $texts = array(); - $success = false; - foreach($vProperties as $vProperty) { - // If we got all the way here, we'll need to validate the - // text-match filter. - $success = Sabre_DAV_StringUtil::textMatch($vProperty[$filter['name']]->value, $filter['text-match']['value'], $filter['text-match']['collation'], $filter['text-match']['match-type']); - if ($success) break; - } - if ($filter['text-match']['negate-condition']) { - $success = !$success; - } - - } // else - - // There are two conditions where we can already determine wether - // or not this filter succeeds. - if ($test==='anyof' && $success) { - return true; - } - if ($test==='allof' && !$success) { - return false; - } - - } - - // If we got all the way here, it means we haven't been able to - // determine early if the test failed or not. - // - // This implies for 'anyof' that the test failed, and for 'allof' that - // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - - } - - /** - * Validates if a text-filter can be applied to a specific property. - * - * @param array $texts - * @param array $filters - * @param string $test - * @return bool - */ - protected function validateTextMatches(array $texts, array $filters, $test) { - - foreach($filters as $filter) { - - $success = false; - foreach($texts as $haystack) { - $success = Sabre_DAV_StringUtil::textMatch($haystack, $filter['value'], $filter['collation'], $filter['match-type']); - - // Breaking on the first match - if ($success) break; - } - if ($filter['negate-condition']) { - $success = !$success; - } - - if ($success && $test==='anyof') - return true; - - if (!$success && $test=='allof') - return false; - - - } - - // If we got all the way here, it means we haven't been able to - // determine early if the test failed or not. - // - // This implies for 'anyof' that the test failed, and for 'allof' that - // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - - } - - -} diff --git a/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php b/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php deleted file mode 100644 index d57d3a6e7bdfb3494b4f48300029e553e3c4f57c..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php - -/** - * Supported-address-data property - * - * This property is a representation of the supported-address-data property - * in the CardDAV namespace. - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CardDAV_Property_SupportedAddressData extends Sabre_DAV_Property { - - /** - * supported versions - * - * @var array - */ - protected $supportedData = array(); - - /** - * Creates the property - * - * @param array $components - */ - public function __construct(array $supportedData = null) { - - if (is_null($supportedData)) { - $supportedData = array( - array('contentType' => 'text/vcard', 'version' => '3.0'), - array('contentType' => 'text/vcard', 'version' => '4.0'), - ); - } - - $this->supportedData = $supportedData; - - } - - /** - * Serializes the property in a DOMDocument - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - - $prefix = - isset($server->xmlNamespaces[Sabre_CardDAV_Plugin::NS_CARDDAV]) ? - $server->xmlNamespaces[Sabre_CardDAV_Plugin::NS_CARDDAV] : - 'card'; - - foreach($this->supportedData as $supported) { - - $caldata = $doc->createElementNS(Sabre_CardDAV_Plugin::NS_CARDDAV, $prefix . ':address-data-type'); - $caldata->setAttribute('content-type',$supported['contentType']); - $caldata->setAttribute('version',$supported['version']); - $node->appendChild($caldata); - - } - - } - -} diff --git a/3rdparty/Sabre/CardDAV/UserAddressBooks.php b/3rdparty/Sabre/CardDAV/UserAddressBooks.php deleted file mode 100644 index e9f2de7f741e0ed553911b3acf61e973390932ed..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/UserAddressBooks.php +++ /dev/null @@ -1,240 +0,0 @@ -<?php - -/** - * UserAddressBooks class - * - * The UserAddressBooks collection contains a list of addressbooks associated with a user - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CardDAV_UserAddressBooks extends Sabre_DAV_Collection implements Sabre_DAV_IExtendedCollection, Sabre_DAVACL_IACL { - - /** - * Principal uri - * - * @var array - */ - protected $principalUri; - - /** - * carddavBackend - * - * @var Sabre_CardDAV_Backend_Abstract - */ - protected $carddavBackend; - - /** - * Constructor - * - * @param Sabre_CardDAV_Backend_Abstract $carddavBackend - * @param string $principalUri - */ - public function __construct(Sabre_CardDAV_Backend_Abstract $carddavBackend, $principalUri) { - - $this->carddavBackend = $carddavBackend; - $this->principalUri = $principalUri; - - } - - /** - * Returns the name of this object - * - * @return string - */ - public function getName() { - - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalUri); - return $name; - - } - - /** - * Updates the name of this object - * - * @param string $name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_MethodNotAllowed(); - - } - - /** - * Deletes this object - * - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_MethodNotAllowed(); - - } - - /** - * Returns the last modification date - * - * @return int - */ - public function getLastModified() { - - return null; - - } - - /** - * Creates a new file under this object. - * - * This is currently not allowed - * - * @param string $filename - * @param resource $data - * @return void - */ - public function createFile($filename, $data=null) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); - - } - - /** - * Creates a new directory under this object. - * - * This is currently not allowed. - * - * @param string $filename - * @return void - */ - public function createDirectory($filename) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); - - } - - /** - * Returns a single calendar, by name - * - * @param string $name - * @todo needs optimizing - * @return Sabre_CardDAV_AddressBook - */ - public function getChild($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) - return $child; - - } - throw new Sabre_DAV_Exception_FileNotFound('Addressbook with name \'' . $name . '\' could not be found'); - - } - - /** - * Returns a list of addressbooks - * - * @return array - */ - public function getChildren() { - - $addressbooks = $this->carddavBackend->getAddressbooksForUser($this->principalUri); - $objs = array(); - foreach($addressbooks as $addressbook) { - $objs[] = new Sabre_CardDAV_AddressBook($this->carddavBackend, $addressbook); - } - return $objs; - - } - - /** - * Creates a new addressbook - * - * @param string $name - * @param array $resourceType - * @param array $properties - * @return void - */ - public function createExtendedCollection($name, array $resourceType, array $properties) { - - if (!in_array('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook',$resourceType) || count($resourceType)!==2) { - throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); - } - $this->carddavBackend->createAddressBook($this->principalUri, $name, $properties); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->principalUri; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalUri, - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->principalUri, - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - -} diff --git a/3rdparty/Sabre/CardDAV/Version.php b/3rdparty/Sabre/CardDAV/Version.php deleted file mode 100644 index 900fbf5e75c22861fd27901ea93ae8fe81c211b5..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/CardDAV/Version.php +++ /dev/null @@ -1,26 +0,0 @@ -<?php - -/** - * Version Class - * - * This class contains the Sabre_CardDAV version information - * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_CardDAV_Version { - - /** - * Full version number - */ - const VERSION = '1.5.3'; - - /** - * Stability : alpha, beta, stable - */ - const STABILITY = 'stable'; - -} diff --git a/3rdparty/Sabre/DAV/Auth/Backend/AbstractBasic.php b/3rdparty/Sabre/DAV/Auth/Backend/AbstractBasic.php deleted file mode 100644 index 11bab8c7af78b024f568a753af54af8c0be93444..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/AbstractBasic.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/** - * HTTP Basic authentication backend class - * - * This class can be used by authentication objects wishing to use HTTP Basic - * Most of the digest logic is handled, implementors just need to worry about - * the validateUserPass method. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author James David Low (http://jameslow.com/) - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_Auth_Backend_AbstractBasic implements Sabre_DAV_Auth_IBackend { - - /** - * This variable holds the currently logged in username. - * - * @var string|null - */ - protected $currentUser; - - /** - * Validates a username and password - * - * This method should return true or false depending on if login - * succeeded. - * - * @return bool - */ - abstract protected function validateUserPass($username, $password); - - /** - * Returns information about the currently logged in username. - * - * If nobody is currently logged in, this method should return null. - * - * @return string|null - */ - public function getCurrentUser() { - return $this->currentUser; - } - - - /** - * Authenticates the user based on the current request. - * - * If authentication is succesful, true must be returned. - * If authentication fails, an exception must be thrown. - * - * @throws Sabre_DAV_Exception_NotAuthenticated - * @return bool - */ - public function authenticate(Sabre_DAV_Server $server,$realm) { - - $auth = new Sabre_HTTP_BasicAuth(); - $auth->setHTTPRequest($server->httpRequest); - $auth->setHTTPResponse($server->httpResponse); - $auth->setRealm($realm); - $userpass = $auth->getUserPass(); - if (!$userpass) { - $auth->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('No basic authentication headers were found'); - } - - // Authenticates the user - if (!$this->validateUserPass($userpass[0],$userpass[1])) { - $auth->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('Username or password does not match'); - } - $this->currentUser = $userpass[0]; - return true; - } - - -} - diff --git a/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php b/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php deleted file mode 100644 index 5bdc72753ece623b8bb5c9634c42d7494ba7ccf5..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php +++ /dev/null @@ -1,96 +0,0 @@ -<?php - -/** - * HTTP Digest authentication backend class - * - * This class can be used by authentication objects wishing to use HTTP Digest - * Most of the digest logic is handled, implementors just need to worry about - * the getDigestHash method - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_Auth_Backend_AbstractDigest implements Sabre_DAV_Auth_IBackend { - - /** - * This variable holds the currently logged in username. - * - * @var array|null - */ - protected $currentUser; - - /** - * Returns a users digest hash based on the username and realm. - * - * If the user was not known, null must be returned. - * - * @param string $realm - * @param string $username - * @return string|null - */ - abstract public function getDigestHash($realm,$username); - - /** - * Authenticates the user based on the current request. - * - * If authentication is succesful, true must be returned. - * If authentication fails, an exception must be thrown. - * - * @throws Sabre_DAV_Exception_NotAuthenticated - * @return bool - */ - public function authenticate(Sabre_DAV_Server $server,$realm) { - - $digest = new Sabre_HTTP_DigestAuth(); - - // Hooking up request and response objects - $digest->setHTTPRequest($server->httpRequest); - $digest->setHTTPResponse($server->httpResponse); - - $digest->setRealm($realm); - $digest->init(); - - $username = $digest->getUsername(); - - // No username was given - if (!$username) { - $digest->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('No digest authentication headers were found'); - } - - $hash = $this->getDigestHash($realm, $username); - // If this was false, the user account didn't exist - if ($hash===false || is_null($hash)) { - $digest->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('The supplied username was not on file'); - } - if (!is_string($hash)) { - throw new Sabre_DAV_Exception('The returned value from getDigestHash must be a string or null'); - } - - // If this was false, the password or part of the hash was incorrect. - if (!$digest->validateA1($hash)) { - $digest->requireLogin(); - throw new Sabre_DAV_Exception_NotAuthenticated('Incorrect username'); - } - - $this->currentUser = $username; - return true; - - } - - /** - * Returns the currently logged in username. - * - * @return string|null - */ - public function getCurrentUser() { - - return $this->currentUser; - - } - -} diff --git a/3rdparty/Sabre/DAV/Auth/Backend/Apache.php b/3rdparty/Sabre/DAV/Auth/Backend/Apache.php deleted file mode 100644 index 6bcd76bdcb0ca5c81f2a7d9ad167c03ed1a92054..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/Apache.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php - -/** - * Apache authenticator - * - * This authentication backend assumes that authentication has been - * conifgured in apache, rather than within SabreDAV. - * - * Make sure apache is properly configured for this to work. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Auth_Backend_Apache implements Sabre_DAV_Auth_IBackend { - - /** - * Current apache user - * - * @var string - */ - protected $remoteUser; - - /** - * Authenticates the user based on the current request. - * - * If authentication is succesful, true must be returned. - * If authentication fails, an exception must be thrown. - * - * @return bool - */ - public function authenticate(Sabre_DAV_Server $server,$realm) { - - $remoteUser = $server->httpRequest->getRawServerValue('REMOTE_USER'); - if (is_null($remoteUser)) { - throw new Sabre_DAV_Exception('We did not receive the $_SERVER[REMOTE_USER] property. This means that apache might have been misconfigured'); - } - - $this->remoteUser = $remoteUser; - return true; - - } - - /** - * Returns information about the currently logged in user. - * - * If nobody is currently logged in, this method should return null. - * - * @return array|null - */ - public function getCurrentUser() { - - return $this->remoteUser; - - } - -} - diff --git a/3rdparty/Sabre/DAV/Auth/Backend/File.php b/3rdparty/Sabre/DAV/Auth/Backend/File.php deleted file mode 100644 index db1f04c477250bec0aab04cb7adbac38af7939e5..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/File.php +++ /dev/null @@ -1,76 +0,0 @@ -<?php - -/** - * This is an authentication backend that uses a file to manage passwords. - * - * The backend file must conform to Apache's htdigest format - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Auth_Backend_File extends Sabre_DAV_Auth_Backend_AbstractDigest { - - /** - * List of users - * - * @var array - */ - protected $users = array(); - - /** - * Creates the backend object. - * - * If the filename argument is passed in, it will parse out the specified file fist. - * - * @param string $filename - * @return void - */ - public function __construct($filename=null) { - - if (!is_null($filename)) - $this->loadFile($filename); - - } - - /** - * Loads an htdigest-formatted file. This method can be called multiple times if - * more than 1 file is used. - * - * @param string $filename - * @return void - */ - public function loadFile($filename) { - - foreach(file($filename,FILE_IGNORE_NEW_LINES) as $line) { - - if (substr_count($line, ":") !== 2) - throw new Sabre_DAV_Exception('Malformed htdigest file. Every line should contain 2 colons'); - - list($username,$realm,$A1) = explode(':',$line); - - if (!preg_match('/^[a-zA-Z0-9]{32}$/', $A1)) - throw new Sabre_DAV_Exception('Malformed htdigest file. Invalid md5 hash'); - - $this->users[$realm . ':' . $username] = $A1; - - } - - } - - /** - * Returns a users' information - * - * @param string $realm - * @param string $username - * @return string - */ - public function getDigestHash($realm, $username) { - - return isset($this->users[$realm . ':' . $username])?$this->users[$realm . ':' . $username]:false; - - } - -} diff --git a/3rdparty/Sabre/DAV/Auth/Backend/PDO.php b/3rdparty/Sabre/DAV/Auth/Backend/PDO.php deleted file mode 100644 index 0301503601e2f853c6d40d3c9252b0f08bc6ab35..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Auth/Backend/PDO.php +++ /dev/null @@ -1,66 +0,0 @@ -<?php - -/** - * This is an authentication backend that uses a file to manage passwords. - * - * The backend file must conform to Apache's htdigest format - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Auth_Backend_PDO extends Sabre_DAV_Auth_Backend_AbstractDigest { - - /** - * Reference to PDO connection - * - * @var PDO - */ - protected $pdo; - - /** - * PDO table name we'll be using - * - * @var string - */ - protected $tableName; - - - /** - * Creates the backend object. - * - * If the filename argument is passed in, it will parse out the specified file fist. - * - * @param string $filename - * @param string $tableName The PDO table name to use - * @return void - */ - public function __construct(PDO $pdo, $tableName = 'users') { - - $this->pdo = $pdo; - $this->tableName = $tableName; - - } - - /** - * Returns the digest hash for a user. - * - * @param string $realm - * @param string $username - * @return string|null - */ - public function getDigestHash($realm,$username) { - - $stmt = $this->pdo->prepare('SELECT username, digesta1 FROM `'.$this->tableName.'` WHERE username = ?'); - $stmt->execute(array($username)); - $result = $stmt->fetchAll(); - - if (!count($result)) return; - - return $result[0]['digesta1']; - - } - -} diff --git a/3rdparty/Sabre/DAV/Auth/IBackend.php b/3rdparty/Sabre/DAV/Auth/IBackend.php deleted file mode 100644 index 1f67af4c2d90eabc8eacfb862b15c17592a28595..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Auth/IBackend.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php - -/** - * This is the base class for any authentication object. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAV_Auth_IBackend { - - /** - * Authenticates the user based on the current request. - * - * If authentication is succesful, true must be returned. - * If authentication fails, an exception must be thrown. - * - * @return bool - */ - function authenticate(Sabre_DAV_Server $server,$realm); - - /** - * Returns information about the currently logged in username. - * - * If nobody is currently logged in, this method should return null. - * - * @return string|null - */ - function getCurrentUser(); - -} - diff --git a/3rdparty/Sabre/DAV/Auth/Plugin.php b/3rdparty/Sabre/DAV/Auth/Plugin.php deleted file mode 100644 index f3718fcf469d53c7039523c98de6f697fd3512bf..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Auth/Plugin.php +++ /dev/null @@ -1,111 +0,0 @@ -<?php - -/** - * This plugin provides Authentication for a WebDAV server. - * - * It relies on a Backend object, which provides user information. - * - * Additionally, it provides support for: - * * {DAV:}current-user-principal property from RFC5397 - * * {DAV:}principal-collection-set property from RFC3744 - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Auth_Plugin extends Sabre_DAV_ServerPlugin { - - /** - * Reference to main server object - * - * @var Sabre_DAV_Server - */ - private $server; - - /** - * Authentication backend - * - * @var Sabre_DAV_Auth_Backend_Abstract - */ - private $authBackend; - - /** - * The authentication realm. - * - * @var string - */ - private $realm; - - /** - * __construct - * - * @param Sabre_DAV_Auth_Backend_Abstract $authBackend - * @param string $realm - * @return void - */ - public function __construct(Sabre_DAV_Auth_IBackend $authBackend, $realm) { - - $this->authBackend = $authBackend; - $this->realm = $realm; - - } - - /** - * Initializes the plugin. This function is automatically called by the server - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'),10); - - } - - /** - * Returns a plugin name. - * - * Using this name other plugins will be able to access other plugins - * using Sabre_DAV_Server::getPlugin - * - * @return string - */ - public function getPluginName() { - - return 'auth'; - - } - - /** - * Returns the current users' principal uri. - * - * If nobody is logged in, this will return null. - * - * @return string|null - */ - public function getCurrentUser() { - - $userInfo = $this->authBackend->getCurrentUser(); - if (!$userInfo) return null; - - return $userInfo; - - } - - /** - * This method is called before any HTTP method and forces users to be authenticated - * - * @param string $method - * @throws Sabre_DAV_Exception_NotAuthenticated - * @return bool - */ - public function beforeMethod($method, $uri) { - - $this->authBackend->authenticate($this->server,$this->realm); - - } - -} diff --git a/3rdparty/Sabre/DAV/Browser/GuessContentType.php b/3rdparty/Sabre/DAV/Browser/GuessContentType.php deleted file mode 100644 index ee8c698d782412ef00ba66327a3053ec0c8bd0c6..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Browser/GuessContentType.php +++ /dev/null @@ -1,97 +0,0 @@ -<?php - -/** - * GuessContentType plugin - * - * A lot of the built-in File objects just return application/octet-stream - * as a content-type by default. This is a problem for some clients, because - * they expect a correct contenttype. - * - * There's really no accurate, fast and portable way to determine the contenttype - * so this extension does what the rest of the world does, and guesses it based - * on the file extension. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Browser_GuessContentType extends Sabre_DAV_ServerPlugin { - - /** - * List of recognized file extensions - * - * Feel free to add more - * - * @var array - */ - public $extensionMap = array( - - // images - 'jpg' => 'image/jpeg', - 'gif' => 'image/gif', - 'png' => 'image/png', - - // groupware - 'ics' => 'text/calendar', - 'vcf' => 'text/x-vcard', - - // text - 'txt' => 'text/plain', - - ); - - /** - * Initializes the plugin - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - // Using a relatively low priority (200) to allow other extensions - // to set the content-type first. - $server->subscribeEvent('afterGetProperties',array($this,'afterGetProperties'),200); - - } - - /** - * Handler for teh afterGetProperties event - * - * @param string $path - * @param array $properties - * @return void - */ - public function afterGetProperties($path, &$properties) { - - if (array_key_exists('{DAV:}getcontenttype', $properties[404])) { - - list(, $fileName) = Sabre_DAV_URLUtil::splitPath($path); - $contentType = $this->getContentType($fileName); - - if ($contentType) { - $properties[200]['{DAV:}getcontenttype'] = $contentType; - unset($properties[404]['{DAV:}getcontenttype']); - } - - } - - } - - /** - * Simple method to return the contenttype - * - * @param string $fileName - * @return string - */ - protected function getContentType($fileName) { - - // Just grabbing the extension - $extension = strtolower(substr($fileName,strrpos($fileName,'.')+1)); - if (isset($this->extensionMap[$extension])) - return $this->extensionMap[$extension]; - - } - -} diff --git a/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php b/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php deleted file mode 100644 index a66b57a3a90ac89ba9038cf0caa085f194c536fd..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php - -/** - * This is a simple plugin that will map any GET request for non-files to - * PROPFIND allprops-requests. - * - * This should allow easy debugging of PROPFIND - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Browser_MapGetToPropFind extends Sabre_DAV_ServerPlugin { - - /** - * reference to server class - * - * @var Sabre_DAV_Server - */ - protected $server; - - /** - * Initializes the plugin and subscribes to events - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'httpGetInterceptor')); - } - - /** - * This method intercepts GET requests to non-files, and changes it into an HTTP PROPFIND request - * - * @param string $method - * @return bool - */ - public function httpGetInterceptor($method, $uri) { - - if ($method!='GET') return true; - - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_DAV_IFile) return; - - $this->server->invokeMethod('PROPFIND',$uri); - return false; - - } - -} diff --git a/3rdparty/Sabre/DAV/Browser/Plugin.php b/3rdparty/Sabre/DAV/Browser/Plugin.php deleted file mode 100644 index cd5617babb160819ad04d72cb4cc48c27c3fad99..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Browser/Plugin.php +++ /dev/null @@ -1,285 +0,0 @@ -<?php - -/** - * Browser Plugin - * - * This plugin provides a html representation, so that a WebDAV server may be accessed - * using a browser. - * - * The class intercepts GET requests to collection resources and generates a simple - * html index. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Browser_Plugin extends Sabre_DAV_ServerPlugin { - - /** - * reference to server class - * - * @var Sabre_DAV_Server - */ - protected $server; - - /** - * enableEditing - * - * @var bool - */ - protected $enablePost = true; - - /** - * Creates the object. - * - * By default it will allow file creation and uploads. - * Specify the first argument as false to disable this - * - * @param bool $enablePost - * @return void - */ - public function __construct($enablePost=true) { - - $this->enablePost = $enablePost; - - } - - /** - * Initializes the plugin and subscribes to events - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'httpGetInterceptor')); - if ($this->enablePost) $this->server->subscribeEvent('unknownMethod',array($this,'httpPOSTHandler')); - } - - /** - * This method intercepts GET requests to collections and returns the html - * - * @param string $method - * @return bool - */ - public function httpGetInterceptor($method, $uri) { - - if ($method!='GET') return true; - - try { - $node = $this->server->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // We're simply stopping when the file isn't found to not interfere - // with other plugins. - return; - } - if ($node instanceof Sabre_DAV_IFile) - return; - - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->setHeader('Content-Type','text/html; charset=utf-8'); - - $this->server->httpResponse->sendBody( - $this->generateDirectoryIndex($uri) - ); - - return false; - - } - - /** - * Handles POST requests for tree operations - * - * This method is not yet used. - * - * @param string $method - * @return bool - */ - public function httpPOSTHandler($method, $uri) { - - if ($method!='POST') return true; - if (isset($_POST['sabreAction'])) switch($_POST['sabreAction']) { - - case 'mkcol' : - if (isset($_POST['name']) && trim($_POST['name'])) { - // Using basename() because we won't allow slashes - list(, $folderName) = Sabre_DAV_URLUtil::splitPath(trim($_POST['name'])); - $this->server->createDirectory($uri . '/' . $folderName); - } - break; - case 'put' : - if ($_FILES) $file = current($_FILES); - else break; - $newName = trim($file['name']); - list(, $newName) = Sabre_DAV_URLUtil::splitPath(trim($file['name'])); - if (isset($_POST['name']) && trim($_POST['name'])) - $newName = trim($_POST['name']); - - // Making sure we only have a 'basename' component - list(, $newName) = Sabre_DAV_URLUtil::splitPath($newName); - - - if (is_uploaded_file($file['tmp_name'])) { - $parent = $this->server->tree->getNodeForPath(trim($uri,'/')); - $parent->createFile($newName,fopen($file['tmp_name'],'r')); - } - - } - $this->server->httpResponse->setHeader('Location',$this->server->httpRequest->getUri()); - return false; - - } - - /** - * Escapes a string for html. - * - * @param string $value - * @return void - */ - public function escapeHTML($value) { - - return htmlspecialchars($value,ENT_QUOTES,'UTF-8'); - - } - - /** - * Generates the html directory index for a given url - * - * @param string $path - * @return string - */ - public function generateDirectoryIndex($path) { - - $html = "<html> -<head> - <title>Index for " . $this->escapeHTML($path) . "/ - SabreDAV " . Sabre_DAV_Version::VERSION . "</title> - <style type=\"text/css\"> body { Font-family: arial}</style> -</head> -<body> - <h1>Index for " . $this->escapeHTML($path) . "/</h1> - <table> - <tr><th>Name</th><th>Type</th><th>Size</th><th>Last modified</th></tr> - <tr><td colspan=\"4\"><hr /></td></tr>"; - - $files = $this->server->getPropertiesForPath($path,array( - '{DAV:}displayname', - '{DAV:}resourcetype', - '{DAV:}getcontenttype', - '{DAV:}getcontentlength', - '{DAV:}getlastmodified', - ),1); - - $parent = $this->server->tree->getNodeForPath($path); - - - if ($path) { - - list($parentUri) = Sabre_DAV_URLUtil::splitPath($path); - $fullPath = Sabre_DAV_URLUtil::encodePath($this->server->getBaseUri() . $parentUri); - - $html.= "<tr> -<td><a href=\"{$fullPath}\">..</a></td> -<td>[parent]</td> -<td></td> -<td></td> -</tr>"; - - } - - foreach($files as $k=>$file) { - - // This is the current directory, we can skip it - if (rtrim($file['href'],'/')==$path) continue; - - list(, $name) = Sabre_DAV_URLUtil::splitPath($file['href']); - - $type = null; - - - if (isset($file[200]['{DAV:}resourcetype'])) { - $type = $file[200]['{DAV:}resourcetype']->getValue(); - - // resourcetype can have multiple values - if (!is_array($type)) $type = array($type); - - foreach($type as $k=>$v) { - - // Some name mapping is preferred - switch($v) { - case '{DAV:}collection' : - $type[$k] = 'Collection'; - break; - case '{DAV:}principal' : - $type[$k] = 'Principal'; - break; - case '{urn:ietf:params:xml:ns:carddav}addressbook' : - $type[$k] = 'Addressbook'; - break; - case '{urn:ietf:params:xml:ns:caldav}calendar' : - $type[$k] = 'Calendar'; - break; - } - - } - $type = implode(', ', $type); - } - - // If no resourcetype was found, we attempt to use - // the contenttype property - if (!$type && isset($file[200]['{DAV:}getcontenttype'])) { - $type = $file[200]['{DAV:}getcontenttype']; - } - if (!$type) $type = 'Unknown'; - - $size = isset($file[200]['{DAV:}getcontentlength'])?(int)$file[200]['{DAV:}getcontentlength']:''; - $lastmodified = isset($file[200]['{DAV:}getlastmodified'])?$file[200]['{DAV:}getlastmodified']->getTime()->format(DateTime::ATOM):''; - - $fullPath = Sabre_DAV_URLUtil::encodePath('/' . trim($this->server->getBaseUri() . ($path?$path . '/':'') . $name,'/')); - - $displayName = isset($file[200]['{DAV:}displayname'])?$file[200]['{DAV:}displayname']:$name; - - $name = $this->escapeHTML($name); - $displayName = $this->escapeHTML($displayName); - $type = $this->escapeHTML($type); - - $html.= "<tr> -<td><a href=\"{$fullPath}\">{$displayName}</a></td> -<td>{$type}</td> -<td>{$size}</td> -<td>{$lastmodified}</td> -</tr>"; - - } - - $html.= "<tr><td colspan=\"4\"><hr /></td></tr>"; - - if ($this->enablePost && $parent instanceof Sabre_DAV_ICollection) { - $html.= '<tr><td><form method="post" action=""> - <h3>Create new folder</h3> - <input type="hidden" name="sabreAction" value="mkcol" /> - Name: <input type="text" name="name" /><br /> - <input type="submit" value="create" /> - </form> - <form method="post" action="" enctype="multipart/form-data"> - <h3>Upload file</h3> - <input type="hidden" name="sabreAction" value="put" /> - Name (optional): <input type="text" name="name" /><br /> - File: <input type="file" name="file" /><br /> - <input type="submit" value="upload" /> - </form> - </td></tr>'; - } - - $html.= "</table> - <address>Generated by SabreDAV " . Sabre_DAV_Version::VERSION ."-". Sabre_DAV_Version::STABILITY . " (c)2007-2011 <a href=\"http://code.google.com/p/sabredav/\">http://code.google.com/p/sabredav/</a></address> -</body> -</html>"; - - return $html; - - } - -} diff --git a/3rdparty/Sabre/DAV/Client.php b/3rdparty/Sabre/DAV/Client.php deleted file mode 100644 index fc6a6fff083e4ea2747d2fdb3d843c4570757c75..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Client.php +++ /dev/null @@ -1,431 +0,0 @@ -<?php - -/** - * SabreDAV DAV client - * - * This client wraps around Curl to provide a convenient API to a WebDAV - * server. - * - * NOTE: This class is experimental, it's api will likely change in the future. - * - * @package Sabre - * @subpackage DAVClient - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Client { - - public $propertyMap = array(); - - protected $baseUri; - protected $userName; - protected $password; - protected $proxy; - - /** - * Constructor - * - * Settings are provided through the 'settings' argument. The following - * settings are supported: - * - * * baseUri - * * userName (optional) - * * password (optional) - * * proxy (optional) - * - * @param array $settings - */ - public function __construct(array $settings) { - - if (!isset($settings['baseUri'])) { - throw new InvalidArgumentException('A baseUri must be provided'); - } - - $validSettings = array( - 'baseUri', - 'userName', - 'password', - 'proxy' - ); - - foreach($validSettings as $validSetting) { - if (isset($settings[$validSetting])) { - $this->$validSetting = $settings[$validSetting]; - } - } - - $this->propertyMap['{DAV:}resourcetype'] = 'Sabre_DAV_Property_ResourceType'; - - } - - /** - * Does a PROPFIND request - * - * The list of requested properties must be specified as an array, in clark - * notation. - * - * The returned array will contain a list of filenames as keys, and - * properties as values. - * - * The properties array will contain the list of properties. Only properties - * that are actually returned from the server (without error) will be - * returned, anything else is discarded. - * - * Depth should be either 0 or 1. A depth of 1 will cause a request to be - * made to the server to also return all child resources. - * - * @param string $url - * @param array $properties - * @param int $depth - * @return array - */ - public function propFind($url, array $properties, $depth = 0) { - - $body = '<?xml version="1.0"?>' . "\n"; - $body.= '<d:propfind xmlns:d="DAV:">' . "\n"; - $body.= ' <d:prop>' . "\n"; - - foreach($properties as $property) { - - list( - $namespace, - $elementName - ) = Sabre_DAV_XMLUtil::parseClarkNotation($property); - - if ($namespace === 'DAV:') { - $body.=' <d:' . $elementName . ' />' . "\n"; - } else { - $body.=" <x:" . $elementName . " xmlns:x=\"" . $namespace . "\"/>\n"; - } - - } - - $body.= ' </d:prop>' . "\n"; - $body.= '</d:propfind>'; - - $response = $this->request('PROPFIND', $url, $body, array( - 'Depth' => $depth, - 'Content-Type' => 'application/xml' - )); - - $result = $this->parseMultiStatus($response['body']); - - // If depth was 0, we only return the top item - if ($depth===0) { - reset($result); - $result = current($result); - return $result[200]; - } - - $newResult = array(); - foreach($result as $href => $statusList) { - - $newResult[$href] = $statusList[200]; - - } - - return $newResult; - - } - - /** - * Updates a list of properties on the server - * - * The list of properties must have clark-notation properties for the keys, - * and the actual (string) value for the value. If the value is null, an - * attempt is made to delete the property. - * - * @todo Must be building the request using the DOM, and does not yet - * support complex properties. - * @param string $url - * @param array $properties - * @return void - */ - public function propPatch($url, array $properties) { - - $body = '<?xml version="1.0"?>' . "\n"; - $body.= '<d:propertyupdate xmlns:d="DAV:">' . "\n"; - - foreach($properties as $propName => $propValue) { - - list( - $namespace, - $elementName - ) = Sabre_DAV_XMLUtil::parseClarkNotation($propName); - - if ($propValue === null) { - - $body.="<d:remove><d:prop>\n"; - - if ($namespace === 'DAV:') { - $body.=' <d:' . $elementName . ' />' . "\n"; - } else { - $body.=" <x:" . $elementName . " xmlns:x=\"" . $namespace . "\"/>\n"; - } - - $body.="</d:prop></d:remove>\n"; - - } else { - - $body.="<d:set><d:prop>\n"; - if ($namespace === 'DAV:') { - $body.=' <d:' . $elementName . '>'; - } else { - $body.=" <x:" . $elementName . " xmlns:x=\"" . $namespace . "\">"; - } - // Shitty.. i know - $body.=htmlspecialchars($propValue, ENT_NOQUOTES, 'UTF-8'); - if ($namespace === 'DAV:') { - $body.='</d:' . $elementName . '>' . "\n"; - } else { - $body.="</x:" . $elementName . ">\n"; - } - $body.="</d:prop></d:set>\n"; - - } - - } - - $body.= '</d:propertyupdate>'; - - $response = $this->request('PROPPATCH', $url, $body, array( - 'Content-Type' => 'application/xml' - )); - - } - - /** - * Performs an HTTP options request - * - * This method returns all the features from the 'DAV:' header as an array. - * If there was no DAV header, or no contents this method will return an - * empty array. - * - * @return array - */ - public function options() { - - $result = $this->request('OPTIONS'); - if (!isset($result['headers']['dav'])) { - return array(); - } - - $features = explode(',', $result['headers']['dav']); - foreach($features as &$v) { - $v = trim($v); - } - return $features; - - } - - /** - * Performs an actual HTTP request, and returns the result. - * - * If the specified url is relative, it will be expanded based on the base - * url. - * - * The returned array contains 3 keys: - * * body - the response body - * * httpCode - a HTTP code (200, 404, etc) - * * headers - a list of response http headers. The header names have - * been lowercased. - * - * @param string $method - * @param string $url - * @param string $body - * @param array $headers - * @return array - */ - public function request($method, $url = '', $body = null, $headers = array()) { - - $url = $this->getAbsoluteUrl($url); - - $curlSettings = array( - CURLOPT_RETURNTRANSFER => true, - CURLOPT_CUSTOMREQUEST => $method, - CURLOPT_POSTFIELDS => $body, - // Return headers as part of the response - CURLOPT_HEADER => true - ); - - // Adding HTTP headers - $nHeaders = array(); - foreach($headers as $key=>$value) { - - $nHeaders[] = $key . ': ' . $value; - - } - $curlSettings[CURLOPT_HTTPHEADER] = $nHeaders; - - if ($this->proxy) { - $curlSettings[CURLOPT_PROXY] = $this->proxy; - } - - if ($this->userName) { - $curlSettings[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC | CURLAUTH_DIGEST; - $curlSettings[CURLOPT_USERPWD] = $this->userName . ':' . $this->password; - } - - list( - $response, - $curlInfo, - $curlErrNo, - $curlError - ) = $this->curlRequest($url, $curlSettings); - - $headerBlob = substr($response, 0, $curlInfo['header_size']); - $response = substr($response, $curlInfo['header_size']); - - // In the case of 100 Continue, or redirects we'll have multiple lists - // of headers for each separate HTTP response. We can easily split this - // because they are separated by \r\n\r\n - $headerBlob = explode("\r\n\r\n", trim($headerBlob, "\r\n")); - - // We only care about the last set of headers - $headerBlob = $headerBlob[count($headerBlob)-1]; - - // Splitting headers - $headerBlob = explode("\r\n", $headerBlob); - - $headers = array(); - foreach($headerBlob as $header) { - $parts = explode(':', $header, 2); - if (count($parts)==2) { - $headers[strtolower(trim($parts[0]))] = trim($parts[1]); - } - } - - $response = array( - 'body' => $response, - 'statusCode' => $curlInfo['http_code'], - 'headers' => $headers - ); - - if ($curlErrNo) { - throw new Sabre_DAV_Exception('[CURL] Error while making request: ' . $curlError . ' (error code: ' . $curlErrNo . ')'); - } - - if ($response['statusCode']>=400) { - throw new Sabre_DAV_Exception('HTTP error response. (errorcode ' . $response['statusCode'] . ')'); - } - - return $response; - - } - - /** - * Wrapper for all curl functions. - * - * The only reason this was split out in a separate method, is so it - * becomes easier to unittest. - * - * @param string $url - * @param array $settings - * @return - */ - protected function curlRequest($url, $settings) { - - $curl = curl_init($url); - curl_setopt_array($curl, $settings); - - return array( - curl_exec($curl), - curl_getinfo($curl), - curl_errno($curl), - curl_error($curl) - ); - - } - - /** - * Returns the full url based on the given url (which may be relative). All - * urls are expanded based on the base url as given by the server. - * - * @param string $url - * @return string - */ - protected function getAbsoluteUrl($url) { - - // If the url starts with http:// or https://, the url is already absolute. - if (preg_match('/^http(s?):\/\//', $url)) { - return $url; - } - - // If the url starts with a slash, we must calculate the url based off - // the root of the base url. - if (strpos($url,'/') === 0) { - $parts = parse_url($this->baseUri); - return $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port'])?':' . $parts['port']:'') . $url; - } - - // Otherwise... - return $this->baseUri . $url; - - } - - /** - * Parses a WebDAV multistatus response body - * - * This method returns an array with the following structure - * - * array( - * 'url/to/resource' => array( - * '200' => array( - * '{DAV:}property1' => 'value1', - * '{DAV:}property2' => 'value2', - * ), - * '404' => array( - * '{DAV:}property1' => null, - * '{DAV:}property2' => null, - * ), - * ) - * 'url/to/resource2' => array( - * .. etc .. - * ) - * ) - * - * - * @param string $body xml body - * @return array - */ - public function parseMultiStatus($body) { - - $body = Sabre_DAV_XMLUtil::convertDAVNamespace($body); - - $responseXML = simplexml_load_string($body, null, LIBXML_NOBLANKS | LIBXML_NOCDATA); - if ($responseXML===false) { - throw new InvalidArgumentException('The passed data is not valid XML'); - } - - $responseXML->registerXPathNamespace('d','DAV:'); - - $propResult = array(); - - foreach($responseXML->xpath('d:response') as $response) { - - $response->registerXPathNamespace('d','DAV:'); - $href = $response->xpath('d:href'); - $href = (string)$href[0]; - - $properties = array(); - - foreach($response->xpath('d:propstat') as $propStat) { - - $propStat->registerXPathNamespace('d','DAV:'); - $status = $propStat->xpath('d:status'); - list($httpVersion, $statusCode, $message) = explode(' ', (string)$status[0],3); - - $properties[$statusCode] = Sabre_DAV_XMLUtil::parseProperties(dom_import_simplexml($propStat), $this->propertyMap); - - } - - $propResult[$href] = $properties; - - } - - return $propResult; - - } - -} diff --git a/3rdparty/Sabre/DAV/Collection.php b/3rdparty/Sabre/DAV/Collection.php deleted file mode 100644 index 9da04c12792fc1324e8b7a502079441a4decc714..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Collection.php +++ /dev/null @@ -1,90 +0,0 @@ -<?php - -/** - * Collection class - * - * This is a helper class, that should aid in getting collections classes setup. - * Most of its methods are implemented, and throw permission denied exceptions - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_Collection extends Sabre_DAV_Node implements Sabre_DAV_ICollection { - - /** - * Returns a child object, by its name. - * - * This method makes use of the getChildren method to grab all the child nodes, and compares the name. - * Generally its wise to override this, as this can usually be optimized - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - foreach($this->getChildren() as $child) { - - if ($child->getName()==$name) return $child; - - } - throw new Sabre_DAV_Exception_FileNotFound('File not found: ' . $name); - - } - - /** - * Checks is a child-node exists. - * - * It is generally a good idea to try and override this. Usually it can be optimized. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - try { - - $this->getChild($name); - return true; - - } catch(Sabre_DAV_Exception_FileNotFound $e) { - - return false; - - } - - } - - /** - * Creates a new file in the directory - * - * @param string $name Name of the file - * @param resource $data Initial payload, passed as a readable stream resource. - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function createFile($name, $data = null) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to create file (filename ' . $name . ')'); - - } - - /** - * Creates a new subdirectory - * - * @param string $name - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function createDirectory($name) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to create directory'); - - } - - -} - diff --git a/3rdparty/Sabre/DAV/Directory.php b/3rdparty/Sabre/DAV/Directory.php deleted file mode 100644 index 86af4827b3edf5555142e6e875b28f060fe7f338..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Directory.php +++ /dev/null @@ -1,17 +0,0 @@ -<?php - -/** - * Directory class - * - * This class is now deprecated in favor of the Sabre_DAV_Collection class. - * - * @package Sabre - * @subpackage DAV - * @deprecated Use Sabre_DAV_Collection instead - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_Directory extends Sabre_DAV_Collection { -} - diff --git a/3rdparty/Sabre/DAV/Exception.php b/3rdparty/Sabre/DAV/Exception.php deleted file mode 100644 index 61f8b87c0a62f15de6cd09e90383093094f0b799..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception.php +++ /dev/null @@ -1,63 +0,0 @@ -<?php - -/** - * SabreDAV base exception - * - * This is SabreDAV's base exception file, use this to implement your own exception. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ - -/** - * Main Exception class. - * - * This class defines a getHTTPCode method, which should return the appropriate HTTP code for the Exception occured. - * The default for this is 500. - * - * This class also allows you to generate custom xml data for your exceptions. This will be displayed - * in the 'error' element in the failing response. - */ -class Sabre_DAV_Exception extends Exception { - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 500; - - } - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - - } - - /** - * This method allows the exception to return any extra HTTP response headers. - * - * The headers must be returned as an array. - * - * @return array - */ - public function getHTTPHeaders(Sabre_DAV_Server $server) { - - return array(); - - } - -} - diff --git a/3rdparty/Sabre/DAV/Exception/BadRequest.php b/3rdparty/Sabre/DAV/Exception/BadRequest.php deleted file mode 100644 index 7025bb1031745b8a94b16afc4e83fa81b11de872..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/BadRequest.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php - -/** - * BadRequest - * - * The BadRequest is thrown when the user submitted an invalid HTTP request - * BadRequest - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_BadRequest extends Sabre_DAV_Exception { - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 400; - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/Conflict.php b/3rdparty/Sabre/DAV/Exception/Conflict.php deleted file mode 100644 index 7eaa08178ae2f16f2417a13ef1dd6833037b871a..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/Conflict.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php - -/** - * Conflict - * - * A 409 Conflict is thrown when a user tried to make a directory over an existing - * file or in a parent directory that doesn't exist. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_Conflict extends Sabre_DAV_Exception { - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 409; - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/ConflictingLock.php b/3rdparty/Sabre/DAV/Exception/ConflictingLock.php deleted file mode 100644 index 279f63dfde783a5c0fd6955f486f4d8832dfa530..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/ConflictingLock.php +++ /dev/null @@ -1,35 +0,0 @@ -<?php - -/** - * ConflictingLock - * - * Similar to Exception_Locked, this exception thrown when a LOCK request - * was made, on a resource which was already locked - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_ConflictingLock extends Sabre_DAV_Exception_Locked { - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - if ($this->lock) { - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:no-conflicting-lock'); - $errorNode->appendChild($error); - if (!is_object($this->lock)) var_dump($this->lock); - $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:','d:href',$this->lock->uri)); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/FileNotFound.php b/3rdparty/Sabre/DAV/Exception/FileNotFound.php deleted file mode 100644 index b20e4a2fb3ff7b1bed6024700969ad415d5185a5..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/FileNotFound.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php - -/** - * FileNotFound - * - * This Exception is thrown when a Node couldn't be found. It returns HTTP error code 404 - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_FileNotFound extends Sabre_DAV_Exception { - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 404; - - } - -} - diff --git a/3rdparty/Sabre/DAV/Exception/Forbidden.php b/3rdparty/Sabre/DAV/Exception/Forbidden.php deleted file mode 100644 index 167f3c2760a8b38704d19fa340fba7327882d383..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/Forbidden.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php - -/** - * Forbidden - * - * This exception is thrown whenever a user tries to do an operation he's not allowed to - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_Forbidden extends Sabre_DAV_Exception { - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 403; - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/InsufficientStorage.php b/3rdparty/Sabre/DAV/Exception/InsufficientStorage.php deleted file mode 100644 index 15007cdd352524fd362c754a75bdc7b1ad84ce2e..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/InsufficientStorage.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php - -/** - * InsufficientStorage - * - * This Exception can be thrown, when for example a harddisk is full or a quota is exceeded - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_InsufficientStorage extends Sabre_DAV_Exception { - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 507; - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/InvalidResourceType.php b/3rdparty/Sabre/DAV/Exception/InvalidResourceType.php deleted file mode 100644 index f06810a25ef58ba2c2b67d71f6accce60d814a7a..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/InvalidResourceType.php +++ /dev/null @@ -1,33 +0,0 @@ -<?php - -/** - * InvalidResourceType - * - * This exception is thrown when the user tried to create a new collection, with - * a special resourcetype value that was not recognized by the server. - * - * See RFC5689 section 3.3 - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_InvalidResourceType extends Sabre_DAV_Exception_Forbidden { - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:valid-resourcetype'); - $errorNode->appendChild($error); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php b/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php deleted file mode 100644 index 47032cffc75de30033010bfd3a632c5de0ee6b01..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php +++ /dev/null @@ -1,39 +0,0 @@ -<?php - -/** - * LockTokenMatchesRequestUri - * - * This exception is thrown by UNLOCK if a supplied lock-token is invalid - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_LockTokenMatchesRequestUri extends Sabre_DAV_Exception_Conflict { - - /** - * Creates the exception - */ - public function __construct() { - - $this->message = 'The locktoken supplied does not match any locks on this entity'; - - } - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:lock-token-matches-request-uri'); - $errorNode->appendChild($error); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/Locked.php b/3rdparty/Sabre/DAV/Exception/Locked.php deleted file mode 100644 index b4bb2e0378cc55ed509258da4a5af79b3f853efe..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/Locked.php +++ /dev/null @@ -1,67 +0,0 @@ -<?php - -/** - * Locked - * - * The 423 is thrown when a client tried to access a resource that was locked, without supplying a valid lock token - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_Locked extends Sabre_DAV_Exception { - - /** - * Lock information - * - * @var Sabre_DAV_Locks_LockInfo - */ - protected $lock; - - /** - * Creates the exception - * - * A LockInfo object should be passed if the user should be informed - * which lock actually has the file locked. - * - * @param Sabre_DAV_Locks_LockInfo $lock - */ - public function __construct(Sabre_DAV_Locks_LockInfo $lock = null) { - - $this->lock = $lock; - - } - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 423; - - } - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - if ($this->lock) { - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:lock-token-submitted'); - $errorNode->appendChild($error); - if (!is_object($this->lock)) var_dump($this->lock); - $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:','d:href',$this->lock->uri)); - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php b/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php deleted file mode 100644 index 02c145ffeb635de6320a707ed191963ae8da28e9..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php +++ /dev/null @@ -1,44 +0,0 @@ -<?php - -/** - * MethodNotAllowed - * - * The 405 is thrown when a client tried to create a directory on an already existing directory - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_MethodNotAllowed extends Sabre_DAV_Exception { - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 405; - - } - - /** - * This method allows the exception to return any extra HTTP response headers. - * - * The headers must be returned as an array. - * - * @return array - */ - public function getHTTPHeaders(Sabre_DAV_Server $server) { - - $methods = $server->getAllowedMethods($server->getRequestUri()); - - return array( - 'Allow' => strtoupper(implode(', ',$methods)), - ); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php b/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php deleted file mode 100644 index 1faffddfa00d58f171ed2ac3a6de00145438110b..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/NotAuthenticated.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php - -/** - * NotAuthenticated - * - * This exception is thrown when the client did not provide valid - * authentication credentials. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_NotAuthenticated extends Sabre_DAV_Exception { - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 401; - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/NotImplemented.php b/3rdparty/Sabre/DAV/Exception/NotImplemented.php deleted file mode 100644 index cd7f609b09df436604e39bf82528854ad349bbd3..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/NotImplemented.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php - -/** - * NotImplemented - * - * This exception is thrown when the client tried to call an unsupported HTTP method or other feature - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_NotImplemented extends Sabre_DAV_Exception { - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 501; - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/PreconditionFailed.php b/3rdparty/Sabre/DAV/Exception/PreconditionFailed.php deleted file mode 100644 index ebcb9f5b9ac858e0a77907bd8785d4e4f0b582f0..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/PreconditionFailed.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php - -/** - * PreconditionFailed - * - * This exception is normally thrown when a client submitted a conditional request, - * like for example an If, If-None-Match or If-Match header, which caused the HTTP - * request to not execute (the condition of the header failed) - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_PreconditionFailed extends Sabre_DAV_Exception { - - /** - * When this exception is thrown, the header-name might be set. - * - * This allows the exception-catching code to determine which HTTP header - * caused the exception. - * - * @var string - */ - public $header = null; - - /** - * Create the exception - * - * @param string $message - * @param string $header - */ - public function __construct($message, $header=null) { - - parent::__construct($message); - $this->header = $header; - - } - - /** - * Returns the HTTP statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 412; - - } - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - if ($this->header) { - $prop = $errorNode->ownerDocument->createElement('s:header'); - $prop->nodeValue = $this->header; - $errorNode->appendChild($prop); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php b/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php deleted file mode 100644 index e4ed601b16cd8d37d3663379a17de1a5bd29171a..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php +++ /dev/null @@ -1,30 +0,0 @@ -<?php - -/** - * ReportNotImplemented - * - * This exception is thrown when the client requested an unknown report through the REPORT method - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_ReportNotImplemented extends Sabre_DAV_Exception_NotImplemented { - - /** - * This method allows the exception to include additonal information into the WebDAV error response - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:supported-report'); - $errorNode->appendChild($error); - - } - -} diff --git a/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php b/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php deleted file mode 100644 index 37abbd729d11724077faf53b3240cf153d99b0be..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php +++ /dev/null @@ -1,29 +0,0 @@ -<?php - -/** - * RequestedRangeNotSatisfiable - * - * This exception is normally thrown when the user - * request a range that is out of the entity bounds. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_RequestedRangeNotSatisfiable extends Sabre_DAV_Exception { - - /** - * returns the http statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 416; - - } - -} - diff --git a/3rdparty/Sabre/DAV/Exception/UnsupportedMediaType.php b/3rdparty/Sabre/DAV/Exception/UnsupportedMediaType.php deleted file mode 100644 index 4c37d8997cf0a63ac09aa20091160b09bd87c092..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Exception/UnsupportedMediaType.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php - -/** - * UnSupportedMediaType - * - * The 415 Unsupported Media Type status code is generally sent back when the client - * tried to call an HTTP method, with a body the server didn't understand - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Exception_UnsupportedMediaType extends Sabre_DAV_Exception { - - /** - * returns the http statuscode for this exception - * - * @return int - */ - public function getHTTPCode() { - - return 415; - - } - -} diff --git a/3rdparty/Sabre/DAV/FS/Directory.php b/3rdparty/Sabre/DAV/FS/Directory.php deleted file mode 100644 index ebd6a6c505e2bd10140d963bdbb1d6829b65f9f2..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/FS/Directory.php +++ /dev/null @@ -1,121 +0,0 @@ -<?php - -/** - * Directory class - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_FS_Directory extends Sabre_DAV_FS_Node implements Sabre_DAV_ICollection, Sabre_DAV_IQuota { - - /** - * Creates a new file in the directory - * - * data is a readable stream resource - * - * @param string $name Name of the file - * @param resource $data Initial payload - * @return void - */ - public function createFile($name, $data = null) { - - $newPath = $this->path . '/' . $name; - file_put_contents($newPath,$data); - - } - - /** - * Creates a new subdirectory - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - $newPath = $this->path . '/' . $name; - mkdir($newPath); - - } - - /** - * Returns a specific child node, referenced by its name - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - $path = $this->path . '/' . $name; - - if (!file_exists($path)) throw new Sabre_DAV_Exception_FileNotFound('File with name ' . $path . ' could not be located'); - - if (is_dir($path)) { - - return new Sabre_DAV_FS_Directory($path); - - } else { - - return new Sabre_DAV_FS_File($path); - - } - - } - - /** - * Returns an array with all the child nodes - * - * @return Sabre_DAV_INode[] - */ - public function getChildren() { - - $nodes = array(); - foreach(scandir($this->path) as $node) if($node!='.' && $node!='..') $nodes[] = $this->getChild($node); - return $nodes; - - } - - /** - * Checks if a child exists. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - $path = $this->path . '/' . $name; - return file_exists($path); - - } - - /** - * Deletes all files in this directory, and then itself - * - * @return void - */ - public function delete() { - - foreach($this->getChildren() as $child) $child->delete(); - rmdir($this->path); - - } - - /** - * Returns available diskspace information - * - * @return array - */ - public function getQuotaInfo() { - - return array( - disk_total_space($this->path)-disk_free_space($this->path), - disk_free_space($this->path) - ); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FS/File.php b/3rdparty/Sabre/DAV/FS/File.php deleted file mode 100644 index 262187d7e8ab8c1abeb60d8b9584920d2b05fe55..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/FS/File.php +++ /dev/null @@ -1,89 +0,0 @@ -<?php - -/** - * File class - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_FS_File extends Sabre_DAV_FS_Node implements Sabre_DAV_IFile { - - /** - * Updates the data - * - * @param resource $data - * @return void - */ - public function put($data) { - - file_put_contents($this->path,$data); - - } - - /** - * Returns the data - * - * @return string - */ - public function get() { - - return fopen($this->path,'r'); - - } - - /** - * Delete the current file - * - * @return void - */ - public function delete() { - - unlink($this->path); - - } - - /** - * Returns the size of the node, in bytes - * - * @return int - */ - public function getSize() { - - return filesize($this->path); - - } - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * Return null if the ETag can not effectively be determined - * - * @return mixed - */ - public function getETag() { - - return null; - - } - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - * - * @return mixed - */ - public function getContentType() { - - return null; - - } - -} - diff --git a/3rdparty/Sabre/DAV/FS/Node.php b/3rdparty/Sabre/DAV/FS/Node.php deleted file mode 100644 index b8d7bcfe8461c11dc4448098889dacf29939aa4a..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/FS/Node.php +++ /dev/null @@ -1,81 +0,0 @@ -<?php - -/** - * Base node-class - * - * The node class implements the method used by both the File and the Directory classes - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_FS_Node implements Sabre_DAV_INode { - - /** - * The path to the current node - * - * @var string - */ - protected $path; - - /** - * Sets up the node, expects a full path name - * - * @param string $path - * @return void - */ - public function __construct($path) { - - $this->path = $path; - - } - - - - /** - * Returns the name of the node - * - * @return string - */ - public function getName() { - - list(, $name) = Sabre_DAV_URLUtil::splitPath($this->path); - return $name; - - } - - /** - * Renames the node - * - * @param string $name The new name - * @return void - */ - public function setName($name) { - - list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); - list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); - - $newPath = $parentPath . '/' . $newName; - rename($this->path,$newPath); - - $this->path = $newPath; - - } - - - - /** - * Returns the last modification time, as a unix timestamp - * - * @return int - */ - public function getLastModified() { - - return filemtime($this->path); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FSExt/Directory.php b/3rdparty/Sabre/DAV/FSExt/Directory.php deleted file mode 100644 index c43d4385ac7b75cb20d19857501cebef51039aa9..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/FSExt/Directory.php +++ /dev/null @@ -1,135 +0,0 @@ -<?php - -/** - * Directory class - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_FSExt_Directory extends Sabre_DAV_FSExt_Node implements Sabre_DAV_ICollection, Sabre_DAV_IQuota { - - /** - * Creates a new file in the directory - * - * @param string $name Name of the file - * @param resource $data Initial payload - * @return void - */ - public function createFile($name, $data = null) { - - // We're not allowing dots - if ($name=='.' || $name=='..') throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - $newPath = $this->path . '/' . $name; - file_put_contents($newPath,$data); - - } - - /** - * Creates a new subdirectory - * - * @param string $name - * @return void - */ - public function createDirectory($name) { - - // We're not allowing dots - if ($name=='.' || $name=='..') throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - $newPath = $this->path . '/' . $name; - mkdir($newPath); - - } - - /** - * Returns a specific child node, referenced by its name - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - $path = $this->path . '/' . $name; - - if (!file_exists($path)) throw new Sabre_DAV_Exception_FileNotFound('File could not be located'); - if ($name=='.' || $name=='..') throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - - if (is_dir($path)) { - - return new Sabre_DAV_FSExt_Directory($path); - - } else { - - return new Sabre_DAV_FSExt_File($path); - - } - - } - - /** - * Checks if a child exists. - * - * @param string $name - * @return bool - */ - public function childExists($name) { - - if ($name=='.' || $name=='..') - throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - - $path = $this->path . '/' . $name; - return file_exists($path); - - } - - /** - * Returns an array with all the child nodes - * - * @return Sabre_DAV_INode[] - */ - public function getChildren() { - - $nodes = array(); - foreach(scandir($this->path) as $node) if($node!='.' && $node!='..' && $node!='.sabredav') $nodes[] = $this->getChild($node); - return $nodes; - - } - - /** - * Deletes all files in this directory, and then itself - * - * @return void - */ - public function delete() { - - // Deleting all children - foreach($this->getChildren() as $child) $child->delete(); - - // Removing resource info, if its still around - if (file_exists($this->path . '/.sabredav')) unlink($this->path . '/.sabredav'); - - // Removing the directory itself - rmdir($this->path); - - return parent::delete(); - - } - - /** - * Returns available diskspace information - * - * @return array - */ - public function getQuotaInfo() { - - return array( - disk_total_space($this->path)-disk_free_space($this->path), - disk_free_space($this->path) - ); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FSExt/File.php b/3rdparty/Sabre/DAV/FSExt/File.php deleted file mode 100644 index 7a8e7a11f21308dd0d285670030cebd925fdd1e2..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/FSExt/File.php +++ /dev/null @@ -1,88 +0,0 @@ -<?php - -/** - * File class - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_FSExt_File extends Sabre_DAV_FSExt_Node implements Sabre_DAV_IFile { - - /** - * Updates the data - * - * data is a readable stream resource. - * - * @param resource $data - * @return void - */ - public function put($data) { - - file_put_contents($this->path,$data); - - } - - /** - * Returns the data - * - * @return string - */ - public function get() { - - return fopen($this->path,'r'); - - } - - /** - * Delete the current file - * - * @return void - */ - public function delete() { - - unlink($this->path); - return parent::delete(); - - } - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * Return null if the ETag can not effectively be determined - */ - public function getETag() { - - return '"' . md5_file($this->path). '"'; - - } - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - */ - public function getContentType() { - - return null; - - } - - /** - * Returns the size of the file, in bytes - * - * @return int - */ - public function getSize() { - - return filesize($this->path); - - } - -} - diff --git a/3rdparty/Sabre/DAV/FSExt/Node.php b/3rdparty/Sabre/DAV/FSExt/Node.php deleted file mode 100644 index 9e36222bfd325a6bbe164bea5670e120fb83caf1..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/FSExt/Node.php +++ /dev/null @@ -1,276 +0,0 @@ -<?php - -/** - * Base node-class - * - * The node class implements the method used by both the File and the Directory classes - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_FSExt_Node extends Sabre_DAV_FS_Node implements Sabre_DAV_ILockable, Sabre_DAV_IProperties { - - /** - * Returns all the locks on this node - * - * @return array - */ - function getLocks() { - - $resourceData = $this->getResourceData(); - $locks = $resourceData['locks']; - foreach($locks as $k=>$lock) { - if (time() > $lock->timeout + $lock->created) unset($locks[$k]); - } - return $locks; - - } - - /** - * Locks this node - * - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return void - */ - function lock(Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 1800; - $lockInfo->created = time(); - - $resourceData = $this->getResourceData(); - if (!isset($resourceData['locks'])) $resourceData['locks'] = array(); - $current = null; - foreach($resourceData['locks'] as $k=>$lock) { - if ($lock->token === $lockInfo->token) $current = $k; - } - if (!is_null($current)) $resourceData['locks'][$current] = $lockInfo; - else $resourceData['locks'][] = $lockInfo; - - $this->putResourceData($resourceData); - - } - - /** - * Removes a lock from this node - * - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - function unlock(Sabre_DAV_Locks_LockInfo $lockInfo) { - - //throw new Sabre_DAV_Exception('bla'); - $resourceData = $this->getResourceData(); - foreach($resourceData['locks'] as $k=>$lock) { - - if ($lock->token === $lockInfo->token) { - - unset($resourceData['locks'][$k]); - $this->putResourceData($resourceData); - return true; - - } - } - return false; - - } - - /** - * Updates properties on this node, - * - * @param array $mutations - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public function updateProperties($properties) { - - $resourceData = $this->getResourceData(); - - $result = array(); - - foreach($properties as $propertyName=>$propertyValue) { - - // If it was null, we need to delete the property - if (is_null($propertyValue)) { - if (isset($resourceData['properties'][$propertyName])) { - unset($resourceData['properties'][$propertyName]); - } - } else { - $resourceData['properties'][$propertyName] = $propertyValue; - } - - } - - $this->putResourceData($resourceData); - return true; - } - - /** - * Returns a list of properties for this nodes.; - * - * The properties list is a list of propertynames the client requested, encoded as xmlnamespace#tagName, for example: http://www.example.org/namespace#author - * If the array is empty, all properties should be returned - * - * @param array $properties - * @return void - */ - function getProperties($properties) { - - $resourceData = $this->getResourceData(); - - // if the array was empty, we need to return everything - if (!$properties) return $resourceData['properties']; - - $props = array(); - foreach($properties as $property) { - if (isset($resourceData['properties'][$property])) $props[$property] = $resourceData['properties'][$property]; - } - - return $props; - - } - - /** - * Returns the path to the resource file - * - * @return string - */ - protected function getResourceInfoPath() { - - list($parentDir) = Sabre_DAV_URLUtil::splitPath($this->path); - return $parentDir . '/.sabredav'; - - } - - /** - * Returns all the stored resource information - * - * @return array - */ - protected function getResourceData() { - - $path = $this->getResourceInfoPath(); - if (!file_exists($path)) return array('locks'=>array(), 'properties' => array()); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'r'); - flock($handle,LOCK_SH); - $data = ''; - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // We're all good - fclose($handle); - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (!isset($data[$this->getName()])) { - return array('locks'=>array(), 'properties' => array()); - } - - $data = $data[$this->getName()]; - if (!isset($data['locks'])) $data['locks'] = array(); - if (!isset($data['properties'])) $data['properties'] = array(); - return $data; - - } - - /** - * Updates the resource information - * - * @param array $newData - * @return void - */ - protected function putResourceData(array $newData) { - - $path = $this->getResourceInfoPath(); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); - $data = ''; - - rewind($handle); - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - $data[$this->getName()] = $newData; - ftruncate($handle,0); - rewind($handle); - - fwrite($handle,serialize($data)); - fclose($handle); - - } - - /** - * Renames the node - * - * @param string $name The new name - * @return void - */ - public function setName($name) { - - list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); - list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); - $newPath = $parentPath . '/' . $newName; - - // We're deleting the existing resourcedata, and recreating it - // for the new path. - $resourceData = $this->getResourceData(); - $this->deleteResourceData(); - - rename($this->path,$newPath); - $this->path = $newPath; - $this->putResourceData($resourceData); - - - } - - public function deleteResourceData() { - - // When we're deleting this node, we also need to delete any resource information - $path = $this->getResourceInfoPath(); - if (!file_exists($path)) return true; - - // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); - $data = ''; - - rewind($handle); - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (isset($data[$this->getName()])) unset($data[$this->getName()]); - ftruncate($handle,0); - rewind($handle); - fwrite($handle,serialize($data)); - fclose($handle); - - } - - public function delete() { - - return $this->deleteResourceData(); - - } - -} - diff --git a/3rdparty/Sabre/DAV/File.php b/3rdparty/Sabre/DAV/File.php deleted file mode 100644 index b74bd9525b34cc8452466b260ca8be4c9fc9e16e..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/File.php +++ /dev/null @@ -1,81 +0,0 @@ -<?php - -/** - * File class - * - * This is a helper class, that should aid in getting file classes setup. - * Most of its methods are implemented, and throw permission denied exceptions - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_File extends Sabre_DAV_Node implements Sabre_DAV_IFile { - - /** - * Updates the data - * - * data is a readable stream resource. - * - * @param resource $data - * @return void - */ - public function put($data) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to change data'); - - } - - /** - * Returns the data - * - * This method may either return a string or a readable stream resource - * - * @return mixed - */ - public function get() { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to read this file'); - - } - - /** - * Returns the size of the file, in bytes. - * - * @return int - */ - public function getSize() { - - return 0; - - } - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * Return null if the ETag can not effectively be determined - */ - public function getETag() { - - return null; - - } - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - */ - public function getContentType() { - - return null; - - } - -} - diff --git a/3rdparty/Sabre/DAV/ICollection.php b/3rdparty/Sabre/DAV/ICollection.php deleted file mode 100644 index 0667d88899d2d307c025cc247503506f0d9311e5..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/ICollection.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php - -/** - * The ICollection Interface - * - * This interface should be implemented by each class that represents a collection - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAV_ICollection extends Sabre_DAV_INode { - - /** - * Creates a new file in the directory - * - * data is a readable stream resource - * - * @param string $name Name of the file - * @param resource $data Initial payload - * @return void - */ - function createFile($name, $data = null); - - /** - * Creates a new subdirectory - * - * @param string $name - * @return void - */ - function createDirectory($name); - - /** - * Returns a specific child node, referenced by its name - * - * @param string $name - * @return Sabre_DAV_INode - */ - function getChild($name); - - /** - * Returns an array with all the child nodes - * - * @return Sabre_DAV_INode[] - */ - function getChildren(); - - /** - * Checks if a child-node with the specified name exists - * - * @return bool - */ - function childExists($name); - -} - diff --git a/3rdparty/Sabre/DAV/IExtendedCollection.php b/3rdparty/Sabre/DAV/IExtendedCollection.php deleted file mode 100644 index b8db1ab2f26917a03d5266e22ab157efc3e132bc..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/IExtendedCollection.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php - -/** - * The IExtendedCollection interface. - * - * This interface can be used to create special-type of collection-resources - * as defined by RFC 5689. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAV_IExtendedCollection extends Sabre_DAV_ICollection { - - /** - * Creates a new collection - * - * @param string $name - * @param array $resourceType - * @param array $properties - * @return void - */ - function createExtendedCollection($name, array $resourceType, array $properties); - -} - diff --git a/3rdparty/Sabre/DAV/IFile.php b/3rdparty/Sabre/DAV/IFile.php deleted file mode 100644 index 446ec86187b3a42f9770683de660b95ff87f3cfb..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/IFile.php +++ /dev/null @@ -1,63 +0,0 @@ -<?php - -/** - * This interface represents a file or leaf in the tree. - * - * The nature of a file is, as you might be aware of, that it doesn't contain sub-nodes and has contents - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAV_IFile extends Sabre_DAV_INode { - - /** - * Updates the data - * - * The data argument is a readable stream resource. - * - * @param resource $data - * @return void - */ - function put($data); - - /** - * Returns the data - * - * This method may either return a string or a readable stream resource - * - * @return mixed - */ - function get(); - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - * - * @return void - */ - function getContentType(); - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * - * Return null if the ETag can not effectively be determined - * - * @return void - */ - function getETag(); - - /** - * Returns the size of the node, in bytes - * - * @return int - */ - function getSize(); - -} - diff --git a/3rdparty/Sabre/DAV/ILockable.php b/3rdparty/Sabre/DAV/ILockable.php deleted file mode 100644 index f9fb3a702511eccfd4684c22c606237e1255570b..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/ILockable.php +++ /dev/null @@ -1,38 +0,0 @@ -<?php - -/** - * Implement this class to support locking - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAV_ILockable extends Sabre_DAV_INode { - - /** - * Returns an array with locks currently on the node - * - * @return Sabre_DAV_Locks_LockInfo[] - */ - function getLocks(); - - /** - * Creates a new lock on the file. - * - * @param Sabre_DAV_Locks_LockInfo $lockInfo The lock information - * @return void - */ - function lock(Sabre_DAV_Locks_LockInfo $lockInfo); - - /** - * Unlocks a file - * - * @param Sabre_DAV_Locks_LockInfo $lockInfo The lock information - * @return void - */ - function unlock(Sabre_DAV_Locks_LockInfo $lockInfo); - -} - diff --git a/3rdparty/Sabre/DAV/INode.php b/3rdparty/Sabre/DAV/INode.php deleted file mode 100644 index c0b96bf53775370a3374259b51196a0b26e48b1b..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/INode.php +++ /dev/null @@ -1,44 +0,0 @@ -<?php - -/** - * The INode interface is the base interface, and the parent class of both ICollection and IFile - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAV_INode { - - /** - * Deleted the current node - * - * @return void - */ - function delete(); - - /** - * Returns the name of the node - * - * @return string - */ - function getName(); - - /** - * Renames the node - * - * @param string $name The new name - * @return void - */ - function setName($name); - - /** - * Returns the last modification time, as a unix timestamp - * - * @return int - */ - function getLastModified(); - -} - diff --git a/3rdparty/Sabre/DAV/IProperties.php b/3rdparty/Sabre/DAV/IProperties.php deleted file mode 100644 index af17cad24affd88f1fe8633b25dae128b6b6460f..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/IProperties.php +++ /dev/null @@ -1,67 +0,0 @@ -<?php - -/** - * IProperties interface - * - * Implement this interface to support custom WebDAV properties requested and sent from clients. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAV_IProperties extends Sabre_DAV_INode { - - /** - * Updates properties on this node, - * - * The properties array uses the propertyName in clark-notation as key, - * and the array value for the property value. In the case a property - * should be deleted, the property value will be null. - * - * This method must be atomic. If one property cannot be changed, the - * entire operation must fail. - * - * If the operation was successful, true can be returned. - * If the operation failed, false can be returned. - * - * Deletion of a non-existant property is always succesful. - * - * Lastly, it is optional to return detailed information about any - * failures. In this case an array should be returned with the following - * structure: - * - * array( - * 403 => array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param array $mutations - * @return bool|array - */ - function updateProperties($mutations); - - /** - * Returns a list of properties for this nodes. - * - * The properties list is a list of propertynames the client requested, - * encoded in clark-notation {xmlnamespace}tagname - * - * If the array is empty, it means 'all properties' were requested. - * - * @param array $properties - * @return void - */ - function getProperties($properties); - -} - diff --git a/3rdparty/Sabre/DAV/IQuota.php b/3rdparty/Sabre/DAV/IQuota.php deleted file mode 100644 index 8ff1a4597f85d43610439216f9c8ecc440429a0c..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/IQuota.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php - -/** - * IQuota interface - * - * Implement this interface to add the ability to return quota information. The ObjectTree - * will check for quota information on any given node. If the information is not available it will - * attempt to fetch the information from the root node. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAV_IQuota extends Sabre_DAV_ICollection { - - /** - * Returns the quota information - * - * This method MUST return an array with 2 values, the first being the total used space, - * the second the available space (in bytes) - */ - function getQuotaInfo(); - -} - diff --git a/3rdparty/Sabre/DAV/Locks/Backend/Abstract.php b/3rdparty/Sabre/DAV/Locks/Backend/Abstract.php deleted file mode 100644 index b09f93ddac79e41d1aa9497d7739a8a20d5d15d9..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Locks/Backend/Abstract.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php - -/** - * The Lock manager allows you to handle all file-locks centrally. - * - * This is an alternative approach to doing this on a per-node basis - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_Locks_Backend_Abstract { - - /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects - * - * This method should return all the locks for a particular uri, including - * locks that might be set on a parent uri. - * - * If returnChildLocks is set to true, this method should also look for - * any locks in the subtree of the uri for locks. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - abstract function getLocks($uri, $returnChildLocks); - - /** - * Locks a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - abstract function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo); - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - abstract function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo); - -} - diff --git a/3rdparty/Sabre/DAV/Locks/Backend/FS.php b/3rdparty/Sabre/DAV/Locks/Backend/FS.php deleted file mode 100644 index 8653f55b1c6f9a116733392332975ff7c5a97e48..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Locks/Backend/FS.php +++ /dev/null @@ -1,189 +0,0 @@ -<?php - -/** - * The Lock manager allows you to handle all file-locks centrally. - * - * This Lock Manager is now deprecated. It has a bug that allows parent - * collections to be deletes when children deeper in the tree are locked. - * - * You are recommended to use either the PDO or the File backend instead. - * - * This Lock Manager stores all its data in the filesystem. - * - * @package Sabre - * @subpackage DAV - * @deprecated - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Locks_Backend_FS extends Sabre_DAV_Locks_Backend_Abstract { - - /** - * The default data directory - * - * @var string - */ - private $dataDir; - - public function __construct($dataDir) { - - $this->dataDir = $dataDir; - - } - - protected function getFileNameForUri($uri) { - - return $this->dataDir . '/sabredav_' . md5($uri) . '.locks'; - - } - - - /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects - * - * This method should return all the locks for a particular uri, including - * locks that might be set on a parent uri. - * - * If returnChildLocks is set to true, this method should also look for - * any locks in the subtree of the uri for locks. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks) { - - $lockList = array(); - $currentPath = ''; - - foreach(explode('/',$uri) as $uriPart) { - - // weird algorithm that can probably be improved, but we're traversing the path top down - if ($currentPath) $currentPath.='/'; - $currentPath.=$uriPart; - - $uriLocks = $this->getData($currentPath); - - foreach($uriLocks as $uriLock) { - - // Unless we're on the leaf of the uri-tree we should ingore locks with depth 0 - if($uri==$currentPath || $uriLock->depth!=0) { - $uriLock->uri = $currentPath; - $lockList[] = $uriLock; - } - - } - - } - - // Checking if we can remove any of these locks - foreach($lockList as $k=>$lock) { - if (time() > $lock->timeout + $lock->created) unset($lockList[$k]); - } - return $lockList; - - } - - /** - * Locks a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 1800; - $lockInfo->created = time(); - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - if ($lock->token == $lockInfo->token) unset($locks[$k]); - } - $locks[] = $lockInfo; - $this->putData($uri,$locks); - return true; - - } - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - - if ($lock->token == $lockInfo->token) { - - unset($locks[$k]); - $this->putData($uri,$locks); - return true; - - } - } - return false; - - } - - /** - * Returns the stored data for a uri - * - * @param string $uri - * @return array - */ - protected function getData($uri) { - - $path = $this->getFilenameForUri($uri); - if (!file_exists($path)) return array(); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'r'); - flock($handle,LOCK_SH); - $data = ''; - - // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); - } - - // We're all good - fclose($handle); - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (!$data) return array(); - return $data; - - } - - /** - * Updates the lock information - * - * @param string $uri - * @param array $newData - * @return void - */ - protected function putData($uri,array $newData) { - - $path = $this->getFileNameForUri($uri); - - // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); - ftruncate($handle,0); - rewind($handle); - - fwrite($handle,serialize($newData)); - fclose($handle); - - } - -} - diff --git a/3rdparty/Sabre/DAV/Locks/Backend/File.php b/3rdparty/Sabre/DAV/Locks/Backend/File.php deleted file mode 100644 index f65b20c4306728f93cd9c00968db46d6008f816c..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Locks/Backend/File.php +++ /dev/null @@ -1,175 +0,0 @@ -<?php - -/** - * The Lock manager allows you to handle all file-locks centrally. - * - * This Lock Manager stores all its data in a single file. - * - * Note that this is not nearly as robust as a database, you are encouraged - * to use the PDO backend instead. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Locks_Backend_File extends Sabre_DAV_Locks_Backend_Abstract { - - /** - * The storage file - * - * @var string - */ - private $locksFile; - - /** - * Constructor - * - * @param string $locksFile path to file - */ - public function __construct($locksFile) { - - $this->locksFile = $locksFile; - - } - - /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects - * - * This method should return all the locks for a particular uri, including - * locks that might be set on a parent uri. - * - * If returnChildLocks is set to true, this method should also look for - * any locks in the subtree of the uri for locks. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks) { - - $newLocks = array(); - $currentPath = ''; - - $locks = $this->getData(); - foreach($locks as $lock) { - - if ($lock->uri === $uri || - //deep locks on parents - ($lock->depth!=0 && strpos($uri, $lock->uri . '/')===0) || - - // locks on children - ($returnChildLocks && (strpos($lock->uri, $uri . '/')===0)) ) { - - $newLocks[] = $lock; - - } - - } - - // Checking if we can remove any of these locks - foreach($newLocks as $k=>$lock) { - if (time() > $lock->timeout + $lock->created) unset($newLocks[$k]); - } - return $newLocks; - - } - - /** - * Locks a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 1800; - $lockInfo->created = time(); - $lockInfo->uri = $uri; - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - if ($lock->token == $lockInfo->token) unset($locks[$k]); - } - $locks[] = $lockInfo; - $this->putData($locks); - return true; - - } - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - - if ($lock->token == $lockInfo->token) { - - unset($locks[$k]); - $this->putData($locks); - return true; - - } - } - return false; - - } - - /** - * Loads the lockdata from the filesystem. - * - * @return array - */ - protected function getData() { - - if (!file_exists($this->locksFile)) return array(); - - // opening up the file, and creating a shared lock - $handle = fopen($this->locksFile,'r'); - flock($handle,LOCK_SH); - - // Reading data until the eof - $data = stream_get_contents($handle); - - // We're all good - fclose($handle); - - // Unserializing and checking if the resource file contains data for this file - $data = unserialize($data); - if (!$data) return array(); - return $data; - - } - - /** - * Saves the lockdata - * - * @param array $newData - * @return void - */ - protected function putData(array $newData) { - - // opening up the file, and creating an exclusive lock - $handle = fopen($this->locksFile,'a+'); - flock($handle,LOCK_EX); - - // We can only truncate and rewind once the lock is acquired. - ftruncate($handle,0); - rewind($handle); - - fwrite($handle,serialize($newData)); - fclose($handle); - - } - -} - diff --git a/3rdparty/Sabre/DAV/Locks/Backend/PDO.php b/3rdparty/Sabre/DAV/Locks/Backend/PDO.php deleted file mode 100644 index c3923af19d3ea6d5eae4235711b175ef24672d71..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Locks/Backend/PDO.php +++ /dev/null @@ -1,165 +0,0 @@ -<?php - -/** - * The Lock manager allows you to handle all file-locks centrally. - * - * This Lock Manager stores all its data in a database. You must pass a PDO - * connection object in the constructor. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Locks_Backend_PDO extends Sabre_DAV_Locks_Backend_Abstract { - - /** - * The PDO connection object - * - * @var pdo - */ - private $pdo; - - /** - * The PDO tablename this backend uses. - * - * @var string - */ - protected $tableName; - - /** - * Constructor - * - * @param PDO $pdo - * @param string $tableName - */ - public function __construct(PDO $pdo, $tableName = 'locks') { - - $this->pdo = $pdo; - $this->tableName = $tableName; - - } - - /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects - * - * This method should return all the locks for a particular uri, including - * locks that might be set on a parent uri. - * - * If returnChildLocks is set to true, this method should also look for - * any locks in the subtree of the uri for locks. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks) { - - // NOTE: the following 10 lines or so could be easily replaced by - // pure sql. MySQL's non-standard string concatination prevents us - // from doing this though. - $query = 'SELECT owner, token, timeout, created, scope, depth, uri FROM `'.$this->tableName.'` WHERE ((created + timeout) > CAST(? AS UNSIGNED INTEGER)) AND ((uri = ?)'; - $params = array(time(),$uri); - - // We need to check locks for every part in the uri. - $uriParts = explode('/',$uri); - - // We already covered the last part of the uri - array_pop($uriParts); - - $currentPath=''; - - foreach($uriParts as $part) { - - if ($currentPath) $currentPath.='/'; - $currentPath.=$part; - - $query.=' OR (depth!=0 AND uri = ?)'; - $params[] = $currentPath; - - } - - if ($returnChildLocks) { - - $query.=' OR (uri LIKE ?)'; - $params[] = $uri . '/%'; - - } - $query.=')'; - - $stmt = $this->pdo->prepare($query); - $stmt->execute($params); - $result = $stmt->fetchAll(); - - $lockList = array(); - foreach($result as $row) { - - $lockInfo = new Sabre_DAV_Locks_LockInfo(); - $lockInfo->owner = $row['owner']; - $lockInfo->token = $row['token']; - $lockInfo->timeout = $row['timeout']; - $lockInfo->created = $row['created']; - $lockInfo->scope = $row['scope']; - $lockInfo->depth = $row['depth']; - $lockInfo->uri = $row['uri']; - $lockList[] = $lockInfo; - - } - - return $lockList; - - } - - /** - * Locks a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - // We're making the lock timeout 30 minutes - $lockInfo->timeout = 30*60; - $lockInfo->created = time(); - $lockInfo->uri = $uri; - - $locks = $this->getLocks($uri,false); - $exists = false; - foreach($locks as $k=>$lock) { - if ($lock->token == $lockInfo->token) $exists = true; - } - - if ($exists) { - $stmt = $this->pdo->prepare('UPDATE `'.$this->tableName.'` SET owner = ?, timeout = ?, scope = ?, depth = ?, uri = ?, created = ? WHERE token = ?'); - $stmt->execute(array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); - } else { - $stmt = $this->pdo->prepare('INSERT INTO `'.$this->tableName.'` (owner,timeout,scope,depth,uri,created,token) VALUES (?,?,?,?,?,?,?)'); - $stmt->execute(array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); - } - - return true; - - } - - - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->tableName.'` WHERE uri = ? AND token = ?'); - $stmt->execute(array($uri,$lockInfo->token)); - - return $stmt->rowCount()===1; - - } - -} - diff --git a/3rdparty/Sabre/DAV/Locks/LockInfo.php b/3rdparty/Sabre/DAV/Locks/LockInfo.php deleted file mode 100644 index 6a064466f4015303ca802b44b05d2617e33ce0ad..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Locks/LockInfo.php +++ /dev/null @@ -1,81 +0,0 @@ -<?php - -/** - * LockInfo class - * - * An object of the LockInfo class holds all the information relevant to a - * single lock. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Locks_LockInfo { - - /** - * A shared lock - */ - const SHARED = 1; - - /** - * An exclusive lock - */ - const EXCLUSIVE = 2; - - /** - * A never expiring timeout - */ - const TIMEOUT_INFINITE = -1; - - /** - * The owner of the lock - * - * @var string - */ - public $owner; - - /** - * The locktoken - * - * @var string - */ - public $token; - - /** - * How long till the lock is expiring - * - * @var int - */ - public $timeout; - - /** - * UNIX Timestamp of when this lock was created - * - * @var int - */ - public $created; - - /** - * Exclusive or shared lock - * - * @var int - */ - public $scope = self::EXCLUSIVE; - - /** - * Depth of lock, can be 0 or Sabre_DAV_Server::DEPTH_INFINITY - */ - public $depth = 0; - - /** - * The uri this lock locks - * - * TODO: This value is not always set - * @var mixed - */ - public $uri; - -} - diff --git a/3rdparty/Sabre/DAV/Locks/Plugin.php b/3rdparty/Sabre/DAV/Locks/Plugin.php deleted file mode 100644 index 461e2847e0ae8e562827294eb4d550b19b3b4530..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Locks/Plugin.php +++ /dev/null @@ -1,680 +0,0 @@ -<?php - -/** - * Locking plugin - * - * This plugin provides locking support to a WebDAV server. - * The easiest way to get started, is by hooking it up as such: - * - * $lockBackend = new Sabre_DAV_Locks_Backend_File('./mylockdb'); - * $lockPlugin = new Sabre_DAV_Locks_Plugin($lockBackend); - * $server->addPlugin($lockPlugin); - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { - - /** - * locksBackend - * - * @var Sabre_DAV_Locks_Backend_Abstract - */ - private $locksBackend; - - /** - * server - * - * @var Sabre_DAV_Server - */ - private $server; - - /** - * __construct - * - * @param Sabre_DAV_Locks_Backend_Abstract $locksBackend - * @return void - */ - public function __construct(Sabre_DAV_Locks_Backend_Abstract $locksBackend = null) { - - $this->locksBackend = $locksBackend; - - } - - /** - * Initializes the plugin - * - * This method is automatically called by the Server class after addPlugin. - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('unknownMethod',array($this,'unknownMethod')); - $server->subscribeEvent('beforeMethod',array($this,'beforeMethod'),50); - $server->subscribeEvent('afterGetProperties',array($this,'afterGetProperties')); - - } - - /** - * Returns a plugin name. - * - * Using this name other plugins will be able to access other plugins - * using Sabre_DAV_Server::getPlugin - * - * @return string - */ - public function getPluginName() { - - return 'locks'; - - } - - /** - * This method is called by the Server if the user used an HTTP method - * the server didn't recognize. - * - * This plugin intercepts the LOCK and UNLOCK methods. - * - * @param string $method - * @return bool - */ - public function unknownMethod($method, $uri) { - - switch($method) { - - case 'LOCK' : $this->httpLock($uri); return false; - case 'UNLOCK' : $this->httpUnlock($uri); return false; - - } - - } - - /** - * This method is called after most properties have been found - * it allows us to add in any Lock-related properties - * - * @param string $path - * @param array $properties - * @return bool - */ - public function afterGetProperties($path,&$newProperties) { - - foreach($newProperties[404] as $propName=>$discard) { - - $node = null; - - switch($propName) { - - case '{DAV:}supportedlock' : - $val = false; - if ($this->locksBackend) $val = true; - else { - if (!$node) $node = $this->server->tree->getNodeForPath($path); - if ($node instanceof Sabre_DAV_ILockable) $val = true; - } - $newProperties[200][$propName] = new Sabre_DAV_Property_SupportedLock($val); - unset($newProperties[404][$propName]); - break; - - case '{DAV:}lockdiscovery' : - $newProperties[200][$propName] = new Sabre_DAV_Property_LockDiscovery($this->getLocks($path)); - unset($newProperties[404][$propName]); - break; - - } - - - } - return true; - - } - - - /** - * This method is called before the logic for any HTTP method is - * handled. - * - * This plugin uses that feature to intercept access to locked resources. - * - * @param string $method - * @param string $uri - * @return bool - */ - public function beforeMethod($method, $uri) { - - switch($method) { - - case 'DELETE' : - $lastLock = null; - if (!$this->validateLock($uri,$lastLock, true)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - case 'MKCOL' : - case 'PROPPATCH' : - case 'PUT' : - $lastLock = null; - if (!$this->validateLock($uri,$lastLock)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - case 'MOVE' : - $lastLock = null; - if (!$this->validateLock(array( - $uri, - $this->server->calculateUri($this->server->httpRequest->getHeader('Destination')), - ),$lastLock, true)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - case 'COPY' : - $lastLock = null; - if (!$this->validateLock( - $this->server->calculateUri($this->server->httpRequest->getHeader('Destination')), - $lastLock, true)) - throw new Sabre_DAV_Exception_Locked($lastLock); - break; - } - - return true; - - } - - /** - * Use this method to tell the server this plugin defines additional - * HTTP methods. - * - * This method is passed a uri. It should only return HTTP methods that are - * available for the specified uri. - * - * @param string $uri - * @return array - */ - public function getHTTPMethods($uri) { - - if ($this->locksBackend || - $this->server->tree->getNodeForPath($uri) instanceof Sabre_DAV_ILocks) { - return array('LOCK','UNLOCK'); - } - return array(); - - } - - /** - * Returns a list of features for the HTTP OPTIONS Dav: header. - * - * In this case this is only the number 2. The 2 in the Dav: header - * indicates the server supports locks. - * - * @return array - */ - public function getFeatures() { - - return array(2); - - } - - /** - * Returns all lock information on a particular uri - * - * This function should return an array with Sabre_DAV_Locks_LockInfo objects. If there are no locks on a file, return an empty array. - * - * Additionally there is also the possibility of locks on parent nodes, so we'll need to traverse every part of the tree - * If the $returnChildLocks argument is set to true, we'll also traverse all the children of the object - * for any possible locks and return those as well. - * - * @param string $uri - * @param bool $returnChildLocks - * @return array - */ - public function getLocks($uri, $returnChildLocks = false) { - - $lockList = array(); - $currentPath = ''; - foreach(explode('/',$uri) as $uriPart) { - - $uriLocks = array(); - if ($currentPath) $currentPath.='/'; - $currentPath.=$uriPart; - - try { - - $node = $this->server->tree->getNodeForPath($currentPath); - if ($node instanceof Sabre_DAV_ILockable) $uriLocks = $node->getLocks(); - - } catch (Sabre_DAV_Exception_FileNotFound $e){ - // In case the node didn't exist, this could be a lock-null request - } - - foreach($uriLocks as $uriLock) { - - // Unless we're on the leaf of the uri-tree we should ignore locks with depth 0 - if($uri==$currentPath || $uriLock->depth!=0) { - $uriLock->uri = $currentPath; - $lockList[] = $uriLock; - } - - } - - } - if ($this->locksBackend) - $lockList = array_merge($lockList,$this->locksBackend->getLocks($uri, $returnChildLocks)); - - return $lockList; - - } - - /** - * Locks an uri - * - * The WebDAV lock request can be operated to either create a new lock on a file, or to refresh an existing lock - * If a new lock is created, a full XML body should be supplied, containing information about the lock such as the type - * of lock (shared or exclusive) and the owner of the lock - * - * If a lock is to be refreshed, no body should be supplied and there should be a valid If header containing the lock - * - * Additionally, a lock can be requested for a non-existant file. In these case we're obligated to create an empty file as per RFC4918:S7.3 - * - * @param string $uri - * @return void - */ - protected function httpLock($uri) { - - $lastLock = null; - if (!$this->validateLock($uri,$lastLock)) { - - // If the existing lock was an exclusive lock, we need to fail - if (!$lastLock || $lastLock->scope == Sabre_DAV_Locks_LockInfo::EXCLUSIVE) { - //var_dump($lastLock); - throw new Sabre_DAV_Exception_ConflictingLock($lastLock); - } - - } - - if ($body = $this->server->httpRequest->getBody(true)) { - // This is a new lock request - $lockInfo = $this->parseLockRequest($body); - $lockInfo->depth = $this->server->getHTTPDepth(); - $lockInfo->uri = $uri; - if($lastLock && $lockInfo->scope != Sabre_DAV_Locks_LockInfo::SHARED) throw new Sabre_DAV_Exception_ConflictingLock($lastLock); - - } elseif ($lastLock) { - - // This must have been a lock refresh - $lockInfo = $lastLock; - - // The resource could have been locked through another uri. - if ($uri!=$lockInfo->uri) $uri = $lockInfo->uri; - - } else { - - // There was neither a lock refresh nor a new lock request - throw new Sabre_DAV_Exception_BadRequest('An xml body is required for lock requests'); - - } - - if ($timeout = $this->getTimeoutHeader()) $lockInfo->timeout = $timeout; - - $newFile = false; - - // If we got this far.. we should go check if this node actually exists. If this is not the case, we need to create it first - try { - $node = $this->server->tree->getNodeForPath($uri); - - // We need to call the beforeWriteContent event for RFC3744 - $this->server->broadcastEvent('beforeWriteContent',array($uri)); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - // It didn't, lets create it - $this->server->createFile($uri,fopen('php://memory','r')); - $newFile = true; - - } - - $this->lockNode($uri,$lockInfo); - - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->setHeader('Lock-Token','<opaquelocktoken:' . $lockInfo->token . '>'); - $this->server->httpResponse->sendStatus($newFile?201:200); - $this->server->httpResponse->sendBody($this->generateLockResponse($lockInfo)); - - } - - /** - * Unlocks a uri - * - * This WebDAV method allows you to remove a lock from a node. The client should provide a valid locktoken through the Lock-token http header - * The server should return 204 (No content) on success - * - * @param string $uri - * @return void - */ - protected function httpUnlock($uri) { - - $lockToken = $this->server->httpRequest->getHeader('Lock-Token'); - - // If the locktoken header is not supplied, we need to throw a bad request exception - if (!$lockToken) throw new Sabre_DAV_Exception_BadRequest('No lock token was supplied'); - - $locks = $this->getLocks($uri); - - // Windows sometimes forgets to include < and > in the Lock-Token - // header - if ($lockToken[0]!=='<') $lockToken = '<' . $lockToken . '>'; - - foreach($locks as $lock) { - - if ('<opaquelocktoken:' . $lock->token . '>' == $lockToken) { - - $this->server->broadcastEvent('beforeUnlock',array($uri, $lock)); - $this->unlockNode($uri,$lock); - $this->server->httpResponse->setHeader('Content-Length','0'); - $this->server->httpResponse->sendStatus(204); - return; - - } - - } - - // If we got here, it means the locktoken was invalid - throw new Sabre_DAV_Exception_LockTokenMatchesRequestUri(); - - } - - /** - * Locks a uri - * - * All the locking information is supplied in the lockInfo object. The object has a suggested timeout, but this can be safely ignored - * It is important that if the existing timeout is ignored, the property is overwritten, as this needs to be sent back to the client - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return void - */ - public function lockNode($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - if (!$this->server->broadcastEvent('beforeLock',array($uri,$lockInfo))) return; - - try { - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_DAV_ILockable) return $node->lock($lockInfo); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // In case the node didn't exist, this could be a lock-null request - } - if ($this->locksBackend) return $this->locksBackend->lock($uri,$lockInfo); - throw new Sabre_DAV_Exception_MethodNotAllowed('Locking support is not enabled for this resource. No Locking backend was found so if you didn\'t expect this error, please check your configuration.'); - - } - - /** - * Unlocks a uri - * - * This method removes a lock from a uri. It is assumed all the supplied information is correct and verified - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return void - */ - public function unlockNode($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - if (!$this->server->broadcastEvent('beforeUnlock',array($uri,$lockInfo))) return; - try { - $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_DAV_ILockable) return $node->unlock($lockInfo); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // In case the node didn't exist, this could be a lock-null request - } - - if ($this->locksBackend) return $this->locksBackend->unlock($uri,$lockInfo); - - } - - - /** - * Returns the contents of the HTTP Timeout header. - * - * The method formats the header into an integer. - * - * @return int - */ - public function getTimeoutHeader() { - - $header = $this->server->httpRequest->getHeader('Timeout'); - - if ($header) { - - if (stripos($header,'second-')===0) $header = (int)(substr($header,7)); - else if (strtolower($header)=='infinite') $header=Sabre_DAV_Locks_LockInfo::TIMEOUT_INFINITE; - else throw new Sabre_DAV_Exception_BadRequest('Invalid HTTP timeout header'); - - } else { - - $header = 0; - - } - - return $header; - - } - - /** - * Generates the response for successfull LOCK requests - * - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return string - */ - protected function generateLockResponse(Sabre_DAV_Locks_LockInfo $lockInfo) { - - $dom = new DOMDocument('1.0','utf-8'); - $dom->formatOutput = true; - - $prop = $dom->createElementNS('DAV:','d:prop'); - $dom->appendChild($prop); - - $lockDiscovery = $dom->createElementNS('DAV:','d:lockdiscovery'); - $prop->appendChild($lockDiscovery); - - $lockObj = new Sabre_DAV_Property_LockDiscovery(array($lockInfo),true); - $lockObj->serialize($this->server,$lockDiscovery); - - return $dom->saveXML(); - - } - - /** - * validateLock should be called when a write operation is about to happen - * It will check if the requested url is locked, and see if the correct lock tokens are passed - * - * @param mixed $urls List of relevant urls. Can be an array, a string or nothing at all for the current request uri - * @param mixed $lastLock This variable will be populated with the last checked lock object (Sabre_DAV_Locks_LockInfo) - * @param bool $checkChildLocks If set to true, this function will also look for any locks set on child resources of the supplied urls. This is needed for for example deletion of entire trees. - * @return bool - */ - protected function validateLock($urls = null,&$lastLock = null, $checkChildLocks = false) { - - if (is_null($urls)) { - $urls = array($this->server->getRequestUri()); - } elseif (is_string($urls)) { - $urls = array($urls); - } elseif (!is_array($urls)) { - throw new Sabre_DAV_Exception('The urls parameter should either be null, a string or an array'); - } - - $conditions = $this->getIfConditions(); - - // We're going to loop through the urls and make sure all lock conditions are satisfied - foreach($urls as $url) { - - $locks = $this->getLocks($url, $checkChildLocks); - - // If there were no conditions, but there were locks, we fail - if (!$conditions && $locks) { - reset($locks); - $lastLock = current($locks); - return false; - } - - // If there were no locks or conditions, we go to the next url - if (!$locks && !$conditions) continue; - - foreach($conditions as $condition) { - - if (!$condition['uri']) { - $conditionUri = $this->server->getRequestUri(); - } else { - $conditionUri = $this->server->calculateUri($condition['uri']); - } - - // If the condition has a url, and it isn't part of the affected url at all, check the next condition - if ($conditionUri && strpos($url,$conditionUri)!==0) continue; - - // The tokens array contians arrays with 2 elements. 0=true/false for normal/not condition, 1=locktoken - // At least 1 condition has to be satisfied - foreach($condition['tokens'] as $conditionToken) { - - $etagValid = true; - $lockValid = true; - - // key 2 can contain an etag - if ($conditionToken[2]) { - - $uri = $conditionUri?$conditionUri:$this->server->getRequestUri(); - $node = $this->server->tree->getNodeForPath($uri); - $etagValid = $node->getETag()==$conditionToken[2]; - - } - - // key 1 can contain a lock token - if ($conditionToken[1]) { - - $lockValid = false; - // Match all the locks - foreach($locks as $lockIndex=>$lock) { - - $lockToken = 'opaquelocktoken:' . $lock->token; - - // Checking NOT - if (!$conditionToken[0] && $lockToken != $conditionToken[1]) { - - // Condition valid, onto the next - $lockValid = true; - break; - } - if ($conditionToken[0] && $lockToken == $conditionToken[1]) { - - $lastLock = $lock; - // Condition valid and lock matched - unset($locks[$lockIndex]); - $lockValid = true; - break; - - } - - } - - } - - // If, after checking both etags and locks they are stil valid, - // we can continue with the next condition. - if ($etagValid && $lockValid) continue 2; - } - // No conditions matched, so we fail - throw new Sabre_DAV_Exception_PreconditionFailed('The tokens provided in the if header did not match','If'); - } - - // Conditions were met, we'll also need to check if all the locks are gone - if (count($locks)) { - - reset($locks); - - // There's still locks, we fail - $lastLock = current($locks); - return false; - - } - - - } - - // We got here, this means every condition was satisfied - return true; - - } - - /** - * This method is created to extract information from the WebDAV HTTP 'If:' header - * - * The If header can be quite complex, and has a bunch of features. We're using a regex to extract all relevant information - * The function will return an array, containg structs with the following keys - * - * * uri - the uri the condition applies to. If this is returned as an - * empty string, this implies it's referring to the request url. - * * tokens - The lock token. another 2 dimensional array containg 2 elements (0 = true/false.. If this is a negative condition its set to false, 1 = the actual token) - * * etag - an etag, if supplied - * - * @return void - */ - public function getIfConditions() { - - $header = $this->server->httpRequest->getHeader('If'); - if (!$header) return array(); - - $matches = array(); - - $regex = '/(?:\<(?P<uri>.*?)\>\s)?\((?P<not>Not\s)?(?:\<(?P<token>[^\>]*)\>)?(?:\s?)(?:\[(?P<etag>[^\]]*)\])?\)/im'; - preg_match_all($regex,$header,$matches,PREG_SET_ORDER); - - $conditions = array(); - - foreach($matches as $match) { - - $condition = array( - 'uri' => $match['uri'], - 'tokens' => array( - array($match['not']?0:1,$match['token'],isset($match['etag'])?$match['etag']:'') - ), - ); - - if (!$condition['uri'] && count($conditions)) $conditions[count($conditions)-1]['tokens'][] = array( - $match['not']?0:1, - $match['token'], - isset($match['etag'])?$match['etag']:'' - ); - else { - $conditions[] = $condition; - } - - } - - return $conditions; - - } - - /** - * Parses a webdav lock xml body, and returns a new Sabre_DAV_Locks_LockInfo object - * - * @param string $body - * @return Sabre_DAV_Locks_LockInfo - */ - protected function parseLockRequest($body) { - - $xml = simplexml_load_string($body,null,LIBXML_NOWARNING); - $xml->registerXPathNamespace('d','DAV:'); - $lockInfo = new Sabre_DAV_Locks_LockInfo(); - - $children = $xml->children("DAV:"); - $lockInfo->owner = (string)$children->owner; - - $lockInfo->token = Sabre_DAV_UUIDUtil::getUUID(); - $lockInfo->scope = count($xml->xpath('d:lockscope/d:exclusive'))>0?Sabre_DAV_Locks_LockInfo::EXCLUSIVE:Sabre_DAV_Locks_LockInfo::SHARED; - - return $lockInfo; - - } - - -} diff --git a/3rdparty/Sabre/DAV/Mount/Plugin.php b/3rdparty/Sabre/DAV/Mount/Plugin.php deleted file mode 100644 index f93a1aa25a1f00793e848d2fdb752ab092be785d..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Mount/Plugin.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php - -/** - * This plugin provides support for RFC4709: Mounting WebDAV servers - * - * Simply append ?mount to any collection to generate the davmount response. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - */ -class Sabre_DAV_Mount_Plugin extends Sabre_DAV_ServerPlugin { - - /** - * Reference to Server class - * - * @var Sabre_DAV_Server - */ - private $server; - - /** - * Initializes the plugin and registers event handles - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'), 90); - - } - - /** - * 'beforeMethod' event handles. This event handles intercepts GET requests ending - * with ?mount - * - * @param string $method - * @return void - */ - public function beforeMethod($method, $uri) { - - if ($method!='GET') return; - if ($this->server->httpRequest->getQueryString()!='mount') return; - - $currentUri = $this->server->httpRequest->getAbsoluteUri(); - - // Stripping off everything after the ? - list($currentUri) = explode('?',$currentUri); - - $this->davMount($currentUri); - - // Returning false to break the event chain - return false; - - } - - /** - * Generates the davmount response - * - * @param string $uri absolute uri - * @return void - */ - public function davMount($uri) { - - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->setHeader('Content-Type','application/davmount+xml'); - ob_start(); - echo '<?xml version="1.0"?>', "\n"; - echo "<dm:mount xmlns:dm=\"http://purl.org/NET/webdav/mount\">\n"; - echo " <dm:url>", htmlspecialchars($uri, ENT_NOQUOTES, 'UTF-8'), "</dm:url>\n"; - echo "</dm:mount>"; - $this->server->httpResponse->sendBody(ob_get_clean()); - - } - - -} diff --git a/3rdparty/Sabre/DAV/Node.php b/3rdparty/Sabre/DAV/Node.php deleted file mode 100644 index 0510df5fdf28156bd1941cce78f1734992377308..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Node.php +++ /dev/null @@ -1,55 +0,0 @@ -<?php - -/** - * Node class - * - * This is a helper class, that should aid in getting nodes setup. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_Node implements Sabre_DAV_INode { - - /** - * Returns the last modification time - * - * In this case, it will simply return the current time - * - * @return int - */ - public function getLastModified() { - - return time(); - - } - - /** - * Deleted the current node - * - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to delete node'); - - } - - /** - * Renames the node - * - * @throws Sabre_DAV_Exception_Forbidden - * @param string $name The new name - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to rename file'); - - } - -} - diff --git a/3rdparty/Sabre/DAV/ObjectTree.php b/3rdparty/Sabre/DAV/ObjectTree.php deleted file mode 100644 index f12a36837052c058d4a35e7ae30a0c48d4aeb13e..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/ObjectTree.php +++ /dev/null @@ -1,154 +0,0 @@ -<?php - -/** - * ObjectTree class - * - * This implementation of the Tree class makes use of the INode, IFile and ICollection API's - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_ObjectTree extends Sabre_DAV_Tree { - - /** - * The root node - * - * @var Sabre_DAV_ICollection - */ - protected $rootNode; - - /** - * This is the node cache. Accessed nodes are stored here - * - * @var array - */ - protected $cache = array(); - - /** - * Creates the object - * - * This method expects the rootObject to be passed as a parameter - * - * @param Sabre_DAV_ICollection $rootNode - * @return void - */ - public function __construct(Sabre_DAV_ICollection $rootNode) { - - $this->rootNode = $rootNode; - - } - - /** - * Returns the INode object for the requested path - * - * @param string $path - * @return Sabre_DAV_INode - */ - public function getNodeForPath($path) { - - $path = trim($path,'/'); - if (isset($this->cache[$path])) return $this->cache[$path]; - - //if (!$path || $path=='.') return $this->rootNode; - $currentNode = $this->rootNode; - $i=0; - // We're splitting up the path variable into folder/subfolder components and traverse to the correct node.. - foreach(explode('/',$path) as $pathPart) { - - // If this part of the path is just a dot, it actually means we can skip it - if ($pathPart=='.' || $pathPart=='') continue; - - if (!($currentNode instanceof Sabre_DAV_ICollection)) - throw new Sabre_DAV_Exception_FileNotFound('Could not find node at path: ' . $path); - - $currentNode = $currentNode->getChild($pathPart); - - } - - $this->cache[$path] = $currentNode; - return $currentNode; - - } - - /** - * This function allows you to check if a node exists. - * - * @param string $path - * @return bool - */ - public function nodeExists($path) { - - try { - - // The root always exists - if ($path==='') return true; - - list($parent, $base) = Sabre_DAV_URLUtil::splitPath($path); - - $parentNode = $this->getNodeForPath($parent); - if (!$parentNode instanceof Sabre_DAV_ICollection) return false; - return $parentNode->childExists($base); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - return false; - - } - - } - - /** - * Returns a list of childnodes for a given path. - * - * @param string $path - * @return array - */ - public function getChildren($path) { - - $node = $this->getNodeForPath($path); - $children = $node->getChildren(); - foreach($children as $child) { - - $this->cache[trim($path,'/') . '/' . $child->getName()] = $child; - - } - return $children; - - } - - /** - * This method is called with every tree update - * - * Examples of tree updates are: - * * node deletions - * * node creations - * * copy - * * move - * * renaming nodes - * - * If Tree classes implement a form of caching, this will allow - * them to make sure caches will be expired. - * - * If a path is passed, it is assumed that the entire subtree is dirty - * - * @param string $path - * @return void - */ - public function markDirty($path) { - - // We don't care enough about sub-paths - // flushing the entire cache - $path = trim($path,'/'); - foreach($this->cache as $nodePath=>$node) { - if ($nodePath == $path || strpos($nodePath,$path.'/')===0) - unset($this->cache[$nodePath]); - - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property.php b/3rdparty/Sabre/DAV/Property.php deleted file mode 100644 index 577535b012769b418a41f58487dd8c1718551a2e..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Property.php +++ /dev/null @@ -1,25 +0,0 @@ -<?php - -/** - * Abstract property class - * - * Extend this class to create custom complex properties - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_Property { - - abstract function serialize(Sabre_DAV_Server $server, DOMElement $prop); - - static function unserialize(DOMElement $prop) { - - throw new Sabre_DAV_Exception('Unserialize has not been implemented for this class'); - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property/GetLastModified.php b/3rdparty/Sabre/DAV/Property/GetLastModified.php deleted file mode 100644 index 4a81262997148025ecc68f28d55c243c8f6e0f1a..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Property/GetLastModified.php +++ /dev/null @@ -1,75 +0,0 @@ -<?php - -/** - * This property represents the {DAV:}getlastmodified property. - * - * Although this is normally a simple property, windows requires us to add - * some new attributes. - * - * This class uses unix timestamps internally, and converts them to RFC 1123 times for - * serialization - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Property_GetLastModified extends Sabre_DAV_Property { - - /** - * time - * - * @var int - */ - public $time; - - /** - * __construct - * - * @param int|DateTime $time - * @return void - */ - public function __construct($time) { - - if ($time instanceof DateTime) { - $this->time = $time; - } elseif (is_int($time) || ctype_digit($time)) { - $this->time = new DateTime('@' . $time); - } else { - $this->time = new DateTime($time); - } - - // Setting timezone to UTC - $this->time->setTimezone(new DateTimeZone('UTC')); - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server, DOMElement $prop) { - - $doc = $prop->ownerDocument; - $prop->setAttribute('xmlns:b','urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/'); - $prop->setAttribute('b:dt','dateTime.rfc1123'); - $prop->nodeValue = $this->time->format(DateTime::RFC1123); - - } - - /** - * getTime - * - * @return DateTime - */ - public function getTime() { - - return $this->time; - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property/Href.php b/3rdparty/Sabre/DAV/Property/Href.php deleted file mode 100644 index 3294ff2ac6848fcf0564af191c10c2a7e9cd010b..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Property/Href.php +++ /dev/null @@ -1,91 +0,0 @@ -<?php - -/** - * Href property - * - * The href property represpents a url within a {DAV:}href element. - * This is used by many WebDAV extensions, but not really within the WebDAV core spec - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Property_Href extends Sabre_DAV_Property implements Sabre_DAV_Property_IHref { - - /** - * href - * - * @var string - */ - private $href; - - /** - * Automatically prefix the url with the server base directory - * - * @var bool - */ - private $autoPrefix = true; - - /** - * __construct - * - * @param string $href - * @return void - */ - public function __construct($href, $autoPrefix = true) { - - $this->href = $href; - $this->autoPrefix = $autoPrefix; - - } - - /** - * Returns the uri - * - * @return string - */ - public function getHref() { - - return $this->href; - - } - - /** - * Serializes this property. - * - * It will additionally prepend the href property with the server's base uri. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - $prefix = $server->xmlNamespaces['DAV:']; - - $elem = $dom->ownerDocument->createElement($prefix . ':href'); - $elem->nodeValue = ($this->autoPrefix?$server->getBaseUri():'') . $this->href; - $dom->appendChild($elem); - - } - - /** - * Unserializes this property from a DOM Element - * - * This method returns an instance of this class. - * It will only decode {DAV:}href values. For non-compatible elements null will be returned. - * - * @param DOMElement $dom - * @return Sabre_DAV_Property_Href - */ - static function unserialize(DOMElement $dom) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild)==='{DAV:}href') { - return new self($dom->firstChild->textContent,false); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/HrefList.php b/3rdparty/Sabre/DAV/Property/HrefList.php deleted file mode 100644 index 76a5512901c6ded74e7ccfc33d2f1460dfcae8d3..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Property/HrefList.php +++ /dev/null @@ -1,96 +0,0 @@ -<?php - -/** - * HrefList property - * - * This property contains multiple {DAV:}href elements, each containing a url. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Property_HrefList extends Sabre_DAV_Property { - - /** - * hrefs - * - * @var array - */ - private $hrefs; - - /** - * Automatically prefix the url with the server base directory - * - * @var bool - */ - private $autoPrefix = true; - - /** - * __construct - * - * @param array $hrefs - * @param bool $autoPrefix - */ - public function __construct(array $hrefs, $autoPrefix = true) { - - $this->hrefs = $hrefs; - $this->autoPrefix = $autoPrefix; - - } - - /** - * Returns the uris - * - * @return array - */ - public function getHrefs() { - - return $this->hrefs; - - } - - /** - * Serializes this property. - * - * It will additionally prepend the href property with the server's base uri. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - $prefix = $server->xmlNamespaces['DAV:']; - - foreach($this->hrefs as $href) { - $elem = $dom->ownerDocument->createElement($prefix . ':href'); - $elem->nodeValue = ($this->autoPrefix?$server->getBaseUri():'') . $href; - $dom->appendChild($elem); - } - - } - - /** - * Unserializes this property from a DOM Element - * - * This method returns an instance of this class. - * It will only decode {DAV:}href values. - * - * @param DOMElement $dom - * @return Sabre_DAV_Property_Href - */ - static function unserialize(DOMElement $dom) { - - $hrefs = array(); - foreach($dom->childNodes as $child) { - if (Sabre_DAV_XMLUtil::toClarkNotation($child)==='{DAV:}href') { - $hrefs[] = $child->textContent; - } - } - return new self($hrefs, false); - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/IHref.php b/3rdparty/Sabre/DAV/Property/IHref.php deleted file mode 100644 index 29d76a44fcd3fb5cbcc143c829c72b07eeb53b3a..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Property/IHref.php +++ /dev/null @@ -1,25 +0,0 @@ -<?php - -/** - * IHref interface - * - * Any property implementing this interface can expose a related url. - * This is used by certain subsystems to aquire more information about for example - * the owner of a file - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAV_Property_IHref { - - /** - * getHref - * - * @return string - */ - function getHref(); - -} diff --git a/3rdparty/Sabre/DAV/Property/LockDiscovery.php b/3rdparty/Sabre/DAV/Property/LockDiscovery.php deleted file mode 100644 index 05c7470b4ed86f61448c47f6f11f6f76b74190e7..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Property/LockDiscovery.php +++ /dev/null @@ -1,102 +0,0 @@ -<?php - -/** - * Represents {DAV:}lockdiscovery property - * - * This property contains all the open locks on a given resource - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Property_LockDiscovery extends Sabre_DAV_Property { - - /** - * locks - * - * @var array - */ - public $locks; - - /** - * Should we show the locktoken as well? - * - * @var bool - */ - public $revealLockToken; - - /** - * Hides the {DAV:}lockroot element from the response. - * - * It was reported that showing the lockroot in the response can break - * Office 2000 compatibility. - */ - static public $hideLockRoot = false; - - /** - * __construct - * - * @param array $locks - * @param bool $revealLockToken - * @return void - */ - public function __construct($locks,$revealLockToken = false) { - - $this->locks = $locks; - $this->revealLockToken = $revealLockToken; - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - $doc = $prop->ownerDocument; - - foreach($this->locks as $lock) { - - $activeLock = $doc->createElementNS('DAV:','d:activelock'); - $prop->appendChild($activeLock); - - $lockScope = $doc->createElementNS('DAV:','d:lockscope'); - $activeLock->appendChild($lockScope); - - $lockScope->appendChild($doc->createElementNS('DAV:','d:' . ($lock->scope==Sabre_DAV_Locks_LockInfo::EXCLUSIVE?'exclusive':'shared'))); - - $lockType = $doc->createElementNS('DAV:','d:locktype'); - $activeLock->appendChild($lockType); - - $lockType->appendChild($doc->createElementNS('DAV:','d:write')); - - /* {DAV:}lockroot */ - if (!self::$hideLockRoot) { - $lockRoot = $doc->createElementNS('DAV:','d:lockroot'); - $activeLock->appendChild($lockRoot); - $href = $doc->createElementNS('DAV:','d:href'); - $href->appendChild($doc->createTextNode($server->getBaseUri() . $lock->uri)); - $lockRoot->appendChild($href); - } - - $activeLock->appendChild($doc->createElementNS('DAV:','d:depth',($lock->depth == Sabre_DAV_Server::DEPTH_INFINITY?'infinity':$lock->depth))); - $activeLock->appendChild($doc->createElementNS('DAV:','d:timeout','Second-' . $lock->timeout)); - - if ($this->revealLockToken) { - $lockToken = $doc->createElementNS('DAV:','d:locktoken'); - $activeLock->appendChild($lockToken); - $lockToken->appendChild($doc->createElementNS('DAV:','d:href','opaquelocktoken:' . $lock->token)); - } - - $activeLock->appendChild($doc->createElementNS('DAV:','d:owner',$lock->owner)); - - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property/ResourceType.php b/3rdparty/Sabre/DAV/Property/ResourceType.php deleted file mode 100644 index 2c606c22d60de7c84e4711a3e8c00f8355436ab4..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Property/ResourceType.php +++ /dev/null @@ -1,125 +0,0 @@ -<?php - -/** - * This class represents the {DAV:}resourcetype property - * - * Normally for files this is empty, and for collection {DAV:}collection. - * However, other specs define different values for this. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Property_ResourceType extends Sabre_DAV_Property { - - /** - * resourceType - * - * @var array - */ - public $resourceType = array(); - - /** - * __construct - * - * @param mixed $resourceType - * @return void - */ - public function __construct($resourceType = array()) { - - if ($resourceType === Sabre_DAV_Server::NODE_FILE) - $this->resourceType = array(); - elseif ($resourceType === Sabre_DAV_Server::NODE_DIRECTORY) - $this->resourceType = array('{DAV:}collection'); - elseif (is_array($resourceType)) - $this->resourceType = $resourceType; - else - $this->resourceType = array($resourceType); - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - $propName = null; - $rt = $this->resourceType; - - foreach($rt as $resourceType) { - if (preg_match('/^{([^}]*)}(.*)$/',$resourceType,$propName)) { - - if (isset($server->xmlNamespaces[$propName[1]])) { - $prop->appendChild($prop->ownerDocument->createElement($server->xmlNamespaces[$propName[1]] . ':' . $propName[2])); - } else { - $prop->appendChild($prop->ownerDocument->createElementNS($propName[1],'custom:' . $propName[2])); - } - - } - } - - } - - /** - * Returns the values in clark-notation - * - * For example array('{DAV:}collection') - * - * @return array - */ - public function getValue() { - - return $this->resourceType; - - } - - /** - * Checks if the principal contains a certain value - * - * @param string $type - * @return bool - */ - public function is($type) { - - return in_array($type, $this->resourceType); - - } - - /** - * Adds a resourcetype value to this property - * - * @param string $type - * @return void - */ - public function add($type) { - - $this->resourceType[] = $type; - $this->resourceType = array_unique($this->resourceType); - - } - - /** - * Unserializes a DOM element into a ResourceType property. - * - * @param DOMElement $dom - * @return void - */ - static public function unserialize(DOMElement $dom) { - - $value = array(); - foreach($dom->childNodes as $child) { - - $value[] = Sabre_DAV_XMLUtil::toClarkNotation($child); - - } - - return new self($value); - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/Response.php b/3rdparty/Sabre/DAV/Property/Response.php deleted file mode 100644 index 7d3a2db0387d190966a801d0488a69f3e610be5e..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Property/Response.php +++ /dev/null @@ -1,156 +0,0 @@ -<?php - -/** - * Response property - * - * This class represents the {DAV:}response XML element. - * This is used by the Server class to encode individual items within a multistatus - * response. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Property_Response extends Sabre_DAV_Property implements Sabre_DAV_Property_IHref { - - /** - * Url for the response - * - * @var string - */ - private $href; - - /** - * Propertylist, ordered by HTTP status code - * - * @var array - */ - private $responseProperties; - - /** - * The responseProperties argument is a list of properties - * within an array with keys representing HTTP status codes - * - * @param string $href - * @param array $responseProperties - * @return void - */ - public function __construct($href,array $responseProperties) { - - $this->href = $href; - $this->responseProperties = $responseProperties; - - } - - /** - * Returns the url - * - * @return string - */ - public function getHref() { - - return $this->href; - - } - - /** - * Returns the property list - * - * @return array - */ - public function getResponseProperties() { - - return $this->responseProperties; - - } - - /** - * serialize - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - $document = $dom->ownerDocument; - $properties = $this->responseProperties; - - $xresponse = $document->createElement('d:response'); - $dom->appendChild($xresponse); - - $uri = Sabre_DAV_URLUtil::encodePath($this->href); - - // Adding the baseurl to the beginning of the url - $uri = $server->getBaseUri() . $uri; - - $xresponse->appendChild($document->createElement('d:href',$uri)); - - // The properties variable is an array containing properties, grouped by - // HTTP status - foreach($properties as $httpStatus=>$propertyGroup) { - - // The 'href' is also in this array, and it's special cased. - // We will ignore it - if ($httpStatus=='href') continue; - - // If there are no properties in this group, we can also just carry on - if (!count($propertyGroup)) continue; - - $xpropstat = $document->createElement('d:propstat'); - $xresponse->appendChild($xpropstat); - - $xprop = $document->createElement('d:prop'); - $xpropstat->appendChild($xprop); - - $nsList = $server->xmlNamespaces; - - foreach($propertyGroup as $propertyName=>$propertyValue) { - - $propName = null; - preg_match('/^{([^}]*)}(.*)$/',$propertyName,$propName); - - // special case for empty namespaces - if ($propName[1]=='') { - - $currentProperty = $document->createElement($propName[2]); - $xprop->appendChild($currentProperty); - $currentProperty->setAttribute('xmlns',''); - - } else { - - if (!isset($nsList[$propName[1]])) { - $nsList[$propName[1]] = 'x' . count($nsList); - } - - // If the namespace was defined in the top-level xml namespaces, it means - // there was already a namespace declaration, and we don't have to worry about it. - if (isset($server->xmlNamespaces[$propName[1]])) { - $currentProperty = $document->createElement($nsList[$propName[1]] . ':' . $propName[2]); - } else { - $currentProperty = $document->createElementNS($propName[1],$nsList[$propName[1]].':' . $propName[2]); - } - $xprop->appendChild($currentProperty); - - } - - if (is_scalar($propertyValue)) { - $text = $document->createTextNode($propertyValue); - $currentProperty->appendChild($text); - } elseif ($propertyValue instanceof Sabre_DAV_Property) { - $propertyValue->serialize($server,$currentProperty); - } elseif (!is_null($propertyValue)) { - throw new Sabre_DAV_Exception('Unknown property value type: ' . gettype($propertyValue) . ' for property: ' . $propertyName); - } - - } - - $xpropstat->appendChild($document->createElement('d:status',$server->httpResponse->getStatusMessage($httpStatus))); - - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/ResponseList.php b/3rdparty/Sabre/DAV/Property/ResponseList.php deleted file mode 100644 index cd70b12861d05130f1cf0f399bdf74b2be710109..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Property/ResponseList.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php - -/** - * ResponseList property - * - * This class represents multiple {DAV:}response XML elements. - * This is used by the Server class to encode items within a multistatus - * response. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Property_ResponseList extends Sabre_DAV_Property { - - /** - * Response objects. - * - * @var array - */ - private $responses; - - /** - * The only valid argument is a list of Sabre_DAV_Property_Response - * objects. - * - * @param array $responses; - * @return void - */ - public function __construct($responses) { - - foreach($responses as $response) { - if (!($response instanceof Sabre_DAV_Property_Response)) { - throw new InvalidArgumentException('You must pass an array of Sabre_DAV_Property_Response objects'); - } - } - $this->responses = $responses; - - } - - /** - * serialize - * - * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - foreach($this->responses as $response) { - $response->serialize($server, $dom); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Property/SupportedLock.php b/3rdparty/Sabre/DAV/Property/SupportedLock.php deleted file mode 100644 index 01e63f58d9d5136a4f4b9aa5734d8acfdfd4b231..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Property/SupportedLock.php +++ /dev/null @@ -1,76 +0,0 @@ -<?php - -/** - * This class represents the {DAV:}supportedlock property - * - * This property contains information about what kind of locks - * this server supports. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Property_SupportedLock extends Sabre_DAV_Property { - - /** - * supportsLocks - * - * @var mixed - */ - public $supportsLocks = false; - - /** - * __construct - * - * @param mixed $supportsLocks - * @return void - */ - public function __construct($supportsLocks) { - - $this->supportsLocks = $supportsLocks; - - } - - /** - * serialize - * - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - $doc = $prop->ownerDocument; - - if (!$this->supportsLocks) return null; - - $lockEntry1 = $doc->createElementNS('DAV:','d:lockentry'); - $lockEntry2 = $doc->createElementNS('DAV:','d:lockentry'); - - $prop->appendChild($lockEntry1); - $prop->appendChild($lockEntry2); - - $lockScope1 = $doc->createElementNS('DAV:','d:lockscope'); - $lockScope2 = $doc->createElementNS('DAV:','d:lockscope'); - $lockType1 = $doc->createElementNS('DAV:','d:locktype'); - $lockType2 = $doc->createElementNS('DAV:','d:locktype'); - - $lockEntry1->appendChild($lockScope1); - $lockEntry1->appendChild($lockType1); - $lockEntry2->appendChild($lockScope2); - $lockEntry2->appendChild($lockType2); - - $lockScope1->appendChild($doc->createElementNS('DAV:','d:exclusive')); - $lockScope2->appendChild($doc->createElementNS('DAV:','d:shared')); - - $lockType1->appendChild($doc->createElementNS('DAV:','d:write')); - $lockType2->appendChild($doc->createElementNS('DAV:','d:write')); - - //$frag->appendXML('<d:lockentry><d:lockscope><d:exclusive /></d:lockscope><d:locktype><d:write /></d:locktype></d:lockentry>'); - //$frag->appendXML('<d:lockentry><d:lockscope><d:shared /></d:lockscope><d:locktype><d:write /></d:locktype></d:lockentry>'); - - } - -} - diff --git a/3rdparty/Sabre/DAV/Property/SupportedReportSet.php b/3rdparty/Sabre/DAV/Property/SupportedReportSet.php deleted file mode 100644 index acd9219c0f70656392622d700aebcba38f81e52c..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Property/SupportedReportSet.php +++ /dev/null @@ -1,110 +0,0 @@ -<?php - -/** - * supported-report-set property. - * - * This property is defined in RFC3253, but since it's - * so common in other webdav-related specs, it is part of the core server. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Property_SupportedReportSet extends Sabre_DAV_Property { - - /** - * List of reports - * - * @var array - */ - protected $reports = array(); - - /** - * Creates the property - * - * Any reports passed in the constructor - * should be valid report-types in clark-notation. - * - * Either a string or an array of strings must be passed. - * - * @param mixed $reports - * @return void - */ - public function __construct($reports = null) { - - if (!is_null($reports)) - $this->addReport($reports); - - } - - /** - * Adds a report to this property - * - * The report must be a string in clark-notation. - * Multiple reports can be specified as an array. - * - * @param mixed $report - * @return void - */ - public function addReport($report) { - - if (!is_array($report)) $report = array($report); - - foreach($report as $r) { - - if (!preg_match('/^{([^}]*)}(.*)$/',$r)) - throw new Sabre_DAV_Exception('Reportname must be in clark-notation'); - - $this->reports[] = $r; - - } - - } - - /** - * Returns the list of supported reports - * - * @return array - */ - public function getValue() { - - return $this->reports; - - } - - /** - * Serializes the node - * - * @param Sabre_DAV_Server $server - * @param DOMElement $prop - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - - foreach($this->reports as $reportName) { - - $supportedReport = $prop->ownerDocument->createElement('d:supported-report'); - $prop->appendChild($supportedReport); - - $report = $prop->ownerDocument->createElement('d:report'); - $supportedReport->appendChild($report); - - preg_match('/^{([^}]*)}(.*)$/',$reportName,$matches); - - list(, $namespace, $element) = $matches; - - $prefix = isset($server->xmlNamespaces[$namespace])?$server->xmlNamespaces[$namespace]:null; - - if ($prefix) { - $report->appendChild($prop->ownerDocument->createElement($prefix . ':' . $element)); - } else { - $report->appendChild($prop->ownerDocument->createElementNS($namespace, 'x:' . $element)); - } - - } - - } - -} diff --git a/3rdparty/Sabre/DAV/Server.php b/3rdparty/Sabre/DAV/Server.php deleted file mode 100644 index 3d76d4f1918e9cabff7576e6d94805d4cdd02d5d..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Server.php +++ /dev/null @@ -1,1941 +0,0 @@ -<?php - -/** - * Main DAV server class - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Server { - - /** - * Inifinity is used for some request supporting the HTTP Depth header and indicates that the operation should traverse the entire tree - */ - const DEPTH_INFINITY = -1; - - /** - * Nodes that are files, should have this as the type property - */ - const NODE_FILE = 1; - - /** - * Nodes that are directories, should use this value as the type property - */ - const NODE_DIRECTORY = 2; - - const PROP_SET = 1; - const PROP_REMOVE = 2; - - /** - * XML namespace for all SabreDAV related elements - */ - const NS_SABREDAV = 'http://sabredav.org/ns'; - - /** - * The tree object - * - * @var Sabre_DAV_Tree - */ - public $tree; - - /** - * The base uri - * - * @var string - */ - protected $baseUri = null; - - /** - * httpResponse - * - * @var Sabre_HTTP_Response - */ - public $httpResponse; - - /** - * httpRequest - * - * @var Sabre_HTTP_Request - */ - public $httpRequest; - - /** - * The list of plugins - * - * @var array - */ - protected $plugins = array(); - - /** - * This array contains a list of callbacks we should call when certain events are triggered - * - * @var array - */ - protected $eventSubscriptions = array(); - - /** - * This is a default list of namespaces. - * - * If you are defining your own custom namespace, add it here to reduce - * bandwidth and improve legibility of xml bodies. - * - * @var array - */ - public $xmlNamespaces = array( - 'DAV:' => 'd', - 'http://sabredav.org/ns' => 's', - ); - - /** - * The propertymap can be used to map properties from - * requests to property classes. - * - * @var array - */ - public $propertyMap = array( - '{DAV:}resourcetype' => 'Sabre_DAV_Property_ResourceType', - ); - - public $protectedProperties = array( - // RFC4918 - '{DAV:}getcontentlength', - '{DAV:}getetag', - '{DAV:}getlastmodified', - '{DAV:}lockdiscovery', - '{DAV:}resourcetype', - '{DAV:}supportedlock', - - // RFC4331 - '{DAV:}quota-available-bytes', - '{DAV:}quota-used-bytes', - - // RFC3744 - '{DAV:}supported-privilege-set', - '{DAV:}current-user-privilege-set', - '{DAV:}acl', - '{DAV:}acl-restrictions', - '{DAV:}inherited-acl-set', - - ); - - /** - * This is a flag that allow or not showing file, line and code - * of the exception in the returned XML - * - * @var bool - */ - public $debugExceptions = false; - - /** - * This property allows you to automatically add the 'resourcetype' value - * based on a node's classname or interface. - * - * The preset ensures that {DAV:}collection is automaticlly added for nodes - * implementing Sabre_DAV_ICollection. - * - * @var array - */ - public $resourceTypeMapping = array( - 'Sabre_DAV_ICollection' => '{DAV:}collection', - ); - - - /** - * Sets up the server - * - * If a Sabre_DAV_Tree object is passed as an argument, it will - * use it as the directory tree. If a Sabre_DAV_INode is passed, it - * will create a Sabre_DAV_ObjectTree and use the node as the root. - * - * If nothing is passed, a Sabre_DAV_SimpleCollection is created in - * a Sabre_DAV_ObjectTree. - * - * If an array is passed, we automatically create a root node, and use - * the nodes in the array as top-level children. - * - * @param Sabre_DAV_Tree $tree The tree object - * @return void - */ - public function __construct($treeOrNode = null) { - - if ($treeOrNode instanceof Sabre_DAV_Tree) { - $this->tree = $treeOrNode; - } elseif ($treeOrNode instanceof Sabre_DAV_INode) { - $this->tree = new Sabre_DAV_ObjectTree($treeOrNode); - } elseif (is_array($treeOrNode)) { - - // If it's an array, a list of nodes was passed, and we need to - // create the root node. - foreach($treeOrNode as $node) { - if (!($node instanceof Sabre_DAV_INode)) { - throw new Sabre_DAV_Exception('Invalid argument passed to constructor. If you\'re passing an array, all the values must implement Sabre_DAV_INode'); - } - } - - $root = new Sabre_DAV_SimpleCollection('root', $treeOrNode); - $this->tree = new Sabre_DAV_ObjectTree($root); - - } elseif (is_null($treeOrNode)) { - $root = new Sabre_DAV_SimpleCollection('root'); - $this->tree = new Sabre_DAV_ObjectTree($root); - } else { - throw new Sabre_DAV_Exception('Invalid argument passed to constructor. Argument must either be an instance of Sabre_DAV_Tree, Sabre_DAV_INode, an array or null'); - } - $this->httpResponse = new Sabre_HTTP_Response(); - $this->httpRequest = new Sabre_HTTP_Request(); - - } - - /** - * Starts the DAV Server - * - * @return void - */ - public function exec() { - - try { - - $this->invokeMethod($this->httpRequest->getMethod(), $this->getRequestUri()); - - } catch (Exception $e) { - - $DOM = new DOMDocument('1.0','utf-8'); - $DOM->formatOutput = true; - - $error = $DOM->createElementNS('DAV:','d:error'); - $error->setAttribute('xmlns:s',self::NS_SABREDAV); - $DOM->appendChild($error); - - $error->appendChild($DOM->createElement('s:exception',get_class($e))); - $error->appendChild($DOM->createElement('s:message',$e->getMessage())); - if ($this->debugExceptions) { - $error->appendChild($DOM->createElement('s:file',$e->getFile())); - $error->appendChild($DOM->createElement('s:line',$e->getLine())); - $error->appendChild($DOM->createElement('s:code',$e->getCode())); - $error->appendChild($DOM->createElement('s:stacktrace',$e->getTraceAsString())); - - } - $error->appendChild($DOM->createElement('s:sabredav-version',Sabre_DAV_Version::VERSION)); - - if($e instanceof Sabre_DAV_Exception) { - - $httpCode = $e->getHTTPCode(); - $e->serialize($this,$error); - $headers = $e->getHTTPHeaders($this); - - } else { - - $httpCode = 500; - $headers = array(); - - } - $headers['Content-Type'] = 'application/xml; charset=utf-8'; - - $this->httpResponse->sendStatus($httpCode); - $this->httpResponse->setHeaders($headers); - $this->httpResponse->sendBody($DOM->saveXML()); - - } - - } - - /** - * Sets the base server uri - * - * @param string $uri - * @return void - */ - public function setBaseUri($uri) { - - // If the baseUri does not end with a slash, we must add it - if ($uri[strlen($uri)-1]!=='/') - $uri.='/'; - - $this->baseUri = $uri; - - } - - /** - * Returns the base responding uri - * - * @return string - */ - public function getBaseUri() { - - if (is_null($this->baseUri)) $this->baseUri = $this->guessBaseUri(); - return $this->baseUri; - - } - - /** - * This method attempts to detect the base uri. - * Only the PATH_INFO variable is considered. - * - * If this variable is not set, the root (/) is assumed. - * - * @return void - */ - public function guessBaseUri() { - - $pathInfo = $this->httpRequest->getRawServerValue('PATH_INFO'); - $uri = $this->httpRequest->getRawServerValue('REQUEST_URI'); - - // If PATH_INFO is found, we can assume it's accurate. - if (!empty($pathInfo)) { - - // We need to make sure we ignore the QUERY_STRING part - if ($pos = strpos($uri,'?')) - $uri = substr($uri,0,$pos); - - // PATH_INFO is only set for urls, such as: /example.php/path - // in that case PATH_INFO contains '/path'. - // Note that REQUEST_URI is percent encoded, while PATH_INFO is - // not, Therefore they are only comparable if we first decode - // REQUEST_INFO as well. - $decodedUri = Sabre_DAV_URLUtil::decodePath($uri); - - // A simple sanity check: - if(substr($decodedUri,strlen($decodedUri)-strlen($pathInfo))===$pathInfo) { - $baseUri = substr($decodedUri,0,strlen($decodedUri)-strlen($pathInfo)); - return rtrim($baseUri,'/') . '/'; - } - - throw new Sabre_DAV_Exception('The REQUEST_URI ('. $uri . ') did not end with the contents of PATH_INFO (' . $pathInfo . '). This server might be misconfigured.'); - - } - - // The last fallback is that we're just going to assume the server root. - return '/'; - - } - - /** - * Adds a plugin to the server - * - * For more information, console the documentation of Sabre_DAV_ServerPlugin - * - * @param Sabre_DAV_ServerPlugin $plugin - * @return void - */ - public function addPlugin(Sabre_DAV_ServerPlugin $plugin) { - - $this->plugins[$plugin->getPluginName()] = $plugin; - $plugin->initialize($this); - - } - - /** - * Returns an initialized plugin by it's name. - * - * This function returns null if the plugin was not found. - * - * @param string $name - * @return Sabre_DAV_ServerPlugin - */ - public function getPlugin($name) { - - if (isset($this->plugins[$name])) - return $this->plugins[$name]; - - // This is a fallback and deprecated. - foreach($this->plugins as $plugin) { - if (get_class($plugin)===$name) return $plugin; - } - - return null; - - } - - /** - * Returns all plugins - * - * @return array - */ - public function getPlugins() { - - return $this->plugins; - - } - - - - /** - * Subscribe to an event. - * - * When the event is triggered, we'll call all the specified callbacks. - * It is possible to control the order of the callbacks through the - * priority argument. - * - * This is for example used to make sure that the authentication plugin - * is triggered before anything else. If it's not needed to change this - * number, it is recommended to ommit. - * - * @param string $event - * @param callback $callback - * @param int $priority - * @return void - */ - public function subscribeEvent($event, $callback, $priority = 100) { - - if (!isset($this->eventSubscriptions[$event])) { - $this->eventSubscriptions[$event] = array(); - } - while(isset($this->eventSubscriptions[$event][$priority])) $priority++; - $this->eventSubscriptions[$event][$priority] = $callback; - ksort($this->eventSubscriptions[$event]); - - } - - /** - * Broadcasts an event - * - * This method will call all subscribers. If one of the subscribers returns false, the process stops. - * - * The arguments parameter will be sent to all subscribers - * - * @param string $eventName - * @param array $arguments - * @return bool - */ - public function broadcastEvent($eventName,$arguments = array()) { - - if (isset($this->eventSubscriptions[$eventName])) { - - foreach($this->eventSubscriptions[$eventName] as $subscriber) { - - $result = call_user_func_array($subscriber,$arguments); - if ($result===false) return false; - - } - - } - - return true; - - } - - /** - * Handles a http request, and execute a method based on its name - * - * @param string $method - * @param string $uri - * @return void - */ - public function invokeMethod($method, $uri) { - - $method = strtoupper($method); - - if (!$this->broadcastEvent('beforeMethod',array($method, $uri))) return; - - // Make sure this is a HTTP method we support - $internalMethods = array( - 'OPTIONS', - 'GET', - 'HEAD', - 'DELETE', - 'PROPFIND', - 'MKCOL', - 'PUT', - 'PROPPATCH', - 'COPY', - 'MOVE', - 'REPORT' - ); - - if (in_array($method,$internalMethods)) { - - call_user_func(array($this,'http' . $method), $uri); - - } else { - - if ($this->broadcastEvent('unknownMethod',array($method, $uri))) { - // Unsupported method - throw new Sabre_DAV_Exception_NotImplemented(); - } - - } - - } - - // {{{ HTTP Method implementations - - /** - * HTTP OPTIONS - * - * @param string $uri - * @return void - */ - protected function httpOptions($uri) { - - $methods = $this->getAllowedMethods($uri); - - $this->httpResponse->setHeader('Allow',strtoupper(implode(', ',$methods))); - $features = array('1','3', 'extended-mkcol'); - - foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures()); - - $this->httpResponse->setHeader('DAV',implode(', ',$features)); - $this->httpResponse->setHeader('MS-Author-Via','DAV'); - $this->httpResponse->setHeader('Accept-Ranges','bytes'); - $this->httpResponse->setHeader('X-Sabre-Version',Sabre_DAV_Version::VERSION); - $this->httpResponse->setHeader('Content-Length',0); - $this->httpResponse->sendStatus(200); - - } - - /** - * HTTP GET - * - * This method simply fetches the contents of a uri, like normal - * - * @param string $uri - * @return void - */ - protected function httpGet($uri) { - - $node = $this->tree->getNodeForPath($uri,0); - - if (!$this->checkPreconditions(true)) return false; - - if (!($node instanceof Sabre_DAV_IFile)) throw new Sabre_DAV_Exception_NotImplemented('GET is only implemented on File objects'); - $body = $node->get(); - - // Converting string into stream, if needed. - if (is_string($body)) { - $stream = fopen('php://temp','r+'); - fwrite($stream,$body); - rewind($stream); - $body = $stream; - } - - /* - * TODO: getetag, getlastmodified, getsize should also be used using - * this method - */ - $httpHeaders = $this->getHTTPHeaders($uri); - - /* ContentType needs to get a default, because many webservers will otherwise - * default to text/html, and we don't want this for security reasons. - */ - if (!isset($httpHeaders['Content-Type'])) { - $httpHeaders['Content-Type'] = 'application/octet-stream'; - } - - - if (isset($httpHeaders['Content-Length'])) { - - $nodeSize = $httpHeaders['Content-Length']; - - // Need to unset Content-Length, because we'll handle that during figuring out the range - unset($httpHeaders['Content-Length']); - - } else { - $nodeSize = null; - } - - $this->httpResponse->setHeaders($httpHeaders); - - $range = $this->getHTTPRange(); - $ifRange = $this->httpRequest->getHeader('If-Range'); - $ignoreRangeHeader = false; - - // If ifRange is set, and range is specified, we first need to check - // the precondition. - if ($nodeSize && $range && $ifRange) { - - // if IfRange is parsable as a date we'll treat it as a DateTime - // otherwise, we must treat it as an etag. - try { - $ifRangeDate = new DateTime($ifRange); - - // It's a date. We must check if the entity is modified since - // the specified date. - if (!isset($httpHeaders['Last-Modified'])) $ignoreRangeHeader = true; - else { - $modified = new DateTime($httpHeaders['Last-Modified']); - if($modified > $ifRangeDate) $ignoreRangeHeader = true; - } - - } catch (Exception $e) { - - // It's an entity. We can do a simple comparison. - if (!isset($httpHeaders['ETag'])) $ignoreRangeHeader = true; - elseif ($httpHeaders['ETag']!==$ifRange) $ignoreRangeHeader = true; - } - } - - // We're only going to support HTTP ranges if the backend provided a filesize - if (!$ignoreRangeHeader && $nodeSize && $range) { - - // Determining the exact byte offsets - if (!is_null($range[0])) { - - $start = $range[0]; - $end = $range[1]?$range[1]:$nodeSize-1; - if($start >= $nodeSize) - throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The start offset (' . $range[0] . ') exceeded the size of the entity (' . $nodeSize . ')'); - - if($end < $start) throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The end offset (' . $range[1] . ') is lower than the start offset (' . $range[0] . ')'); - if($end >= $nodeSize) $end = $nodeSize-1; - - } else { - - $start = $nodeSize-$range[1]; - $end = $nodeSize-1; - - if ($start<0) $start = 0; - - } - - // New read/write stream - $newStream = fopen('php://temp','r+'); - - stream_copy_to_stream($body, $newStream, $end-$start+1, $start); - rewind($newStream); - - $this->httpResponse->setHeader('Content-Length', $end-$start+1); - $this->httpResponse->setHeader('Content-Range','bytes ' . $start . '-' . $end . '/' . $nodeSize); - $this->httpResponse->sendStatus(206); - $this->httpResponse->sendBody($newStream); - - - } else { - - if ($nodeSize) $this->httpResponse->setHeader('Content-Length',$nodeSize); - $this->httpResponse->sendStatus(200); - $this->httpResponse->sendBody($body); - - } - - } - - /** - * HTTP HEAD - * - * This method is normally used to take a peak at a url, and only get the HTTP response headers, without the body - * This is used by clients to determine if a remote file was changed, so they can use a local cached version, instead of downloading it again - * - * @param string $uri - * @return void - */ - protected function httpHead($uri) { - - $node = $this->tree->getNodeForPath($uri); - /* This information is only collection for File objects. - * Ideally we want to throw 405 Method Not Allowed for every - * non-file, but MS Office does not like this - */ - if ($node instanceof Sabre_DAV_IFile) { - $headers = $this->getHTTPHeaders($this->getRequestUri()); - if (!isset($headers['Content-Type'])) { - $headers['Content-Type'] = 'application/octet-stream'; - } - $this->httpResponse->setHeaders($headers); - } - $this->httpResponse->sendStatus(200); - - } - - /** - * HTTP Delete - * - * The HTTP delete method, deletes a given uri - * - * @param string $uri - * @return void - */ - protected function httpDelete($uri) { - - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return; - $this->tree->delete($uri); - - $this->httpResponse->sendStatus(204); - $this->httpResponse->setHeader('Content-Length','0'); - - } - - - /** - * WebDAV PROPFIND - * - * This WebDAV method requests information about an uri resource, or a list of resources - * If a client wants to receive the properties for a single resource it will add an HTTP Depth: header with a 0 value - * If the value is 1, it means that it also expects a list of sub-resources (e.g.: files in a directory) - * - * The request body contains an XML data structure that has a list of properties the client understands - * The response body is also an xml document, containing information about every uri resource and the requested properties - * - * It has to return a HTTP 207 Multi-status status code - * - * @param string $uri - * @return void - */ - protected function httpPropfind($uri) { - - // $xml = new Sabre_DAV_XMLReader(file_get_contents('php://input')); - $requestedProperties = $this->parsePropfindRequest($this->httpRequest->getBody(true)); - - $depth = $this->getHTTPDepth(1); - // The only two options for the depth of a propfind is 0 or 1 - if ($depth!=0) $depth = 1; - - $newProperties = $this->getPropertiesForPath($uri,$requestedProperties,$depth); - - // This is a multi-status response - $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - - // Normally this header is only needed for OPTIONS responses, however.. - // iCal seems to also depend on these being set for PROPFIND. Since - // this is not harmful, we'll add it. - $features = array('1','3', 'extended-mkcol'); - foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures()); - $this->httpResponse->setHeader('DAV',implode(', ',$features)); - - $data = $this->generateMultiStatus($newProperties); - $this->httpResponse->sendBody($data); - - } - - /** - * WebDAV PROPPATCH - * - * This method is called to update properties on a Node. The request is an XML body with all the mutations. - * In this XML body it is specified which properties should be set/updated and/or deleted - * - * @param string $uri - * @return void - */ - protected function httpPropPatch($uri) { - - $newProperties = $this->parsePropPatchRequest($this->httpRequest->getBody(true)); - - $result = $this->updateProperties($uri, $newProperties); - - $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - - $this->httpResponse->sendBody( - $this->generateMultiStatus(array($result)) - ); - - } - - /** - * HTTP PUT method - * - * This HTTP method updates a file, or creates a new one. - * - * If a new resource was created, a 201 Created status code should be returned. If an existing resource is updated, it's a 200 Ok - * - * @param string $uri - * @return void - */ - protected function httpPut($uri) { - - $body = $this->httpRequest->getBody(); - - // Intercepting Content-Range - if ($this->httpRequest->getHeader('Content-Range')) { - /** - Content-Range is dangerous for PUT requests: PUT per definition - stores a full resource. draft-ietf-httpbis-p2-semantics-15 says - in section 7.6: - An origin server SHOULD reject any PUT request that contains a - Content-Range header field, since it might be misinterpreted as - partial content (or might be partial content that is being mistakenly - PUT as a full representation). Partial content updates are possible - by targeting a separately identified resource with state that - overlaps a portion of the larger resource, or by using a different - method that has been specifically defined for partial updates (for - example, the PATCH method defined in [RFC5789]). - This clarifies RFC2616 section 9.6: - The recipient of the entity MUST NOT ignore any Content-* - (e.g. Content-Range) headers that it does not understand or implement - and MUST return a 501 (Not Implemented) response in such cases. - OTOH is a PUT request with a Content-Range currently the only way to - continue an aborted upload request and is supported by curl, mod_dav, - Tomcat and others. Since some clients do use this feature which results - in unexpected behaviour (cf PEAR::HTTP_WebDAV_Client 1.0.1), we reject - all PUT requests with a Content-Range for now. - */ - - throw new Sabre_DAV_Exception_NotImplemented('PUT with Content-Range is not allowed.'); - } - - // Intercepting the Finder problem - if (($expected = $this->httpRequest->getHeader('X-Expected-Entity-Length')) && $expected > 0) { - - /** - Many webservers will not cooperate well with Finder PUT requests, - because it uses 'Chunked' transfer encoding for the request body. - - The symptom of this problem is that Finder sends files to the - server, but they arrive as 0-lenght files in PHP. - - If we don't do anything, the user might think they are uploading - files successfully, but they end up empty on the server. Instead, - we throw back an error if we detect this. - - The reason Finder uses Chunked, is because it thinks the files - might change as it's being uploaded, and therefore the - Content-Length can vary. - - Instead it sends the X-Expected-Entity-Length header with the size - of the file at the very start of the request. If this header is set, - but we don't get a request body we will fail the request to - protect the end-user. - */ - - // Only reading first byte - $firstByte = fread($body,1); - if (strlen($firstByte)!==1) { - throw new Sabre_DAV_Exception_Forbidden('This server is not compatible with OS/X finder. Consider using a different WebDAV client or webserver.'); - } - - // The body needs to stay intact, so we copy everything to a - // temporary stream. - - $newBody = fopen('php://temp','r+'); - fwrite($newBody,$firstByte); - stream_copy_to_stream($body, $newBody); - rewind($newBody); - - $body = $newBody; - - } - - if ($this->tree->nodeExists($uri)) { - - $node = $this->tree->getNodeForPath($uri); - - // Checking If-None-Match and related headers. - if (!$this->checkPreconditions()) return; - - // If the node is a collection, we'll deny it - if (!($node instanceof Sabre_DAV_IFile)) throw new Sabre_DAV_Exception_Conflict('PUT is not allowed on non-files.'); - if (!$this->broadcastEvent('beforeWriteContent',array($this->getRequestUri()))) return false; - - $node->put($body); - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus(204); - - } else { - - // If we got here, the resource didn't exist yet. - if (!$this->createFile($this->getRequestUri(),$body)) { - // For one reason or another the file was not created. - return; - } - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus(201); - - } - - } - - - /** - * WebDAV MKCOL - * - * The MKCOL method is used to create a new collection (directory) on the server - * - * @param string $uri - * @return void - */ - protected function httpMkcol($uri) { - - $requestBody = $this->httpRequest->getBody(true); - - if ($requestBody) { - - $contentType = $this->httpRequest->getHeader('Content-Type'); - if (strpos($contentType,'application/xml')!==0 && strpos($contentType,'text/xml')!==0) { - - // We must throw 415 for unsupport mkcol bodies - throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must have an xml Content-Type'); - - } - - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($requestBody); - if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild)!=='{DAV:}mkcol') { - - // We must throw 415 for unsupport mkcol bodies - throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must be a {DAV:}mkcol request construct.'); - - } - - $properties = array(); - foreach($dom->firstChild->childNodes as $childNode) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($childNode)!=='{DAV:}set') continue; - $properties = array_merge($properties, Sabre_DAV_XMLUtil::parseProperties($childNode, $this->propertyMap)); - - } - if (!isset($properties['{DAV:}resourcetype'])) - throw new Sabre_DAV_Exception_BadRequest('The mkcol request must include a {DAV:}resourcetype property'); - - $resourceType = $properties['{DAV:}resourcetype']->getValue(); - unset($properties['{DAV:}resourcetype']); - - } else { - - $properties = array(); - $resourceType = array('{DAV:}collection'); - - } - - $result = $this->createCollection($uri, $resourceType, $properties); - - if (is_array($result)) { - $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - - $this->httpResponse->sendBody( - $this->generateMultiStatus(array($result)) - ); - - } else { - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus(201); - } - - } - - /** - * WebDAV HTTP MOVE method - * - * This method moves one uri to a different uri. A lot of the actual request processing is done in getCopyMoveInfo - * - * @param string $uri - * @return void - */ - protected function httpMove($uri) { - - $moveInfo = $this->getCopyAndMoveInfo(); - - // If the destination is part of the source tree, we must fail - if ($moveInfo['destination']==$uri) - throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.'); - - if ($moveInfo['destinationExists']) { - - if (!$this->broadcastEvent('beforeUnbind',array($moveInfo['destination']))) return false; - $this->tree->delete($moveInfo['destination']); - - } - - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return false; - if (!$this->broadcastEvent('beforeBind',array($moveInfo['destination']))) return false; - $this->tree->move($uri,$moveInfo['destination']); - $this->broadcastEvent('afterBind',array($moveInfo['destination'])); - - // If a resource was overwritten we should send a 204, otherwise a 201 - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus($moveInfo['destinationExists']?204:201); - - } - - /** - * WebDAV HTTP COPY method - * - * This method copies one uri to a different uri, and works much like the MOVE request - * A lot of the actual request processing is done in getCopyMoveInfo - * - * @param string $uri - * @return void - */ - protected function httpCopy($uri) { - - $copyInfo = $this->getCopyAndMoveInfo(); - // If the destination is part of the source tree, we must fail - if ($copyInfo['destination']==$uri) - throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.'); - - if ($copyInfo['destinationExists']) { - if (!$this->broadcastEvent('beforeUnbind',array($copyInfo['destination']))) return false; - $this->tree->delete($copyInfo['destination']); - - } - if (!$this->broadcastEvent('beforeBind',array($copyInfo['destination']))) return false; - $this->tree->copy($uri,$copyInfo['destination']); - $this->broadcastEvent('afterBind',array($copyInfo['destination'])); - - // If a resource was overwritten we should send a 204, otherwise a 201 - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus($copyInfo['destinationExists']?204:201); - - } - - - - /** - * HTTP REPORT method implementation - * - * Although the REPORT method is not part of the standard WebDAV spec (it's from rfc3253) - * It's used in a lot of extensions, so it made sense to implement it into the core. - * - * @param string $uri - * @return void - */ - protected function httpReport($uri) { - - $body = $this->httpRequest->getBody(true); - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - $reportName = Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild); - - if ($this->broadcastEvent('report',array($reportName,$dom, $uri))) { - - // If broadcastEvent returned true, it means the report was not supported - throw new Sabre_DAV_Exception_ReportNotImplemented(); - - } - - } - - // }}} - // {{{ HTTP/WebDAV protocol helpers - - /** - * Returns an array with all the supported HTTP methods for a specific uri. - * - * @param string $uri - * @return array - */ - public function getAllowedMethods($uri) { - - $methods = array( - 'OPTIONS', - 'GET', - 'HEAD', - 'DELETE', - 'PROPFIND', - 'PUT', - 'PROPPATCH', - 'COPY', - 'MOVE', - 'REPORT' - ); - - // The MKCOL is only allowed on an unmapped uri - try { - $node = $this->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - $methods[] = 'MKCOL'; - } - - // We're also checking if any of the plugins register any new methods - foreach($this->plugins as $plugin) $methods = array_merge($methods,$plugin->getHTTPMethods($uri)); - array_unique($methods); - - return $methods; - - } - - /** - * Gets the uri for the request, keeping the base uri into consideration - * - * @return string - */ - public function getRequestUri() { - - return $this->calculateUri($this->httpRequest->getUri()); - - } - - /** - * Calculates the uri for a request, making sure that the base uri is stripped out - * - * @param string $uri - * @throws Sabre_DAV_Exception_Forbidden A permission denied exception is thrown whenever there was an attempt to supply a uri outside of the base uri - * @return string - */ - public function calculateUri($uri) { - - if ($uri[0]!='/' && strpos($uri,'://')) { - - $uri = parse_url($uri,PHP_URL_PATH); - - } - - $uri = str_replace('//','/',$uri); - - if (strpos($uri,$this->getBaseUri())===0) { - - return trim(Sabre_DAV_URLUtil::decodePath(substr($uri,strlen($this->getBaseUri()))),'/'); - - // A special case, if the baseUri was accessed without a trailing - // slash, we'll accept it as well. - } elseif ($uri.'/' === $this->getBaseUri()) { - - return ''; - - } else { - - throw new Sabre_DAV_Exception_Forbidden('Requested uri (' . $uri . ') is out of base uri (' . $this->getBaseUri() . ')'); - - } - - } - - /** - * Returns the HTTP depth header - * - * This method returns the contents of the HTTP depth request header. If the depth header was 'infinity' it will return the Sabre_DAV_Server::DEPTH_INFINITY object - * It is possible to supply a default depth value, which is used when the depth header has invalid content, or is completely non-existant - * - * @param mixed $default - * @return int - */ - public function getHTTPDepth($default = self::DEPTH_INFINITY) { - - // If its not set, we'll grab the default - $depth = $this->httpRequest->getHeader('Depth'); - - if (is_null($depth)) return $default; - - if ($depth == 'infinity') return self::DEPTH_INFINITY; - - - // If its an unknown value. we'll grab the default - if (!ctype_digit($depth)) return $default; - - return (int)$depth; - - } - - /** - * Returns the HTTP range header - * - * This method returns null if there is no well-formed HTTP range request - * header or array($start, $end). - * - * The first number is the offset of the first byte in the range. - * The second number is the offset of the last byte in the range. - * - * If the second offset is null, it should be treated as the offset of the last byte of the entity - * If the first offset is null, the second offset should be used to retrieve the last x bytes of the entity - * - * return $mixed - */ - public function getHTTPRange() { - - $range = $this->httpRequest->getHeader('range'); - if (is_null($range)) return null; - - // Matching "Range: bytes=1234-5678: both numbers are optional - - if (!preg_match('/^bytes=([0-9]*)-([0-9]*)$/i',$range,$matches)) return null; - - if ($matches[1]==='' && $matches[2]==='') return null; - - return array( - $matches[1]!==''?$matches[1]:null, - $matches[2]!==''?$matches[2]:null, - ); - - } - - - /** - * Returns information about Copy and Move requests - * - * This function is created to help getting information about the source and the destination for the - * WebDAV MOVE and COPY HTTP request. It also validates a lot of information and throws proper exceptions - * - * The returned value is an array with the following keys: - * * destination - Destination path - * * destinationExists - Wether or not the destination is an existing url (and should therefore be overwritten) - * - * @return array - */ - public function getCopyAndMoveInfo() { - - // Collecting the relevant HTTP headers - if (!$this->httpRequest->getHeader('Destination')) throw new Sabre_DAV_Exception_BadRequest('The destination header was not supplied'); - $destination = $this->calculateUri($this->httpRequest->getHeader('Destination')); - $overwrite = $this->httpRequest->getHeader('Overwrite'); - if (!$overwrite) $overwrite = 'T'; - if (strtoupper($overwrite)=='T') $overwrite = true; - elseif (strtoupper($overwrite)=='F') $overwrite = false; - // We need to throw a bad request exception, if the header was invalid - else throw new Sabre_DAV_Exception_BadRequest('The HTTP Overwrite header should be either T or F'); - - list($destinationDir) = Sabre_DAV_URLUtil::splitPath($destination); - - try { - $destinationParent = $this->tree->getNodeForPath($destinationDir); - if (!($destinationParent instanceof Sabre_DAV_ICollection)) throw new Sabre_DAV_Exception_UnsupportedMediaType('The destination node is not a collection'); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - // If the destination parent node is not found, we throw a 409 - throw new Sabre_DAV_Exception_Conflict('The destination node is not found'); - } - - try { - - $destinationNode = $this->tree->getNodeForPath($destination); - - // If this succeeded, it means the destination already exists - // we'll need to throw precondition failed in case overwrite is false - if (!$overwrite) throw new Sabre_DAV_Exception_PreconditionFailed('The destination node already exists, and the overwrite header is set to false','Overwrite'); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - // Destination didn't exist, we're all good - $destinationNode = false; - - - - } - - // These are the three relevant properties we need to return - return array( - 'destination' => $destination, - 'destinationExists' => $destinationNode==true, - 'destinationNode' => $destinationNode, - ); - - } - - /** - * Returns a list of properties for a path - * - * This is a simplified version getPropertiesForPath. - * if you aren't interested in status codes, but you just - * want to have a flat list of properties. Use this method. - * - * @param string $path - * @param array $propertyNames - */ - public function getProperties($path, $propertyNames) { - - $result = $this->getPropertiesForPath($path,$propertyNames,0); - return $result[0][200]; - - } - - /** - * Returns a list of HTTP headers for a particular resource - * - * The generated http headers are based on properties provided by the - * resource. The method basically provides a simple mapping between - * DAV property and HTTP header. - * - * The headers are intended to be used for HEAD and GET requests. - * - * @param string $path - */ - public function getHTTPHeaders($path) { - - $propertyMap = array( - '{DAV:}getcontenttype' => 'Content-Type', - '{DAV:}getcontentlength' => 'Content-Length', - '{DAV:}getlastmodified' => 'Last-Modified', - '{DAV:}getetag' => 'ETag', - ); - - $properties = $this->getProperties($path,array_keys($propertyMap)); - - $headers = array(); - foreach($propertyMap as $property=>$header) { - if (!isset($properties[$property])) continue; - - if (is_scalar($properties[$property])) { - $headers[$header] = $properties[$property]; - - // GetLastModified gets special cased - } elseif ($properties[$property] instanceof Sabre_DAV_Property_GetLastModified) { - $headers[$header] = $properties[$property]->getTime()->format(DateTime::RFC1123); - } - - } - - return $headers; - - } - - /** - * Returns a list of properties for a given path - * - * The path that should be supplied should have the baseUrl stripped out - * The list of properties should be supplied in Clark notation. If the list is empty - * 'allprops' is assumed. - * - * If a depth of 1 is requested child elements will also be returned. - * - * @param string $path - * @param array $propertyNames - * @param int $depth - * @return array - */ - public function getPropertiesForPath($path,$propertyNames = array(),$depth = 0) { - - if ($depth!=0) $depth = 1; - - $returnPropertyList = array(); - - $parentNode = $this->tree->getNodeForPath($path); - $nodes = array( - $path => $parentNode - ); - if ($depth==1 && $parentNode instanceof Sabre_DAV_ICollection) { - foreach($this->tree->getChildren($path) as $childNode) - $nodes[$path . '/' . $childNode->getName()] = $childNode; - } - - // If the propertyNames array is empty, it means all properties are requested. - // We shouldn't actually return everything we know though, and only return a - // sensible list. - $allProperties = count($propertyNames)==0; - - foreach($nodes as $myPath=>$node) { - - $currentPropertyNames = $propertyNames; - - $newProperties = array( - '200' => array(), - '404' => array(), - ); - - if ($allProperties) { - // Default list of propertyNames, when all properties were requested. - $currentPropertyNames = array( - '{DAV:}getlastmodified', - '{DAV:}getcontentlength', - '{DAV:}resourcetype', - '{DAV:}quota-used-bytes', - '{DAV:}quota-available-bytes', - '{DAV:}getetag', - '{DAV:}getcontenttype', - ); - } - - // If the resourceType was not part of the list, we manually add it - // and mark it for removal. We need to know the resourcetype in order - // to make certain decisions about the entry. - // WebDAV dictates we should add a / and the end of href's for collections - $removeRT = false; - if (!in_array('{DAV:}resourcetype',$currentPropertyNames)) { - $currentPropertyNames[] = '{DAV:}resourcetype'; - $removeRT = true; - } - - $result = $this->broadcastEvent('beforeGetProperties',array($myPath, $node, &$currentPropertyNames, &$newProperties)); - // If this method explicitly returned false, we must ignore this - // node as it is inacessible. - if ($result===false) continue; - - if (count($currentPropertyNames) > 0) { - - if ($node instanceof Sabre_DAV_IProperties) - $newProperties['200'] = $newProperties[200] + $node->getProperties($currentPropertyNames); - - } - - - foreach($currentPropertyNames as $prop) { - - if (isset($newProperties[200][$prop])) continue; - - switch($prop) { - case '{DAV:}getlastmodified' : if ($node->getLastModified()) $newProperties[200][$prop] = new Sabre_DAV_Property_GetLastModified($node->getLastModified()); break; - case '{DAV:}getcontentlength' : if ($node instanceof Sabre_DAV_IFile) $newProperties[200][$prop] = (int)$node->getSize(); break; - case '{DAV:}quota-used-bytes' : - if ($node instanceof Sabre_DAV_IQuota) { - $quotaInfo = $node->getQuotaInfo(); - $newProperties[200][$prop] = $quotaInfo[0]; - } - break; - case '{DAV:}quota-available-bytes' : - if ($node instanceof Sabre_DAV_IQuota) { - $quotaInfo = $node->getQuotaInfo(); - $newProperties[200][$prop] = $quotaInfo[1]; - } - break; - case '{DAV:}getetag' : if ($node instanceof Sabre_DAV_IFile && $etag = $node->getETag()) $newProperties[200][$prop] = $etag; break; - case '{DAV:}getcontenttype' : if ($node instanceof Sabre_DAV_IFile && $ct = $node->getContentType()) $newProperties[200][$prop] = $ct; break; - case '{DAV:}supported-report-set' : - $reports = array(); - foreach($this->plugins as $plugin) { - $reports = array_merge($reports, $plugin->getSupportedReportSet($myPath)); - } - $newProperties[200][$prop] = new Sabre_DAV_Property_SupportedReportSet($reports); - break; - case '{DAV:}resourcetype' : - $newProperties[200]['{DAV:}resourcetype'] = new Sabre_DAV_Property_ResourceType(); - foreach($this->resourceTypeMapping as $className => $resourceType) { - if ($node instanceof $className) $newProperties[200]['{DAV:}resourcetype']->add($resourceType); - } - break; - - } - - // If we were unable to find the property, we will list it as 404. - if (!$allProperties && !isset($newProperties[200][$prop])) $newProperties[404][$prop] = null; - - } - - $this->broadcastEvent('afterGetProperties',array(trim($myPath,'/'),&$newProperties)); - - $newProperties['href'] = trim($myPath,'/'); - - // Its is a WebDAV recommendation to add a trailing slash to collectionnames. - // Apple's iCal also requires a trailing slash for principals (rfc 3744). - // Therefore we add a trailing / for any non-file. This might need adjustments - // if we find there are other edge cases. - if ($myPath!='' && isset($newProperties[200]['{DAV:}resourcetype']) && count($newProperties[200]['{DAV:}resourcetype']->getValue())>0) $newProperties['href'] .='/'; - - // If the resourcetype property was manually added to the requested property list, - // we will remove it again. - if ($removeRT) unset($newProperties[200]['{DAV:}resourcetype']); - - $returnPropertyList[] = $newProperties; - - } - - return $returnPropertyList; - - } - - /** - * This method is invoked by sub-systems creating a new file. - * - * Currently this is done by HTTP PUT and HTTP LOCK (in the Locks_Plugin). - * It was important to get this done through a centralized function, - * allowing plugins to intercept this using the beforeCreateFile event. - * - * This method will return true if the file was actually created - * - * @param string $uri - * @param resource $data - * @return bool - */ - public function createFile($uri,$data) { - - list($dir,$name) = Sabre_DAV_URLUtil::splitPath($uri); - - if (!$this->broadcastEvent('beforeBind',array($uri))) return false; - if (!$this->broadcastEvent('beforeCreateFile',array($uri,$data))) return false; - - $parent = $this->tree->getNodeForPath($dir); - $parent->createFile($name,$data); - $this->tree->markDirty($dir); - - $this->broadcastEvent('afterBind',array($uri)); - - return true; - } - - /** - * This method is invoked by sub-systems creating a new directory. - * - * @param string $uri - * @return void - */ - public function createDirectory($uri) { - - $this->createCollection($uri,array('{DAV:}collection'),array()); - - } - - /** - * Use this method to create a new collection - * - * The {DAV:}resourcetype is specified using the resourceType array. - * At the very least it must contain {DAV:}collection. - * - * The properties array can contain a list of additional properties. - * - * @param string $uri The new uri - * @param array $resourceType The resourceType(s) - * @param array $properties A list of properties - * @return void - */ - public function createCollection($uri, array $resourceType, array $properties) { - - list($parentUri,$newName) = Sabre_DAV_URLUtil::splitPath($uri); - - // Making sure {DAV:}collection was specified as resourceType - if (!in_array('{DAV:}collection', $resourceType)) { - throw new Sabre_DAV_Exception_InvalidResourceType('The resourceType for this collection must at least include {DAV:}collection'); - } - - - // Making sure the parent exists - try { - - $parent = $this->tree->getNodeForPath($parentUri); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - throw new Sabre_DAV_Exception_Conflict('Parent node does not exist'); - - } - - // Making sure the parent is a collection - if (!$parent instanceof Sabre_DAV_ICollection) { - throw new Sabre_DAV_Exception_Conflict('Parent node is not a collection'); - } - - - - // Making sure the child does not already exist - try { - $parent->getChild($newName); - - // If we got here.. it means there's already a node on that url, and we need to throw a 405 - throw new Sabre_DAV_Exception_MethodNotAllowed('The resource you tried to create already exists'); - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - // This is correct - } - - - if (!$this->broadcastEvent('beforeBind',array($uri))) return; - - // There are 2 modes of operation. The standard collection - // creates the directory, and then updates properties - // the extended collection can create it directly. - if ($parent instanceof Sabre_DAV_IExtendedCollection) { - - $parent->createExtendedCollection($newName, $resourceType, $properties); - - } else { - - // No special resourcetypes are supported - if (count($resourceType)>1) { - throw new Sabre_DAV_Exception_InvalidResourceType('The {DAV:}resourcetype you specified is not supported here.'); - } - - $parent->createDirectory($newName); - $rollBack = false; - $exception = null; - $errorResult = null; - - if (count($properties)>0) { - - try { - - $errorResult = $this->updateProperties($uri, $properties); - if (!isset($errorResult[200])) { - $rollBack = true; - } - - } catch (Sabre_DAV_Exception $e) { - - $rollBack = true; - $exception = $e; - - } - - } - - if ($rollBack) { - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return; - $this->tree->delete($uri); - - // Re-throwing exception - if ($exception) throw $exception; - - return $errorResult; - } - - } - $this->tree->markDirty($parentUri); - $this->broadcastEvent('afterBind',array($uri)); - - } - - /** - * This method updates a resource's properties - * - * The properties array must be a list of properties. Array-keys are - * property names in clarknotation, array-values are it's values. - * If a property must be deleted, the value should be null. - * - * Note that this request should either completely succeed, or - * completely fail. - * - * The response is an array with statuscodes for keys, which in turn - * contain arrays with propertynames. This response can be used - * to generate a multistatus body. - * - * @param string $uri - * @param array $properties - * @return array - */ - public function updateProperties($uri, array $properties) { - - // we'll start by grabbing the node, this will throw the appropriate - // exceptions if it doesn't. - $node = $this->tree->getNodeForPath($uri); - - $result = array( - 200 => array(), - 403 => array(), - 424 => array(), - ); - $remainingProperties = $properties; - $hasError = false; - - // Running through all properties to make sure none of them are protected - if (!$hasError) foreach($properties as $propertyName => $value) { - if(in_array($propertyName, $this->protectedProperties)) { - $result[403][$propertyName] = null; - unset($remainingProperties[$propertyName]); - $hasError = true; - } - } - - if (!$hasError) { - // Allowing plugins to take care of property updating - $hasError = !$this->broadcastEvent('updateProperties',array( - &$remainingProperties, - &$result, - $node - )); - } - - // If the node is not an instance of Sabre_DAV_IProperties, every - // property is 403 Forbidden - if (!$hasError && count($remainingProperties) && !($node instanceof Sabre_DAV_IProperties)) { - $hasError = true; - foreach($properties as $propertyName=> $value) { - $result[403][$propertyName] = null; - } - $remainingProperties = array(); - } - - // Only if there were no errors we may attempt to update the resource - if (!$hasError) { - - if (count($remainingProperties)>0) { - - $updateResult = $node->updateProperties($remainingProperties); - - if ($updateResult===true) { - // success - foreach($remainingProperties as $propertyName=>$value) { - $result[200][$propertyName] = null; - } - - } elseif ($updateResult===false) { - // The node failed to update the properties for an - // unknown reason - foreach($remainingProperties as $propertyName=>$value) { - $result[403][$propertyName] = null; - } - - } elseif (is_array($updateResult)) { - - // The node has detailed update information - // We need to merge the results with the earlier results. - foreach($updateResult as $status => $props) { - if (is_array($props)) { - if (!isset($result[$status])) - $result[$status] = array(); - - $result[$status] = array_merge($result[$status], $updateResult[$status]); - } - } - - } else { - throw new Sabre_DAV_Exception('Invalid result from updateProperties'); - } - $remainingProperties = array(); - } - - } - - foreach($remainingProperties as $propertyName=>$value) { - // if there are remaining properties, it must mean - // there's a dependency failure - $result[424][$propertyName] = null; - } - - // Removing empty array values - foreach($result as $status=>$props) { - - if (count($props)===0) unset($result[$status]); - - } - $result['href'] = $uri; - return $result; - - } - - /** - * This method checks the main HTTP preconditions. - * - * Currently these are: - * * If-Match - * * If-None-Match - * * If-Modified-Since - * * If-Unmodified-Since - * - * The method will return true if all preconditions are met - * The method will return false, or throw an exception if preconditions - * failed. If false is returned the operation should be aborted, and - * the appropriate HTTP response headers are already set. - * - * Normally this method will throw 412 Precondition Failed for failures - * related to If-None-Match, If-Match and If-Unmodified Since. It will - * set the status to 304 Not Modified for If-Modified_since. - * - * If the $handleAsGET argument is set to true, it will also return 304 - * Not Modified for failure of the If-None-Match precondition. This is the - * desired behaviour for HTTP GET and HTTP HEAD requests. - * - * @return bool - */ - public function checkPreconditions($handleAsGET = false) { - - $uri = $this->getRequestUri(); - $node = null; - $lastMod = null; - $etag = null; - - if ($ifMatch = $this->httpRequest->getHeader('If-Match')) { - - // If-Match contains an entity tag. Only if the entity-tag - // matches we are allowed to make the request succeed. - // If the entity-tag is '*' we are only allowed to make the - // request succeed if a resource exists at that url. - try { - $node = $this->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified and the resource did not exist','If-Match'); - } - - // Only need to check entity tags if they are not * - if ($ifMatch!=='*') { - - // There can be multiple etags - $ifMatch = explode(',',$ifMatch); - $haveMatch = false; - foreach($ifMatch as $ifMatchItem) { - - // Stripping any extra spaces - $ifMatchItem = trim($ifMatchItem,' '); - - $etag = $node->getETag(); - if ($etag===$ifMatchItem) { - $haveMatch = true; - } - } - if (!$haveMatch) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified, but none of the specified the ETags matched.','If-Match'); - } - } - } - - if ($ifNoneMatch = $this->httpRequest->getHeader('If-None-Match')) { - - // The If-None-Match header contains an etag. - // Only if the ETag does not match the current ETag, the request will succeed - // The header can also contain *, in which case the request - // will only succeed if the entity does not exist at all. - $nodeExists = true; - if (!$node) { - try { - $node = $this->tree->getNodeForPath($uri); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - $nodeExists = false; - } - } - if ($nodeExists) { - $haveMatch = false; - if ($ifNoneMatch==='*') $haveMatch = true; - else { - - // There might be multiple etags - $ifNoneMatch = explode(',', $ifNoneMatch); - $etag = $node->getETag(); - - foreach($ifNoneMatch as $ifNoneMatchItem) { - - // Stripping any extra spaces - $ifNoneMatchItem = trim($ifNoneMatchItem,' '); - - if ($etag===$ifNoneMatchItem) $haveMatch = true; - - } - - } - - if ($haveMatch) { - if ($handleAsGET) { - $this->httpResponse->sendStatus(304); - return false; - } else { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-None-Match header was specified, but the ETag matched (or * was specified).','If-None-Match'); - } - } - } - - } - - if (!$ifNoneMatch && ($ifModifiedSince = $this->httpRequest->getHeader('If-Modified-Since'))) { - - // The If-Modified-Since header contains a date. We - // will only return the entity if it has been changed since - // that date. If it hasn't been changed, we return a 304 - // header - // Note that this header only has to be checked if there was no If-None-Match header - // as per the HTTP spec. - $date = Sabre_HTTP_Util::parseHTTPDate($ifModifiedSince); - - if ($date) { - if (is_null($node)) { - $node = $this->tree->getNodeForPath($uri); - } - $lastMod = $node->getLastModified(); - if ($lastMod) { - $lastMod = new DateTime('@' . $lastMod); - if ($lastMod <= $date) { - $this->httpResponse->sendStatus(304); - return false; - } - } - } - } - - if ($ifUnmodifiedSince = $this->httpRequest->getHeader('If-Unmodified-Since')) { - - // The If-Unmodified-Since will allow allow the request if the - // entity has not changed since the specified date. - $date = Sabre_HTTP_Util::parseHTTPDate($ifUnmodifiedSince); - - // We must only check the date if it's valid - if ($date) { - if (is_null($node)) { - $node = $this->tree->getNodeForPath($uri); - } - $lastMod = $node->getLastModified(); - if ($lastMod) { - $lastMod = new DateTime('@' . $lastMod); - if ($lastMod > $date) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Unmodified-Since header was specified, but the entity has been changed since the specified date.','If-Unmodified-Since'); - } - } - } - - } - return true; - - } - - // }}} - // {{{ XML Readers & Writers - - - /** - * Generates a WebDAV propfind response body based on a list of nodes - * - * @param array $fileProperties The list with nodes - * @param array $requestedProperties The properties that should be returned - * @return string - */ - public function generateMultiStatus(array $fileProperties) { - - $dom = new DOMDocument('1.0','utf-8'); - //$dom->formatOutput = true; - $multiStatus = $dom->createElement('d:multistatus'); - $dom->appendChild($multiStatus); - - // Adding in default namespaces - foreach($this->xmlNamespaces as $namespace=>$prefix) { - - $multiStatus->setAttribute('xmlns:' . $prefix,$namespace); - - } - - foreach($fileProperties as $entry) { - - $href = $entry['href']; - unset($entry['href']); - - $response = new Sabre_DAV_Property_Response($href,$entry); - $response->serialize($this,$multiStatus); - - } - - return $dom->saveXML(); - - } - - /** - * This method parses a PropPatch request - * - * PropPatch changes the properties for a resource. This method - * returns a list of properties. - * - * The keys in the returned array contain the property name (e.g.: {DAV:}displayname, - * and the value contains the property value. If a property is to be removed the value - * will be null. - * - * @param string $body xml body - * @return array list of properties in need of updating or deletion - */ - public function parsePropPatchRequest($body) { - - //We'll need to change the DAV namespace declaration to something else in order to make it parsable - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - $newProperties = array(); - - foreach($dom->firstChild->childNodes as $child) { - - if ($child->nodeType !== XML_ELEMENT_NODE) continue; - - $operation = Sabre_DAV_XMLUtil::toClarkNotation($child); - - if ($operation!=='{DAV:}set' && $operation!=='{DAV:}remove') continue; - - $innerProperties = Sabre_DAV_XMLUtil::parseProperties($child, $this->propertyMap); - - foreach($innerProperties as $propertyName=>$propertyValue) { - - if ($operation==='{DAV:}remove') { - $propertyValue = null; - } - - $newProperties[$propertyName] = $propertyValue; - - } - - } - - return $newProperties; - - } - - /** - * This method parses the PROPFIND request and returns its information - * - * This will either be a list of properties, or an empty array; in which case - * an {DAV:}allprop was requested. - * - * @param string $body - * @return array - */ - public function parsePropFindRequest($body) { - - // If the propfind body was empty, it means IE is requesting 'all' properties - if (!$body) return array(); - - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - $elem = $dom->getElementsByTagNameNS('urn:DAV','propfind')->item(0); - return array_keys(Sabre_DAV_XMLUtil::parseProperties($elem)); - - } - - // }}} - -} - diff --git a/3rdparty/Sabre/DAV/ServerPlugin.php b/3rdparty/Sabre/DAV/ServerPlugin.php deleted file mode 100644 index 6909f600c216a169df4a1cee8030d2f205063b6b..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/ServerPlugin.php +++ /dev/null @@ -1,90 +0,0 @@ -<?php - -/** - * The baseclass for all server plugins. - * - * Plugins can modify or extend the servers behaviour. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_ServerPlugin { - - /** - * This initializes the plugin. - * - * This function is called by Sabre_DAV_Server, after - * addPlugin is called. - * - * This method should set up the requires event subscriptions. - * - * @param Sabre_DAV_Server $server - * @return void - */ - abstract public function initialize(Sabre_DAV_Server $server); - - /** - * This method should return a list of server-features. - * - * This is for example 'versioning' and is added to the DAV: header - * in an OPTIONS response. - * - * @return array - */ - public function getFeatures() { - - return array(); - - } - - /** - * Use this method to tell the server this plugin defines additional - * HTTP methods. - * - * This method is passed a uri. It should only return HTTP methods that are - * available for the specified uri. - * - * @param string $uri - * @return array - */ - public function getHTTPMethods($uri) { - - return array(); - - } - - /** - * Returns a plugin name. - * - * Using this name other plugins will be able to access other plugins - * using Sabre_DAV_Server::getPlugin - * - * @return string - */ - public function getPluginName() { - - return get_class($this); - - } - - /** - * Returns a list of reports this plugin supports. - * - * This will be used in the {DAV:}supported-report-set property. - * Note that you still need to subscribe to the 'report' event to actually - * implement them - * - * @param string $uri - * @return array - */ - public function getSupportedReportSet($uri) { - - return array(); - - } - -} - diff --git a/3rdparty/Sabre/DAV/SimpleCollection.php b/3rdparty/Sabre/DAV/SimpleCollection.php deleted file mode 100644 index 223d05fed554bbba58ed608b9fdaff4677c9fb14..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/SimpleCollection.php +++ /dev/null @@ -1,106 +0,0 @@ -<?php - -/** - * SimpleCollection - * - * The SimpleCollection is used to quickly setup static directory structures. - * Just create the object with a proper name, and add children to use it. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_SimpleCollection extends Sabre_DAV_Collection { - - /** - * List of childnodes - * - * @var array - */ - protected $children = array(); - - /** - * Name of this resource - * - * @var string - */ - protected $name; - - /** - * Creates this node - * - * The name of the node must be passed, child nodes can also be bassed. - * This nodes must be instances of Sabre_DAV_INode - * - * @param string $name - * @param array $children - * @return void - */ - public function __construct($name,array $children = array()) { - - $this->name = $name; - foreach($children as $child) { - - if (!($child instanceof Sabre_DAV_INode)) throw new Sabre_DAV_Exception('Only instances of Sabre_DAV_INode are allowed to be passed in the children argument'); - $this->addChild($child); - - } - - } - - /** - * Adds a new childnode to this collection - * - * @param Sabre_DAV_INode $child - * @return void - */ - public function addChild(Sabre_DAV_INode $child) { - - $this->children[$child->getName()] = $child; - - } - - /** - * Returns the name of the collection - * - * @return string - */ - public function getName() { - - return $this->name; - - } - - /** - * Returns a child object, by its name. - * - * This method makes use of the getChildren method to grab all the child nodes, and compares the name. - * Generally its wise to override this, as this can usually be optimized - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_INode - */ - public function getChild($name) { - - if (isset($this->children[$name])) return $this->children[$name]; - throw new Sabre_DAV_Exception_FileNotFound('File not found: ' . $name . ' in \'' . $this->getName() . '\''); - - } - - /** - * Returns a list of children for this collection - * - * @return array - */ - public function getChildren() { - - return array_values($this->children); - - } - - -} - diff --git a/3rdparty/Sabre/DAV/SimpleDirectory.php b/3rdparty/Sabre/DAV/SimpleDirectory.php deleted file mode 100644 index 516a3aa907c8d55511e7d15d421baa29e17a1738..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/SimpleDirectory.php +++ /dev/null @@ -1,21 +0,0 @@ -<?php - -/** - * SimpleDirectory - * - * The SimpleDirectory is used to quickly setup static directory structures. - * Just create the object with a proper name, and add children to use it. - * - * This class is now deprecated, use Sabre_DAV_SimpleCollection instead. - * - * @package Sabre - * @subpackage DAV - * @deprecated Use Sabre_DAV_SimpleCollection instead. - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_SimpleDirectory extends Sabre_DAV_SimpleCollection { - -} - diff --git a/3rdparty/Sabre/DAV/SimpleFile.php b/3rdparty/Sabre/DAV/SimpleFile.php deleted file mode 100644 index 304dff1c5ec22f594281cbef96c36f19e4e9d347..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/SimpleFile.php +++ /dev/null @@ -1,120 +0,0 @@ -<?php - -/** - * SimpleFile - * - * The 'SimpleFile' class is used to easily add read-only immutable files to - * the directory structure. One usecase would be to add a 'readme.txt' to a - * root of a webserver with some standard content. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_SimpleFile extends Sabre_DAV_File { - - /** - * File contents - * - * @var string - */ - protected $contents = array(); - - /** - * Name of this resource - * - * @var string - */ - protected $name; - - /** - * A mimetype, such as 'text/plain' or 'text/html' - * - * @var string - */ - protected $mimeType; - - /** - * Creates this node - * - * The name of the node must be passed, as well as the contents of the - * file. - * - * @param string $name - * @param string $contents - */ - public function __construct($name, $contents, $mimeType = null) { - - $this->name = $name; - $this->contents = $contents; - $this->mimeType = $mimeType; - - } - - /** - * Returns the node name for this file. - * - * This name is used to construct the url. - * - * @return string - */ - public function getName() { - - return $this->name; - - } - - /** - * Returns the data - * - * This method may either return a string or a readable stream resource - * - * @return mixed - */ - public function get() { - - return $this->contents; - - } - - /** - * Returns the size of the file, in bytes. - * - * @return int - */ - public function getSize() { - - return strlen($this->contents); - - } - - /** - * Returns the ETag for a file - * - * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. - * The ETag is an arbritrary string, but MUST be surrounded by double-quotes. - * - * Return null if the ETag can not effectively be determined - */ - public function getETag() { - - return '"' . md5($this->contents) . '"'; - - } - - /** - * Returns the mime-type for a file - * - * If null is returned, we'll assume application/octet-stream - */ - public function getContentType() { - - return $this->mimeType; - - } - -} - -?> diff --git a/3rdparty/Sabre/DAV/StringUtil.php b/3rdparty/Sabre/DAV/StringUtil.php deleted file mode 100644 index 440cf6866ca6a68d5b8e7f2356342db961468b27..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/StringUtil.php +++ /dev/null @@ -1,91 +0,0 @@ -<?php - -/** - * String utility - * - * This class is mainly used to implement the 'text-match' filter, used by both - * the CalDAV calendar-query REPORT, and CardDAV addressbook-query REPORT. - * Because they both need it, it was decided to put it in Sabre_DAV instead. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_StringUtil { - - /** - * Checks if a needle occurs in a haystack ;) - * - * @param string $haystack - * @param string $needle - * @param string $collation - * @param string $matchType - * @return bool - */ - static public function textMatch($haystack, $needle, $collation, $matchType = 'contains') { - - switch($collation) { - - case 'i;ascii-casemap' : - // default strtolower takes locale into consideration - // we don't want this. - $haystack = str_replace(range('a','z'), range('A','Z'), $haystack); - $needle = str_replace(range('a','z'), range('A','Z'), $needle); - break; - - case 'i;octet' : - // Do nothing - break; - - case 'i;unicode-casemap' : - $haystack = mb_strtoupper($haystack, 'UTF-8'); - $needle = mb_strtoupper($needle, 'UTF-8'); - break; - - default : - throw new Sabre_DAV_Exception_BadRequest('Collation type: ' . $collation . ' is not supported'); - - } - - switch($matchType) { - - case 'contains' : - return strpos($haystack, $needle)!==false; - case 'equals' : - return $haystack === $needle; - case 'starts-with' : - return strpos($haystack, $needle)===0; - case 'ends-with' : - return strrpos($haystack, $needle)===strlen($haystack)-strlen($needle); - default : - throw new Sabre_DAV_Exception_BadRequest('Match-type: ' . $matchType . ' is not supported'); - - } - - } - - /** - * This method takes an input string, checks if it's not valid UTF-8 and - * attempts to convert it to UTF-8 if it's not. - * - * Note that currently this can only convert ISO-8559-1 to UTF-8 (latin-1), - * anything else will likely fail. - * - * @param string $input - * @return string - */ - static public function ensureUTF8($input) { - - $encoding = mb_detect_encoding($input , array('UTF-8','ISO-8859-1'), true); - - if ($encoding === 'ISO-8859-1') { - return utf8_encode($input); - } else { - return $input; - } - - } - -} diff --git a/3rdparty/Sabre/DAV/TemporaryFileFilterPlugin.php b/3rdparty/Sabre/DAV/TemporaryFileFilterPlugin.php deleted file mode 100644 index e8276af5613c7815c40be5a308f10c3de52a912b..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/TemporaryFileFilterPlugin.php +++ /dev/null @@ -1,279 +0,0 @@ -<?php - -/** - * Temporary File Filter Plugin - * - * The purpose of this filter is to intercept some of the garbage files - * operation systems and applications tend to generate when mounting - * a WebDAV share as a disk. - * - * It will intercept these files and place them in a separate directory. - * these files are not deleted automatically, so it is adviceable to - * delete these after they are not accessed for 24 hours. - * - * Currently it supports: - * * OS/X style resource forks and .DS_Store - * * desktop.ini and Thumbs.db (windows) - * * .*.swp (vim temporary files) - * * .dat.* (smultron temporary files) - * - * Additional patterns can be added, by adding on to the - * temporaryFilePatterns property. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_TemporaryFileFilterPlugin extends Sabre_DAV_ServerPlugin { - - /** - * This is the list of patterns we intercept. - * If new patterns are added, they must be valid patterns for preg_match. - * - * @var array - */ - public $temporaryFilePatterns = array( - '/^\._(.*)$/', // OS/X resource forks - '/^.DS_Store$/', // OS/X custom folder settings - '/^desktop.ini$/', // Windows custom folder settings - '/^Thumbs.db$/', // Windows thumbnail cache - '/^.(.*).swp$/', // ViM temporary files - '/^\.dat(.*)$/', // Smultron seems to create these - '/^~lock.(.*)#$/', // Windows 7 lockfiles - ); - - /** - * This is the directory where this plugin - * will store it's files. - * - * @var string - */ - private $dataDir; - - /** - * A reference to the main Server class - * - * @var Sabre_DAV_Server - */ - private $server; - - /** - * Creates the plugin. - * - * Make sure you specify a directory for your files. If you don't, we - * will use PHP's directory for session-storage instead, and you might - * not want that. - * - * @param string $dataDir - * @return void - */ - public function __construct($dataDir = null) { - - if (!$dataDir) $dataDir = ini_get('session.save_path').'/sabredav/'; - if (!is_dir($dataDir)) mkdir($dataDir); - $this->dataDir = $dataDir; - - } - - /** - * Initialize the plugin - * - * This is called automatically be the Server class after this plugin is - * added with Sabre_DAV_Server::addPlugin() - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('beforeMethod',array($this,'beforeMethod')); - $server->subscribeEvent('beforeCreateFile',array($this,'beforeCreateFile')); - - } - - /** - * This method is called before any HTTP method handler - * - * This method intercepts any GET, DELETE, PUT and PROPFIND calls to - * filenames that are known to match the 'temporary file' regex. - * - * @param string $method - * @return bool - */ - public function beforeMethod($method, $uri) { - - if (!$tempLocation = $this->isTempFile($uri)) - return true; - - switch($method) { - case 'GET' : - return $this->httpGet($tempLocation); - case 'PUT' : - return $this->httpPut($tempLocation); - case 'PROPFIND' : - return $this->httpPropfind($tempLocation, $uri); - case 'DELETE' : - return $this->httpDelete($tempLocation); - } - return true; - - } - - /** - * This method is invoked if some subsystem creates a new file. - * - * This is used to deal with HTTP LOCK requests which create a new - * file. - * - * @param string $uri - * @param resource $data - * @return bool - */ - public function beforeCreateFile($uri,$data) { - - if ($tempPath = $this->isTempFile($uri)) { - - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - file_put_contents($tempPath,$data); - return false; - } - return true; - - } - - /** - * This method will check if the url matches the temporary file pattern - * if it does, it will return an path based on $this->dataDir for the - * temporary file storage. - * - * @param string $path - * @return boolean|string - */ - protected function isTempFile($path) { - - // We're only interested in the basename. - list(, $tempPath) = Sabre_DAV_URLUtil::splitPath($path); - - foreach($this->temporaryFilePatterns as $tempFile) { - - if (preg_match($tempFile,$tempPath)) { - return $this->dataDir . '/sabredav_' . md5($path) . '.tempfile'; - } - - } - - return false; - - } - - - /** - * This method handles the GET method for temporary files. - * If the file doesn't exist, it will return false which will kick in - * the regular system for the GET method. - * - * @param string $tempLocation - * @return bool - */ - public function httpGet($tempLocation) { - - if (!file_exists($tempLocation)) return true; - - $hR = $this->server->httpResponse; - $hR->setHeader('Content-Type','application/octet-stream'); - $hR->setHeader('Content-Length',filesize($tempLocation)); - $hR->setHeader('X-Sabre-Temp','true'); - $hR->sendStatus(200); - $hR->sendBody(fopen($tempLocation,'r')); - return false; - - } - - /** - * This method handles the PUT method. - * - * @param string $tempLocation - * @return bool - */ - public function httpPut($tempLocation) { - - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - - $newFile = !file_exists($tempLocation); - - if (!$newFile && ($this->server->httpRequest->getHeader('If-None-Match'))) { - throw new Sabre_DAV_Exception_PreconditionFailed('The resource already exists, and an If-None-Match header was supplied'); - } - - file_put_contents($tempLocation,$this->server->httpRequest->getBody()); - $hR->sendStatus($newFile?201:200); - return false; - - } - - /** - * This method handles the DELETE method. - * - * If the file didn't exist, it will return false, which will make the - * standard HTTP DELETE handler kick in. - * - * @param string $tempLocation - * @return bool - */ - public function httpDelete($tempLocation) { - - if (!file_exists($tempLocation)) return true; - - unlink($tempLocation); - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - $hR->sendStatus(204); - return false; - - } - - /** - * This method handles the PROPFIND method. - * - * It's a very lazy method, it won't bother checking the request body - * for which properties were requested, and just sends back a default - * set of properties. - * - * @param string $tempLocation - * @return void - */ - public function httpPropfind($tempLocation, $uri) { - - if (!file_exists($tempLocation)) return true; - - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - $hR->sendStatus(207); - $hR->setHeader('Content-Type','application/xml; charset=utf-8'); - - $requestedProps = $this->server->parsePropFindRequest($this->server->httpRequest->getBody(true)); - - $properties = array( - 'href' => $uri, - 200 => array( - '{DAV:}getlastmodified' => new Sabre_DAV_Property_GetLastModified(filemtime($tempLocation)), - '{DAV:}getcontentlength' => filesize($tempLocation), - '{DAV:}resourcetype' => new Sabre_DAV_Property_ResourceType(null), - '{'.Sabre_DAV_Server::NS_SABREDAV.'}tempFile' => true, - - ), - ); - - $data = $this->server->generateMultiStatus(array($properties)); - $hR->sendBody($data); - return false; - - } - - -} diff --git a/3rdparty/Sabre/DAV/Tree.php b/3rdparty/Sabre/DAV/Tree.php deleted file mode 100644 index 98e6f62c9e588cb5462408884b1bbd9206abde3d..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Tree.php +++ /dev/null @@ -1,192 +0,0 @@ -<?php - -/** - * Abstract tree object - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAV_Tree { - - /** - * This function must return an INode object for a path - * If a Path doesn't exist, thrown an Exception_FileNotFound - * - * @param string $path - * @throws Exception_FileNotFound - * @return Sabre_DAV_INode - */ - abstract function getNodeForPath($path); - - /** - * This function allows you to check if a node exists. - * - * Implementors of this class should override this method to make - * it cheaper. - * - * @param string $path - * @return bool - */ - public function nodeExists($path) { - - try { - - $this->getNodeForPath($path); - return true; - - } catch (Sabre_DAV_Exception_FileNotFound $e) { - - return false; - - } - - } - - /** - * Copies a file from path to another - * - * @param string $sourcePath The source location - * @param string $destinationPath The full destination path - * @return void - */ - public function copy($sourcePath, $destinationPath) { - - $sourceNode = $this->getNodeForPath($sourcePath); - - // grab the dirname and basename components - list($destinationDir, $destinationName) = Sabre_DAV_URLUtil::splitPath($destinationPath); - - $destinationParent = $this->getNodeForPath($destinationDir); - $this->copyNode($sourceNode,$destinationParent,$destinationName); - - $this->markDirty($destinationDir); - - } - - /** - * Moves a file from one location to another - * - * @param string $sourcePath The path to the file which should be moved - * @param string $destinationPath The full destination path, so not just the destination parent node - * @return int - */ - public function move($sourcePath, $destinationPath) { - - list($sourceDir, $sourceName) = Sabre_DAV_URLUtil::splitPath($sourcePath); - list($destinationDir, $destinationName) = Sabre_DAV_URLUtil::splitPath($destinationPath); - - if ($sourceDir===$destinationDir) { - $renameable = $this->getNodeForPath($sourcePath); - $renameable->setName($destinationName); - } else { - $this->copy($sourcePath,$destinationPath); - $this->getNodeForPath($sourcePath)->delete(); - } - $this->markDirty($sourceDir); - $this->markDirty($destinationDir); - - } - - /** - * Deletes a node from the tree - * - * @param string $path - * @return void - */ - public function delete($path) { - - $node = $this->getNodeForPath($path); - $node->delete(); - - list($parent) = Sabre_DAV_URLUtil::splitPath($path); - $this->markDirty($parent); - - } - - /** - * Returns a list of childnodes for a given path. - * - * @param string $path - * @return array - */ - public function getChildren($path) { - - $node = $this->getNodeForPath($path); - return $node->getChildren(); - - } - - /** - * This method is called with every tree update - * - * Examples of tree updates are: - * * node deletions - * * node creations - * * copy - * * move - * * renaming nodes - * - * If Tree classes implement a form of caching, this will allow - * them to make sure caches will be expired. - * - * If a path is passed, it is assumed that the entire subtree is dirty - * - * @param string $path - * @return void - */ - public function markDirty($path) { - - - } - - /** - * copyNode - * - * @param Sabre_DAV_INode $source - * @param Sabre_DAV_ICollection $destination - * @return void - */ - protected function copyNode(Sabre_DAV_INode $source,Sabre_DAV_ICollection $destinationParent,$destinationName = null) { - - if (!$destinationName) $destinationName = $source->getName(); - - if ($source instanceof Sabre_DAV_IFile) { - - $data = $source->get(); - - // If the body was a string, we need to convert it to a stream - if (is_string($data)) { - $stream = fopen('php://temp','r+'); - fwrite($stream,$data); - rewind($stream); - $data = $stream; - } - $destinationParent->createFile($destinationName,$data); - $destination = $destinationParent->getChild($destinationName); - - } elseif ($source instanceof Sabre_DAV_ICollection) { - - $destinationParent->createDirectory($destinationName); - - $destination = $destinationParent->getChild($destinationName); - foreach($source->getChildren() as $child) { - - $this->copyNode($child,$destination); - - } - - } - if ($source instanceof Sabre_DAV_IProperties && $destination instanceof Sabre_DAV_IProperties) { - - $props = $source->getProperties(array()); - $destination->updateProperties($props); - - } - - } - -} - diff --git a/3rdparty/Sabre/DAV/Tree/Filesystem.php b/3rdparty/Sabre/DAV/Tree/Filesystem.php deleted file mode 100644 index 5c611047e073fd4c2642babf24696517c53b2201..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Tree/Filesystem.php +++ /dev/null @@ -1,124 +0,0 @@ -<?php - -/** - * Sabre_DAV_Tree_Filesystem - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Tree_Filesystem extends Sabre_DAV_Tree { - - /** - * Base url on the filesystem. - * - * @var string - */ - protected $basePath; - - /** - * Creates this tree - * - * Supply the path you'd like to share. - * - * @param string $basePath - * @return void - */ - public function __construct($basePath) { - - $this->basePath = $basePath; - - } - - /** - * Returns a new node for the given path - * - * @param string $path - * @return void - */ - public function getNodeForPath($path) { - - $realPath = $this->getRealPath($path); - if (!file_exists($realPath)) throw new Sabre_DAV_Exception_FileNotFound('File at location ' . $realPath . ' not found'); - if (is_dir($realPath)) { - return new Sabre_DAV_FS_Directory($path); - } else { - return new Sabre_DAV_FS_File($path); - } - - } - - /** - * Returns the real filesystem path for a webdav url. - * - * @param string $publicPath - * @return string - */ - protected function getRealPath($publicPath) { - - return rtrim($this->basePath,'/') . '/' . trim($publicPath,'/'); - - } - - /** - * Copies a file or directory. - * - * This method must work recursively and delete the destination - * if it exists - * - * @param string $source - * @param string $destination - * @return void - */ - public function copy($source,$destination) { - - $source = $this->getRealPath($source); - $destination = $this->getRealPath($destination); - $this->realCopy($source,$destination); - - } - - /** - * Used by self::copy - * - * @param string $source - * @param string $destination - * @return void - */ - protected function realCopy($source,$destination) { - - if (is_file($source)) { - copy($source,$destination); - } else { - mkdir($destination); - foreach(scandir($source) as $subnode) { - - if ($subnode=='.' || $subnode=='..') continue; - $this->realCopy($source.'/'.$subnode,$destination.'/'.$subnode); - - } - } - - } - - /** - * Moves a file or directory recursively. - * - * If the destination exists, delete it first. - * - * @param string $source - * @param string $destination - * @return void - */ - public function move($source,$destination) { - - $source = $this->getRealPath($source); - $destination = $this->getRealPath($destination); - rename($source,$destination); - - } - -} - diff --git a/3rdparty/Sabre/DAV/URLUtil.php b/3rdparty/Sabre/DAV/URLUtil.php deleted file mode 100644 index 8f38749264b1f5e3c5b87ec0195f05aa749dbee2..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/URLUtil.php +++ /dev/null @@ -1,125 +0,0 @@ -<?php - -/** - * URL utility class - * - * This class provides methods to deal with encoding and decoding url (percent encoded) strings. - * - * It was not possible to use PHP's built-in methods for this, because some clients don't like - * encoding of certain characters. - * - * Specifically, it was found that GVFS (gnome's webdav client) does not like encoding of ( and - * ). Since these are reserved, but don't have a reserved meaning in url, these characters are - * kept as-is. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_URLUtil { - - /** - * Encodes the path of a url. - * - * slashes (/) are treated as path-separators. - * - * @param string $path - * @return string - */ - static function encodePath($path) { - - $valid_chars = '/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.~()'; - $newStr = ''; - for( $i=0; isset($path[$i]); ++$i ) { - if( strpos($valid_chars,($c=$path[$i]))===false ) $newStr .= '%'.sprintf('%02x',ord($c)); - else $newStr .= $c; - } - return $newStr; - - } - - /** - * Encodes a 1 segment of a path - * - * Slashes are considered part of the name, and are encoded as %2f - * - * @param string $pathSegment - * @return string - */ - static function encodePathSegment($pathSegment) { - - $valid_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.~()'; - $newStr = ''; - for( $i=0; isset($pathSegment[$i]); ++$i ) { - if( strpos($valid_chars,($c=$pathSegment[$i]))===false ) $newStr .= '%'.sprintf('%02x',ord($c)); - else $newStr .= $c; - } - return $newStr; - } - - /** - * Decodes a url-encoded path - * - * @param string $path - * @return string - */ - static function decodePath($path) { - - return self::decodePathSegment($path); - - } - - /** - * Decodes a url-encoded path segment - * - * @param string $path - * @return string - */ - static function decodePathSegment($path) { - - $path = urldecode($path); - $encoding = mb_detect_encoding($path, array('UTF-8','ISO-8859-1')); - - switch($encoding) { - - case 'ISO-8859-1' : - $path = utf8_encode($path); - - } - - return $path; - - } - - /** - * Returns the 'dirname' and 'basename' for a path. - * - * The reason there is a custom function for this purpose, is because - * basename() is locale aware (behaviour changes if C locale or a UTF-8 locale is used) - * and we need a method that just operates on UTF-8 characters. - * - * In addition basename and dirname are platform aware, and will treat backslash (\) as a - * directory separator on windows. - * - * This method returns the 2 components as an array. - * - * If there is no dirname, it will return an empty string. Any / appearing at the end of the - * string is stripped off. - * - * @param string $path - * @return array - */ - static function splitPath($path) { - - $matches = array(); - if(preg_match('/^(?:(?:(.*)(?:\/+))?([^\/]+))(?:\/?)$/u',$path,$matches)) { - return array($matches[1],$matches[2]); - } else { - return array(null,null); - } - - } - -} diff --git a/3rdparty/Sabre/DAV/UUIDUtil.php b/3rdparty/Sabre/DAV/UUIDUtil.php deleted file mode 100644 index e42a536ad8a3feff157c8c2cebec4be534d30967..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/UUIDUtil.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php - -/** - * UUID Utility - * - * This class has static methods to generate and validate UUID's. - * UUIDs are used a decent amount within various *DAV standards, so it made - * sense to include it. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_UUIDUtil { - - /** - * Returns a pseudo-random v4 UUID - * - * This function is based on a comment by Andrew Moore on php.net - * - * @see http://www.php.net/manual/en/function.uniqid.php#94959 - * @return void - */ - static function getUUID() { - - return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', - // 32 bits for "time_low" - mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), - - // 16 bits for "time_mid" - mt_rand( 0, 0xffff ), - - // 16 bits for "time_hi_and_version", - // four most significant bits holds version number 4 - mt_rand( 0, 0x0fff ) | 0x4000, - - // 16 bits, 8 bits for "clk_seq_hi_res", - // 8 bits for "clk_seq_low", - // two most significant bits holds zero and one for variant DCE1.1 - mt_rand( 0, 0x3fff ) | 0x8000, - - // 48 bits for "node" - mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) - ); - } - - /** - * Checks if a string is a valid UUID. - * - * @param string $uuid - * @return bool - */ - static function validateUUID($uuid) { - - return preg_match( - '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i', - $uuid - ) == true; - - } - -} diff --git a/3rdparty/Sabre/DAV/Version.php b/3rdparty/Sabre/DAV/Version.php deleted file mode 100644 index 6bece1985e4e9706b7a7e41f1b738a61672e7b73..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/Version.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php - -/** - * This class contains the SabreDAV version constants. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_Version { - - /** - * Full version number - */ - const VERSION = '1.5.4'; - - /** - * Stability : alpha, beta, stable - */ - const STABILITY = 'stable'; - -} diff --git a/3rdparty/Sabre/DAV/XMLUtil.php b/3rdparty/Sabre/DAV/XMLUtil.php deleted file mode 100644 index bd05be4b2297b77e36c47d62904ff964617a0516..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAV/XMLUtil.php +++ /dev/null @@ -1,183 +0,0 @@ -<?php - -/** - * XML utilities for WebDAV - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAV_XMLUtil { - - /** - * Returns the 'clark notation' for an element. - * - * For example, and element encoded as: - * <b:myelem xmlns:b="http://www.example.org/" /> - * will be returned as: - * {http://www.example.org}myelem - * - * This format is used throughout the SabreDAV sourcecode. - * Elements encoded with the urn:DAV namespace will - * be returned as if they were in the DAV: namespace. This is to avoid - * compatibility problems. - * - * This function will return null if a nodetype other than an Element is passed. - * - * @param DOMElement $dom - * @return string - */ - static function toClarkNotation(DOMNode $dom) { - - if ($dom->nodeType !== XML_ELEMENT_NODE) return null; - - // Mapping back to the real namespace, in case it was dav - if ($dom->namespaceURI=='urn:DAV') $ns = 'DAV:'; else $ns = $dom->namespaceURI; - - // Mapping to clark notation - return '{' . $ns . '}' . $dom->localName; - - } - - /** - * Parses a clark-notation string, and returns the namespace and element - * name components. - * - * If the string was invalid, it will throw an InvalidArgumentException. - * - * @param string $str - * @throws InvalidArgumentException - * @return array - */ - static function parseClarkNotation($str) { - - if (!preg_match('/^{([^}]*)}(.*)$/',$str,$matches)) { - throw new InvalidArgumentException('\'' . $str . '\' is not a valid clark-notation formatted string'); - } - - return array( - $matches[1], - $matches[2] - ); - - } - - /** - * This method takes an XML document (as string) and converts all instances of the - * DAV: namespace to urn:DAV - * - * This is unfortunately needed, because the DAV: namespace violates the xml namespaces - * spec, and causes the DOM to throw errors - */ - static function convertDAVNamespace($xmlDocument) { - - // This is used to map the DAV: namespace to urn:DAV. This is needed, because the DAV: - // namespace is actually a violation of the XML namespaces specification, and will cause errors - return preg_replace("/xmlns(:[A-Za-z0-9_]*)?=(\"|\')DAV:(\\2)/","xmlns\\1=\\2urn:DAV\\2",$xmlDocument); - - } - - /** - * This method provides a generic way to load a DOMDocument for WebDAV use. - * - * This method throws a Sabre_DAV_Exception_BadRequest exception for any xml errors. - * It does not preserve whitespace, and it converts the DAV: namespace to urn:DAV. - * - * @param string $xml - * @throws Sabre_DAV_Exception_BadRequest - * @return DOMDocument - */ - static function loadDOMDocument($xml) { - - if (empty($xml)) - throw new Sabre_DAV_Exception_BadRequest('Empty XML document sent'); - - // The BitKinex client sends xml documents as UTF-16. PHP 5.3.1 (and presumably lower) - // does not support this, so we must intercept this and convert to UTF-8. - if (substr($xml,0,12) === "\x3c\x00\x3f\x00\x78\x00\x6d\x00\x6c\x00\x20\x00") { - - // Note: the preceeding byte sequence is "<?xml" encoded as UTF_16, without the BOM. - $xml = iconv('UTF-16LE','UTF-8',$xml); - - // Because the xml header might specify the encoding, we must also change this. - // This regex looks for the string encoding="UTF-16" and replaces it with - // encoding="UTF-8". - $xml = preg_replace('|<\?xml([^>]*)encoding="UTF-16"([^>]*)>|u','<?xml\1encoding="UTF-8"\2>',$xml); - - } - - // Retaining old error setting - $oldErrorSetting = libxml_use_internal_errors(true); - - // Clearing any previous errors - libxml_clear_errors(); - - $dom = new DOMDocument(); - $dom->loadXML(self::convertDAVNamespace($xml),LIBXML_NOWARNING | LIBXML_NOERROR); - - // We don't generally care about any whitespace - $dom->preserveWhiteSpace = false; - - if ($error = libxml_get_last_error()) { - libxml_clear_errors(); - throw new Sabre_DAV_Exception_BadRequest('The request body had an invalid XML body. (message: ' . $error->message . ', errorcode: ' . $error->code . ', line: ' . $error->line . ')'); - } - - // Restoring old mechanism for error handling - if ($oldErrorSetting===false) libxml_use_internal_errors(false); - - return $dom; - - } - - /** - * Parses all WebDAV properties out of a DOM Element - * - * Generally WebDAV properties are encloded in {DAV:}prop elements. This - * method helps by going through all these and pulling out the actual - * propertynames, making them array keys and making the property values, - * well.. the array values. - * - * If no value was given (self-closing element) null will be used as the - * value. This is used in for example PROPFIND requests. - * - * Complex values are supported through the propertyMap argument. The - * propertyMap should have the clark-notation properties as it's keys, and - * classnames as values. - * - * When any of these properties are found, the unserialize() method will be - * (statically) called. The result of this method is used as the value. - * - * @param DOMElement $parentNode - * @param array $propertyMap - * @return array - */ - static function parseProperties(DOMElement $parentNode, array $propertyMap = array()) { - - $propList = array(); - foreach($parentNode->childNodes as $propNode) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($propNode)!=='{DAV:}prop') continue; - - foreach($propNode->childNodes as $propNodeData) { - - /* If there are no elements in here, we actually get 1 text node, this special case is dedicated to netdrive */ - if ($propNodeData->nodeType != XML_ELEMENT_NODE) continue; - - $propertyName = Sabre_DAV_XMLUtil::toClarkNotation($propNodeData); - if (isset($propertyMap[$propertyName])) { - $propList[$propertyName] = call_user_func(array($propertyMap[$propertyName],'unserialize'),$propNodeData); - } else { - $propList[$propertyName] = $propNodeData->textContent; - } - } - - - } - return $propList; - - } - -} diff --git a/3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php b/3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php deleted file mode 100644 index a361e054610dd2251f3bb1961b879a95de39d79a..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php +++ /dev/null @@ -1,121 +0,0 @@ -<?php - -/** - * Principals Collection - * - * This is a helper class that easily allows you to create a collection that - * has a childnode for every principal. - * - * To use this class, simply implement the getChildForPrincipal method. - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_DAVACL_AbstractPrincipalCollection extends Sabre_DAV_Collection { - - /** - * Node or 'directory' name. - * - * @var string - */ - protected $path; - - /** - * Principal backend - * - * @var Sabre_DAVACL_IPrincipalBackend - */ - protected $principalBackend; - - /** - * If this value is set to true, it effectively disables listing of users - * it still allows user to find other users if they have an exact url. - * - * @var bool - */ - public $disableListing = false; - - /** - * Creates the object - * - * This object must be passed the principal backend. This object will - * filter all principals from a specfied prefix ($principalPrefix). The - * default is 'principals', if your principals are stored in a different - * collection, override $principalPrefix - * - * - * @param Sabre_DAVACL_IPrincipalBackend $principalBackend - * @param string $principalPrefix - * @param string $nodeName - */ - public function __construct(Sabre_DAVACL_IPrincipalBackend $principalBackend, $principalPrefix = 'principals') { - - $this->principalPrefix = $principalPrefix; - $this->principalBackend = $principalBackend; - - } - - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principalInfo - * @return Sabre_DAVACL_IPrincipal - */ - abstract function getChildForPrincipal(array $principalInfo); - - /** - * Returns the name of this collection. - * - * @return string - */ - public function getName() { - - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalPrefix); - return $name; - - } - - /** - * Return the list of users - * - * @return void - */ - public function getChildren() { - - if ($this->disableListing) - throw new Sabre_DAV_Exception_MethodNotAllowed('Listing members of this collection is disabled'); - - $children = array(); - foreach($this->principalBackend->getPrincipalsByPrefix($this->principalPrefix) as $principalInfo) { - - $children[] = $this->getChildForPrincipal($principalInfo); - - - } - return $children; - - } - - /** - * Returns a child object, by its name. - * - * @param string $name - * @throws Sabre_DAV_Exception_FileNotFound - * @return Sabre_DAV_IPrincipal - */ - public function getChild($name) { - - $principalInfo = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/' . $name); - if (!$principalInfo) throw new Sabre_DAV_Exception_FileNotFound('Principal with name ' . $name . ' not found'); - return $this->getChildForPrincipal($principalInfo); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Exception/AceConflict.php b/3rdparty/Sabre/DAVACL/Exception/AceConflict.php deleted file mode 100644 index d10aeb4345c6ff2c653f139db50f904dbf779093..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Exception/AceConflict.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php - -/** - * Sabre_DAVACL_Exception_AceConflict - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Exception_AceConflict extends Sabre_DAV_Exception_Conflict { - - /** - * Adds in extra information in the xml response. - * - * This method adds the {DAV:}no-ace-conflict element as defined in rfc3744 - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $doc = $errorNode->ownerDocument; - - $np = $doc->createElementNS('DAV:','d:no-ace-conflict'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php b/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php deleted file mode 100644 index 024ab6641f35a851aad6d01b1790482dda6e058d..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php +++ /dev/null @@ -1,80 +0,0 @@ -<?php - -/** - * NeedPrivileges - * - * The 403-need privileges is thrown when a user didn't have the appropriate - * permissions to perform an operation - * - * @package Sabre - * @subpackage DAVACL - * @version $Id$ - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Exception_NeedPrivileges extends Sabre_DAV_Exception_Forbidden { - - /** - * The relevant uri - * - * @var string - */ - protected $uri; - - /** - * The privileges the user didn't have. - * - * @var array - */ - protected $privileges; - - /** - * Constructor - * - * @param string $uri - * @param array $privileges - */ - public function __construct($uri,array $privileges) { - - $this->uri = $uri; - $this->privileges = $privileges; - - } - - /** - * Adds in extra information in the xml response. - * - * This method adds the {DAV:}need-privileges element as defined in rfc3744 - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $doc = $errorNode->ownerDocument; - - $np = $doc->createElementNS('DAV:','d:need-privileges'); - $errorNode->appendChild($np); - - foreach($this->privileges as $privilege) { - - $resource = $doc->createElementNS('DAV:','d:resource'); - $np->appendChild($resource); - - $resource->appendChild($doc->createElementNS('DAV:','d:href',$server->getBaseUri() . $this->uri)); - - $priv = $doc->createElementNS('DAV:','d:privilege'); - $resource->appendChild($priv); - - preg_match('/^{([^}]*)}(.*)$/',$privilege,$privilegeParts); - $priv->appendChild($doc->createElementNS($privilegeParts[1],'d:' . $privilegeParts[2])); - - - } - - } - -} - diff --git a/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php b/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php deleted file mode 100644 index 60f49ebff4adec68e1eee8454628737909961310..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NoAbstract.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php - -/** - * Sabre_DAVACL_Exception_NoAbstract - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Exception_NoAbstract extends Sabre_DAV_Exception_PreconditionFailed { - - /** - * Adds in extra information in the xml response. - * - * This method adds the {DAV:}no-abstract element as defined in rfc3744 - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $doc = $errorNode->ownerDocument; - - $np = $doc->createElementNS('DAV:','d:no-abstract'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php b/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php deleted file mode 100644 index e056dc9e4f70ff2c25e2a679fdb4e4669f2db2c9..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php - -/** - * Sabre_DAVACL_Exception_NotRecognizedPrincipal - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Exception_NotRecognizedPrincipal extends Sabre_DAV_Exception_PreconditionFailed { - - /** - * Adds in extra information in the xml response. - * - * This method adds the {DAV:}recognized-principal element as defined in rfc3744 - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $doc = $errorNode->ownerDocument; - - $np = $doc->createElementNS('DAV:','d:recognized-principal'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php b/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php deleted file mode 100644 index 27db7cdd7dd43be716b6248a8d4acdf73505e707..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php - -/** - * Sabre_DAVACL_Exception_NotSupportedPrivilege - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Exception_NotSupportedPrivilege extends Sabre_DAV_Exception_PreconditionFailed { - - /** - * Adds in extra information in the xml response. - * - * This method adds the {DAV:}not-supported-privilege element as defined in rfc3744 - * - * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $doc = $errorNode->ownerDocument; - - $np = $doc->createElementNS('DAV:','d:not-supported-privilege'); - $errorNode->appendChild($np); - - } - -} - -?> diff --git a/3rdparty/Sabre/DAVACL/IACL.php b/3rdparty/Sabre/DAVACL/IACL.php deleted file mode 100644 index 506be4248d76b8bca9facd87097c128846e4f2bd..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/IACL.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php - -/** - * ACL-enabled node - * - * If you want to add WebDAV ACL to a node, you must implement this class - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAVACL_IACL extends Sabre_DAV_INode { - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - function getOwner(); - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - function getGroup(); - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - function getACL(); - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - function setACL(array $acl); - -} diff --git a/3rdparty/Sabre/DAVACL/IPrincipal.php b/3rdparty/Sabre/DAVACL/IPrincipal.php deleted file mode 100644 index 7868811db76394ef6101516b627bde7d1da54929..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/IPrincipal.php +++ /dev/null @@ -1,75 +0,0 @@ -<?php - -/** - * IPrincipal interface - * - * Implement this interface to define your own principals - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAVACL_IPrincipal extends Sabre_DAV_INode { - - /** - * Returns a list of altenative urls for a principal - * - * This can for example be an email address, or ldap url. - * - * @return array - */ - function getAlternateUriSet(); - - /** - * Returns the full principal url - * - * @return string - */ - function getPrincipalUrl(); - - /** - * Returns the list of group members - * - * If this principal is a group, this function should return - * all member principal uri's for the group. - * - * @return array - */ - function getGroupMemberSet(); - - /** - * Returns the list of groups this principal is member of - * - * If this principal is a member of a (list of) groups, this function - * should return a list of principal uri's for it's members. - * - * @return array - */ - function getGroupMembership(); - - /** - * Sets a list of group members - * - * If this principal is a group, this method sets all the group members. - * The list of members is always overwritten, never appended to. - * - * This method should throw an exception if the members could not be set. - * - * @param array $principals - * @return void - */ - function setGroupMemberSet(array $principals); - - /** - * Returns the displayname - * - * This should be a human readable name for the principal. - * If none is available, return the nodename. - * - * @return string - */ - function getDisplayName(); - -} diff --git a/3rdparty/Sabre/DAVACL/IPrincipalBackend.php b/3rdparty/Sabre/DAVACL/IPrincipalBackend.php deleted file mode 100644 index 8899f6f80dffda4e838cf963ec1ce6ade41660f7..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/IPrincipalBackend.php +++ /dev/null @@ -1,73 +0,0 @@ -<?php - -/** - * Implement this interface to create your own principal backends. - * - * Creating backends for principals is entirely optional. You can also - * implement Sabre_DAVACL_IPrincipal directly. This interface is used solely by - * Sabre_DAVACL_AbstractPrincipalCollection. - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -interface Sabre_DAVACL_IPrincipalBackend { - - /** - * Returns a list of principals based on a prefix. - * - * This prefix will often contain something like 'principals'. You are only - * expected to return principals that are in this base path. - * - * You are expected to return at least a 'uri' for every user, you can - * return any additional properties if you wish so. Common properties are: - * {DAV:}displayname - * {http://sabredav.org/ns}email-address - This is a custom SabreDAV - * field that's actualy injected in a number of other properties. If - * you have an email address, use this property. - * - * @param string $prefixPath - * @return array - */ - function getPrincipalsByPrefix($prefixPath); - - /** - * Returns a specific principal, specified by it's path. - * The returned structure should be the exact same as from - * getPrincipalsByPrefix. - * - * @param string $path - * @return array - */ - function getPrincipalByPath($path); - - /** - * Returns the list of members for a group-principal - * - * @param string $principal - * @return array - */ - function getGroupMemberSet($principal); - - /** - * Returns the list of groups a principal is a member of - * - * @param string $principal - * @return array - */ - function getGroupMembership($principal); - - /** - * Updates the list of group members for a group principal. - * - * The principals should be passed as a list of uri's. - * - * @param string $principal - * @param array $members - * @return void - */ - function setGroupMemberSet($principal, array $members); - -} diff --git a/3rdparty/Sabre/DAVACL/Plugin.php b/3rdparty/Sabre/DAVACL/Plugin.php deleted file mode 100644 index b964bdb5dec84466b71002cf4cce356174b5bb97..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Plugin.php +++ /dev/null @@ -1,1238 +0,0 @@ -<?php - -/** - * SabreDAV ACL Plugin - * - * This plugin provides funcitonality to enforce ACL permissions. - * ACL is defined in RFC3744. - * - * In addition it also provides support for the {DAV:}current-user-principal - * property, defined in RFC5397 and the {DAV:}expand-property report, as - * defined in RFC3253. - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { - - /** - * Recursion constants - * - * This only checks the base node - */ - const R_PARENT = 1; - - /** - * Recursion constants - * - * This checks every node in the tree - */ - const R_RECURSIVE = 2; - - /** - * Recursion constants - * - * This checks every parentnode in the tree, but not leaf-nodes. - */ - const R_RECURSIVEPARENTS = 3; - - /** - * Reference to server object. - * - * @var Sabre_DAV_Server - */ - protected $server; - - /** - * List of urls containing principal collections. - * Modify this if your principals are located elsewhere. - * - * @var array - */ - public $principalCollectionSet = array( - 'principals', - ); - - /** - * By default ACL is only enforced for nodes that have ACL support (the - * ones that implement Sabre_DAVACL_IACL). For any other node, access is - * always granted. - * - * To override this behaviour you can turn this setting off. This is useful - * if you plan to fully support ACL in the entire tree. - * - * @var bool - */ - public $allowAccessToNodesWithoutACL = true; - - /** - * By default nodes that are inaccessible by the user, can still be seen - * in directory listings (PROPFIND on parent with Depth: 1) - * - * In certain cases it's desirable to hide inaccessible nodes. Setting this - * to true will cause these nodes to be hidden from directory listings. - * - * @var bool - */ - public $hideNodesFromListings = false; - - /** - * This string is prepended to the username of the currently logged in - * user. This allows the plugin to determine the principal path based on - * the username. - * - * @var string - */ - public $defaultUsernamePath = 'principals'; - - /** - * Returns a list of features added by this plugin. - * - * This list is used in the response of a HTTP OPTIONS request. - * - * @return array - */ - public function getFeatures() { - - return array('access-control'); - - } - - /** - * Returns a list of available methods for a given url - * - * @param string $uri - * @return array - */ - public function getMethods($uri) { - - return array('ACL'); - - } - - /** - * Returns a plugin name. - * - * Using this name other plugins will be able to access other plugins - * using Sabre_DAV_Server::getPlugin - * - * @return string - */ - public function getPluginName() { - - return 'acl'; - - } - - /** - * Returns a list of reports this plugin supports. - * - * This will be used in the {DAV:}supported-report-set property. - * Note that you still need to subscribe to the 'report' event to actually - * implement them - * - * @param string $uri - * @return array - */ - public function getSupportedReportSet($uri) { - - return array( - '{DAV:}expand-property', - '{DAV:}principal-property-search', - '{DAV:}principal-search-property-set', - ); - - } - - - /** - * Checks if the current user has the specified privilege(s). - * - * You can specify a single privilege, or a list of privileges. - * This method will throw an exception if the privilege is not available - * and return true otherwise. - * - * @param string $uri - * @param array|string $privileges - * @param bool $throwExceptions if set to false, this method won't through exceptions. - * @throws Sabre_DAVACL_Exception_NeedPrivileges - * @return bool - */ - public function checkPrivileges($uri,$privileges,$recursion = self::R_PARENT, $throwExceptions = true) { - - if (!is_array($privileges)) $privileges = array($privileges); - - $acl = $this->getCurrentUserPrivilegeSet($uri); - - if (is_null($acl)) { - if ($this->allowAccessToNodesWithoutACL) { - return true; - } else { - if ($throwExceptions) - throw new Sabre_DAVACL_Exception_NeedPrivileges($uri,$privileges); - else - return false; - - } - } - - $failed = array(); - foreach($privileges as $priv) { - - if (!in_array($priv, $acl)) { - $failed[] = $priv; - } - - } - - if ($failed) { - if ($throwExceptions) - throw new Sabre_DAVACL_Exception_NeedPrivileges($uri,$failed); - else - return false; - } - return true; - - } - - /** - * Returns the standard users' principal. - * - * This is one authorative principal url for the current user. - * This method will return null if the user wasn't logged in. - * - * @return string|null - */ - public function getCurrentUserPrincipal() { - - $authPlugin = $this->server->getPlugin('auth'); - if (is_null($authPlugin)) return null; - - $userName = $authPlugin->getCurrentUser(); - if (!$userName) return null; - - return $this->defaultUsernamePath . '/' . $userName; - - } - - /** - * Returns a list of principals that's associated to the current - * user, either directly or through group membership. - * - * @return array - */ - public function getCurrentUserPrincipals() { - - $currentUser = $this->getCurrentUserPrincipal(); - - if (is_null($currentUser)) return array(); - - $check = array($currentUser); - $principals = array($currentUser); - - while(count($check)) { - - $principal = array_shift($check); - - $node = $this->server->tree->getNodeForPath($principal); - if ($node instanceof Sabre_DAVACL_IPrincipal) { - foreach($node->getGroupMembership() as $groupMember) { - - if (!in_array($groupMember, $principals)) { - - $check[] = $groupMember; - $principals[] = $groupMember; - - } - - } - - } - - } - - return $principals; - - } - - /** - * Returns the supported privilege structure for this ACL plugin. - * - * See RFC3744 for more details. Currently we default on a simple, - * standard structure. - * - * @return array - */ - public function getSupportedPrivilegeSet() { - - return array( - 'privilege' => '{DAV:}all', - 'abstract' => true, - 'aggregates' => array( - array( - 'privilege' => '{DAV:}read', - 'aggregates' => array( - array( - 'privilege' => '{DAV:}read-acl', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}read-current-user-privilege-set', - 'abstract' => true, - ), - ), - ), // {DAV:}read - array( - 'privilege' => '{DAV:}write', - 'aggregates' => array( - array( - 'privilege' => '{DAV:}write-acl', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}write-properties', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}write-content', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}bind', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}unbind', - 'abstract' => true, - ), - array( - 'privilege' => '{DAV:}unlock', - 'abstract' => true, - ), - ), - ), // {DAV:}write - ), - ); // {DAV:}all - - } - - /** - * Returns the supported privilege set as a flat list - * - * This is much easier to parse. - * - * The returned list will be index by privilege name. - * The value is a struct containing the following properties: - * - aggregates - * - abstract - * - concrete - * - * @return array - */ - final public function getFlatPrivilegeSet() { - - $privs = $this->getSupportedPrivilegeSet(); - - $flat = array(); - $this->getFPSTraverse($privs, null, $flat); - - return $flat; - - } - - /** - * Traverses the privilege set tree for reordering - * - * This function is solely used by getFlatPrivilegeSet, and would have been - * a closure if it wasn't for the fact I need to support PHP 5.2. - * - * @return void - */ - final private function getFPSTraverse($priv, $concrete, &$flat) { - - $myPriv = array( - 'privilege' => $priv['privilege'], - 'abstract' => isset($priv['abstract']) && $priv['abstract'], - 'aggregates' => array(), - 'concrete' => isset($priv['abstract']) && $priv['abstract']?$concrete:$priv['privilege'], - ); - - if (isset($priv['aggregates'])) - foreach($priv['aggregates'] as $subPriv) $myPriv['aggregates'][] = $subPriv['privilege']; - - $flat[$priv['privilege']] = $myPriv; - - if (isset($priv['aggregates'])) { - - foreach($priv['aggregates'] as $subPriv) { - - $this->getFPSTraverse($subPriv, $myPriv['concrete'], $flat); - - } - - } - - } - - /** - * Returns the full ACL list. - * - * Either a uri or a Sabre_DAV_INode may be passed. - * - * null will be returned if the node doesn't support ACLs. - * - * @param string|Sabre_DAV_INode $node - * @return array - */ - public function getACL($node) { - - if (is_string($node)) { - $node = $this->server->tree->getNodeForPath($node); - } - if ($node instanceof Sabre_DAVACL_IACL) { - return $node->getACL(); - } - return null; - - } - - /** - * Returns a list of privileges the current user has - * on a particular node. - * - * Either a uri or a Sabre_DAV_INode may be passed. - * - * null will be returned if the node doesn't support ACLs. - * - * @param string|Sabre_DAV_INode $node - * @return array - */ - public function getCurrentUserPrivilegeSet($node) { - - if (is_string($node)) { - $node = $this->server->tree->getNodeForPath($node); - } - - $acl = $this->getACL($node); - if (is_null($acl)) return null; - - $principals = $this->getCurrentUserPrincipals(); - - $collected = array(); - - foreach($acl as $ace) { - - if (in_array($ace['principal'], $principals)) { - $collected[] = $ace; - } - - } - - // Now we deduct all aggregated privileges. - $flat = $this->getFlatPrivilegeSet(); - - $collected2 = array(); - foreach($collected as $privilege) { - - $collected2[] = $privilege['privilege']; - foreach($flat[$privilege['privilege']]['aggregates'] as $subPriv) { - if (!in_array($subPriv, $collected2)) - $collected2[] = $subPriv; - } - - } - - return $collected2; - - } - - /** - * Sets up the plugin - * - * This method is automatically called by the server class. - * - * @param Sabre_DAV_Server $server - * @return void - */ - public function initialize(Sabre_DAV_Server $server) { - - $this->server = $server; - $server->subscribeEvent('beforeGetProperties',array($this,'beforeGetProperties')); - - $server->subscribeEvent('beforeMethod', array($this,'beforeMethod'),20); - $server->subscribeEvent('beforeBind', array($this,'beforeBind'),20); - $server->subscribeEvent('beforeUnbind', array($this,'beforeUnbind'),20); - $server->subscribeEvent('updateProperties',array($this,'updateProperties')); - $server->subscribeEvent('beforeUnlock', array($this,'beforeUnlock'),20); - $server->subscribeEvent('report',array($this,'report')); - $server->subscribeEvent('unknownMethod', array($this, 'unknownMethod')); - - array_push($server->protectedProperties, - '{DAV:}alternate-URI-set', - '{DAV:}principal-URL', - '{DAV:}group-membership', - '{DAV:}principal-collection-set', - '{DAV:}current-user-principal', - '{DAV:}supported-privilege-set', - '{DAV:}current-user-privilege-set', - '{DAV:}acl', - '{DAV:}acl-restrictions', - '{DAV:}inherited-acl-set', - '{DAV:}owner', - '{DAV:}group' - ); - - // Automatically mapping nodes implementing IPrincipal to the - // {DAV:}principal resourcetype. - $server->resourceTypeMapping['Sabre_DAVACL_IPrincipal'] = '{DAV:}principal'; - - // Mapping the group-member-set property to the HrefList property - // class. - $server->propertyMap['{DAV:}group-member-set'] = 'Sabre_DAV_Property_HrefList'; - - } - - - /* {{{ Event handlers */ - - /** - * Triggered before any method is handled - * - * @param string $method - * @param string $uri - * @return void - */ - public function beforeMethod($method, $uri) { - - $exists = $this->server->tree->nodeExists($uri); - - // If the node doesn't exists, none of these checks apply - if (!$exists) return; - - switch($method) { - - case 'GET' : - case 'HEAD' : - case 'OPTIONS' : - // For these 3 we only need to know if the node is readable. - $this->checkPrivileges($uri,'{DAV:}read'); - break; - - case 'PUT' : - case 'LOCK' : - case 'UNLOCK' : - // This method requires the write-content priv if the node - // already exists, and bind on the parent if the node is being - // created. - // The bind privilege is handled in the beforeBind event. - $this->checkPrivileges($uri,'{DAV:}write-content'); - break; - - - case 'PROPPATCH' : - $this->checkPrivileges($uri,'{DAV:}write-properties'); - break; - - case 'ACL' : - $this->checkPrivileges($uri,'{DAV:}write-acl'); - break; - - case 'COPY' : - case 'MOVE' : - // Copy requires read privileges on the entire source tree. - // If the target exists write-content normally needs to be - // checked, however, we're deleting the node beforehand and - // creating a new one after, so this is handled by the - // beforeUnbind event. - // - // The creation of the new node is handled by the beforeBind - // event. - // - // If MOVE is used beforeUnbind will also be used to check if - // the sourcenode can be deleted. - $this->checkPrivileges($uri,'{DAV:}read',self::R_RECURSIVE); - - break; - - } - - } - - /** - * Triggered before a new node is created. - * - * This allows us to check permissions for any operation that creates a - * new node, such as PUT, MKCOL, MKCALENDAR, LOCK, COPY and MOVE. - * - * @param string $uri - * @return void - */ - public function beforeBind($uri) { - - list($parentUri,$nodeName) = Sabre_DAV_URLUtil::splitPath($uri); - $this->checkPrivileges($parentUri,'{DAV:}bind'); - - } - - /** - * Triggered before a node is deleted - * - * This allows us to check permissions for any operation that will delete - * an existing node. - * - * @param string $uri - * @return void - */ - public function beforeUnbind($uri) { - - list($parentUri,$nodeName) = Sabre_DAV_URLUtil::splitPath($uri); - $this->checkPrivileges($parentUri,'{DAV:}unbind',self::R_RECURSIVEPARENTS); - - } - - /** - * Triggered before a node is unlocked. - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lock - * @TODO: not yet implemented - * @return void - */ - public function beforeUnlock($uri, Sabre_DAV_Locks_LockInfo $lock) { - - - } - - /** - * Triggered before properties are looked up in specific nodes. - * - * @param string $uri - * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties - * @TODO really should be broken into multiple methods, or even a class. - * @return void - */ - public function beforeGetProperties($uri, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) { - - // Checking the read permission - if (!$this->checkPrivileges($uri,'{DAV:}read',self::R_PARENT,false)) { - - // User is not allowed to read properties - if ($this->hideNodesFromListings) { - return false; - } - - // Marking all requested properties as '403'. - foreach($requestedProperties as $key=>$requestedProperty) { - unset($requestedProperties[$key]); - $returnedProperties[403][$requestedProperty] = null; - } - return; - - } - - /* Adding principal properties */ - if ($node instanceof Sabre_DAVACL_IPrincipal) { - - if (false !== ($index = array_search('{DAV:}alternate-URI-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}alternate-URI-set'] = new Sabre_DAV_Property_HrefList($node->getAlternateUriSet()); - - } - if (false !== ($index = array_search('{DAV:}principal-URL', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}principal-URL'] = new Sabre_DAV_Property_Href($node->getPrincipalUrl() . '/'); - - } - if (false !== ($index = array_search('{DAV:}group-member-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}group-member-set'] = new Sabre_DAV_Property_HrefList($node->getGroupMemberSet()); - - } - if (false !== ($index = array_search('{DAV:}group-membership', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}group-membership'] = new Sabre_DAV_Property_HrefList($node->getGroupMembership()); - - } - - if (false !== ($index = array_search('{DAV:}displayname', $requestedProperties))) { - - $returnedProperties[200]['{DAV:}displayname'] = $node->getDisplayName(); - - } - - } - if (false !== ($index = array_search('{DAV:}principal-collection-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $val = $this->principalCollectionSet; - // Ensuring all collections end with a slash - foreach($val as $k=>$v) $val[$k] = $v . '/'; - $returnedProperties[200]['{DAV:}principal-collection-set'] = new Sabre_DAV_Property_HrefList($val); - - } - if (false !== ($index = array_search('{DAV:}current-user-principal', $requestedProperties))) { - - unset($requestedProperties[$index]); - if ($url = $this->getCurrentUserPrincipal()) { - $returnedProperties[200]['{DAV:}current-user-principal'] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF, $url . '/'); - } else { - $returnedProperties[200]['{DAV:}current-user-principal'] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::UNAUTHENTICATED); - } - - } - if (false !== ($index = array_search('{DAV:}supported-privilege-set', $requestedProperties))) { - - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}supported-privilege-set'] = new Sabre_DAVACL_Property_SupportedPrivilegeSet($this->getSupportedPrivilegeSet()); - - } - if (false !== ($index = array_search('{DAV:}current-user-privilege-set', $requestedProperties))) { - - if (!$this->checkPrivileges($uri, '{DAV:}read-current-user-privilege-set', self::R_PARENT, false)) { - $returnedProperties[403]['{DAV:}current-user-privilege-set'] = null; - unset($requestedProperties[$index]); - } else { - $val = $this->getCurrentUserPrivilegeSet($node); - if (!is_null($val)) { - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}current-user-privilege-set'] = new Sabre_DAVACL_Property_CurrentUserPrivilegeSet($val); - } - } - - } - - /* The ACL property contains all the permissions */ - if (false !== ($index = array_search('{DAV:}acl', $requestedProperties))) { - - if (!$this->checkPrivileges($uri, '{DAV:}read-acl', self::R_PARENT, false)) { - - unset($requestedProperties[$index]); - $returnedProperties[403]['{DAV:}acl'] = null; - - } else { - - $acl = $this->getACL($node); - if (!is_null($acl)) { - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}acl'] = new Sabre_DAVACL_Property_Acl($this->getACL($node)); - } - - } - - } - - } - - /** - * This method intercepts PROPPATCH methods and make sure the - * group-member-set is updated correctly. - * - * @param array $propertyDelta - * @param array $result - * @param Sabre_DAV_INode $node - * @return void - */ - public function updateProperties(&$propertyDelta, &$result, Sabre_DAV_INode $node) { - - if (!array_key_exists('{DAV:}group-member-set', $propertyDelta)) - return; - - if (is_null($propertyDelta['{DAV:}group-member-set'])) { - $memberSet = array(); - } elseif ($propertyDelta['{DAV:}group-member-set'] instanceof Sabre_DAV_Property_HrefList) { - $memberSet = $propertyDelta['{DAV:}group-member-set']->getHrefs(); - } else { - throw new Sabre_DAV_Exception('The group-member-set property MUST be an instance of Sabre_DAV_Property_HrefList or null'); - } - - if (!($node instanceof Sabre_DAVACL_IPrincipal)) { - $result[403]['{DAV:}group-member-set'] = null; - unset($propertyDelta['{DAV:}group-member-set']); - - // Returning false will stop the updateProperties process - return false; - } - - $node->setGroupMemberSet($memberSet); - - $result[200]['{DAV:}group-member-set'] = null; - unset($propertyDelta['{DAV:}group-member-set']); - - } - - /** - * This method handels HTTP REPORT requests - * - * @param string $reportName - * @param DOMNode $dom - * @return void - */ - public function report($reportName, $dom) { - - switch($reportName) { - - case '{DAV:}principal-property-search' : - $this->principalPropertySearchReport($dom); - return false; - case '{DAV:}principal-search-property-set' : - $this->principalSearchPropertySetReport($dom); - return false; - case '{DAV:}expand-property' : - $this->expandPropertyReport($dom); - return false; - - } - - } - - /** - * This event is triggered for any HTTP method that is not known by the - * webserver. - * - * @param string $method - * @param string $uri - * @return void - */ - public function unknownMethod($method, $uri) { - - if ($method!=='ACL') return; - - $this->httpACL($uri); - return false; - - } - - /** - * This method is responsible for handling the 'ACL' event. - * - * @param string $uri - * @return void - */ - public function httpACL($uri) { - - $body = $this->server->httpRequest->getBody(true); - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - - $newAcl = - Sabre_DAVACL_Property_Acl::unserialize($dom->firstChild) - ->getPrivileges(); - - // Normalizing urls - foreach($newAcl as $k=>$newAce) { - $newAcl[$k]['principal'] = $this->server->calculateUri($newAce['principal']); - } - - $node = $this->server->tree->getNodeForPath($uri); - - if (!($node instanceof Sabre_DAVACL_IACL)) { - throw new Sabre_DAV_Exception_MethodNotAllowed('This node does not support the ACL method'); - } - - $oldAcl = $this->getACL($node); - - $supportedPrivileges = $this->getFlatPrivilegeSet(); - - /* Checking if protected principals from the existing principal set are - not overwritten. */ - foreach($oldAcl as $k=>$oldAce) { - - if (!isset($oldAce['protected']) || !$oldAce['protected']) continue; - - $found = false; - foreach($newAcl as $newAce) { - if ( - $newAce['privilege'] === $oldAce['privilege'] && - $newAce['principal'] === $oldAce['principal'] && - $newAce['protected'] - ) - $found = true; - } - - if (!$found) - throw new Sabre_DAVACL_Exception_AceConflict('This resource contained a protected {DAV:}ace, but this privilege did not occur in the ACL request'); - - } - - foreach($newAcl as $k=>$newAce) { - - // Do we recognize the privilege - if (!isset($supportedPrivileges[$newAce['privilege']])) { - throw new Sabre_DAVACL_Exception_NotSupportedPrivilege('The privilege you specified (' . $newAce['privilege'] . ') is not recognized by this server'); - } - - if ($supportedPrivileges[$newAce['privilege']]['abstract']) { - throw new Sabre_DAVACL_Exception_NoAbstract('The privilege you specified (' . $newAce['privilege'] . ') is an abstract privilege'); - } - - // Looking up the principal - try { - $principal = $this->server->tree->getNodeForPath($newAce['principal']); - } catch (Sabre_DAV_Exception_FileNotFound $e) { - throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified principal (' . $newAce['principal'] . ') does not exist'); - } - if (!($principal instanceof Sabre_DAVACL_IPrincipal)) { - throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified uri (' . $newAce['principal'] . ') is not a principal'); - } - - } - $node->setACL($newAcl); - - } - - /* }}} */ - - /* Reports {{{ */ - - /** - * The expand-property report is defined in RFC3253 section 3-8. - * - * This report is very similar to a standard PROPFIND. The difference is - * that it has the additional ability to look at properties containing a - * {DAV:}href element, follow that property and grab additional elements - * there. - * - * Other rfc's, such as ACL rely on this report, so it made sense to put - * it in this plugin. - * - * @param DOMElement $dom - * @return void - */ - protected function expandPropertyReport($dom) { - - $requestedProperties = $this->parseExpandPropertyReportRequest($dom->firstChild->firstChild); - $depth = $this->server->getHTTPDepth(0); - $requestUri = $this->server->getRequestUri(); - - $result = $this->expandProperties($requestUri,$requestedProperties,$depth); - - $dom = new DOMDocument('1.0','utf-8'); - $dom->formatOutput = true; - $multiStatus = $dom->createElement('d:multistatus'); - $dom->appendChild($multiStatus); - - // Adding in default namespaces - foreach($this->server->xmlNamespaces as $namespace=>$prefix) { - - $multiStatus->setAttribute('xmlns:' . $prefix,$namespace); - - } - - foreach($result as $response) { - $response->serialize($this->server, $multiStatus); - } - - $xml = $dom->saveXML(); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->sendBody($xml); - - } - - /** - * This method is used by expandPropertyReport to parse - * out the entire HTTP request. - * - * @param DOMElement $node - * @return array - */ - protected function parseExpandPropertyReportRequest($node) { - - $requestedProperties = array(); - do { - - if (Sabre_DAV_XMLUtil::toClarkNotation($node)!=='{DAV:}property') continue; - - if ($node->firstChild) { - - $children = $this->parseExpandPropertyReportRequest($node->firstChild); - - } else { - - $children = array(); - - } - - $namespace = $node->getAttribute('namespace'); - if (!$namespace) $namespace = 'DAV:'; - - $propName = '{'.$namespace.'}' . $node->getAttribute('name'); - $requestedProperties[$propName] = $children; - - } while ($node = $node->nextSibling); - - return $requestedProperties; - - } - - /** - * This method expands all the properties and returns - * a list with property values - * - * @param array $path - * @param array $requestedProperties the list of required properties - * @param array $depth - */ - protected function expandProperties($path,array $requestedProperties,$depth) { - - $foundProperties = $this->server->getPropertiesForPath($path,array_keys($requestedProperties),$depth); - - $result = array(); - - foreach($foundProperties as $node) { - - foreach($requestedProperties as $propertyName=>$childRequestedProperties) { - - // We're only traversing if sub-properties were requested - if(count($childRequestedProperties)===0) continue; - - // We only have to do the expansion if the property was found - // and it contains an href element. - if (!array_key_exists($propertyName,$node[200])) continue; - - if ($node[200][$propertyName] instanceof Sabre_DAV_Property_IHref) { - $hrefs = array($node[200][$propertyName]->getHref()); - } elseif ($node[200][$propertyName] instanceof Sabre_DAV_Property_HrefList) { - $hrefs = $node[200][$propertyName]->getHrefs(); - } - - $childProps = array(); - foreach($hrefs as $href) { - $childProps = array_merge($childProps, $this->expandProperties($href,$childRequestedProperties,0)); - } - $node[200][$propertyName] = new Sabre_DAV_Property_ResponseList($childProps); - - } - $result[] = new Sabre_DAV_Property_Response($path, $node); - - } - - return $result; - - } - - /** - * principalSearchPropertySetReport - * - * This method responsible for handing the - * {DAV:}principal-search-property-set report. This report returns a list - * of properties the client may search on, using the - * {DAV:}principal-property-search report. - * - * @param DOMDocument $dom - * @return void - */ - protected function principalSearchPropertySetReport(DOMDocument $dom) { - - $searchProperties = array( - '{DAV:}displayname' => 'display name' - ); - - $httpDepth = $this->server->getHTTPDepth(0); - if ($httpDepth!==0) { - throw new Sabre_DAV_Exception_BadRequest('This report is only defined when Depth: 0'); - } - - if ($dom->firstChild->hasChildNodes()) - throw new Sabre_DAV_Exception_BadRequest('The principal-search-property-set report element is not allowed to have child elements'); - - $dom = new DOMDocument('1.0','utf-8'); - $dom->formatOutput = true; - $root = $dom->createElement('d:principal-search-property-set'); - $dom->appendChild($root); - // Adding in default namespaces - foreach($this->server->xmlNamespaces as $namespace=>$prefix) { - - $root->setAttribute('xmlns:' . $prefix,$namespace); - - } - - $nsList = $this->server->xmlNamespaces; - - foreach($searchProperties as $propertyName=>$description) { - - $psp = $dom->createElement('d:principal-search-property'); - $root->appendChild($psp); - - $prop = $dom->createElement('d:prop'); - $psp->appendChild($prop); - - $propName = null; - preg_match('/^{([^}]*)}(.*)$/',$propertyName,$propName); - - $currentProperty = $dom->createElement($nsList[$propName[1]] . ':' . $propName[2]); - $prop->appendChild($currentProperty); - - $descriptionElem = $dom->createElement('d:description'); - $descriptionElem->setAttribute('xml:lang','en'); - $descriptionElem->appendChild($dom->createTextNode($description)); - $psp->appendChild($descriptionElem); - - - } - - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->sendBody($dom->saveXML()); - - } - - /** - * principalPropertySearchReport - * - * This method is reponsible for handing the - * {DAV:}principal-property-search report. This report can be used for - * clients to search for groups of principals, based on the value of one - * or more properties. - * - * @param DOMDocument $dom - * @return void - */ - protected function principalPropertySearchReport(DOMDocument $dom) { - - $searchableProperties = array( - '{DAV:}displayname' => 'display name' - - ); - - list($searchProperties, $requestedProperties, $applyToPrincipalCollectionSet) = $this->parsePrincipalPropertySearchReportRequest($dom); - - $result = array(); - - if ($applyToPrincipalCollectionSet) { - $uris = array(); - } else { - $uris = array($this->server->getRequestUri()); - } - - $lookupResults = array(); - foreach($uris as $uri) { - - $p = array_keys($searchProperties); - $p[] = '{DAV:}resourcetype'; - $r = $this->server->getPropertiesForPath($uri, $p, 1); - - // The first item in the results is the parent, so we get rid of it. - array_shift($r); - $lookupResults = array_merge($lookupResults, $r); - } - - $matches = array(); - - foreach($lookupResults as $lookupResult) { - - // We're only looking for principals - if (!isset($lookupResult[200]['{DAV:}resourcetype']) || - (!($lookupResult[200]['{DAV:}resourcetype'] instanceof Sabre_DAV_Property_ResourceType)) || - !$lookupResult[200]['{DAV:}resourcetype']->is('{DAV:}principal')) continue; - - foreach($searchProperties as $searchProperty=>$searchValue) { - if (!isset($searchableProperties[$searchProperty])) { - // If a property is not 'searchable', the spec dictates - // this is not a match. - continue; - } - - if (isset($lookupResult[200][$searchProperty]) && - mb_stripos($lookupResult[200][$searchProperty], $searchValue, 0, 'UTF-8')!==false) { - $matches[] = $lookupResult['href']; - } - - } - - } - - $matchProperties = array(); - - foreach($matches as $match) { - - list($result) = $this->server->getPropertiesForPath($match, $requestedProperties, 0); - $matchProperties[] = $result; - - } - - $xml = $this->server->generateMultiStatus($matchProperties); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->sendBody($xml); - - } - - /** - * parsePrincipalPropertySearchReportRequest - * - * This method parses the request body from a - * {DAV:}principal-property-search report. - * - * This method returns an array with two elements: - * 1. an array with properties to search on, and their values - * 2. a list of propertyvalues that should be returned for the request. - * - * @param DOMDocument $dom - * @return array - */ - protected function parsePrincipalPropertySearchReportRequest($dom) { - - $httpDepth = $this->server->getHTTPDepth(0); - if ($httpDepth!==0) { - throw new Sabre_DAV_Exception_BadRequest('This report is only defined when Depth: 0'); - } - - $searchProperties = array(); - - $applyToPrincipalCollectionSet = false; - - // Parsing the search request - foreach($dom->firstChild->childNodes as $searchNode) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($searchNode) == '{DAV:}apply-to-principal-collection-set') - $applyToPrincipalCollectionSet = true; - - if (Sabre_DAV_XMLUtil::toClarkNotation($searchNode)!=='{DAV:}property-search') - continue; - - $propertyName = null; - $propertyValue = null; - - foreach($searchNode->childNodes as $childNode) { - - switch(Sabre_DAV_XMLUtil::toClarkNotation($childNode)) { - - case '{DAV:}prop' : - $property = Sabre_DAV_XMLUtil::parseProperties($searchNode); - reset($property); - $propertyName = key($property); - break; - - case '{DAV:}match' : - $propertyValue = $childNode->textContent; - break; - - } - - - } - - if (is_null($propertyName) || is_null($propertyValue)) - throw new Sabre_DAV_Exception_BadRequest('Invalid search request. propertyname: ' . $propertyName . '. propertvvalue: ' . $propertyValue); - - $searchProperties[$propertyName] = $propertyValue; - - } - - return array($searchProperties, array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)), $applyToPrincipalCollectionSet); - - } - - - /* }}} */ - -} diff --git a/3rdparty/Sabre/DAVACL/Principal.php b/3rdparty/Sabre/DAVACL/Principal.php deleted file mode 100644 index 790603c900f33f3361bcab9cdbea308744dd1383..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Principal.php +++ /dev/null @@ -1,263 +0,0 @@ -<?php - -/** - * Principal class - * - * This class is a representation of a simple principal - * - * Many WebDAV specs require a user to show up in the directory - * structure. - * - * This principal also has basic ACL settings, only allowing the principal - * access it's own principal. - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Principal extends Sabre_DAV_Node implements Sabre_DAVACL_IPrincipal, Sabre_DAV_IProperties, Sabre_DAVACL_IACL { - - /** - * Struct with principal information. - * - * @var array - */ - protected $principalProperties; - - /** - * Principal backend - * - * @var Sabre_DAVACL_IPrincipalBackend - */ - protected $principalBackend; - - /** - * Creates the principal object - * - * @param array $principalProperties - */ - public function __construct(Sabre_DAVACL_IPrincipalBackend $principalBackend, array $principalProperties = array()) { - - if (!isset($principalProperties['uri'])) { - throw new Sabre_DAV_Exception('The principal properties must at least contain the \'uri\' key'); - } - $this->principalBackend = $principalBackend; - $this->principalProperties = $principalProperties; - - } - - /** - * Returns the full principal url - * - * @return string - */ - public function getPrincipalUrl() { - - return $this->principalProperties['uri']; - - } - - /** - * Returns a list of altenative urls for a principal - * - * This can for example be an email address, or ldap url. - * - * @return array - */ - public function getAlternateUriSet() { - - $uris = array(); - if (isset($this->principalProperties['{DAV:}alternate-URI-set'])) { - - $uris = $this->principalProperties['{DAV:}alternate-URI-set']; - - } - - if (isset($this->principalProperties['{http://sabredav.org/ns}email-address'])) { - $uris[] = 'mailto:' . $this->principalProperties['{http://sabredav.org/ns}email-address']; - } - - return array_unique($uris); - - } - - /** - * Returns the list of group members - * - * If this principal is a group, this function should return - * all member principal uri's for the group. - * - * @return array - */ - public function getGroupMemberSet() { - - return $this->principalBackend->getGroupMemberSet($this->principalProperties['uri']); - - } - - /** - * Returns the list of groups this principal is member of - * - * If this principal is a member of a (list of) groups, this function - * should return a list of principal uri's for it's members. - * - * @return array - */ - public function getGroupMembership() { - - return $this->principalBackend->getGroupMemberShip($this->principalProperties['uri']); - - } - - - /** - * Sets a list of group members - * - * If this principal is a group, this method sets all the group members. - * The list of members is always overwritten, never appended to. - * - * This method should throw an exception if the members could not be set. - * - * @param array $principals - * @return void - */ - public function setGroupMemberSet(array $groupMembers) { - - $this->principalBackend->setGroupMemberSet($this->principalProperties['uri'], $groupMembers); - - } - - - /** - * Returns this principals name. - * - * @return string - */ - public function getName() { - - $uri = $this->principalProperties['uri']; - list(, $name) = Sabre_DAV_URLUtil::splitPath($uri); - - return $name; - - } - - /** - * Returns the name of the user - * - * @return void - */ - public function getDisplayName() { - - if (isset($this->principalProperties['{DAV:}displayname'])) { - return $this->principalProperties['{DAV:}displayname']; - } else { - return $this->getName(); - } - - } - - /** - * Returns a list of properties - * - * @param array $requestedProperties - * @return void - */ - public function getProperties($requestedProperties) { - - $newProperties = array(); - foreach($requestedProperties as $propName) { - - if (isset($this->principalProperties[$propName])) { - $newProperties[$propName] = $this->principalProperties[$propName]; - } - - } - - return $newProperties; - - } - - /** - * Updates this principals properties. - * - * Currently this is not supported - * - * @param array $properties - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public function updateProperties($properties) { - - return false; - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->principalProperties['uri']; - - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'], - 'protected' => true, - ), - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Updating ACLs is not allowed here'); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php b/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php deleted file mode 100644 index 55bd1903c9bfe5a626524bcf9f6d01b17eeca78a..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php +++ /dev/null @@ -1,206 +0,0 @@ -<?php - -/** - * PDO principal backend - * - * This is a simple principal backend that maps exactly to the users table, as - * used by Sabre_DAV_Auth_Backend_PDO. - * - * It assumes all principals are in a single collection. The default collection - * is 'principals/', but this can be overriden. - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_PrincipalBackend_PDO implements Sabre_DAVACL_IPrincipalBackend { - - /** - * pdo - * - * @var PDO - */ - protected $pdo; - - /** - * PDO table name for 'principals' - * - * @var string - */ - protected $tableName; - - /** - * PDO table name for 'group members' - * - * @var string - */ - protected $groupMembersTableName; - - /** - * Sets up the backend. - * - * @param PDO $pdo - * @param string $tableName - */ - public function __construct(PDO $pdo, $tableName = 'principals', $groupMembersTableName = 'groupmembers') { - - $this->pdo = $pdo; - $this->tableName = $tableName; - $this->groupMembersTableName = $groupMembersTableName; - - } - - - /** - * Returns a list of principals based on a prefix. - * - * This prefix will often contain something like 'principals'. You are only - * expected to return principals that are in this base path. - * - * You are expected to return at least a 'uri' for every user, you can - * return any additional properties if you wish so. Common properties are: - * {DAV:}displayname - * {http://sabredav.org/ns}email-address - This is a custom SabreDAV - * field that's actualy injected in a number of other properties. If - * you have an email address, use this property. - * - * @param string $prefixPath - * @return array - */ - public function getPrincipalsByPrefix($prefixPath) { - $result = $this->pdo->query('SELECT uri, email, displayname FROM `'. $this->tableName . '`'); - - $principals = array(); - - while($row = $result->fetch(PDO::FETCH_ASSOC)) { - - // Checking if the principal is in the prefix - list($rowPrefix) = Sabre_DAV_URLUtil::splitPath($row['uri']); - if ($rowPrefix !== $prefixPath) continue; - - $principals[] = array( - 'uri' => $row['uri'], - '{DAV:}displayname' => $row['displayname']?$row['displayname']:basename($row['uri']), - '{http://sabredav.org/ns}email-address' => $row['email'], - ); - - } - - return $principals; - - } - - /** - * Returns a specific principal, specified by it's path. - * The returned structure should be the exact same as from - * getPrincipalsByPrefix. - * - * @param string $path - * @return array - */ - public function getPrincipalByPath($path) { - - $stmt = $this->pdo->prepare('SELECT id, uri, email, displayname FROM `'.$this->tableName.'` WHERE uri = ?'); - $stmt->execute(array($path)); - - $users = array(); - - $row = $stmt->fetch(PDO::FETCH_ASSOC); - if (!$row) return; - - return array( - 'id' => $row['id'], - 'uri' => $row['uri'], - '{DAV:}displayname' => $row['displayname']?$row['displayname']:basename($row['uri']), - '{http://sabredav.org/ns}email-address' => $row['email'], - ); - - } - - /** - * Returns the list of members for a group-principal - * - * @param string $principal - * @return array - */ - public function getGroupMemberSet($principal) { - - $principal = $this->getPrincipalByPath($principal); - if (!$principal) throw new Sabre_DAV_Exception('Principal not found'); - - $stmt = $this->pdo->prepare('SELECT principals.uri as uri FROM `'.$this->groupMembersTableName.'` AS groupmembers LEFT JOIN `'.$this->tableName.'` AS principals ON groupmembers.member_id = principals.id WHERE groupmembers.principal_id = ?'); - $stmt->execute(array($principal['id'])); - - $result = array(); - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $result[] = $row['uri']; - } - return $result; - - } - - /** - * Returns the list of groups a principal is a member of - * - * @param string $principal - * @return array - */ - public function getGroupMembership($principal) { - - $principal = $this->getPrincipalByPath($principal); - if (!$principal) throw new Sabre_DAV_Exception('Principal not found'); - - $stmt = $this->pdo->prepare('SELECT principals.uri as uri FROM `'.$this->groupMembersTableName.'` AS groupmembers LEFT JOIN `'.$this->tableName.'` AS principals ON groupmembers.principal_id = principals.id WHERE groupmembers.member_id = ?'); - $stmt->execute(array($principal['id'])); - - $result = array(); - while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - $result[] = $row['uri']; - } - return $result; - - } - - /** - * Updates the list of group members for a group principal. - * - * The principals should be passed as a list of uri's. - * - * @param string $principal - * @param array $members - * @return void - */ - public function setGroupMemberSet($principal, array $members) { - - // Grabbing the list of principal id's. - $stmt = $this->pdo->prepare('SELECT id, uri FROM `'.$this->tableName.'` WHERE uri IN (? ' . str_repeat(', ? ', count($members)) . ');'); - $stmt->execute(array_merge(array($principal), $members)); - - $memberIds = array(); - $principalId = null; - - while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - if ($row['uri'] == $principal) { - $principalId = $row['id']; - } else { - $memberIds[] = $row['id']; - } - } - if (!$principalId) throw new Sabre_DAV_Exception('Principal not found'); - - // Wiping out old members - $stmt = $this->pdo->prepare('DELETE FROM `'.$this->groupMembersTableName.'` WHERE principal_id = ?;'); - $stmt->execute(array($principalId)); - - foreach($memberIds as $memberId) { - - $stmt = $this->pdo->prepare('INSERT INTO `'.$this->groupMembersTableName.'` (principal_id, member_id) VALUES (?, ?);'); - $stmt->execute(array($principalId, $memberId)); - - } - - } - -} diff --git a/3rdparty/Sabre/DAVACL/PrincipalCollection.php b/3rdparty/Sabre/DAVACL/PrincipalCollection.php deleted file mode 100644 index 4d22bf8aa7509b5e6d153e8f4788ffa3bbf80df6..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/PrincipalCollection.php +++ /dev/null @@ -1,35 +0,0 @@ -<?php - -/** - * Principals Collection - * - * This collection represents a list of users. It uses - * Sabre_DAV_Auth_Backend to determine which users are available on the list. - * - * The users are instances of Sabre_DAV_Auth_Principal - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_PrincipalCollection extends Sabre_DAVACL_AbstractPrincipalCollection { - - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principal - * @return Sabre_DAV_INode - */ - public function getChildForPrincipal(array $principal) { - - return new Sabre_DAVACL_Principal($this->principalBackend, $principal); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/Acl.php b/3rdparty/Sabre/DAVACL/Property/Acl.php deleted file mode 100644 index e41e7411310af9e7286da705c45ae587ad9431bc..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Property/Acl.php +++ /dev/null @@ -1,186 +0,0 @@ -<?php - -/** - * This class represents the {DAV:}acl property - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Property_Acl extends Sabre_DAV_Property { - - /** - * List of privileges - * - * @var array - */ - private $privileges; - - /** - * Wether or not the server base url is required to be prefixed when - * serializing the property. - * - * @var boolean - */ - private $prefixBaseUrl; - - /** - * Constructor - * - * This object requires a structure similar to the return value from - * Sabre_DAVACL_Plugin::getACL(). - * - * Each privilege is a an array with at least a 'privilege' property, and a - * 'principal' property. A privilege may have a 'protected' property as - * well. - * - * The prefixBaseUrl should be set to false, if the supplied principal urls - * are already full urls. If this is kept to true, the servers base url - * will automatically be prefixed. - * - * @param bool $prefixBaseUrl - * @param array $privileges - */ - public function __construct(array $privileges, $prefixBaseUrl = true) { - - $this->privileges = $privileges; - $this->prefixBaseUrl = $prefixBaseUrl; - - } - - /** - * Returns the list of privileges for this property - * - * @return array - */ - public function getPrivileges() { - - return $this->privileges; - - } - - /** - * Serializes the property into a DOMElement - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - foreach($this->privileges as $ace) { - - $this->serializeAce($doc, $node, $ace, $server); - - } - - } - - /** - * Unserializes the {DAV:}acl xml element. - * - * @param DOMElement $dom - * @return Sabre_DAVACL_Property_Acl - */ - static public function unserialize(DOMElement $dom) { - - $privileges = array(); - $xaces = $dom->getElementsByTagNameNS('urn:DAV','ace'); - for($ii=0; $ii < $xaces->length; $ii++) { - - $xace = $xaces->item($ii); - $principal = $xace->getElementsByTagNameNS('urn:DAV','principal'); - if ($principal->length !== 1) { - throw new Sabre_DAV_Exception_BadRequest('Each {DAV:}ace element must have one {DAV:}principal element'); - } - $principal = Sabre_DAVACL_Property_Principal::unserialize($principal->item(0)); - - if ($principal->getType()!==Sabre_DAVACL_Property_Principal::HREF) { - throw new Sabre_DAV_Exception_NotImplemented('Currently only uri based principals are support, {DAV:}all, {DAV:}unauthenticated and {DAV:}authenticated are not implemented yet'); - } - - $principal = $principal->getHref(); - $protected = false; - - if ($xace->getElementsByTagNameNS('urn:DAV','protected')->length > 0) { - $protected = true; - } - - $grants = $xace->getElementsByTagNameNS('urn:DAV','grant'); - if ($grants->length < 1) { - throw new Sabre_DAV_Exception_NotImplemented('Every {DAV:}ace element must have a {DAV:}grant element. {DAV:}deny is not yet supported'); - } - $grant = $grants->item(0); - - $xprivs = $grant->getElementsByTagNameNS('urn:DAV','privilege'); - for($jj=0; $jj<$xprivs->length; $jj++) { - - $xpriv = $xprivs->item($jj); - - $privilegeName = null; - - for ($kk=0;$kk<$xpriv->childNodes->length;$kk++) { - - $childNode = $xpriv->childNodes->item($kk); - if ($t = Sabre_DAV_XMLUtil::toClarkNotation($childNode)) { - $privilegeName = $t; - break; - } - } - if (is_null($privilegeName)) { - throw new Sabre_DAV_Exception_BadRequest('{DAV:}privilege elements must have a privilege element contained within them.'); - } - - $privileges[] = array( - 'principal' => $principal, - 'protected' => $protected, - 'privilege' => $privilegeName, - ); - - } - - } - - return new self($privileges); - - } - - /** - * Serializes a single access control entry. - * - * @param DOMDocument $doc - * @param DOMElement $node - * @param array $ace - * @param Sabre_DAV_Server $server - * @return void - */ - private function serializeAce($doc,$node,$ace, $server) { - - $xace = $doc->createElementNS('DAV:','d:ace'); - $node->appendChild($xace); - - $principal = $doc->createElementNS('DAV:','d:principal'); - $xace->appendChild($principal); - $principal->appendChild($doc->createElementNS('DAV:','d:href',($this->prefixBaseUrl?$server->getBaseUri():'') . $ace['principal'] . '/')); - - $grant = $doc->createElementNS('DAV:','d:grant'); - $xace->appendChild($grant); - - $privParts = null; - - preg_match('/^{([^}]*)}(.*)$/',$ace['privilege'],$privParts); - - $xprivilege = $doc->createElementNS('DAV:','d:privilege'); - $grant->appendChild($xprivilege); - - $xprivilege->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); - - if (isset($ace['protected']) && $ace['protected']) - $xace->appendChild($doc->createElement('d:protected')); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php b/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php deleted file mode 100644 index 72274597b3194c5309039799b9cad51417b83cb8..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php +++ /dev/null @@ -1,75 +0,0 @@ -<?php - -/** - * CurrentUserPrivilegeSet - * - * This class represents the current-user-privilege-set property. When - * requested, it contain all the privileges a user has on a specific node. - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Property_CurrentUserPrivilegeSet extends Sabre_DAV_Property { - - /** - * List of privileges - * - * @var array - */ - private $privileges; - - /** - * Creates the object - * - * Pass the privileges in clark-notation - * - * @param array $privileges - */ - public function __construct(array $privileges) { - - $this->privileges = $privileges; - - } - - /** - * Serializes the property in the DOM - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - foreach($this->privileges as $privName) { - - $this->serializePriv($doc,$node,$privName); - - } - - } - - /** - * Serializes one privilege - * - * @param DOMDocument $doc - * @param DOMElement $node - * @param string $privName - * @return void - */ - protected function serializePriv($doc,$node,$privName) { - - $xp = $doc->createElementNS('DAV:','d:privilege'); - $node->appendChild($xp); - - $privParts = null; - preg_match('/^{([^}]*)}(.*)$/',$privName,$privParts); - - $xp->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/Principal.php b/3rdparty/Sabre/DAVACL/Property/Principal.php deleted file mode 100644 index dad9a3550fb5678f493d74dd8efcaacc6d77ca53..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Property/Principal.php +++ /dev/null @@ -1,154 +0,0 @@ -<?php - -/** - * Principal property - * - * The principal property represents a principal from RFC3744 (ACL). - * The property can be used to specify a principal or pseudo principals. - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Property_Principal extends Sabre_DAV_Property implements Sabre_DAV_Property_IHref { - - /** - * To specify a not-logged-in user, use the UNAUTHENTICTED principal - */ - const UNAUTHENTICATED = 1; - - /** - * To specify any principal that is logged in, use AUTHENTICATED - */ - const AUTHENTICATED = 2; - - /** - * Specific princpals can be specified with the HREF - */ - const HREF = 3; - - /** - * Principal-type - * - * Must be one of the UNAUTHENTICATED, AUTHENTICATED or HREF constants. - * - * @var int - */ - private $type; - - /** - * Url to principal - * - * This value is only used for the HREF principal type. - * - * @var string - */ - private $href; - - /** - * Creates the property. - * - * The 'type' argument must be one of the type constants defined in this class. - * - * 'href' is only required for the HREF type. - * - * @param int $type - * @param string $href - * @return void - */ - public function __construct($type, $href = null) { - - $this->type = $type; - - if ($type===self::HREF && is_null($href)) { - throw new Sabre_DAV_Exception('The href argument must be specified for the HREF principal type.'); - } - $this->href = $href; - - } - - /** - * Returns the principal type - * - * @return int - */ - public function getType() { - - return $this->type; - - } - - /** - * Returns the principal uri. - * - * @return string - */ - public function getHref() { - - return $this->href; - - } - - /** - * Serializes the property into a DOMElement. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server, DOMElement $node) { - - $prefix = $server->xmlNamespaces['DAV:']; - switch($this->type) { - - case self::UNAUTHENTICATED : - $node->appendChild( - $node->ownerDocument->createElement($prefix . ':unauthenticated') - ); - break; - case self::AUTHENTICATED : - $node->appendChild( - $node->ownerDocument->createElement($prefix . ':authenticated') - ); - break; - case self::HREF : - $href = $node->ownerDocument->createElement($prefix . ':href'); - $href->nodeValue = $server->getBaseUri() . $this->href; - $node->appendChild($href); - break; - - } - - } - - /** - * Deserializes a DOM element into a property object. - * - * @param DOMElement $dom - * @return Sabre_DAV_Property_Principal - */ - static public function unserialize(DOMElement $dom) { - - $parent = $dom->firstChild; - while(!Sabre_DAV_XMLUtil::toClarkNotation($parent)) { - $parent = $parent->nextSibling; - } - - switch(Sabre_DAV_XMLUtil::toClarkNotation($parent)) { - - case '{DAV:}unauthenticated' : - return new self(self::UNAUTHENTICATED); - case '{DAV:}authenticated' : - return new self(self::AUTHENTICATED); - case '{DAV:}href': - return new self(self::HREF, $parent->textContent); - default : - throw new Sabre_DAV_Exception_BadRequest('Unexpected element (' . Sabre_DAV_XMLUtil::toClarkNotation($parent) . '). Could not deserialize'); - - } - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php b/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php deleted file mode 100644 index 93c3895035d0a44c115ce095a0b3e4bda0406380..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php +++ /dev/null @@ -1,92 +0,0 @@ -<?php - -/** - * SupportedPrivilegeSet property - * - * This property encodes the {DAV:}supported-privilege-set property, as defined - * in rfc3744. Please consult the rfc for details about it's structure. - * - * This class expects a structure like the one given from - * Sabre_DAVACL_Plugin::getSupportedPrivilegeSet as the argument in its - * constructor. - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Property_SupportedPrivilegeSet extends Sabre_DAV_Property { - - /** - * privileges - * - * @var array - */ - private $privileges; - - /** - * Constructor - * - * @param array $privileges - */ - public function __construct(array $privileges) { - - $this->privileges = $privileges; - - } - - /** - * Serializes the property into a domdocument. - * - * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void - */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - $this->serializePriv($doc, $node, $this->privileges); - - } - - /** - * Serializes a property - * - * This is a recursive function. - * - * @param DOMDocument $doc - * @param DOMElement $node - * @param array $privilege - * @return void - */ - private function serializePriv($doc,$node,$privilege) { - - $xsp = $doc->createElementNS('DAV:','d:supported-privilege'); - $node->appendChild($xsp); - - $xp = $doc->createElementNS('DAV:','d:privilege'); - $xsp->appendChild($xp); - - $privParts = null; - preg_match('/^{([^}]*)}(.*)$/',$privilege['privilege'],$privParts); - - $xp->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); - - if (isset($privilege['abstract']) && $privilege['abstract']) { - $xsp->appendChild($doc->createElementNS('DAV:','d:abstract')); - } - - if (isset($privilege['description'])) { - $xsp->appendChild($doc->createElementNS('DAV:','d:description',$privilege['description'])); - } - - if (isset($privilege['aggregates'])) { - foreach($privilege['aggregates'] as $subPrivilege) { - $this->serializePriv($doc,$xsp,$subPrivilege); - } - } - - } - -} diff --git a/3rdparty/Sabre/DAVACL/Version.php b/3rdparty/Sabre/DAVACL/Version.php deleted file mode 100644 index 124463e311e1c04d01acbc1f9da56e5d6d38bc4e..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/DAVACL/Version.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php - -/** - * This class contains the SabreDAV version constants. - * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_DAVACL_Version { - - /** - * Full version number - */ - const VERSION = '1.5.2'; - - /** - * Stability : alpha, beta, stable - */ - const STABILITY = 'stable'; - -} diff --git a/3rdparty/Sabre/HTTP/AWSAuth.php b/3rdparty/Sabre/HTTP/AWSAuth.php deleted file mode 100644 index 5e4668cd94d8ff35589282aa4af9d9cba2d828bd..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/HTTP/AWSAuth.php +++ /dev/null @@ -1,226 +0,0 @@ -<?php - -/** - * HTTP AWS Authentication handler - * - * Use this class to leverage amazon's AWS authentication header - * - * @package Sabre - * @subpackage HTTP - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_HTTP_AWSAuth extends Sabre_HTTP_AbstractAuth { - - /** - * The signature supplied by the HTTP client - * - * @var string - */ - private $signature = null; - - /** - * The accesskey supplied by the HTTP client - * - * @var string - */ - private $accessKey = null; - - /** - * An error code, if any - * - * This value will be filled with one of the ERR_* contants - * - * @var int - */ - public $errorCode = 0; - - const ERR_NOAWSHEADER = 1; - const ERR_MD5CHECKSUMWRONG = 2; - const ERR_INVALIDDATEFORMAT = 3; - const ERR_REQUESTTIMESKEWED = 4; - const ERR_INVALIDSIGNATURE = 5; - - /** - * Gathers all information from the headers - * - * This method needs to be called prior to anything else. - * - * @return bool - */ - public function init() { - - $authHeader = $this->httpRequest->getHeader('Authorization'); - $authHeader = explode(' ',$authHeader); - - if ($authHeader[0]!='AWS' || !isset($authHeader[1])) { - $this->errorCode = self::ERR_NOAWSHEADER; - return false; - } - - list($this->accessKey,$this->signature) = explode(':',$authHeader[1]); - - return true; - - } - - /** - * Returns the username for the request - * - * @return string - */ - public function getAccessKey() { - - return $this->accessKey; - - } - - /** - * Validates the signature based on the secretKey - * - * @return bool - */ - public function validate($secretKey) { - - $contentMD5 = $this->httpRequest->getHeader('Content-MD5'); - - if ($contentMD5) { - // We need to validate the integrity of the request - $body = $this->httpRequest->getBody(true); - $this->httpRequest->setBody($body,true); - - if ($contentMD5!=base64_encode(md5($body,true))) { - // content-md5 header did not match md5 signature of body - $this->errorCode = self::ERR_MD5CHECKSUMWRONG; - return false; - } - - } - - if (!$requestDate = $this->httpRequest->getHeader('x-amz-date')) - $requestDate = $this->httpRequest->getHeader('Date'); - - if (!$this->validateRFC2616Date($requestDate)) - return false; - - $amzHeaders = $this->getAmzHeaders(); - - $signature = base64_encode( - $this->hmacsha1($secretKey, - $this->httpRequest->getMethod() . "\n" . - $contentMD5 . "\n" . - $this->httpRequest->getHeader('Content-type') . "\n" . - $requestDate . "\n" . - $amzHeaders . - $this->httpRequest->getURI() - ) - ); - - if ($this->signature != $signature) { - - $this->errorCode = self::ERR_INVALIDSIGNATURE; - return false; - - } - - return true; - - } - - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - public function requireLogin() { - - $this->httpResponse->setHeader('WWW-Authenticate','AWS'); - $this->httpResponse->sendStatus(401); - - } - - /** - * Makes sure the supplied value is a valid RFC2616 date. - * - * If we would just use strtotime to get a valid timestamp, we have no way of checking if a - * user just supplied the word 'now' for the date header. - * - * This function also makes sure the Date header is within 15 minutes of the operating - * system date, to prevent replay attacks. - * - * @param string $dateHeader - * @return bool - */ - protected function validateRFC2616Date($dateHeader) { - - $date = Sabre_HTTP_Util::parseHTTPDate($dateHeader); - - // Unknown format - if (!$date) { - $this->errorCode = self::ERR_INVALIDDATEFORMAT; - return false; - } - - $min = new DateTime('-15 minutes'); - $max = new DateTime('+15 minutes'); - - // We allow 15 minutes around the current date/time - if ($date > $max || $date < $min) { - $this->errorCode = self::ERR_REQUESTTIMESKEWED; - return false; - } - - return $date; - - } - - /** - * Returns a list of AMZ headers - * - * @return void - */ - protected function getAmzHeaders() { - - $amzHeaders = array(); - $headers = $this->httpRequest->getHeaders(); - foreach($headers as $headerName => $headerValue) { - if (strpos(strtolower($headerName),'x-amz-')===0) { - $amzHeaders[strtolower($headerName)] = str_replace(array("\r\n"),array(' '),$headerValue) . "\n"; - } - } - ksort($amzHeaders); - - $headerStr = ''; - foreach($amzHeaders as $h=>$v) { - $headerStr.=$h.':'.$v; - } - - return $headerStr; - - } - - /** - * Generates an HMAC-SHA1 signature - * - * @param string $key - * @param string $message - * @return string - */ - private function hmacsha1($key, $message) { - - $blocksize=64; - if (strlen($key)>$blocksize) - $key=pack('H*', sha1($key)); - $key=str_pad($key,$blocksize,chr(0x00)); - $ipad=str_repeat(chr(0x36),$blocksize); - $opad=str_repeat(chr(0x5c),$blocksize); - $hmac = pack('H*',sha1(($key^$opad).pack('H*',sha1(($key^$ipad).$message)))); - return $hmac; - - } - -} diff --git a/3rdparty/Sabre/HTTP/AbstractAuth.php b/3rdparty/Sabre/HTTP/AbstractAuth.php deleted file mode 100644 index eb528f6fdee56dd507f63eb511952ff6298d49d2..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/HTTP/AbstractAuth.php +++ /dev/null @@ -1,111 +0,0 @@ -<?php - -/** - * HTTP Authentication baseclass - * - * This class has the common functionality for BasicAuth and DigestAuth - * - * @package Sabre - * @subpackage HTTP - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_HTTP_AbstractAuth { - - /** - * The realm will be displayed in the dialog boxes - * - * This identifier can be changed through setRealm() - * - * @var string - */ - protected $realm = 'SabreDAV'; - - /** - * HTTP response helper - * - * @var Sabre_HTTP_Response - */ - protected $httpResponse; - - - /** - * HTTP request helper - * - * @var Sabre_HTTP_Request - */ - protected $httpRequest; - - /** - * __construct - * - */ - public function __construct() { - - $this->httpResponse = new Sabre_HTTP_Response(); - $this->httpRequest = new Sabre_HTTP_Request(); - - } - - /** - * Sets an alternative HTTP response object - * - * @param Sabre_HTTP_Response $response - * @return void - */ - public function setHTTPResponse(Sabre_HTTP_Response $response) { - - $this->httpResponse = $response; - - } - - /** - * Sets an alternative HTTP request object - * - * @param Sabre_HTTP_Request $request - * @return void - */ - public function setHTTPRequest(Sabre_HTTP_Request $request) { - - $this->httpRequest = $request; - - } - - - /** - * Sets the realm - * - * The realm is often displayed in authentication dialog boxes - * Commonly an application name displayed here - * - * @param string $realm - * @return void - */ - public function setRealm($realm) { - - $this->realm = $realm; - - } - - /** - * Returns the realm - * - * @return string - */ - public function getRealm() { - - return $this->realm; - - } - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - abstract public function requireLogin(); - -} diff --git a/3rdparty/Sabre/HTTP/BasicAuth.php b/3rdparty/Sabre/HTTP/BasicAuth.php deleted file mode 100644 index 35c22d22dc3837dcd51fe7d87f654b9ff3c1ce18..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/HTTP/BasicAuth.php +++ /dev/null @@ -1,61 +0,0 @@ -<?php - -/** - * HTTP Basic Authentication handler - * - * Use this class for easy http authentication setup - * - * @package Sabre - * @subpackage HTTP - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_HTTP_BasicAuth extends Sabre_HTTP_AbstractAuth { - - /** - * Returns the supplied username and password. - * - * The returned array has two values: - * * 0 - username - * * 1 - password - * - * If nothing was supplied, 'false' will be returned - * - * @return mixed - */ - public function getUserPass() { - - // Apache and mod_php - if (($user = $this->httpRequest->getRawServerValue('PHP_AUTH_USER')) && ($pass = $this->httpRequest->getRawServerValue('PHP_AUTH_PW'))) { - - return array($user,$pass); - - } - - // Most other webservers - $auth = $this->httpRequest->getHeader('Authorization'); - - if (!$auth) return false; - - if (strpos(strtolower($auth),'basic')!==0) return false; - - return explode(':', base64_decode(substr($auth, 6))); - - } - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - public function requireLogin() { - - $this->httpResponse->setHeader('WWW-Authenticate','Basic realm="' . $this->realm . '"'); - $this->httpResponse->sendStatus(401); - - } - -} diff --git a/3rdparty/Sabre/HTTP/DigestAuth.php b/3rdparty/Sabre/HTTP/DigestAuth.php deleted file mode 100644 index 5e7559295710025ba5bd86f777f75b68a1fac17e..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/HTTP/DigestAuth.php +++ /dev/null @@ -1,234 +0,0 @@ -<?php - -/** - * HTTP Digest Authentication handler - * - * Use this class for easy http digest authentication. - * Instructions: - * - * 1. Create the object - * 2. Call the setRealm() method with the realm you plan to use - * 3. Call the init method function. - * 4. Call the getUserName() function. This function may return false if no - * authentication information was supplied. Based on the username you - * should check your internal database for either the associated password, - * or the so-called A1 hash of the digest. - * 5. Call either validatePassword() or validateA1(). This will return true - * or false. - * 6. To make sure an authentication prompt is displayed, call the - * requireLogin() method. - * - * - * @package Sabre - * @subpackage HTTP - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_HTTP_DigestAuth extends Sabre_HTTP_AbstractAuth { - - /** - * These constants are used in setQOP(); - */ - const QOP_AUTH = 1; - const QOP_AUTHINT = 2; - - protected $nonce; - protected $opaque; - protected $digestParts; - protected $A1; - protected $qop = self::QOP_AUTH; - - /** - * Initializes the object - */ - public function __construct() { - - $this->nonce = uniqid(); - $this->opaque = md5($this->realm); - parent::__construct(); - - } - - /** - * Gathers all information from the headers - * - * This method needs to be called prior to anything else. - * - * @return void - */ - public function init() { - - $digest = $this->getDigest(); - $this->digestParts = $this->parseDigest($digest); - - } - - /** - * Sets the quality of protection value. - * - * Possible values are: - * Sabre_HTTP_DigestAuth::QOP_AUTH - * Sabre_HTTP_DigestAuth::QOP_AUTHINT - * - * Multiple values can be specified using logical OR. - * - * QOP_AUTHINT ensures integrity of the request body, but this is not - * supported by most HTTP clients. QOP_AUTHINT also requires the entire - * request body to be md5'ed, which can put strains on CPU and memory. - * - * @param int $qop - * @return void - */ - public function setQOP($qop) { - - $this->qop = $qop; - - } - - /** - * Validates the user. - * - * The A1 parameter should be md5($username . ':' . $realm . ':' . $password); - * - * @param string $A1 - * @return bool - */ - public function validateA1($A1) { - - $this->A1 = $A1; - return $this->validate(); - - } - - /** - * Validates authentication through a password. The actual password must be provided here. - * It is strongly recommended not store the password in plain-text and use validateA1 instead. - * - * @param string $password - * @return bool - */ - public function validatePassword($password) { - - $this->A1 = md5($this->digestParts['username'] . ':' . $this->realm . ':' . $password); - return $this->validate(); - - } - - /** - * Returns the username for the request - * - * @return string - */ - public function getUsername() { - - return $this->digestParts['username']; - - } - - /** - * Validates the digest challenge - * - * @return bool - */ - protected function validate() { - - $A2 = $this->httpRequest->getMethod() . ':' . $this->digestParts['uri']; - - if ($this->digestParts['qop']=='auth-int') { - // Making sure we support this qop value - if (!($this->qop & self::QOP_AUTHINT)) return false; - // We need to add an md5 of the entire request body to the A2 part of the hash - $body = $this->httpRequest->getBody(true); - $this->httpRequest->setBody($body,true); - $A2 .= ':' . md5($body); - } else { - - // We need to make sure we support this qop value - if (!($this->qop & self::QOP_AUTH)) return false; - } - - $A2 = md5($A2); - - $validResponse = md5("{$this->A1}:{$this->digestParts['nonce']}:{$this->digestParts['nc']}:{$this->digestParts['cnonce']}:{$this->digestParts['qop']}:{$A2}"); - - return $this->digestParts['response']==$validResponse; - - - } - - /** - * Returns an HTTP 401 header, forcing login - * - * This should be called when username and password are incorrect, or not supplied at all - * - * @return void - */ - public function requireLogin() { - - $qop = ''; - switch($this->qop) { - case self::QOP_AUTH : $qop = 'auth'; break; - case self::QOP_AUTHINT : $qop = 'auth-int'; break; - case self::QOP_AUTH | self::QOP_AUTHINT : $qop = 'auth,auth-int'; break; - } - - $this->httpResponse->setHeader('WWW-Authenticate','Digest realm="' . $this->realm . '",qop="'.$qop.'",nonce="' . $this->nonce . '",opaque="' . $this->opaque . '"'); - $this->httpResponse->sendStatus(401); - - } - - - /** - * This method returns the full digest string. - * - * It should be compatibile with mod_php format and other webservers. - * - * If the header could not be found, null will be returned - * - * @return mixed - */ - public function getDigest() { - - // mod_php - $digest = $this->httpRequest->getRawServerValue('PHP_AUTH_DIGEST'); - if ($digest) return $digest; - - // most other servers - $digest = $this->httpRequest->getHeader('Authorization'); - - if ($digest && strpos(strtolower($digest),'digest')===0) { - return substr($digest,7); - } else { - return null; - } - - } - - - /** - * Parses the different pieces of the digest string into an array. - * - * This method returns false if an incomplete digest was supplied - * - * @param string $digest - * @return mixed - */ - protected function parseDigest($digest) { - - // protect against missing data - $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1); - $data = array(); - - preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $digest, $matches, PREG_SET_ORDER); - - foreach ($matches as $m) { - $data[$m[1]] = $m[2] ? $m[2] : $m[3]; - unset($needed_parts[$m[1]]); - } - - return $needed_parts ? false : $data; - - } - -} diff --git a/3rdparty/Sabre/HTTP/Request.php b/3rdparty/Sabre/HTTP/Request.php deleted file mode 100644 index 95a64171aab612faed7a2459f7bbedb4d983d3a7..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/HTTP/Request.php +++ /dev/null @@ -1,243 +0,0 @@ -<?php - -/** - * HTTP Request information - * - * This object can be used to easily access information about an HTTP request. - * It can additionally be used to create 'mock' requests. - * - * This class mostly operates indepentend, but because of the nature of a single - * request per run it can operate as a singleton. For more information check out - * the behaviour around 'defaultInputStream'. - * - * @package Sabre - * @subpackage HTTP - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_HTTP_Request { - - /** - * PHP's $_SERVER data - * - * @var string - */ - protected $_SERVER; - - /** - * The request body, if any. - * - * This is stored in the form of a stream resource. - * - * @var resource - */ - protected $body = null; - - /** - * This will be set as the 'default' inputStream for a specific HTTP request - * We sometimes need to retain, or rebuild this if we need multiple runs - * of parsing the original HTTP request. - * - * @var resource - */ - static $defaultInputStream=null; - - /** - * Sets up the object - * - * The serverData array can be used to override usage of PHP's - * global _SERVER variable. - * - * @param array $serverData - */ - public function __construct($serverData = null) { - - if ($serverData) $this->_SERVER = $serverData; - else $this->_SERVER =& $_SERVER; - - } - - /** - * Returns the value for a specific http header. - * - * This method returns null if the header did not exist. - * - * @param string $name - * @return string - */ - public function getHeader($name) { - - $name = strtoupper(str_replace(array('-'),array('_'),$name)); - if (isset($this->_SERVER['HTTP_' . $name])) { - return $this->_SERVER['HTTP_' . $name]; - } - - // There's a few headers that seem to end up in the top-level - // server array. - switch($name) { - case 'CONTENT_TYPE' : - case 'CONTENT_LENGTH' : - if (isset($this->_SERVER[$name])) { - return $this->_SERVER[$name]; - } - break; - - } - return; - - } - - /** - * Returns all (known) HTTP headers. - * - * All headers are converted to lower-case, and additionally all underscores - * are automatically converted to dashes - * - * @return array - */ - public function getHeaders() { - - $hdrs = array(); - foreach($this->_SERVER as $key=>$value) { - - switch($key) { - case 'CONTENT_LENGTH' : - case 'CONTENT_TYPE' : - $hdrs[strtolower(str_replace('_','-',$key))] = $value; - break; - default : - if (strpos($key,'HTTP_')===0) { - $hdrs[substr(strtolower(str_replace('_','-',$key)),5)] = $value; - } - break; - } - - } - - return $hdrs; - - } - - /** - * Returns the HTTP request method - * - * This is for example POST or GET - * - * @return string - */ - public function getMethod() { - - return $this->_SERVER['REQUEST_METHOD']; - - } - - /** - * Returns the requested uri - * - * @return string - */ - public function getUri() { - - return $this->_SERVER['REQUEST_URI']; - - } - - /** - * Will return protocol + the hostname + the uri - * - * @return void - */ - public function getAbsoluteUri() { - - // Checking if the request was made through HTTPS. The last in line is for IIS - $protocol = isset($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS']!='off'); - return ($protocol?'https':'http') . '://' . $this->getHeader('Host') . $this->getUri(); - - } - - /** - * Returns everything after the ? from the current url - * - * @return string - */ - public function getQueryString() { - - return isset($this->_SERVER['QUERY_STRING'])?$this->_SERVER['QUERY_STRING']:''; - - } - - /** - * Returns the HTTP request body body - * - * This method returns a readable stream resource. - * If the asString parameter is set to true, a string is sent instead. - * - * @param bool asString - * @return resource - */ - public function getBody($asString = false) { - - if (is_null($this->body)) { - if (!is_null(self::$defaultInputStream)) { - $this->body = self::$defaultInputStream; - } else { - $this->body = fopen('php://input','r'); - self::$defaultInputStream = $this->body; - } - } - if ($asString) { - $body = stream_get_contents($this->body); - return $body; - } else { - return $this->body; - } - - } - - /** - * Sets the contents of the HTTP request body - * - * This method can either accept a string, or a readable stream resource. - * - * If the setAsDefaultInputStream is set to true, it means for this run of the - * script the supplied body will be used instead of php://input. - * - * @param mixed $body - * @param bool $setAsDefaultInputStream - * @return void - */ - public function setBody($body,$setAsDefaultInputStream = false) { - - if(is_resource($body)) { - $this->body = $body; - } else { - - $stream = fopen('php://temp','r+'); - fputs($stream,$body); - rewind($stream); - // String is assumed - $this->body = $stream; - } - if ($setAsDefaultInputStream) { - self::$defaultInputStream = $this->body; - } - - } - - /** - * Returns a specific item from the _SERVER array. - * - * Do not rely on this feature, it is for internal use only. - * - * @param string $field - * @return string - */ - public function getRawServerValue($field) { - - return isset($this->_SERVER[$field])?$this->_SERVER[$field]:null; - - } - -} - diff --git a/3rdparty/Sabre/HTTP/Response.php b/3rdparty/Sabre/HTTP/Response.php deleted file mode 100644 index dce6feac55336bab4e20ac6ed00c3ed5edd48c5f..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/HTTP/Response.php +++ /dev/null @@ -1,152 +0,0 @@ -<?php - -/** - * Sabre_HTTP_Response - * - * @package Sabre - * @subpackage HTTP - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_HTTP_Response { - - /** - * Returns a full HTTP status message for an HTTP status code - * - * @param int $code - * @return string - */ - public function getStatusMessage($code) { - - $msg = array( - 100 => 'Continue', - 101 => 'Switching Protocols', - 102 => 'Processing', - 200 => 'OK', - 201 => 'Created', - 202 => 'Accepted', - 203 => 'Non-Authorative Information', - 204 => 'No Content', - 205 => 'Reset Content', - 206 => 'Partial Content', - 207 => 'Multi-Status', // RFC 4918 - 208 => 'Already Reported', // RFC 5842 - 226 => 'IM Used', // RFC 3229 - 300 => 'Multiple Choices', - 301 => 'Moved Permanently', - 302 => 'Found', - 303 => 'See Other', - 304 => 'Not Modified', - 305 => 'Use Proxy', - 306 => 'Reserved', - 307 => 'Temporary Redirect', - 400 => 'Bad request', - 401 => 'Unauthorized', - 402 => 'Payment Required', - 403 => 'Forbidden', - 404 => 'Not Found', - 405 => 'Method Not Allowed', - 406 => 'Not Acceptable', - 407 => 'Proxy Authentication Required', - 408 => 'Request Timeout', - 409 => 'Conflict', - 410 => 'Gone', - 411 => 'Length Required', - 412 => 'Precondition failed', - 413 => 'Request Entity Too Large', - 414 => 'Request-URI Too Long', - 415 => 'Unsupported Media Type', - 416 => 'Requested Range Not Satisfiable', - 417 => 'Expectation Failed', - 418 => 'I\'m a teapot', // RFC 2324 - 422 => 'Unprocessable Entity', // RFC 4918 - 423 => 'Locked', // RFC 4918 - 424 => 'Failed Dependency', // RFC 4918 - 426 => 'Upgrade required', - 500 => 'Internal Server Error', - 501 => 'Not Implemented', - 502 => 'Bad Gateway', - 503 => 'Service Unavailable', - 504 => 'Gateway Timeout', - 505 => 'HTTP Version not supported', - 506 => 'Variant Also Negotiates', - 507 => 'Unsufficient Storage', // RFC 4918 - 508 => 'Loop Detected', // RFC 5842 - 509 => 'Bandwidth Limit Exceeded', // non-standard - 510 => 'Not extended', - ); - - return 'HTTP/1.1 ' . $code . ' ' . $msg[$code]; - - } - - /** - * Sends an HTTP status header to the client - * - * @param int $code HTTP status code - * @return void - */ - public function sendStatus($code) { - - if (!headers_sent()) - return header($this->getStatusMessage($code)); - else return false; - - } - - /** - * Sets an HTTP header for the response - * - * @param string $name - * @param string $value - * @return void - */ - public function setHeader($name, $value, $replace = true) { - - $value = str_replace(array("\r","\n"),array('\r','\n'),$value); - if (!headers_sent()) - return header($name . ': ' . $value, $replace); - else return false; - - } - - /** - * Sets a bunch of HTTP Headers - * - * headersnames are specified as keys, value in the array value - * - * @param array $headers - * @return void - */ - public function setHeaders(array $headers) { - - foreach($headers as $key=>$value) - $this->setHeader($key, $value); - - } - - /** - * Sends the entire response body - * - * This method can accept either an open filestream, or a string. - * - * @param mixed $body - * @return void - */ - public function sendBody($body) { - - if (is_resource($body)) { - - fpassthru($body); - - } else { - - // We assume a string - echo $body; - - } - - } - -} diff --git a/3rdparty/Sabre/HTTP/Util.php b/3rdparty/Sabre/HTTP/Util.php deleted file mode 100644 index 8a6bd7df487bd297982d0a8a00d4e0692fd07aba..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/HTTP/Util.php +++ /dev/null @@ -1,65 +0,0 @@ -<?php - -/** - * HTTP utility methods - * - * @package Sabre - * @subpackage HTTP - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @author Paul Voegler - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_HTTP_Util { - - /** - * Parses a RFC2616-compatible date string - * - * This method returns false if the date is invalid - * - * @param string $dateHeader - * @return bool|DateTime - */ - static function parseHTTPDate($dateHeader) { - - //RFC 2616 section 3.3.1 Full Date - //Only the format is checked, valid ranges are checked by strtotime below - $month = '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)'; - $weekday = '(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)'; - $wkday = '(Mon|Tue|Wed|Thu|Fri|Sat|Sun)'; - $time = '[0-2]\d(\:[0-5]\d){2}'; - $date3 = $month . ' ([1-3]\d| \d)'; - $date2 = '[0-3]\d\-' . $month . '\-\d\d'; - //4-digit year cannot begin with 0 - unix timestamp begins in 1970 - $date1 = '[0-3]\d ' . $month . ' [1-9]\d{3}'; - - //ANSI C's asctime() format - //4-digit year cannot begin with 0 - unix timestamp begins in 1970 - $asctime_date = $wkday . ' ' . $date3 . ' ' . $time . ' [1-9]\d{3}'; - //RFC 850, obsoleted by RFC 1036 - $rfc850_date = $weekday . ', ' . $date2 . ' ' . $time . ' GMT'; - //RFC 822, updated by RFC 1123 - $rfc1123_date = $wkday . ', ' . $date1 . ' ' . $time . ' GMT'; - //allowed date formats by RFC 2616 - $HTTP_date = "($rfc1123_date|$rfc850_date|$asctime_date)"; - - //allow for space around the string and strip it - $dateHeader = trim($dateHeader, ' '); - if (!preg_match('/^' . $HTTP_date . '$/', $dateHeader)) - return false; - - //append implicit GMT timezone to ANSI C time format - if (strpos($dateHeader, ' GMT') === false) - $dateHeader .= ' GMT'; - - - $realDate = strtotime($dateHeader); - //strtotime can return -1 or false in case of error - if ($realDate !== false && $realDate >= 0) - return new DateTime('@' . $realDate, new DateTimeZone('UTC')); - - return false; - - } - -} diff --git a/3rdparty/Sabre/HTTP/Version.php b/3rdparty/Sabre/HTTP/Version.php deleted file mode 100644 index 67be232fc26b4ce1ec0519775995ebf25bb4ff2b..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/HTTP/Version.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php - -/** - * This class contains the Sabre_HTTP version constants. - * - * @package Sabre - * @subpackage HTTP - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_HTTP_Version { - - /** - * Full version number - */ - const VERSION = '1.5.3'; - - /** - * Stability : alpha, beta, stable - */ - const STABILITY = 'stable'; - -} diff --git a/3rdparty/Sabre/LICENCE b/3rdparty/Sabre/LICENCE deleted file mode 100644 index 3d07eaace836198ab96fe64cc329c02872516ca4..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/LICENCE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (C) 2007-2011 Rooftop Solutions. -Copyright (C) 2007-2009 FileMobile inc. -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 SabreDAV 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. diff --git a/3rdparty/Sabre/VObject/Component.php b/3rdparty/Sabre/VObject/Component.php deleted file mode 100644 index 47cf9f3d8125b889cdf16ac9c49199c22cc38170..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/Component.php +++ /dev/null @@ -1,254 +0,0 @@ -<?php - -/** - * VObject Component - * - * This class represents a VCALENDAR/VCARD component. A component is for example - * VEVENT, VTODO and also VCALENDAR. It starts with BEGIN:COMPONENTNAME and - * ends with END:COMPONENTNAME - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_VObject_Component extends Sabre_VObject_Element { - - /** - * Name, for example VEVENT - * - * @var string - */ - public $name; - - /** - * Children properties and components - * - * @var array - */ - public $children = array(); - - - /** - * Creates a new component. - * - * By default this object will iterate over its own children, but this can - * be overridden with the iterator argument - * - * @param string $name - * @param Sabre_VObject_ElementList $iterator - */ - public function __construct($name, Sabre_VObject_ElementList $iterator = null) { - - $this->name = strtoupper($name); - if (!is_null($iterator)) $this->iterator = $iterator; - - } - - /** - * Turns the object back into a serialized blob. - * - * @return string - */ - public function serialize() { - - $str = "BEGIN:" . $this->name . "\r\n"; - foreach($this->children as $child) $str.=$child->serialize(); - $str.= "END:" . $this->name . "\r\n"; - - return $str; - - } - - - /** - * Adds a new componenten or element - * - * You can call this method with the following syntaxes: - * - * add(Sabre_VObject_Element $element) - * add(string $name, $value) - * - * The first version adds an Element - * The second adds a property as a string. - * - * @param mixed $item - * @param mixed $itemValue - * @return void - */ - public function add($item, $itemValue = null) { - - if ($item instanceof Sabre_VObject_Element) { - if (!is_null($itemValue)) { - throw new InvalidArgumentException('The second argument must not be specified, when passing a VObject'); - } - $item->parent = $this; - $this->children[] = $item; - } elseif(is_string($item)) { - - if (!is_scalar($itemValue)) { - throw new InvalidArgumentException('The second argument must be scalar'); - } - $item = new Sabre_VObject_Property($item,$itemValue); - $item->parent = $this; - $this->children[] = $item; - - } else { - - throw new InvalidArgumentException('The first argument must either be a Sabre_VObject_Element or a string'); - - } - - } - - /** - * Returns an iterable list of children - * - * @return Sabre_VObject_ElementList - */ - public function children() { - - return new Sabre_VObject_ElementList($this->children); - - } - - /** - * Returns an array with elements that match the specified name. - * - * This function is also aware of MIME-Directory groups (as they appear in - * vcards). This means that if a property is grouped as "HOME.EMAIL", it - * will also be returned when searching for just "EMAIL". If you want to - * search for a property in a specific group, you can select on the entire - * string ("HOME.EMAIL"). If you want to search on a specific property that - * has not been assigned a group, specify ".EMAIL". - * - * Keys are retained from the 'children' array, which may be confusing in - * certain cases. - * - * @param string $name - * @return array - */ - public function select($name) { - - $group = null; - $name = strtoupper($name); - if (strpos($name,'.')!==false) { - list($group,$name) = explode('.', $name, 2); - } - - $result = array(); - foreach($this->children as $key=>$child) { - - if ( - strtoupper($child->name) === $name && - (is_null($group) || ( $child instanceof Sabre_VObject_Property && strtoupper($child->group) === $group)) - ) { - - $result[$key] = $child; - - } - } - - reset($result); - return $result; - - } - - /* Magic property accessors {{{ */ - - /** - * Using 'get' you will either get a propery or component, - * - * If there were no child-elements found with the specified name, - * null is returned. - * - * @param string $name - * @return void - */ - public function __get($name) { - - $matches = $this->select($name); - if (count($matches)===0) { - return null; - } else { - $firstMatch = current($matches); - $firstMatch->setIterator(new Sabre_VObject_ElementList(array_values($matches))); - return $firstMatch; - } - - } - - /** - * This method checks if a sub-element with the specified name exists. - * - * @param string $name - * @return bool - */ - public function __isset($name) { - - $matches = $this->select($name); - return count($matches)>0; - - } - - /** - * Using the setter method you can add properties or subcomponents - * - * You can either pass a Sabre_VObject_Component, Sabre_VObject_Property - * object, or a string to automatically create a Property. - * - * If the item already exists, it will be removed. If you want to add - * a new item with the same name, always use the add() method. - * - * @param string $name - * @param mixed $value - * @return void - */ - public function __set($name, $value) { - - $matches = $this->select($name); - $overWrite = count($matches)?key($matches):null; - - if ($value instanceof Sabre_VObject_Component || $value instanceof Sabre_VObject_Property) { - $value->parent = $this; - if (!is_null($overWrite)) { - $this->children[$overWrite] = $value; - } else { - $this->children[] = $value; - } - } elseif (is_scalar($value)) { - $property = new Sabre_VObject_Property($name,$value); - $property->parent = $this; - if (!is_null($overWrite)) { - $this->children[$overWrite] = $property; - } else { - $this->children[] = $property; - } - } else { - throw new InvalidArgumentException('You must pass a Sabre_VObject_Component, Sabre_VObject_Property or scalar type'); - } - - } - - /** - * Removes all properties and components within this component. - * - * @param string $name - * @return void - */ - public function __unset($name) { - - $matches = $this->select($name); - foreach($matches as $k=>$child) { - - unset($this->children[$k]); - $child->parent = null; - - } - - } - - /* }}} */ - -} diff --git a/3rdparty/Sabre/VObject/Element.php b/3rdparty/Sabre/VObject/Element.php deleted file mode 100644 index 8d2b0aaacd1ee5ce9bde985eb00b058f8151da55..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/Element.php +++ /dev/null @@ -1,15 +0,0 @@ -<?php - -/** - * Base class for all elements - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_VObject_Element extends Sabre_VObject_Node { - - -} diff --git a/3rdparty/Sabre/VObject/Element/DateTime.php b/3rdparty/Sabre/VObject/Element/DateTime.php deleted file mode 100644 index 3350ec02c88a9b00705790e338a1e3c9e9303fb3..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/Element/DateTime.php +++ /dev/null @@ -1,245 +0,0 @@ -<?php - -/** - * DateTime property - * - * This element is used for iCalendar properties such as the DTSTART property. - * It basically provides a few helper functions that make it easier to deal - * with these. It supports both DATE-TIME and DATE values. - * - * In order to use this correctly, you must call setDateTime and getDateTime to - * retrieve and modify dates respectively. - * - * If you use the 'value' or properties directly, this object does not keep - * reference and results might appear incorrectly. - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_VObject_Element_DateTime extends Sabre_VObject_Property { - - /** - * Local 'floating' time - */ - const LOCAL = 1; - - /** - * UTC-based time - */ - const UTC = 2; - - /** - * Local time plus timezone - */ - const LOCALTZ = 3; - - /** - * Only a date, time is ignored - */ - const DATE = 4; - - /** - * DateTime representation - * - * @var DateTime - */ - protected $dateTime; - - /** - * dateType - * - * @var int - */ - protected $dateType; - - /** - * Updates the Date and Time. - * - * @param DateTime $dt - * @param int $dateType - * @return void - */ - public function setDateTime(DateTime $dt, $dateType = self::LOCALTZ) { - - switch($dateType) { - - case self::LOCAL : - $this->setValue($dt->format('Ymd\\THis')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case self::UTC : - $dt->setTimeZone(new DateTimeZone('UTC')); - $this->setValue($dt->format('Ymd\\THis\\Z')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case self::LOCALTZ : - $this->setValue($dt->format('Ymd\\THis')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE-TIME'); - $this->offsetSet('TZID', $dt->getTimeZone()->getName()); - break; - case self::DATE : - $this->setValue($dt->format('Ymd')); - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - $this->offsetSet('VALUE','DATE'); - break; - default : - throw new InvalidArgumentException('You must pass a valid dateType constant'); - - } - $this->dateTime = $dt; - $this->dateType = $dateType; - - } - - /** - * Returns the current DateTime value. - * - * If no value was set, this method returns null. - * - * @return DateTime|null - */ - public function getDateTime() { - - if ($this->dateTime) - return $this->dateTime; - - list( - $this->dateType, - $this->dateTime - ) = self::parseData($this->value, $this); - return $this->dateTime; - - } - - /** - * Returns the type of Date format. - * - * This method returns one of the format constants. If no date was set, - * this method will return null. - * - * @return int|null - */ - public function getDateType() { - - if ($this->dateType) - return $this->dateType; - - list( - $this->dateType, - $this->dateTime, - ) = self::parseData($this->value, $this); - return $this->dateType; - - } - - /** - * Parses the internal data structure to figure out what the current date - * and time is. - * - * The returned array contains two elements: - * 1. A 'DateType' constant (as defined on this class), or null. - * 2. A DateTime object (or null) - * - * @param string|null $propertyValue The string to parse (yymmdd or - * ymmddThhmmss, etc..) - * @param Sabre_VObject_Property|null $property The instance of the - * property we're parsing. - * @return array - */ - static public function parseData($propertyValue, Sabre_VObject_Property $property = null) { - - if (is_null($propertyValue)) { - return array(null, null); - } - - $date = '(?P<year>[1-2][0-9]{3})(?P<month>[0-1][0-9])(?P<date>[0-3][0-9])'; - $time = '(?P<hour>[0-2][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9])'; - $regex = "/^$date(T$time(?P<isutc>Z)?)?$/"; - - if (!preg_match($regex, $propertyValue, $matches)) { - throw new InvalidArgumentException($propertyValue . ' is not a valid DateTime or Date string'); - } - - if (!isset($matches['hour'])) { - // Date-only - return array( - self::DATE, - new DateTime($matches['year'] . '-' . $matches['month'] . '-' . $matches['date'] . ' 00:00:00'), - ); - } - - $dateStr = - $matches['year'] .'-' . - $matches['month'] . '-' . - $matches['date'] . ' ' . - $matches['hour'] . ':' . - $matches['minute'] . ':' . - $matches['second']; - - if (isset($matches['isutc'])) { - $dt = new DateTime($dateStr,new DateTimeZone('UTC')); - $dt->setTimeZone(new DateTimeZone('UTC')); - return array( - self::UTC, - $dt - ); - } - - // Finding the timezone. - $tzid = $property['TZID']; - if (!$tzid) { - return array( - self::LOCAL, - new DateTime($dateStr) - ); - } - - try { - $tz = new DateTimeZone($tzid->value); - } catch (Exception $e) { - - // The id was invalid, we're going to try to find the information - // through the VTIMEZONE object. - - // First we find the root object - $root = $property; - while($root->parent) { - $root = $root->parent; - } - - if (isset($root->VTIMEZONE)) { - foreach($root->VTIMEZONE as $vtimezone) { - if (((string)$vtimezone->TZID) == $tzid) { - if (isset($vtimezone->{'X-LIC-LOCATION'})) { - $tzid = (string)$vtimezone->{'X-LIC-LOCATION'}; - } - } - } - } - - $tz = new DateTimeZone($tzid); - - } - $dt = new DateTime($dateStr, $tz); - $dt->setTimeZone($tz); - - return array( - self::LOCALTZ, - $dt - ); - - } - -} - -?> diff --git a/3rdparty/Sabre/VObject/Element/MultiDateTime.php b/3rdparty/Sabre/VObject/Element/MultiDateTime.php deleted file mode 100644 index dc6ca5abb8021e90300f97176c05ec0686fd6530..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/Element/MultiDateTime.php +++ /dev/null @@ -1,168 +0,0 @@ -<?php - -/** - * Multi-DateTime property - * - * This element is used for iCalendar properties such as the EXDATE property. - * It basically provides a few helper functions that make it easier to deal - * with these. It supports both DATE-TIME and DATE values. - * - * In order to use this correctly, you must call setDateTimes and getDateTimes - * to retrieve and modify dates respectively. - * - * If you use the 'value' or properties directly, this object does not keep - * reference and results might appear incorrectly. - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_VObject_Element_MultiDateTime extends Sabre_VObject_Property { - - /** - * DateTime representation - * - * @var DateTime[] - */ - protected $dateTimes; - - /** - * dateType - * - * This is one of the Sabre_VObject_Element_DateTime constants. - * - * @var int - */ - protected $dateType; - - /** - * Updates the value - * - * @param array $dt Must be an array of DateTime objects. - * @param int $dateType - * @return void - */ - public function setDateTimes(array $dt, $dateType = Sabre_VObject_Element_DateTime::LOCALTZ) { - - foreach($dt as $i) - if (!$i instanceof DateTime) - throw new InvalidArgumentException('You must pass an array of DateTime objects'); - - $this->offsetUnset('VALUE'); - $this->offsetUnset('TZID'); - switch($dateType) { - - case Sabre_VObject_Element_DateTime::LOCAL : - $val = array(); - foreach($dt as $i) { - $val[] = $i->format('Ymd\\THis'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case Sabre_VObject_Element_DateTime::UTC : - $val = array(); - foreach($dt as $i) { - $i->setTimeZone(new DateTimeZone('UTC')); - $val[] = $i->format('Ymd\\THis\\Z'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE-TIME'); - break; - case Sabre_VObject_Element_DateTime::LOCALTZ : - $val = array(); - foreach($dt as $i) { - $val[] = $i->format('Ymd\\THis'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE-TIME'); - $this->offsetSet('TZID', $dt[0]->getTimeZone()->getName()); - break; - case Sabre_VObject_Element_DateTime::DATE : - $val = array(); - foreach($dt as $i) { - $val[] = $i->format('Ymd'); - } - $this->setValue(implode(',',$val)); - $this->offsetSet('VALUE','DATE'); - break; - default : - throw new InvalidArgumentException('You must pass a valid dateType constant'); - - } - $this->dateTimes = $dt; - $this->dateType = $dateType; - - } - - /** - * Returns the current DateTime value. - * - * If no value was set, this method returns null. - * - * @return array|null - */ - public function getDateTimes() { - - if ($this->dateTimes) - return $this->dateTimes; - - $dts = array(); - - if (!$this->value) { - $this->dateTimes = null; - $this->dateType = null; - return null; - } - - foreach(explode(',',$this->value) as $val) { - list( - $type, - $dt - ) = Sabre_VObject_Element_DateTime::parseData($val, $this); - $dts[] = $dt; - $this->dateType = $type; - } - $this->dateTimes = $dts; - return $this->dateTimes; - - } - - /** - * Returns the type of Date format. - * - * This method returns one of the format constants. If no date was set, - * this method will return null. - * - * @return int|null - */ - public function getDateType() { - - if ($this->dateType) - return $this->dateType; - - if (!$this->value) { - $this->dateTimes = null; - $this->dateType = null; - return null; - } - - $dts = array(); - foreach(explode(',',$this->value) as $val) { - list( - $type, - $dt - ) = Sabre_VObject_Element_DateTime::parseData($val, $this); - $dts[] = $dt; - $this->dateType = $type; - } - $this->dateTimes = $dts; - return $this->dateType; - - } - -} - -?> diff --git a/3rdparty/Sabre/VObject/ElementList.php b/3rdparty/Sabre/VObject/ElementList.php deleted file mode 100644 index 9922cd587bcdaa3603dc574c130c8bf0faa9a34d..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/ElementList.php +++ /dev/null @@ -1,172 +0,0 @@ -<?php - -/** - * VObject ElementList - * - * This class represents a list of elements. Lists are the result of queries, - * such as doing $vcalendar->vevent where there's multiple VEVENT objects. - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_VObject_ElementList implements Iterator, Countable, ArrayAccess { - - /** - * Inner elements - * - * @var array - */ - protected $elements = array(); - - /** - * Creates the element list. - * - * @param array $elements - */ - public function __construct(array $elements) { - - $this->elements = $elements; - - } - - /* {{{ Iterator interface */ - - /** - * Current position - * - * @var int - */ - private $key = 0; - - /** - * Returns current item in iteration - * - * @return Sabre_VObject_Element - */ - public function current() { - - return $this->elements[$this->key]; - - } - - /** - * To the next item in the iterator - * - * @return void - */ - public function next() { - - $this->key++; - - } - - /** - * Returns the current iterator key - * - * @return int - */ - public function key() { - - return $this->key; - - } - - /** - * Returns true if the current position in the iterator is a valid one - * - * @return bool - */ - public function valid() { - - return isset($this->elements[$this->key]); - - } - - /** - * Rewinds the iterator - * - * @return void - */ - public function rewind() { - - $this->key = 0; - - } - - /* }}} */ - - /* {{{ Countable interface */ - - /** - * Returns the number of elements - * - * @return int - */ - public function count() { - - return count($this->elements); - - } - - /* }}} */ - - /* {{{ ArrayAccess Interface */ - - - /** - * Checks if an item exists through ArrayAccess. - * - * @param int $offset - * @return bool - */ - public function offsetExists($offset) { - - return isset($this->elements[$offset]); - - } - - /** - * Gets an item through ArrayAccess. - * - * @param int $offset - * @return mixed - */ - public function offsetGet($offset) { - - return $this->elements[$offset]; - - } - - /** - * Sets an item through ArrayAccess. - * - * @param int $offset - * @param mixed $value - * @return void - */ - public function offsetSet($offset,$value) { - - throw new LogicException('You can not add new objects to an ElementList'); - - } - - /** - * Sets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return void - */ - public function offsetUnset($offset) { - - throw new LogicException('You can not remove objects from an ElementList'); - - } - - /* }}} */ - -} diff --git a/3rdparty/Sabre/VObject/Node.php b/3rdparty/Sabre/VObject/Node.php deleted file mode 100644 index 7100b62f1cb2a916f43bb64190fae8734539172a..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/Node.php +++ /dev/null @@ -1,149 +0,0 @@ -<?php - -/** - * Base class for all nodes - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -abstract class Sabre_VObject_Node implements IteratorAggregate, ArrayAccess, Countable { - - /** - * Turns the object back into a serialized blob. - * - * @return string - */ - abstract function serialize(); - - /** - * Iterator override - * - * @var Sabre_VObject_ElementList - */ - protected $iterator = null; - - /** - * A link to the parent node - * - * @var Sabre_VObject_Node - */ - protected $parent = null; - - /* {{{ IteratorAggregator interface */ - - /** - * Returns the iterator for this object - * - * @return Sabre_VObject_ElementList - */ - public function getIterator() { - - if (!is_null($this->iterator)) - return $this->iterator; - - return new Sabre_VObject_ElementList(array($this)); - - } - - /** - * Sets the overridden iterator - * - * Note that this is not actually part of the iterator interface - * - * @param Sabre_VObject_ElementList $iterator - * @return void - */ - public function setIterator(Sabre_VObject_ElementList $iterator) { - - $this->iterator = $iterator; - - } - - /* }}} */ - - /* {{{ Countable interface */ - - /** - * Returns the number of elements - * - * @return int - */ - public function count() { - - $it = $this->getIterator(); - return $it->count(); - - } - - /* }}} */ - - /* {{{ ArrayAccess Interface */ - - - /** - * Checks if an item exists through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return bool - */ - public function offsetExists($offset) { - - $iterator = $this->getIterator(); - return $iterator->offsetExists($offset); - - } - - /** - * Gets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return mixed - */ - public function offsetGet($offset) { - - $iterator = $this->getIterator(); - return $iterator->offsetGet($offset); - - } - - /** - * Sets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @param mixed $value - * @return void - */ - public function offsetSet($offset,$value) { - - $iterator = $this->getIterator(); - return $iterator->offsetSet($offset,$value); - - } - - /** - * Sets an item through ArrayAccess. - * - * This method just forwards the request to the inner iterator - * - * @param int $offset - * @return void - */ - public function offsetUnset($offset) { - - $iterator = $this->getIterator(); - return $iterator->offsetUnset($offset); - - } - - /* }}} */ - -} diff --git a/3rdparty/Sabre/VObject/Parameter.php b/3rdparty/Sabre/VObject/Parameter.php deleted file mode 100644 index 9ebab6ec69ba89d929efd85a7f5544d48444c126..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/Parameter.php +++ /dev/null @@ -1,81 +0,0 @@ -<?php - -/** - * VObject Parameter - * - * This class represents a parameter. A parameter is always tied to a property. - * In the case of: - * DTSTART;VALUE=DATE:20101108 - * VALUE=DATE would be the parameter name and value. - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_VObject_Parameter extends Sabre_VObject_Node { - - /** - * Parameter name - * - * @var string - */ - public $name; - - /** - * Parameter value - * - * @var string - */ - public $value; - - /** - * Sets up the object - * - * @param string $name - * @param string $value - */ - public function __construct($name, $value = null) { - - $this->name = strtoupper($name); - $this->value = $value; - - } - - /** - * Turns the object back into a serialized blob. - * - * @return string - */ - public function serialize() { - - $src = array( - '\\', - "\n", - ';', - ',', - ); - $out = array( - '\\\\', - '\n', - '\;', - '\,', - ); - - return $this->name . '=' . str_replace($src, $out, $this->value); - - } - - /** - * Called when this object is being cast to a string - * - * @return string - */ - public function __toString() { - - return $this->value; - - } - -} diff --git a/3rdparty/Sabre/VObject/ParseException.php b/3rdparty/Sabre/VObject/ParseException.php deleted file mode 100644 index ed4ef2e859275a5e3bf24015bf5870b632a35b2c..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/ParseException.php +++ /dev/null @@ -1,12 +0,0 @@ -<?php - -/** - * Exception thrown by Sabre_VObject_Reader if an invalid object was attempted to be parsed. - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_VObject_ParseException extends Exception { } diff --git a/3rdparty/Sabre/VObject/Property.php b/3rdparty/Sabre/VObject/Property.php deleted file mode 100644 index 060582290438d8dd520960c54b79a108305eb2e9..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/Property.php +++ /dev/null @@ -1,289 +0,0 @@ -<?php - -/** - * VObject Property - * - * A property in VObject is usually in the form PARAMNAME:paramValue. - * An example is : SUMMARY:Weekly meeting - * - * Properties can also have parameters: - * SUMMARY;LANG=en:Weekly meeting. - * - * Parameters can be accessed using the ArrayAccess interface. - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_VObject_Property extends Sabre_VObject_Element { - - /** - * Propertyname - * - * @var string - */ - public $name; - - /** - * Group name - * - * This may be something like 'HOME' for vcards. - * - * @var string - */ - public $group; - - /** - * Property parameters - * - * @var array - */ - public $parameters = array(); - - /** - * Property value - * - * @var string - */ - public $value; - - /** - * Creates a new property object - * - * By default this object will iterate over its own children, but this can - * be overridden with the iterator argument - * - * @param string $name - * @param string $value - * @param Sabre_VObject_ElementList $iterator - */ - public function __construct($name, $value = null, $iterator = null) { - - $name = strtoupper($name); - $group = null; - if (strpos($name,'.')!==false) { - list($group, $name) = explode('.', $name); - } - $this->name = $name; - $this->group = $group; - if (!is_null($iterator)) $this->iterator = $iterator; - $this->setValue($value); - - } - - /** - * Updates the internal value - * - * @param string $value - * @return void - */ - public function setValue($value) { - - $this->value = $value; - - } - - /** - * Turns the object back into a serialized blob. - * - * @return string - */ - public function serialize() { - - $str = $this->name; - if ($this->group) $str = $this->group . '.' . $this->name; - - if (count($this->parameters)) { - foreach($this->parameters as $param) { - - $str.=';' . $param->serialize(); - - } - } - $src = array( - '\\', - "\n", - ); - $out = array( - '\\\\', - '\n', - ); - $str.=':' . str_replace($src, $out, $this->value); - - $out = ''; - while(strlen($str)>0) { - if (strlen($str)>75) { - $out.= substr($str,0,75) . "\r\n"; - $str = ' ' . substr($str,75); - } else { - $out.=$str . "\r\n"; - $str=''; - break; - } - } - - return $out; - - } - - /** - * Adds a new componenten or element - * - * You can call this method with the following syntaxes: - * - * add(Sabre_VObject_Parameter $element) - * add(string $name, $value) - * - * The first version adds an Parameter - * The second adds a property as a string. - * - * @param mixed $item - * @param mixed $itemValue - * @return void - */ - public function add($item, $itemValue = null) { - - if ($item instanceof Sabre_VObject_Parameter) { - if (!is_null($itemValue)) { - throw new InvalidArgumentException('The second argument must not be specified, when passing a VObject'); - } - $item->parent = $this; - $this->parameters[] = $item; - } elseif(is_string($item)) { - - if (!is_scalar($itemValue)) { - throw new InvalidArgumentException('The second argument must be scalar'); - } - $parameter = new Sabre_VObject_Parameter($item,$itemValue); - $parameter->parent = $this; - $this->parameters[] = $parameter; - - } else { - - throw new InvalidArgumentException('The first argument must either be a Sabre_VObject_Element or a string'); - - } - - } - - - /* ArrayAccess interface {{{ */ - - /** - * Checks if an array element exists - * - * @param mixed $name - * @return bool - */ - public function offsetExists($name) { - - if (is_int($name)) return parent::offsetExists($name); - - $name = strtoupper($name); - - foreach($this->parameters as $parameter) { - if ($parameter->name == $name) return true; - } - return false; - - } - - /** - * Returns a parameter, or parameter list. - * - * @param string $name - * @return Sabre_VObject_Element - */ - public function offsetGet($name) { - - if (is_int($name)) return parent::offsetGet($name); - $name = strtoupper($name); - - $result = array(); - foreach($this->parameters as $parameter) { - if ($parameter->name == $name) - $result[] = $parameter; - } - - if (count($result)===0) { - return null; - } elseif (count($result)===1) { - return $result[0]; - } else { - $result[0]->setIterator(new Sabre_VObject_ElementList($result)); - return $result[0]; - } - - } - - /** - * Creates a new parameter - * - * @param string $name - * @param mixed $value - * @return void - */ - public function offsetSet($name, $value) { - - if (is_int($name)) return parent::offsetSet($name, $value); - - if (is_scalar($value)) { - if (!is_string($name)) - throw new InvalidArgumentException('A parameter name must be specified. This means you cannot use the $array[]="string" to add parameters.'); - - $this->offsetUnset($name); - $parameter = new Sabre_VObject_Parameter($name, $value); - $parameter->parent = $this; - $this->parameters[] = $parameter; - - } elseif ($value instanceof Sabre_VObject_Parameter) { - if (!is_null($name)) - throw new InvalidArgumentException('Don\'t specify a parameter name if you\'re passing a Sabre_VObject_Parameter. Add using $array[]=$parameterObject.'); - - $value->parent = $this; - $this->parameters[] = $value; - } else { - throw new InvalidArgumentException('You can only add parameters to the property object'); - } - - } - - /** - * Removes one or more parameters with the specified name - * - * @param string $name - * @return void - */ - public function offsetUnset($name) { - - if (is_int($name)) return parent::offsetUnset($name, $value); - $name = strtoupper($name); - - $result = array(); - foreach($this->parameters as $key=>$parameter) { - if ($parameter->name == $name) { - $parameter->parent = null; - unset($this->parameters[$key]); - } - - } - - } - - /* }}} */ - - /** - * Called when this object is being cast to a string - * - * @return string - */ - public function __toString() { - - return $this->value; - - } - - -} diff --git a/3rdparty/Sabre/VObject/Reader.php b/3rdparty/Sabre/VObject/Reader.php deleted file mode 100644 index 7d1c282838e84e09cccaa4e57f540537e5f3b74d..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/Reader.php +++ /dev/null @@ -1,191 +0,0 @@ -<?php - -/** - * VCALENDAR/VCARD reader - * - * This class reads the vobject file, and returns a full element tree. - * - * - * TODO: this class currently completely works 'statically'. This is pointless, - * and defeats OOP principals. Needs refaxtoring in a future version. - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_VObject_Reader { - - /** - * This array contains a list of Property names that are automatically - * mapped to specific class names. - * - * Adding to this list allows you to specify custom property classes, - * adding extra functionality. - * - * @var array - */ - static public $elementMap = array( - 'DTSTART' => 'Sabre_VObject_Element_DateTime', - 'DTEND' => 'Sabre_VObject_Element_DateTime', - 'COMPLETED' => 'Sabre_VObject_Element_DateTime', - 'DUE' => 'Sabre_VObject_Element_DateTime', - 'EXDATE' => 'Sabre_VObject_Element_MultiDateTime', - ); - - /** - * Parses the file and returns the top component - * - * @param string $data - * @return Sabre_VObject_Element - */ - static function read($data) { - - // Normalizing newlines - $data = str_replace(array("\r","\n\n"), array("\n","\n"), $data); - - $lines = explode("\n", $data); - - // Unfolding lines - $lines2 = array(); - foreach($lines as $line) { - - // Skipping empty lines - if (!$line) continue; - - if ($line[0]===" " || $line[0]==="\t") { - $lines2[count($lines2)-1].=substr($line,1); - } else { - $lines2[] = $line; - } - - } - - unset($lines); - - reset($lines2); - - return self::readLine($lines2); - - } - - /** - * Reads and parses a single line. - * - * This method receives the full array of lines. The array pointer is used - * to traverse. - * - * @param array $lines - * @return Sabre_VObject_Element - */ - static private function readLine(&$lines) { - - $line = current($lines); - $lineNr = key($lines); - next($lines); - - // Components - if (stripos($line,"BEGIN:")===0) { - - // This is a component - $obj = new Sabre_VObject_Component(strtoupper(substr($line,6))); - - $nextLine = current($lines); - - while(stripos($nextLine,"END:")!==0) { - - $obj->add(self::readLine($lines)); - $nextLine = current($lines); - - if ($nextLine===false) - throw new Sabre_VObject_ParseException('Invalid VObject. Document ended prematurely.'); - - } - - // Checking component name of the 'END:' line. - if (substr($nextLine,4)!==$obj->name) { - throw new Sabre_VObject_ParseException('Invalid VObject, expected: "END:' . $obj->name . '" got: "' . $nextLine . '"'); - } - next($lines); - - return $obj; - - } - - // Properties - //$result = preg_match('/(?P<name>[A-Z0-9-]+)(?:;(?P<parameters>^(?<!:):))(.*)$/',$line,$matches); - - - $token = '[A-Z0-9-\/\.]+'; - $parameters = "(?:;(?P<parameters>([^:^\"]|\"([^\"]*)\")*))?"; - $regex = "/^(?P<name>$token)$parameters:(?P<value>.*)$/i"; - - $result = preg_match($regex,$line,$matches); - - if (!$result) { - throw new Sabre_VObject_ParseException('Invalid VObject, line ' . ($lineNr+1) . ' did not follow the icalendar/vcard format'); - } - - $propertyName = strtoupper($matches['name']); - $propertyValue = stripcslashes($matches['value']); - - if (isset(self::$elementMap[$propertyName])) { - $className = self::$elementMap[$propertyName]; - } else { - $className = 'Sabre_VObject_Property'; - } - - $obj = new $className($propertyName, $propertyValue); - - if ($matches['parameters']) { - - foreach(self::readParameters($matches['parameters']) as $param) { - $obj->add($param); - } - } - - return $obj; - - - } - - /** - * Reads a parameter list from a property - * - * This method returns an array of Sabre_VObject_Parameter - * - * @param string $parameters - * @return array - */ - static private function readParameters($parameters) { - - $token = '[A-Z0-9-]+'; - - $paramValue = '(?P<paramValue>[^\"^;]*|"[^"]*")'; - - $regex = "/(?<=^|;)(?P<paramName>$token)(=$paramValue(?=$|;))?/i"; - preg_match_all($regex, $parameters, $matches, PREG_SET_ORDER); - - $params = array(); - foreach($matches as $match) { - - $value = isset($match['paramValue'])?$match['paramValue']:null; - - if (isset($value[0])) { - // Stripping quotes, if needed - if ($value[0] === '"') $value = substr($value,1,strlen($value)-2); - } else { - $value = ''; - } - - $params[] = new Sabre_VObject_Parameter($match['paramName'], stripcslashes($value)); - - } - - return $params; - - } - - -} diff --git a/3rdparty/Sabre/VObject/Version.php b/3rdparty/Sabre/VObject/Version.php deleted file mode 100644 index 937c367e222afa447e57a3628519d860939e21e9..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/Version.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php - -/** - * This class contains the version number for the VObject package - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ -class Sabre_VObject_Version { - - /** - * Full version number - */ - const VERSION = '1.2.4'; - - /** - * Stability : alpha, beta, stable - */ - const STABILITY = 'stable'; - -} diff --git a/3rdparty/Sabre/VObject/includes.php b/3rdparty/Sabre/VObject/includes.php deleted file mode 100644 index f21010fb275a84ea9a672e2c2dd6a26a184e37cb..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/VObject/includes.php +++ /dev/null @@ -1,29 +0,0 @@ -<?php - -/** - * VObject includes - * - * This file automatically includes all VObject classes - * - * @package Sabre - * @subpackage VObject - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ - - -include dirname(__FILE__) . '/ParseException.php'; - -include dirname(__FILE__) . '/Node.php'; -include dirname(__FILE__) . '/Element.php'; -include dirname(__FILE__) . '/ElementList.php'; -include dirname(__FILE__) . '/Parameter.php'; -include dirname(__FILE__) . '/Property.php'; -include dirname(__FILE__) . '/Component.php'; - -include dirname(__FILE__) . '/Element/DateTime.php'; -include dirname(__FILE__) . '/Element/MultiDateTime.php'; - -include dirname(__FILE__) . '/Reader.php'; -include dirname(__FILE__) . '/Version.php'; diff --git a/3rdparty/Sabre/autoload.php b/3rdparty/Sabre/autoload.php deleted file mode 100644 index 0649df655b028c91f6229fe475e04e0df7865faa..0000000000000000000000000000000000000000 --- a/3rdparty/Sabre/autoload.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php - -/** - * SabreDAV's PHP autoloader - * - * If you love the autoloader, and don't care as much about performance, this - * file register a new autoload function using spl_autoload_register. - * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) - * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License - */ - -function Sabre_autoload($className) { - - if(strpos($className,'Sabre_')===0) { - - include dirname(__FILE__) . '/' . str_replace('_','/',substr($className,6)) . '.php'; - - } - -} - -spl_autoload_register('Sabre_autoload'); - diff --git a/3rdparty/System.php b/3rdparty/System.php deleted file mode 100644 index 97de96b14caea8c8d773ee9359fc48d4bff7be73..0000000000000000000000000000000000000000 --- a/3rdparty/System.php +++ /dev/null @@ -1,540 +0,0 @@ -<?php -// -// +----------------------------------------------------------------------+ -// | 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. | -// +----------------------------------------------------------------------+ -// | Authors: Tomas V.V.Cox <cox@idecnet.com> | -// +----------------------------------------------------------------------+ -// -// $Id: System.php,v 1.36 2004/06/15 16:33:46 pajoye 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.36 $ -* @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; - } -} -?> diff --git a/3rdparty/XML/Parser.php b/3rdparty/XML/Parser.php deleted file mode 100644 index 38b4f8fe8a668055ecf77beb1e09c2d226b7dd2d..0000000000000000000000000000000000000000 --- a/3rdparty/XML/Parser.php +++ /dev/null @@ -1,667 +0,0 @@ -<?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. | -// +----------------------------------------------------------------------+ -// | Author: Stig Bakken <ssb@fast.no> | -// | Tomas V.V.Cox <cox@idecnet.com> | -// | Stephan Schmidt <schst@php-tools.net> | -// +----------------------------------------------------------------------+ -// -// $Id: Parser.php,v 1.25 2005/03/25 17:13:10 schst Exp $ - -/** - * XML Parser class. - * - * This is an XML parser based on PHP's "xml" extension, - * based on the bundled expat library. - * - * @category XML - * @package XML_Parser - * @author Stig Bakken <ssb@fast.no> - * @author Tomas V.V.Cox <cox@idecnet.com> - * @author Stephan Schmidt <schst@php-tools.net> - */ - -/** - * uses PEAR's error handling - */ -require_once('PEAR.php'); - -/** - * resource could not be created - */ -define('XML_PARSER_ERROR_NO_RESOURCE', 200); - -/** - * unsupported mode - */ -define('XML_PARSER_ERROR_UNSUPPORTED_MODE', 201); - -/** - * invalid encoding was given - */ -define('XML_PARSER_ERROR_INVALID_ENCODING', 202); - -/** - * specified file could not be read - */ -define('XML_PARSER_ERROR_FILE_NOT_READABLE', 203); - -/** - * invalid input - */ -define('XML_PARSER_ERROR_INVALID_INPUT', 204); - -/** - * remote file cannot be retrieved in safe mode - */ -define('XML_PARSER_ERROR_REMOTE', 205); - -/** - * XML Parser class. - * - * This is an XML parser based on PHP's "xml" extension, - * based on the bundled expat library. - * - * Notes: - * - It requires PHP 4.0.4pl1 or greater - * - From revision 1.17, the function names used by the 'func' mode - * are in the format "xmltag_$elem", for example: use "xmltag_name" - * to handle the <name></name> tags of your xml file. - * - * @category XML - * @package XML_Parser - * @author Stig Bakken <ssb@fast.no> - * @author Tomas V.V.Cox <cox@idecnet.com> - * @author Stephan Schmidt <schst@php-tools.net> - * @todo create XML_Parser_Namespace to parse documents with namespaces - * @todo create XML_Parser_Pull - * @todo Tests that need to be made: - * - mixing character encodings - * - a test using all expat handlers - * - options (folding, output charset) - * - different parsing modes - */ -class XML_Parser extends PEAR -{ - // {{{ properties - - /** - * XML parser handle - * - * @var resource - * @see xml_parser_create() - */ - var $parser; - - /** - * File handle if parsing from a file - * - * @var resource - */ - var $fp; - - /** - * Whether to do case folding - * - * If set to true, all tag and attribute names will - * be converted to UPPER CASE. - * - * @var boolean - */ - var $folding = true; - - /** - * Mode of operation, one of "event" or "func" - * - * @var string - */ - var $mode; - - /** - * Mapping from expat handler function to class method. - * - * @var array - */ - var $handler = array( - 'character_data_handler' => 'cdataHandler', - 'default_handler' => 'defaultHandler', - 'processing_instruction_handler' => 'piHandler', - 'unparsed_entity_decl_handler' => 'unparsedHandler', - 'notation_decl_handler' => 'notationHandler', - 'external_entity_ref_handler' => 'entityrefHandler' - ); - - /** - * source encoding - * - * @var string - */ - var $srcenc; - - /** - * target encoding - * - * @var string - */ - var $tgtenc; - - /** - * handler object - * - * @var object - */ - var $_handlerObj; - - // }}} - - /** - * PHP5 constructor - * - * @param string $srcenc source charset encoding, use NULL (default) to use - * whatever the document specifies - * @param string $mode how this parser object should work, "event" for - * startelement/endelement-type events, "func" - * to have it call functions named after elements - * @param string $tgenc a valid target encoding - */ - function __construct($srcenc = null, $mode = 'event', $tgtenc = null) - { - $this->PEAR('XML_Parser_Error'); - - $this->mode = $mode; - $this->srcenc = $srcenc; - $this->tgtenc = $tgtenc; - } - // }}} - - /** - * Sets the mode of the parser. - * - * Possible modes are: - * - func - * - event - * - * You can set the mode using the second parameter - * in the constructor. - * - * This method is only needed, when switching to a new - * mode at a later point. - * - * @access public - * @param string mode, either 'func' or 'event' - * @return boolean|object true on success, PEAR_Error otherwise - */ - function setMode($mode) - { - if ($mode != 'func' && $mode != 'event') { - $this->raiseError('Unsupported mode given', XML_PARSER_ERROR_UNSUPPORTED_MODE); - } - - $this->mode = $mode; - return true; - } - - /** - * Sets the object, that will handle the XML events - * - * This allows you to create a handler object independent of the - * parser object that you are using and easily switch the underlying - * parser. - * - * If no object will be set, XML_Parser assumes that you - * extend this class and handle the events in $this. - * - * @access public - * @param object object to handle the events - * @return boolean will always return true - * @since v1.2.0beta3 - */ - function setHandlerObj(&$obj) - { - $this->_handlerObj = &$obj; - return true; - } - - /** - * Init the element handlers - * - * @access private - */ - function _initHandlers() - { - if (!is_resource($this->parser)) { - return false; - } - - if (!is_object($this->_handlerObj)) { - $this->_handlerObj = &$this; - } - switch ($this->mode) { - - case 'func': - xml_set_object($this->parser, $this->_handlerObj); - xml_set_element_handler($this->parser, array(&$this, 'funcStartHandler'), array(&$this, 'funcEndHandler')); - break; - - case 'event': - xml_set_object($this->parser, $this->_handlerObj); - xml_set_element_handler($this->parser, 'startHandler', 'endHandler'); - break; - default: - return $this->raiseError('Unsupported mode given', XML_PARSER_ERROR_UNSUPPORTED_MODE); - break; - } - - - /** - * set additional handlers for character data, entities, etc. - */ - foreach ($this->handler as $xml_func => $method) { - if (method_exists($this->_handlerObj, $method)) { - $xml_func = 'xml_set_' . $xml_func; - $xml_func($this->parser, $method); - } - } - } - - // {{{ _create() - - /** - * create the XML parser resource - * - * Has been moved from the constructor to avoid - * problems with object references. - * - * Furthermore it allows us returning an error - * if something fails. - * - * @access private - * @return boolean|object true on success, PEAR_Error otherwise - * - * @see xml_parser_create - */ - function _create() - { - if ($this->srcenc === null) { - $xp = @xml_parser_create(); - } else { - $xp = @xml_parser_create($this->srcenc); - } - if (is_resource($xp)) { - if ($this->tgtenc !== null) { - if (!@xml_parser_set_option($xp, XML_OPTION_TARGET_ENCODING, - $this->tgtenc)) { - return $this->raiseError('invalid target encoding', XML_PARSER_ERROR_INVALID_ENCODING); - } - } - $this->parser = $xp; - $result = $this->_initHandlers($this->mode); - if ($this->isError($result)) { - return $result; - } - xml_parser_set_option($xp, XML_OPTION_CASE_FOLDING, $this->folding); - - return true; - } - return $this->raiseError('Unable to create XML parser resource.', XML_PARSER_ERROR_NO_RESOURCE); - } - - // }}} - // {{{ reset() - - /** - * Reset the parser. - * - * This allows you to use one parser instance - * to parse multiple XML documents. - * - * @access public - * @return boolean|object true on success, PEAR_Error otherwise - */ - function reset() - { - $result = $this->_create(); - if ($this->isError( $result )) { - return $result; - } - return true; - } - - // }}} - // {{{ setInputFile() - - /** - * Sets the input xml file to be parsed - * - * @param string Filename (full path) - * @return resource fopen handle of the given file - * @throws XML_Parser_Error - * @see setInput(), setInputString(), parse() - * @access public - */ - function setInputFile($file) - { - /** - * check, if file is a remote file - */ - if (preg_match('[^(http|ftp)://]', substr($file, 0, 10))) { - if (!ini_get('allow_url_fopen')) { - return $this->raiseError('Remote files cannot be parsed, as safe mode is enabled.', XML_PARSER_ERROR_REMOTE); - } - } - $fp = fopen($file, 'rb'); - if (is_resource($fp)) { - $this->fp = $fp; - return $fp; - } - return $this->raiseError('File could not be opened.', XML_PARSER_ERROR_FILE_NOT_READABLE); - } - - // }}} - // {{{ setInputString() - - /** - * XML_Parser::setInputString() - * - * Sets the xml input from a string - * - * @param string $data a string containing the XML document - * @return null - **/ - function setInputString($data) - { - $this->fp = $data; - return null; - } - - // }}} - // {{{ setInput() - - /** - * Sets the file handle to use with parse(). - * - * You should use setInputFile() or setInputString() if you - * pass a string - * - * @param mixed $fp Can be either a resource returned from fopen(), - * a URL, a local filename or a string. - * @access public - * @see parse() - * @uses setInputString(), setInputFile() - */ - function setInput($fp) - { - if (is_resource($fp)) { - $this->fp = $fp; - return true; - } - // see if it's an absolute URL (has a scheme at the beginning) - elseif (eregi('^[a-z]+://', substr($fp, 0, 10))) { - return $this->setInputFile($fp); - } - // see if it's a local file - elseif (file_exists($fp)) { - return $this->setInputFile($fp); - } - // it must be a string - else { - $this->fp = $fp; - return true; - } - - return $this->raiseError('Illegal input format', XML_PARSER_ERROR_INVALID_INPUT); - } - - // }}} - // {{{ parse() - - /** - * Central parsing function. - * - * @return true|object PEAR error returns true on success, or a PEAR_Error otherwise - * @access public - */ - function parse() - { - /** - * reset the parser - */ - $result = $this->reset(); - if ($this->isError($result)) { - return $result; - } - // if $this->fp was fopened previously - if (is_resource($this->fp)) { - - while ($data = fread($this->fp, 4096)) { - if (!$this->_parseString($data, feof($this->fp))) { - $error = &$this->raiseError(); - $this->free(); - return $error; - } - } - // otherwise, $this->fp must be a string - } else { - if (!$this->_parseString($this->fp, true)) { - $error = &$this->raiseError(); - $this->free(); - return $error; - } - } - $this->free(); - - return true; - } - - /** - * XML_Parser::_parseString() - * - * @param string $data - * @param boolean $eof - * @return bool - * @access private - * @see parseString() - **/ - function _parseString($data, $eof = false) - { - return xml_parse($this->parser, $data, $eof); - } - - // }}} - // {{{ parseString() - - /** - * XML_Parser::parseString() - * - * Parses a string. - * - * @param string $data XML data - * @param boolean $eof If set and TRUE, data is the last piece of data sent in this parser - * @throws XML_Parser_Error - * @return Pear Error|true true on success or a PEAR Error - * @see _parseString() - */ - function parseString($data, $eof = false) - { - if (!isset($this->parser) || !is_resource($this->parser)) { - $this->reset(); - } - - if (!$this->_parseString($data, $eof)) { - $error = &$this->raiseError(); - $this->free(); - return $error; - } - - if ($eof === true) { - $this->free(); - } - return true; - } - - /** - * XML_Parser::free() - * - * Free the internal resources associated with the parser - * - * @return null - **/ - function free() - { - if (isset($this->parser) && is_resource($this->parser)) { - xml_parser_free($this->parser); - unset( $this->parser ); - } - if (isset($this->fp) && is_resource($this->fp)) { - fclose($this->fp); - } - unset($this->fp); - return null; - } - - /** - * XML_Parser::raiseError() - * - * Throws a XML_Parser_Error - * - * @param string $msg the error message - * @param integer $ecode the error message code - * @return XML_Parser_Error - **/ - function raiseError($msg = null, $ecode = 0,$mode = null, - $options = null, - $userinfo = null, - $error_class = null, - $skipmsg = false) - { - $msg = !is_null($msg) ? $msg : $this->parser; - $err = new XML_Parser_Error($msg, $ecode); - return parent::raiseError($err); - } - - // }}} - // {{{ funcStartHandler() - - function funcStartHandler($xp, $elem, $attribs) - { - $func = 'xmltag_' . $elem; - if (strchr($func, '.')) { - $func = str_replace('.', '_', $func); - } - if (method_exists($this->_handlerObj, $func)) { - call_user_func(array(&$this->_handlerObj, $func), $xp, $elem, $attribs); - } elseif (method_exists($this->_handlerObj, 'xmltag')) { - call_user_func(array(&$this->_handlerObj, 'xmltag'), $xp, $elem, $attribs); - } - } - - // }}} - // {{{ funcEndHandler() - - function funcEndHandler($xp, $elem) - { - $func = 'xmltag_' . $elem . '_'; - if (strchr($func, '.')) { - $func = str_replace('.', '_', $func); - } - if (method_exists($this->_handlerObj, $func)) { - call_user_func(array(&$this->_handlerObj, $func), $xp, $elem); - } elseif (method_exists($this->_handlerObj, 'xmltag_')) { - call_user_func(array(&$this->_handlerObj, 'xmltag_'), $xp, $elem); - } - } - - // }}} - // {{{ startHandler() - - /** - * - * @abstract - */ - function startHandler($xp, $elem, $attribs) - { - return NULL; - } - - // }}} - // {{{ endHandler() - - /** - * - * @abstract - */ - function endHandler($xp, $elem) - { - return NULL; - } - - - // }}}me -} - -/** - * error class, replaces PEAR_Error - * - * An instance of this class will be returned - * if an error occurs inside XML_Parser. - * - * There are three advantages over using the standard PEAR_Error: - * - All messages will be prefixed - * - check for XML_Parser error, using is_a( $error, 'XML_Parser_Error' ) - * - messages can be generated from the xml_parser resource - * - * @package XML_Parser - * @access public - * @see PEAR_Error - */ -class XML_Parser_Error extends PEAR_Error -{ - // {{{ properties - - /** - * prefix for all messages - * - * @var string - */ - var $error_message_prefix = 'XML_Parser: '; - - // }}} - // {{{ constructor() - /** - * construct a new error instance - * - * You may either pass a message or an xml_parser resource as first - * parameter. If a resource has been passed, the last error that - * happened will be retrieved and returned. - * - * @access public - * @param string|resource message or parser resource - * @param integer error code - * @param integer error handling - * @param integer error level - */ - function XML_Parser_Error($msgorparser = 'unknown error', $code = 0, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE) - { - if (is_resource($msgorparser)) { - $code = xml_get_error_code($msgorparser); - $msgorparser = sprintf('%s at XML input line %d', - xml_error_string($code), - xml_get_current_line_number($msgorparser)); - } - $this->PEAR_Error($msgorparser, $code, $mode, $level); - } - // }}} -} -?> \ No newline at end of file diff --git a/3rdparty/XML/RPC.php b/3rdparty/XML/RPC.php deleted file mode 100644 index 096b22a0ab5f6146808ab09715c6f7afe500a40a..0000000000000000000000000000000000000000 --- a/3rdparty/XML/RPC.php +++ /dev/null @@ -1,1951 +0,0 @@ -<?php - -/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ - -/** - * PHP implementation of the XML-RPC protocol - * - * This is a PEAR-ified version of Useful inc's XML-RPC for PHP. - * It has support for HTTP transport, proxies and authentication. - * - * PHP versions 4 and 5 - * - * LICENSE: License is granted to use or modify this software - * ("XML-RPC for PHP") for commercial or non-commercial use provided the - * copyright of the author is preserved in any distributed or derivative work. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESSED OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR 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 Web Services - * @package XML_RPC - * @author Edd Dumbill <edd@usefulinc.com> - * @author Stig Bakken <stig@php.net> - * @author Martin Jansen <mj@php.net> - * @author Daniel Convissor <danielc@php.net> - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version CVS: $Id: RPC.php,v 1.83 2005/08/14 20:25:35 danielc Exp $ - * @link http://pear.php.net/package/XML_RPC - */ - - -if (!function_exists('xml_parser_create')) { - PEAR::loadExtension('xml'); -} - -/**#@+ - * Error constants - */ -/** - * Parameter values don't match parameter types - */ -define('XML_RPC_ERROR_INVALID_TYPE', 101); -/** - * Parameter declared to be numeric but the values are not - */ -define('XML_RPC_ERROR_NON_NUMERIC_FOUND', 102); -/** - * Communication error - */ -define('XML_RPC_ERROR_CONNECTION_FAILED', 103); -/** - * The array or struct has already been started - */ -define('XML_RPC_ERROR_ALREADY_INITIALIZED', 104); -/** - * Incorrect parameters submitted - */ -define('XML_RPC_ERROR_INCORRECT_PARAMS', 105); -/** - * Programming error by developer - */ -define('XML_RPC_ERROR_PROGRAMMING', 106); -/**#@-*/ - - -/** - * Data types - * @global string $GLOBALS['XML_RPC_I4'] - */ -$GLOBALS['XML_RPC_I4'] = 'i4'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Int'] - */ -$GLOBALS['XML_RPC_Int'] = 'int'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Boolean'] - */ -$GLOBALS['XML_RPC_Boolean'] = 'boolean'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Double'] - */ -$GLOBALS['XML_RPC_Double'] = 'double'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_String'] - */ -$GLOBALS['XML_RPC_String'] = 'string'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_DateTime'] - */ -$GLOBALS['XML_RPC_DateTime'] = 'dateTime.iso8601'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Base64'] - */ -$GLOBALS['XML_RPC_Base64'] = 'base64'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Array'] - */ -$GLOBALS['XML_RPC_Array'] = 'array'; - -/** - * Data types - * @global string $GLOBALS['XML_RPC_Struct'] - */ -$GLOBALS['XML_RPC_Struct'] = 'struct'; - - -/** - * Data type meta-types - * @global array $GLOBALS['XML_RPC_Types'] - */ -$GLOBALS['XML_RPC_Types'] = array( - $GLOBALS['XML_RPC_I4'] => 1, - $GLOBALS['XML_RPC_Int'] => 1, - $GLOBALS['XML_RPC_Boolean'] => 1, - $GLOBALS['XML_RPC_String'] => 1, - $GLOBALS['XML_RPC_Double'] => 1, - $GLOBALS['XML_RPC_DateTime'] => 1, - $GLOBALS['XML_RPC_Base64'] => 1, - $GLOBALS['XML_RPC_Array'] => 2, - $GLOBALS['XML_RPC_Struct'] => 3, -); - - -/** - * Error message numbers - * @global array $GLOBALS['XML_RPC_err'] - */ -$GLOBALS['XML_RPC_err'] = array( - 'unknown_method' => 1, - 'invalid_return' => 2, - 'incorrect_params' => 3, - 'introspect_unknown' => 4, - 'http_error' => 5, - 'not_response_object' => 6, - 'invalid_request' => 7, -); - -/** - * Error message strings - * @global array $GLOBALS['XML_RPC_str'] - */ -$GLOBALS['XML_RPC_str'] = array( - 'unknown_method' => 'Unknown method', - 'invalid_return' => 'Invalid return payload: enable debugging to examine incoming payload', - 'incorrect_params' => 'Incorrect parameters passed to method', - 'introspect_unknown' => 'Can\'t introspect: method unknown', - 'http_error' => 'Didn\'t receive 200 OK from remote server.', - 'not_response_object' => 'The requested method didn\'t return an XML_RPC_Response object.', - 'invalid_request' => 'Invalid request payload', -); - - -/** - * Default XML encoding (ISO-8859-1, UTF-8 or US-ASCII) - * @global string $GLOBALS['XML_RPC_defencoding'] - */ -$GLOBALS['XML_RPC_defencoding'] = 'UTF-8'; - -/** - * User error codes start at 800 - * @global int $GLOBALS['XML_RPC_erruser'] - */ -$GLOBALS['XML_RPC_erruser'] = 800; - -/** - * XML parse error codes start at 100 - * @global int $GLOBALS['XML_RPC_errxml'] - */ -$GLOBALS['XML_RPC_errxml'] = 100; - - -/** - * Compose backslashes for escaping regexp - * @global string $GLOBALS['XML_RPC_backslash'] - */ -$GLOBALS['XML_RPC_backslash'] = chr(92) . chr(92); - - -/** - * Valid parents of XML elements - * @global array $GLOBALS['XML_RPC_valid_parents'] - */ -$GLOBALS['XML_RPC_valid_parents'] = array( - 'BOOLEAN' => array('VALUE'), - 'I4' => array('VALUE'), - 'INT' => array('VALUE'), - 'STRING' => array('VALUE'), - 'DOUBLE' => array('VALUE'), - 'DATETIME.ISO8601' => array('VALUE'), - 'BASE64' => array('VALUE'), - 'ARRAY' => array('VALUE'), - 'STRUCT' => array('VALUE'), - 'PARAM' => array('PARAMS'), - 'METHODNAME' => array('METHODCALL'), - 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'), - 'MEMBER' => array('STRUCT'), - 'NAME' => array('MEMBER'), - 'DATA' => array('ARRAY'), - 'FAULT' => array('METHODRESPONSE'), - 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'), -); - - -/** - * Stores state during parsing - * - * quick explanation of components: - * + ac = accumulates values - * + qt = decides if quotes are needed for evaluation - * + cm = denotes struct or array (comma needed) - * + isf = indicates a fault - * + lv = indicates "looking for a value": implements the logic - * to allow values with no types to be strings - * + params = stores parameters in method calls - * + method = stores method name - * - * @global array $GLOBALS['XML_RPC_xh'] - */ -$GLOBALS['XML_RPC_xh'] = array(); - - -/** - * Start element handler for the XML parser - * - * @return void - */ -function XML_RPC_se($parser_resource, $name, $attrs) -{ - global $XML_RPC_xh, $XML_RPC_DateTime, $XML_RPC_String, $XML_RPC_valid_parents; - $parser = (int) $parser_resource; - - // if invalid xmlrpc already detected, skip all processing - if ($XML_RPC_xh[$parser]['isf'] >= 2) { - return; - } - - // check for correct element nesting - // top level element can only be of 2 types - if (count($XML_RPC_xh[$parser]['stack']) == 0) { - if ($name != 'METHODRESPONSE' && $name != 'METHODCALL') { - $XML_RPC_xh[$parser]['isf'] = 2; - $XML_RPC_xh[$parser]['isf_reason'] = 'missing top level xmlrpc element'; - return; - } - } else { - // not top level element: see if parent is OK - if (!in_array($XML_RPC_xh[$parser]['stack'][0], $XML_RPC_valid_parents[$name])) { - $name = preg_replace('[^a-zA-Z0-9._-]', '', $name); - $XML_RPC_xh[$parser]['isf'] = 2; - $XML_RPC_xh[$parser]['isf_reason'] = "xmlrpc element $name cannot be child of {$XML_RPC_xh[$parser]['stack'][0]}"; - return; - } - } - - switch ($name) { - case 'STRUCT': - $XML_RPC_xh[$parser]['cm']++; - - // turn quoting off - $XML_RPC_xh[$parser]['qt'] = 0; - - $cur_val = array(); - $cur_val['value'] = array(); - $cur_val['members'] = 1; - array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val); - break; - - case 'ARRAY': - $XML_RPC_xh[$parser]['cm']++; - - // turn quoting off - $XML_RPC_xh[$parser]['qt'] = 0; - - $cur_val = array(); - $cur_val['value'] = array(); - $cur_val['members'] = 0; - array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val); - break; - - case 'NAME': - $XML_RPC_xh[$parser]['ac'] = ''; - break; - - case 'FAULT': - $XML_RPC_xh[$parser]['isf'] = 1; - break; - - case 'PARAM': - $XML_RPC_xh[$parser]['valuestack'] = array(); - break; - - case 'VALUE': - $XML_RPC_xh[$parser]['lv'] = 1; - $XML_RPC_xh[$parser]['vt'] = $XML_RPC_String; - $XML_RPC_xh[$parser]['ac'] = ''; - $XML_RPC_xh[$parser]['qt'] = 0; - // look for a value: if this is still 1 by the - // time we reach the first data segment then the type is string - // by implication and we need to add in a quote - break; - - case 'I4': - case 'INT': - case 'STRING': - case 'BOOLEAN': - case 'DOUBLE': - case 'DATETIME.ISO8601': - case 'BASE64': - $XML_RPC_xh[$parser]['ac'] = ''; // reset the accumulator - - if ($name == 'DATETIME.ISO8601' || $name == 'STRING') { - $XML_RPC_xh[$parser]['qt'] = 1; - - if ($name == 'DATETIME.ISO8601') { - $XML_RPC_xh[$parser]['vt'] = $XML_RPC_DateTime; - } - - } elseif ($name == 'BASE64') { - $XML_RPC_xh[$parser]['qt'] = 2; - } else { - // No quoting is required here -- but - // at the end of the element we must check - // for data format errors. - $XML_RPC_xh[$parser]['qt'] = 0; - } - break; - - case 'MEMBER': - $XML_RPC_xh[$parser]['ac'] = ''; - break; - - case 'DATA': - case 'METHODCALL': - case 'METHODNAME': - case 'METHODRESPONSE': - case 'PARAMS': - // valid elements that add little to processing - break; - } - - - // Save current element to stack - array_unshift($XML_RPC_xh[$parser]['stack'], $name); - - if ($name != 'VALUE') { - $XML_RPC_xh[$parser]['lv'] = 0; - } -} - -/** - * End element handler for the XML parser - * - * @return void - */ -function XML_RPC_ee($parser_resource, $name) -{ - global $XML_RPC_xh, $XML_RPC_Types, $XML_RPC_String; - $parser = (int) $parser_resource; - - if ($XML_RPC_xh[$parser]['isf'] >= 2) { - return; - } - - // push this element from stack - // NB: if XML validates, correct opening/closing is guaranteed and - // we do not have to check for $name == $curr_elem. - // we also checked for proper nesting at start of elements... - $curr_elem = array_shift($XML_RPC_xh[$parser]['stack']); - - switch ($name) { - case 'STRUCT': - case 'ARRAY': - $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']); - $XML_RPC_xh[$parser]['value'] = $cur_val['value']; - $XML_RPC_xh[$parser]['vt'] = strtolower($name); - $XML_RPC_xh[$parser]['cm']--; - break; - - case 'NAME': - $XML_RPC_xh[$parser]['valuestack'][0]['name'] = $XML_RPC_xh[$parser]['ac']; - break; - - case 'BOOLEAN': - // special case here: we translate boolean 1 or 0 into PHP - // constants true or false - if ($XML_RPC_xh[$parser]['ac'] == '1') { - $XML_RPC_xh[$parser]['ac'] = 'true'; - } else { - $XML_RPC_xh[$parser]['ac'] = 'false'; - } - - $XML_RPC_xh[$parser]['vt'] = strtolower($name); - // Drop through intentionally. - - case 'I4': - case 'INT': - case 'STRING': - case 'DOUBLE': - case 'DATETIME.ISO8601': - case 'BASE64': - if ($XML_RPC_xh[$parser]['qt'] == 1) { - // we use double quotes rather than single so backslashification works OK - $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac']; - } elseif ($XML_RPC_xh[$parser]['qt'] == 2) { - $XML_RPC_xh[$parser]['value'] = base64_decode($XML_RPC_xh[$parser]['ac']); - } elseif ($name == 'BOOLEAN') { - $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac']; - } else { - // we have an I4, INT or a DOUBLE - // we must check that only 0123456789-.<space> are characters here - if (!ereg("^[+-]?[0123456789 \t\.]+$", $XML_RPC_xh[$parser]['ac'])) { - XML_RPC_Base::raiseError('Non-numeric value received in INT or DOUBLE', - XML_RPC_ERROR_NON_NUMERIC_FOUND); - $XML_RPC_xh[$parser]['value'] = XML_RPC_ERROR_NON_NUMERIC_FOUND; - } else { - // it's ok, add it on - $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac']; - } - } - - $XML_RPC_xh[$parser]['ac'] = ''; - $XML_RPC_xh[$parser]['qt'] = 0; - $XML_RPC_xh[$parser]['lv'] = 3; // indicate we've found a value - break; - - case 'VALUE': - // deal with a string value - if (strlen($XML_RPC_xh[$parser]['ac']) > 0 && - $XML_RPC_xh[$parser]['vt'] == $XML_RPC_String) { - $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac']; - } - - $temp = new XML_RPC_Value($XML_RPC_xh[$parser]['value'], $XML_RPC_xh[$parser]['vt']); - - $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']); - if (is_array($cur_val)) { - if ($cur_val['members']==0) { - $cur_val['value'][] = $temp; - } else { - $XML_RPC_xh[$parser]['value'] = $temp; - } - array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val); - } else { - $XML_RPC_xh[$parser]['value'] = $temp; - } - break; - - case 'MEMBER': - $XML_RPC_xh[$parser]['ac'] = ''; - $XML_RPC_xh[$parser]['qt'] = 0; - - $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']); - if (is_array($cur_val)) { - if ($cur_val['members']==1) { - $cur_val['value'][$cur_val['name']] = $XML_RPC_xh[$parser]['value']; - } - array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val); - } - break; - - case 'DATA': - $XML_RPC_xh[$parser]['ac'] = ''; - $XML_RPC_xh[$parser]['qt'] = 0; - break; - - case 'PARAM': - $XML_RPC_xh[$parser]['params'][] = $XML_RPC_xh[$parser]['value']; - break; - - case 'METHODNAME': - case 'RPCMETHODNAME': - $XML_RPC_xh[$parser]['method'] = ereg_replace("^[\n\r\t ]+", '', - $XML_RPC_xh[$parser]['ac']); - break; - } - - // if it's a valid type name, set the type - if (isset($XML_RPC_Types[strtolower($name)])) { - $XML_RPC_xh[$parser]['vt'] = strtolower($name); - } -} - -/** - * Character data handler for the XML parser - * - * @return void - */ -function XML_RPC_cd($parser_resource, $data) -{ - global $XML_RPC_xh, $XML_RPC_backslash; - $parser = (int) $parser_resource; - - if ($XML_RPC_xh[$parser]['lv'] != 3) { - // "lookforvalue==3" means that we've found an entire value - // and should discard any further character data - - if ($XML_RPC_xh[$parser]['lv'] == 1) { - // if we've found text and we're just in a <value> then - // turn quoting on, as this will be a string - $XML_RPC_xh[$parser]['qt'] = 1; - // and say we've found a value - $XML_RPC_xh[$parser]['lv'] = 2; - } - - // replace characters that eval would - // do special things with - if (!isset($XML_RPC_xh[$parser]['ac'])) { - $XML_RPC_xh[$parser]['ac'] = ''; - } - $XML_RPC_xh[$parser]['ac'] .= $data; - } -} - -/** - * The common methods and properties for all of the XML_RPC classes - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill <edd@usefulinc.com> - * @author Stig Bakken <stig@php.net> - * @author Martin Jansen <mj@php.net> - * @author Daniel Convissor <danielc@php.net> - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Base { - - /** - * PEAR Error handling - * - * @return object PEAR_Error object - */ - function raiseError($msg, $code) - { - include_once 'PEAR.php'; - if (is_object(@$this)) { - return PEAR::raiseError(get_class($this) . ': ' . $msg, $code); - } else { - return PEAR::raiseError('XML_RPC: ' . $msg, $code); - } - } - - /** - * Tell whether something is a PEAR_Error object - * - * @param mixed $value the item to check - * - * @return bool whether $value is a PEAR_Error object or not - * - * @access public - */ - function isError($value) - { - return is_a($value, 'PEAR_Error'); - } -} - -/** - * The methods and properties for submitting XML RPC requests - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill <edd@usefulinc.com> - * @author Stig Bakken <stig@php.net> - * @author Martin Jansen <mj@php.net> - * @author Daniel Convissor <danielc@php.net> - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Client extends XML_RPC_Base { - - /** - * The path and name of the RPC server script you want the request to go to - * @var string - */ - var $path = ''; - - /** - * The name of the remote server to connect to - * @var string - */ - var $server = ''; - - /** - * The protocol to use in contacting the remote server - * @var string - */ - var $protocol = 'http://'; - - /** - * The port for connecting to the remote server - * - * The default is 80 for http:// connections - * and 443 for https:// and ssl:// connections. - * - * @var integer - */ - var $port = 80; - - /** - * A user name for accessing the RPC server - * @var string - * @see XML_RPC_Client::setCredentials() - */ - var $username = ''; - - /** - * A password for accessing the RPC server - * @var string - * @see XML_RPC_Client::setCredentials() - */ - var $password = ''; - - /** - * The name of the proxy server to use, if any - * @var string - */ - var $proxy = ''; - - /** - * The protocol to use in contacting the proxy server, if any - * @var string - */ - var $proxy_protocol = 'http://'; - - /** - * The port for connecting to the proxy server - * - * The default is 8080 for http:// connections - * and 443 for https:// and ssl:// connections. - * - * @var integer - */ - var $proxy_port = 8080; - - /** - * A user name for accessing the proxy server - * @var string - */ - var $proxy_user = ''; - - /** - * A password for accessing the proxy server - * @var string - */ - var $proxy_pass = ''; - - /** - * The error number, if any - * @var integer - */ - var $errno = 0; - - /** - * The error message, if any - * @var string - */ - var $errstr = ''; - - /** - * The current debug mode (1 = on, 0 = off) - * @var integer - */ - var $debug = 0; - - /** - * The HTTP headers for the current request. - * @var string - */ - var $headers = ''; - - - /** - * Sets the object's properties - * - * @param string $path the path and name of the RPC server script - * you want the request to go to - * @param string $server the URL of the remote server to connect to. - * If this parameter doesn't specify a - * protocol and $port is 443, ssl:// is - * assumed. - * @param integer $port a port for connecting to the remote server. - * Defaults to 80 for http:// connections and - * 443 for https:// and ssl:// connections. - * @param string $proxy the URL of the proxy server to use, if any. - * If this parameter doesn't specify a - * protocol and $port is 443, ssl:// is - * assumed. - * @param integer $proxy_port a port for connecting to the remote server. - * Defaults to 8080 for http:// connections and - * 443 for https:// and ssl:// connections. - * @param string $proxy_user a user name for accessing the proxy server - * @param string $proxy_pass a password for accessing the proxy server - * - * @return void - */ - function XML_RPC_Client($path, $server, $port = 0, - $proxy = '', $proxy_port = 0, - $proxy_user = '', $proxy_pass = '') - { - $this->path = $path; - $this->proxy_user = $proxy_user; - $this->proxy_pass = $proxy_pass; - - preg_match('@^(http://|https://|ssl://)?(.*)$@', $server, $match); - if ($match[1] == '') { - if ($port == 443) { - $this->server = $match[2]; - $this->protocol = 'ssl://'; - $this->port = 443; - } else { - $this->server = $match[2]; - if ($port) { - $this->port = $port; - } - } - } elseif ($match[1] == 'http://') { - $this->server = $match[2]; - if ($port) { - $this->port = $port; - } - } else { - $this->server = $match[2]; - $this->protocol = 'ssl://'; - if ($port) { - $this->port = $port; - } else { - $this->port = 443; - } - } - - if ($proxy) { - preg_match('@^(http://|https://|ssl://)?(.*)$@', $proxy, $match); - if ($match[1] == '') { - if ($proxy_port == 443) { - $this->proxy = $match[2]; - $this->proxy_protocol = 'ssl://'; - $this->proxy_port = 443; - } else { - $this->proxy = $match[2]; - if ($proxy_port) { - $this->proxy_port = $proxy_port; - } - } - } elseif ($match[1] == 'http://') { - $this->proxy = $match[2]; - if ($proxy_port) { - $this->proxy_port = $proxy_port; - } - } else { - $this->proxy = $match[2]; - $this->proxy_protocol = 'ssl://'; - if ($proxy_port) { - $this->proxy_port = $proxy_port; - } else { - $this->proxy_port = 443; - } - } - } - } - - /** - * Change the current debug mode - * - * @param int $in where 1 = on, 0 = off - * - * @return void - */ - function setDebug($in) - { - if ($in) { - $this->debug = 1; - } else { - $this->debug = 0; - } - } - - /** - * Set username and password properties for connecting to the RPC server - * - * @param string $u the user name - * @param string $p the password - * - * @return void - * - * @see XML_RPC_Client::$username, XML_RPC_Client::$password - */ - function setCredentials($u, $p) - { - $this->username = $u; - $this->password = $p; - } - - /** - * Transmit the RPC request via HTTP 1.0 protocol - * - * @param object $msg the XML_RPC_Message object - * @param int $timeout how many seconds to wait for the request - * - * @return object an XML_RPC_Response object. 0 is returned if any - * problems happen. - * - * @see XML_RPC_Message, XML_RPC_Client::XML_RPC_Client(), - * XML_RPC_Client::setCredentials() - */ - function send($msg, $timeout = 0) - { - if (strtolower(get_class($msg)) != 'xml_rpc_message') { - $this->errstr = 'send()\'s $msg parameter must be an' - . ' XML_RPC_Message object.'; - $this->raiseError($this->errstr, XML_RPC_ERROR_PROGRAMMING); - return 0; - } - $msg->debug = $this->debug; - return $this->sendPayloadHTTP10($msg, $this->server, $this->port, - $timeout, $this->username, - $this->password); - } - - /** - * Transmit the RPC request via HTTP 1.0 protocol - * - * Requests should be sent using XML_RPC_Client send() rather than - * calling this method directly. - * - * @param object $msg the XML_RPC_Message object - * @param string $server the server to send the request to - * @param int $port the server port send the request to - * @param int $timeout how many seconds to wait for the request - * before giving up - * @param string $username a user name for accessing the RPC server - * @param string $password a password for accessing the RPC server - * - * @return object an XML_RPC_Response object. 0 is returned if any - * problems happen. - * - * @access protected - * @see XML_RPC_Client::send() - */ - function sendPayloadHTTP10($msg, $server, $port, $timeout = 0, - $username = '', $password = '') - { - /* - * If we're using a proxy open a socket to the proxy server - * instead to the xml-rpc server - */ - if ($this->proxy) { - if ($this->proxy_protocol == 'http://') { - $protocol = ''; - } else { - $protocol = $this->proxy_protocol; - } - if ($timeout > 0) { - $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port, - $this->errno, $this->errstr, $timeout); - } else { - $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port, - $this->errno, $this->errstr); - } - } else { - if ($this->protocol == 'http://') { - $protocol = ''; - } else { - $protocol = $this->protocol; - } - if ($timeout > 0) { - $fp = @fsockopen($protocol . $server, $port, - $this->errno, $this->errstr, $timeout); - } else { - $fp = @fsockopen($protocol . $server, $port, - $this->errno, $this->errstr); - } - } - - /* - * Just raising the error without returning it is strange, - * but keep it here for backwards compatibility. - */ - if (!$fp && $this->proxy) { - $this->raiseError('Connection to proxy server ' - . $this->proxy . ':' . $this->proxy_port - . ' failed. ' . $this->errstr, - XML_RPC_ERROR_CONNECTION_FAILED); - return 0; - } elseif (!$fp) { - $this->raiseError('Connection to RPC server ' - . $server . ':' . $port - . ' failed. ' . $this->errstr, - XML_RPC_ERROR_CONNECTION_FAILED); - return 0; - } - - if ($timeout) { - /* - * Using socket_set_timeout() because stream_set_timeout() - * was introduced in 4.3.0, but we need to support 4.2.0. - */ - socket_set_timeout($fp, $timeout); - } - - // Pre-emptive BC hacks for fools calling sendPayloadHTTP10() directly - if ($username != $this->username) { - $this->setCredentials($username, $password); - } - - // Only create the payload if it was not created previously - if (empty($msg->payload)) { - $msg->createPayload(); - } - $this->createHeaders($msg); - - $op = $this->headers . "\r\n\r\n"; - $op .= $msg->payload; - - if (!fputs($fp, $op, strlen($op))) { - $this->errstr = 'Write error'; - return 0; - } - $resp = $msg->parseResponseFile($fp); - - $meta = socket_get_status($fp); - if ($meta['timed_out']) { - fclose($fp); - $this->errstr = 'RPC server did not send response before timeout.'; - $this->raiseError($this->errstr, XML_RPC_ERROR_CONNECTION_FAILED); - return 0; - } - - fclose($fp); - return $resp; - } - - /** - * Determines the HTTP headers and puts it in the $headers property - * - * @param object $msg the XML_RPC_Message object - * - * @return boolean TRUE if okay, FALSE if the message payload isn't set. - * - * @access protected - */ - function createHeaders($msg) - { - if (empty($msg->payload)) { - return false; - } - if ($this->proxy) { - $this->headers = 'POST ' . $this->protocol . $this->server; - if ($this->proxy_port) { - $this->headers .= ':' . $this->port; - } - } else { - $this->headers = 'POST '; - } - $this->headers .= $this->path. " HTTP/1.0\r\n"; - - $this->headers .= "User-Agent: PEAR XML_RPC\r\n"; - $this->headers .= 'Host: ' . $this->server . "\r\n"; - - if ($this->proxy && $this->proxy_user) { - $this->headers .= 'Proxy-Authorization: Basic ' - . base64_encode("$this->proxy_user:$this->proxy_pass") - . "\r\n"; - } - - // thanks to Grant Rauscher <grant7@firstworld.net> for this - if ($this->username) { - $this->headers .= 'Authorization: Basic ' - . base64_encode("$this->username:$this->password") - . "\r\n"; - } - - $this->headers .= "Content-Type: text/xml\r\n"; - $this->headers .= 'Content-Length: ' . strlen($msg->payload); - return true; - } -} - -/** - * The methods and properties for interpreting responses to XML RPC requests - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill <edd@usefulinc.com> - * @author Stig Bakken <stig@php.net> - * @author Martin Jansen <mj@php.net> - * @author Daniel Convissor <danielc@php.net> - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Response extends XML_RPC_Base -{ - var $xv; - var $fn; - var $fs; - var $hdrs; - - /** - * @return void - */ - function XML_RPC_Response($val, $fcode = 0, $fstr = '') - { - if ($fcode != 0) { - $this->fn = $fcode; - $this->fs = htmlspecialchars($fstr); - } else { - $this->xv = $val; - } - } - - /** - * @return int the error code - */ - function faultCode() - { - if (isset($this->fn)) { - return $this->fn; - } else { - return 0; - } - } - - /** - * @return string the error string - */ - function faultString() - { - return $this->fs; - } - - /** - * @return mixed the value - */ - function value() - { - return $this->xv; - } - - /** - * @return string the error message in XML format - */ - function serialize() - { - $rs = "<methodResponse>\n"; - if ($this->fn) { - $rs .= "<fault> - <value> - <struct> - <member> - <name>faultCode</name> - <value><int>" . $this->fn . "</int></value> - </member> - <member> - <name>faultString</name> - <value><string>" . $this->fs . "</string></value> - </member> - </struct> - </value> -</fault>"; - } else { - $rs .= "<params>\n<param>\n" . $this->xv->serialize() . - "</param>\n</params>"; - } - $rs .= "\n</methodResponse>"; - return $rs; - } -} - -/** - * The methods and properties for composing XML RPC messages - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill <edd@usefulinc.com> - * @author Stig Bakken <stig@php.net> - * @author Martin Jansen <mj@php.net> - * @author Daniel Convissor <danielc@php.net> - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Message extends XML_RPC_Base -{ - /** - * The current debug mode (1 = on, 0 = off) - * @var integer - */ - var $debug = 0; - - /** - * The encoding to be used for outgoing messages - * - * Defaults to the value of <var>$GLOBALS['XML_RPC_defencoding']</var> - * - * @var string - * @see XML_RPC_Message::setSendEncoding(), - * $GLOBALS['XML_RPC_defencoding'], XML_RPC_Message::xml_header() - */ - var $send_encoding = ''; - - /** - * The method presently being evaluated - * @var string - */ - var $methodname = ''; - - /** - * @var array - */ - var $params = array(); - - /** - * The XML message being generated - * @var string - */ - var $payload = ''; - - /** - * @return void - */ - function XML_RPC_Message($meth, $pars = 0) - { - $this->methodname = $meth; - if (is_array($pars) && sizeof($pars) > 0) { - for ($i = 0; $i < sizeof($pars); $i++) { - $this->addParam($pars[$i]); - } - } - } - - /** - * Produces the XML declaration including the encoding attribute - * - * The encoding is determined by this class' <var>$send_encoding</var> - * property. If the <var>$send_encoding</var> property is not set, use - * <var>$GLOBALS['XML_RPC_defencoding']</var>. - * - * @return string the XML declaration and <methodCall> element - * - * @see XML_RPC_Message::setSendEncoding(), - * XML_RPC_Message::$send_encoding, $GLOBALS['XML_RPC_defencoding'] - */ - function xml_header() - { - global $XML_RPC_defencoding; - if (!$this->send_encoding) { - $this->send_encoding = $XML_RPC_defencoding; - } - return '<?xml version="1.0" encoding="' . $this->send_encoding . '"?>' - . "\n<methodCall>\n"; - } - - /** - * @return string the closing </methodCall> tag - */ - function xml_footer() - { - return "</methodCall>\n"; - } - - /** - * @return void - * - * @uses XML_RPC_Message::xml_header(), XML_RPC_Message::xml_footer() - */ - function createPayload() - { - $this->payload = $this->xml_header(); - $this->payload .= '<methodName>' . $this->methodname . "</methodName>\n"; - $this->payload .= "<params>\n"; - for ($i = 0; $i < sizeof($this->params); $i++) { - $p = $this->params[$i]; - $this->payload .= "<param>\n" . $p->serialize() . "</param>\n"; - } - $this->payload .= "</params>\n"; - $this->payload .= $this->xml_footer(); - $this->payload = ereg_replace("[\r\n]+", "\r\n", $this->payload); - } - - /** - * @return string the name of the method - */ - function method($meth = '') - { - if ($meth != '') { - $this->methodname = $meth; - } - return $this->methodname; - } - - /** - * @return string the payload - */ - function serialize() - { - $this->createPayload(); - return $this->payload; - } - - /** - * @return void - */ - function addParam($par) - { - $this->params[] = $par; - } - - /** - * Obtains an XML_RPC_Value object for the given parameter - * - * @param int $i the index number of the parameter to obtain - * - * @return object the XML_RPC_Value object. - * If the parameter doesn't exist, an XML_RPC_Response object. - * - * @since Returns XML_RPC_Response object on error since Release 1.3.0 - */ - function getParam($i) - { - global $XML_RPC_err, $XML_RPC_str; - - if (isset($this->params[$i])) { - return $this->params[$i]; - } else { - $this->raiseError('The submitted request did not contain this parameter', - XML_RPC_ERROR_INCORRECT_PARAMS); - return new XML_RPC_Response(0, $XML_RPC_err['incorrect_params'], - $XML_RPC_str['incorrect_params']); - } - } - - /** - * @return int the number of parameters - */ - function getNumParams() - { - return sizeof($this->params); - } - - /** - * Sets the XML declaration's encoding attribute - * - * @param string $type the encoding type (ISO-8859-1, UTF-8 or US-ASCII) - * - * @return void - * - * @see XML_RPC_Message::$send_encoding, XML_RPC_Message::xml_header() - * @since Method available since Release 1.2.0 - */ - function setSendEncoding($type) - { - $this->send_encoding = $type; - } - - /** - * Determine the XML's encoding via the encoding attribute - * in the XML declaration - * - * If the encoding parameter is not set or is not ISO-8859-1, UTF-8 - * or US-ASCII, $XML_RPC_defencoding will be returned. - * - * @param string $data the XML that will be parsed - * - * @return string the encoding to be used - * - * @link http://php.net/xml_parser_create - * @since Method available since Release 1.2.0 - */ - function getEncoding($data) - { - global $XML_RPC_defencoding; - - if (preg_match('/<\?xml[^>]*\s*encoding\s*=\s*[\'"]([^"\']*)[\'"]/i', - $data, $match)) - { - $match[1] = trim(strtoupper($match[1])); - switch ($match[1]) { - case 'ISO-8859-1': - case 'UTF-8': - case 'US-ASCII': - return $match[1]; - break; - - default: - return $XML_RPC_defencoding; - } - } else { - return $XML_RPC_defencoding; - } - } - - /** - * @return object a new XML_RPC_Response object - */ - function parseResponseFile($fp) - { - $ipd = ''; - while ($data = @fread($fp, 8192)) { - $ipd .= $data; - } - return $this->parseResponse($ipd); - } - - /** - * @return object a new XML_RPC_Response object - */ - function parseResponse($data = '') - { - global $XML_RPC_xh, $XML_RPC_err, $XML_RPC_str, $XML_RPC_defencoding; - - $encoding = $this->getEncoding($data); - $parser_resource = xml_parser_create($encoding); - $parser = (int) $parser_resource; - - $XML_RPC_xh = array(); - $XML_RPC_xh[$parser] = array(); - - $XML_RPC_xh[$parser]['cm'] = 0; - $XML_RPC_xh[$parser]['isf'] = 0; - $XML_RPC_xh[$parser]['ac'] = ''; - $XML_RPC_xh[$parser]['qt'] = ''; - $XML_RPC_xh[$parser]['stack'] = array(); - $XML_RPC_xh[$parser]['valuestack'] = array(); - - xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true); - xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee'); - xml_set_character_data_handler($parser_resource, 'XML_RPC_cd'); - - $hdrfnd = 0; - if ($this->debug) { - print "\n<pre>---GOT---\n"; - print isset($_SERVER['SERVER_PROTOCOL']) ? htmlspecialchars($data) : $data; - print "\n---END---</pre>\n"; - } - - // See if response is a 200 or a 100 then a 200, else raise error. - // But only do this if we're using the HTTP protocol. - if (ereg('^HTTP', $data) && - !ereg('^HTTP/[0-9\.]+ 200 ', $data) && - !preg_match('@^HTTP/[0-9\.]+ 10[0-9]([A-Za-z ]+)?[\r\n]+HTTP/[0-9\.]+ 200@', $data)) - { - $errstr = substr($data, 0, strpos($data, "\n") - 1); - if(defined("DEBUG") && DEBUG) {error_log('HTTP error, got response: ' . $errstr);} - $r = new XML_RPC_Response(0, $XML_RPC_err['http_error'], - $XML_RPC_str['http_error'] . ' (' . - $errstr . ')'); - xml_parser_free($parser_resource); - return $r; - } - - // gotta get rid of headers here - if (!$hdrfnd && ($brpos = strpos($data,"\r\n\r\n"))) { - $XML_RPC_xh[$parser]['ha'] = substr($data, 0, $brpos); - $data = substr($data, $brpos + 4); - $hdrfnd = 1; - } - - /* - * be tolerant of junk after methodResponse - * (e.g. javascript automatically inserted by free hosts) - * thanks to Luca Mariano <luca.mariano@email.it> - */ - $data = substr($data, 0, strpos($data, "</methodResponse>") + 17); - - if (!xml_parse($parser_resource, $data, sizeof($data))) { - // thanks to Peter Kocks <peter.kocks@baygate.com> - if (xml_get_current_line_number($parser_resource) == 1) { - $errstr = 'XML error at line 1, check URL'; - } else { - $errstr = sprintf('XML error: %s at line %d', - xml_error_string(xml_get_error_code($parser_resource)), - xml_get_current_line_number($parser_resource)); - } - if(defined("DEBUG") && DEBUG) {error_log($errstr);} - $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'], - $XML_RPC_str['invalid_return']); - xml_parser_free($parser_resource); - return $r; - } - - xml_parser_free($parser_resource); - - if ($this->debug) { - print "\n<pre>---PARSED---\n"; - var_dump($XML_RPC_xh[$parser]['value']); - print "---END---</pre>\n"; - } - - if ($XML_RPC_xh[$parser]['isf'] > 1) { - $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'], - $XML_RPC_str['invalid_return'].' '.$XML_RPC_xh[$parser]['isf_reason']); - } elseif (!is_object($XML_RPC_xh[$parser]['value'])) { - // then something odd has happened - // and it's time to generate a client side error - // indicating something odd went on - $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'], - $XML_RPC_str['invalid_return']); - } else { - $v = $XML_RPC_xh[$parser]['value']; - $allOK=1; - if ($XML_RPC_xh[$parser]['isf']) { - $f = $v->structmem('faultCode'); - $fs = $v->structmem('faultString'); - $r = new XML_RPC_Response($v, $f->scalarval(), - $fs->scalarval()); - } else { - $r = new XML_RPC_Response($v); - } - } - $r->hdrs = split("\r?\n", $XML_RPC_xh[$parser]['ha'][1]); - return $r; - } -} - -/** - * The methods and properties that represent data in XML RPC format - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill <edd@usefulinc.com> - * @author Stig Bakken <stig@php.net> - * @author Martin Jansen <mj@php.net> - * @author Daniel Convissor <danielc@php.net> - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Value extends XML_RPC_Base -{ - var $me = array(); - var $mytype = 0; - - /** - * @return void - */ - function XML_RPC_Value($val = -1, $type = '') - { - global $XML_RPC_Types; - $this->me = array(); - $this->mytype = 0; - if ($val != -1 || $type != '') { - if ($type == '') { - $type = 'string'; - } - if (!array_key_exists($type, $XML_RPC_Types)) { - // XXX - // need some way to report this error - } elseif ($XML_RPC_Types[$type] == 1) { - $this->addScalar($val, $type); - } elseif ($XML_RPC_Types[$type] == 2) { - $this->addArray($val); - } elseif ($XML_RPC_Types[$type] == 3) { - $this->addStruct($val); - } - } - } - - /** - * @return int returns 1 if successful or 0 if there are problems - */ - function addScalar($val, $type = 'string') - { - global $XML_RPC_Types, $XML_RPC_Boolean; - - if ($this->mytype == 1) { - $this->raiseError('Scalar can have only one value', - XML_RPC_ERROR_INVALID_TYPE); - return 0; - } - $typeof = $XML_RPC_Types[$type]; - if ($typeof != 1) { - $this->raiseError("Not a scalar type (${typeof})", - XML_RPC_ERROR_INVALID_TYPE); - return 0; - } - - if ($type == $XML_RPC_Boolean) { - if (strcasecmp($val, 'true') == 0 - || $val == 1 - || ($val == true && strcasecmp($val, 'false'))) - { - $val = 1; - } else { - $val = 0; - } - } - - if ($this->mytype == 2) { - // we're adding to an array here - $ar = $this->me['array']; - $ar[] = new XML_RPC_Value($val, $type); - $this->me['array'] = $ar; - } else { - // a scalar, so set the value and remember we're scalar - $this->me[$type] = $val; - $this->mytype = $typeof; - } - return 1; - } - - /** - * @return int returns 1 if successful or 0 if there are problems - */ - function addArray($vals) - { - global $XML_RPC_Types; - if ($this->mytype != 0) { - $this->raiseError( - 'Already initialized as a [' . $this->kindOf() . ']', - XML_RPC_ERROR_ALREADY_INITIALIZED); - return 0; - } - $this->mytype = $XML_RPC_Types['array']; - $this->me['array'] = $vals; - return 1; - } - - /** - * @return int returns 1 if successful or 0 if there are problems - */ - function addStruct($vals) - { - global $XML_RPC_Types; - if ($this->mytype != 0) { - $this->raiseError( - 'Already initialized as a [' . $this->kindOf() . ']', - XML_RPC_ERROR_ALREADY_INITIALIZED); - return 0; - } - $this->mytype = $XML_RPC_Types['struct']; - $this->me['struct'] = $vals; - return 1; - } - - /** - * @return void - */ - function dump($ar) - { - reset($ar); - foreach ($ar as $key => $val) { - echo "$key => $val<br />"; - if ($key == 'array') { - foreach ($val as $key2 => $val2) { - echo "-- $key2 => $val2<br />"; - } - } - } - } - - /** - * @return string the data type of the current value - */ - function kindOf() - { - switch ($this->mytype) { - case 3: - return 'struct'; - - case 2: - return 'array'; - - case 1: - return 'scalar'; - - default: - return 'undef'; - } - } - - /** - * @return string the data in XML format - */ - function serializedata($typ, $val) - { - $rs = ''; - global $XML_RPC_Types, $XML_RPC_Base64, $XML_RPC_String, $XML_RPC_Boolean; - if (!array_key_exists($typ, $XML_RPC_Types)) { - // XXX - // need some way to report this error - return; - } - switch ($XML_RPC_Types[$typ]) { - case 3: - // struct - $rs .= "<struct>\n"; - reset($val); - foreach ($val as $key2 => $val2) { - $rs .= "<member><name>${key2}</name>\n"; - $rs .= $this->serializeval($val2); - $rs .= "</member>\n"; - } - $rs .= '</struct>'; - break; - - case 2: - // array - $rs .= "<array>\n<data>\n"; - for ($i = 0; $i < sizeof($val); $i++) { - $rs .= $this->serializeval($val[$i]); - } - $rs .= "</data>\n</array>"; - break; - - case 1: - switch ($typ) { - case $XML_RPC_Base64: - $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>"; - break; - case $XML_RPC_Boolean: - $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>"; - break; - case $XML_RPC_String: - $rs .= "<${typ}>" . htmlspecialchars($val). "</${typ}>"; - break; - default: - $rs .= "<${typ}>${val}</${typ}>"; - } - } - return $rs; - } - - /** - * @return string the data in XML format - */ - function serialize() - { - return $this->serializeval($this); - } - - /** - * @return string the data in XML format - */ - function serializeval($o) - { - if (!is_object($o) || empty($o->me) || !is_array($o->me)) { - return ''; - } - $ar = $o->me; - reset($ar); - list($typ, $val) = each($ar); - return '<value>' . $this->serializedata($typ, $val) . "</value>\n"; - } - - /** - * @return mixed the contents of the element requested - */ - function structmem($m) - { - return $this->me['struct'][$m]; - } - - /** - * @return void - */ - function structreset() - { - reset($this->me['struct']); - } - - /** - * @return the key/value pair of the struct's current element - */ - function structeach() - { - return each($this->me['struct']); - } - - /** - * @return mixed the current value - */ - function getval() - { - // UNSTABLE - global $XML_RPC_BOOLEAN, $XML_RPC_Base64; - - reset($this->me); - $b = current($this->me); - - // contributed by I Sofer, 2001-03-24 - // add support for nested arrays to scalarval - // i've created a new method here, so as to - // preserve back compatibility - - if (is_array($b)) { - foreach ($b as $id => $cont) { - $b[$id] = $cont->scalarval(); - } - } - - // add support for structures directly encoding php objects - if (is_object($b)) { - $t = get_object_vars($b); - foreach ($t as $id => $cont) { - $t[$id] = $cont->scalarval(); - } - foreach ($t as $id => $cont) { - $b->$id = $cont; - } - } - - // end contrib - return $b; - } - - /** - * @return mixed - */ - function scalarval() - { - global $XML_RPC_Boolean, $XML_RPC_Base64; - reset($this->me); - return current($this->me); - } - - /** - * @return string - */ - function scalartyp() - { - global $XML_RPC_I4, $XML_RPC_Int; - reset($this->me); - $a = key($this->me); - if ($a == $XML_RPC_I4) { - $a = $XML_RPC_Int; - } - return $a; - } - - /** - * @return mixed the struct's current element - */ - function arraymem($m) - { - return $this->me['array'][$m]; - } - - /** - * @return int the number of elements in the array - */ - function arraysize() - { - reset($this->me); - list($a, $b) = each($this->me); - return sizeof($b); - } - - /** - * Determines if the item submitted is an XML_RPC_Value object - * - * @param mixed $val the variable to be evaluated - * - * @return bool TRUE if the item is an XML_RPC_Value object - * - * @static - * @since Method available since Release 1.3.0 - */ - function isValue($val) - { - return (strtolower(get_class($val)) == 'xml_rpc_value'); - } -} - -/** - * Return an ISO8601 encoded string - * - * While timezones ought to be supported, the XML-RPC spec says: - * - * "Don't assume a timezone. It should be specified by the server in its - * documentation what assumptions it makes about timezones." - * - * This routine always assumes localtime unless $utc is set to 1, in which - * case UTC is assumed and an adjustment for locale is made when encoding. - * - * @return string the formatted date - */ -function XML_RPC_iso8601_encode($timet, $utc = 0) -{ - if (!$utc) { - $t = strftime('%Y%m%dT%H:%M:%S', $timet); - } else { - if (function_exists('gmstrftime')) { - // gmstrftime doesn't exist in some versions - // of PHP - $t = gmstrftime('%Y%m%dT%H:%M:%S', $timet); - } else { - $t = strftime('%Y%m%dT%H:%M:%S', $timet - date('Z')); - } - } - return $t; -} - -/** - * Convert a datetime string into a Unix timestamp - * - * While timezones ought to be supported, the XML-RPC spec says: - * - * "Don't assume a timezone. It should be specified by the server in its - * documentation what assumptions it makes about timezones." - * - * This routine always assumes localtime unless $utc is set to 1, in which - * case UTC is assumed and an adjustment for locale is made when encoding. - * - * @return int the unix timestamp of the date submitted - */ -function XML_RPC_iso8601_decode($idate, $utc = 0) -{ - $t = 0; - if (ereg('([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})', $idate, $regs)) { - if ($utc) { - $t = gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); - } else { - $t = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); - } - } - return $t; -} - -/** - * Converts an XML_RPC_Value object into native PHP types - * - * @param object $XML_RPC_val the XML_RPC_Value object to decode - * - * @return mixed the PHP values - */ -function XML_RPC_decode($XML_RPC_val) -{ - $kind = $XML_RPC_val->kindOf(); - - if ($kind == 'scalar') { - return $XML_RPC_val->scalarval(); - - } elseif ($kind == 'array') { - $size = $XML_RPC_val->arraysize(); - $arr = array(); - for ($i = 0; $i < $size; $i++) { - $arr[] = XML_RPC_decode($XML_RPC_val->arraymem($i)); - } - return $arr; - - } elseif ($kind == 'struct') { - $XML_RPC_val->structreset(); - $arr = array(); - while (list($key, $value) = $XML_RPC_val->structeach()) { - $arr[$key] = XML_RPC_decode($value); - } - return $arr; - } -} - -/** - * Converts native PHP types into an XML_RPC_Value object - * - * @param mixed $php_val the PHP value or variable you want encoded - * - * @return object the XML_RPC_Value object - */ -function XML_RPC_encode($php_val) -{ - global $XML_RPC_Boolean, $XML_RPC_Int, $XML_RPC_Double, $XML_RPC_String, - $XML_RPC_Array, $XML_RPC_Struct; - - $type = gettype($php_val); - $XML_RPC_val = new XML_RPC_Value; - - switch ($type) { - case 'array': - if (empty($php_val)) { - $XML_RPC_val->addArray($php_val); - break; - } - $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1)); - if (empty($tmp)) { - $arr = array(); - foreach ($php_val as $k => $v) { - $arr[$k] = XML_RPC_encode($v); - } - $XML_RPC_val->addArray($arr); - break; - } - // fall though if it's not an enumerated array - - case 'object': - $arr = array(); - foreach ($php_val as $k => $v) { - $arr[$k] = XML_RPC_encode($v); - } - $XML_RPC_val->addStruct($arr); - break; - - case 'integer': - $XML_RPC_val->addScalar($php_val, $XML_RPC_Int); - break; - - case 'double': - $XML_RPC_val->addScalar($php_val, $XML_RPC_Double); - break; - - case 'string': - case 'NULL': - $XML_RPC_val->addScalar($php_val, $XML_RPC_String); - break; - - case 'boolean': - // Add support for encoding/decoding of booleans, since they - // are supported in PHP - // by <G_Giunta_2001-02-29> - $XML_RPC_val->addScalar($php_val, $XML_RPC_Boolean); - break; - - case 'unknown type': - default: - $XML_RPC_val = false; - } - return $XML_RPC_val; -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ - -?> diff --git a/3rdparty/XML/RPC/Server.php b/3rdparty/XML/RPC/Server.php deleted file mode 100644 index 5c5c04b1f7afa34ea462ef219fb99add9a7ebcfd..0000000000000000000000000000000000000000 --- a/3rdparty/XML/RPC/Server.php +++ /dev/null @@ -1,624 +0,0 @@ -<?php - -/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ - -/** - * Server commands for our PHP implementation of the XML-RPC protocol - * - * This is a PEAR-ified version of Useful inc's XML-RPC for PHP. - * It has support for HTTP transport, proxies and authentication. - * - * PHP versions 4 and 5 - * - * LICENSE: License is granted to use or modify this software - * ("XML-RPC for PHP") for commercial or non-commercial use provided the - * copyright of the author is preserved in any distributed or derivative work. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESSED OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR 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 Web Services - * @package XML_RPC - * @author Edd Dumbill <edd@usefulinc.com> - * @author Stig Bakken <stig@php.net> - * @author Martin Jansen <mj@php.net> - * @author Daniel Convissor <danielc@php.net> - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version CVS: $Id: Server.php,v 1.29 2005/08/14 20:25:35 danielc Exp $ - * @link http://pear.php.net/package/XML_RPC - */ - - -/** - * Pull in the XML_RPC class - */ -require_once 'XML/RPC.php'; - - -/** - * signature for system.listMethods: return = array, - * parameters = a string or nothing - * @global array $GLOBALS['XML_RPC_Server_listMethods_sig'] - */ -$GLOBALS['XML_RPC_Server_listMethods_sig'] = array( - array($GLOBALS['XML_RPC_Array'], - $GLOBALS['XML_RPC_String'] - ), - array($GLOBALS['XML_RPC_Array']) -); - -/** - * docstring for system.listMethods - * @global string $GLOBALS['XML_RPC_Server_listMethods_doc'] - */ -$GLOBALS['XML_RPC_Server_listMethods_doc'] = 'This method lists all the' - . ' methods that the XML-RPC server knows how to dispatch'; - -/** - * signature for system.methodSignature: return = array, - * parameters = string - * @global array $GLOBALS['XML_RPC_Server_methodSignature_sig'] - */ -$GLOBALS['XML_RPC_Server_methodSignature_sig'] = array( - array($GLOBALS['XML_RPC_Array'], - $GLOBALS['XML_RPC_String'] - ) -); - -/** - * docstring for system.methodSignature - * @global string $GLOBALS['XML_RPC_Server_methodSignature_doc'] - */ -$GLOBALS['XML_RPC_Server_methodSignature_doc'] = 'Returns an array of known' - . ' signatures (an array of arrays) for the method name passed. If' - . ' no signatures are known, returns a none-array (test for type !=' - . ' array to detect missing signature)'; - -/** - * signature for system.methodHelp: return = string, - * parameters = string - * @global array $GLOBALS['XML_RPC_Server_methodHelp_sig'] - */ -$GLOBALS['XML_RPC_Server_methodHelp_sig'] = array( - array($GLOBALS['XML_RPC_String'], - $GLOBALS['XML_RPC_String'] - ) -); - -/** - * docstring for methodHelp - * @global string $GLOBALS['XML_RPC_Server_methodHelp_doc'] - */ -$GLOBALS['XML_RPC_Server_methodHelp_doc'] = 'Returns help text if defined' - . ' for the method passed, otherwise returns an empty string'; - -/** - * dispatch map for the automatically declared XML-RPC methods. - * @global array $GLOBALS['XML_RPC_Server_dmap'] - */ -$GLOBALS['XML_RPC_Server_dmap'] = array( - 'system.listMethods' => array( - 'function' => 'XML_RPC_Server_listMethods', - 'signature' => $GLOBALS['XML_RPC_Server_listMethods_sig'], - 'docstring' => $GLOBALS['XML_RPC_Server_listMethods_doc'] - ), - 'system.methodHelp' => array( - 'function' => 'XML_RPC_Server_methodHelp', - 'signature' => $GLOBALS['XML_RPC_Server_methodHelp_sig'], - 'docstring' => $GLOBALS['XML_RPC_Server_methodHelp_doc'] - ), - 'system.methodSignature' => array( - 'function' => 'XML_RPC_Server_methodSignature', - 'signature' => $GLOBALS['XML_RPC_Server_methodSignature_sig'], - 'docstring' => $GLOBALS['XML_RPC_Server_methodSignature_doc'] - ) -); - -/** - * @global string $GLOBALS['XML_RPC_Server_debuginfo'] - */ -$GLOBALS['XML_RPC_Server_debuginfo'] = ''; - - -/** - * Lists all the methods that the XML-RPC server knows how to dispatch - * - * @return object a new XML_RPC_Response object - */ -function XML_RPC_Server_listMethods($server, $m) -{ - global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap; - - $v = new XML_RPC_Value(); - $outAr = array(); - foreach ($server->dmap as $key => $val) { - $outAr[] = new XML_RPC_Value($key, 'string'); - } - foreach ($XML_RPC_Server_dmap as $key => $val) { - $outAr[] = new XML_RPC_Value($key, 'string'); - } - $v->addArray($outAr); - return new XML_RPC_Response($v); -} - -/** - * Returns an array of known signatures (an array of arrays) - * for the given method - * - * If no signatures are known, returns a none-array - * (test for type != array to detect missing signature) - * - * @return object a new XML_RPC_Response object - */ -function XML_RPC_Server_methodSignature($server, $m) -{ - global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap; - - $methName = $m->getParam(0); - $methName = $methName->scalarval(); - if (strpos($methName, 'system.') === 0) { - $dmap = $XML_RPC_Server_dmap; - $sysCall = 1; - } else { - $dmap = $server->dmap; - $sysCall = 0; - } - // print "<!-- ${methName} -->\n"; - if (isset($dmap[$methName])) { - if ($dmap[$methName]['signature']) { - $sigs = array(); - $thesigs = $dmap[$methName]['signature']; - for ($i = 0; $i < sizeof($thesigs); $i++) { - $cursig = array(); - $inSig = $thesigs[$i]; - for ($j = 0; $j < sizeof($inSig); $j++) { - $cursig[] = new XML_RPC_Value($inSig[$j], 'string'); - } - $sigs[] = new XML_RPC_Value($cursig, 'array'); - } - $r = new XML_RPC_Response(new XML_RPC_Value($sigs, 'array')); - } else { - $r = new XML_RPC_Response(new XML_RPC_Value('undef', 'string')); - } - } else { - $r = new XML_RPC_Response(0, $XML_RPC_err['introspect_unknown'], - $XML_RPC_str['introspect_unknown']); - } - return $r; -} - -/** - * Returns help text if defined for the method passed, otherwise returns - * an empty string - * - * @return object a new XML_RPC_Response object - */ -function XML_RPC_Server_methodHelp($server, $m) -{ - global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap; - - $methName = $m->getParam(0); - $methName = $methName->scalarval(); - if (strpos($methName, 'system.') === 0) { - $dmap = $XML_RPC_Server_dmap; - $sysCall = 1; - } else { - $dmap = $server->dmap; - $sysCall = 0; - } - - if (isset($dmap[$methName])) { - if ($dmap[$methName]['docstring']) { - $r = new XML_RPC_Response(new XML_RPC_Value($dmap[$methName]['docstring']), - 'string'); - } else { - $r = new XML_RPC_Response(new XML_RPC_Value('', 'string')); - } - } else { - $r = new XML_RPC_Response(0, $XML_RPC_err['introspect_unknown'], - $XML_RPC_str['introspect_unknown']); - } - return $r; -} - -/** - * @return void - */ -function XML_RPC_Server_debugmsg($m) -{ - global $XML_RPC_Server_debuginfo; - $XML_RPC_Server_debuginfo = $XML_RPC_Server_debuginfo . $m . "\n"; -} - - -/** - * A server for receiving and replying to XML RPC requests - * - * <code> - * $server = new XML_RPC_Server( - * array( - * 'isan8' => - * array( - * 'function' => 'is_8', - * 'signature' => - * array( - * array('boolean', 'int'), - * array('boolean', 'int', 'boolean'), - * array('boolean', 'string'), - * array('boolean', 'string', 'boolean'), - * ), - * 'docstring' => 'Is the value an 8?' - * ), - * ), - * 1, - * 0 - * ); - * </code> - * - * @category Web Services - * @package XML_RPC - * @author Edd Dumbill <edd@usefulinc.com> - * @author Stig Bakken <stig@php.net> - * @author Martin Jansen <mj@php.net> - * @author Daniel Convissor <danielc@php.net> - * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group - * @version Release: 1.4.0 - * @link http://pear.php.net/package/XML_RPC - */ -class XML_RPC_Server -{ - /** - * The dispatch map, listing the methods this server provides. - * @var array - */ - var $dmap = array(); - - /** - * The present response's encoding - * @var string - * @see XML_RPC_Message::getEncoding() - */ - var $encoding = ''; - - /** - * Debug mode (0 = off, 1 = on) - * @var integer - */ - var $debug = 0; - - /** - * The response's HTTP headers - * @var string - */ - var $server_headers = ''; - - /** - * The response's XML payload - * @var string - */ - var $server_payload = ''; - - - /** - * Constructor for the XML_RPC_Server class - * - * @param array $dispMap the dispatch map. An associative array - * explaining each function. The keys of the main - * array are the procedure names used by the - * clients. The value is another associative array - * that contains up to three elements: - * + The 'function' element's value is the name - * of the function or method that gets called. - * To define a class' method: 'class::method'. - * + The 'signature' element (optional) is an - * array describing the return values and - * parameters - * + The 'docstring' element (optional) is a - * string describing what the method does - * @param int $serviceNow should the HTTP response be sent now? - * (1 = yes, 0 = no) - * @param int $debug should debug output be displayed? - * (1 = yes, 0 = no) - * - * @return void - */ - function XML_RPC_Server($dispMap, $serviceNow = 1, $debug = 0) - { - global $HTTP_RAW_POST_DATA; - - if ($debug) { - $this->debug = 1; - } else { - $this->debug = 0; - } - - $this->dmap = $dispMap; - - if ($serviceNow) { - $this->service(); - } else { - $this->createServerPayload(); - $this->createServerHeaders(); - } - } - - /** - * @return string the debug information if debug debug mode is on - */ - function serializeDebug() - { - global $XML_RPC_Server_debuginfo, $HTTP_RAW_POST_DATA; - - if ($this->debug) { - XML_RPC_Server_debugmsg('vvv POST DATA RECEIVED BY SERVER vvv' . "\n" - . $HTTP_RAW_POST_DATA - . "\n" . '^^^ END POST DATA ^^^'); - } - - if ($XML_RPC_Server_debuginfo != '') { - return "<!-- PEAR XML_RPC SERVER DEBUG INFO:\n\n" - . preg_replace('/-(?=-)/', '- ', $XML_RPC_Server_debuginfo) - . "-->\n"; - } else { - return ''; - } - } - - /** - * Sends the response - * - * The encoding and content-type are determined by - * XML_RPC_Message::getEncoding() - * - * @return void - * - * @uses XML_RPC_Server::createServerPayload(), - * XML_RPC_Server::createServerHeaders() - */ - function service() - { - if (!$this->server_payload) { - $this->createServerPayload(); - } - if (!$this->server_headers) { - $this->createServerHeaders(); - } - header($this->server_headers); - print $this->server_payload; - } - - /** - * Generates the payload and puts it in the $server_payload property - * - * @return void - * - * @uses XML_RPC_Server::parseRequest(), XML_RPC_Server::$encoding, - * XML_RPC_Response::serialize(), XML_RPC_Server::serializeDebug() - */ - function createServerPayload() - { - $r = $this->parseRequest(); - $this->server_payload = '<?xml version="1.0" encoding="' - . $this->encoding . '"?>' . "\n" - . $this->serializeDebug() - . $r->serialize(); - } - - /** - * Determines the HTTP headers and puts them in the $server_headers - * property - * - * @return boolean TRUE if okay, FALSE if $server_payload isn't set. - * - * @uses XML_RPC_Server::createServerPayload(), - * XML_RPC_Server::$server_headers - */ - function createServerHeaders() - { - if (!$this->server_payload) { - return false; - } - $this->server_headers = 'Content-Length: ' - . strlen($this->server_payload) . "\r\n" - . 'Content-Type: text/xml;' - . ' charset=' . $this->encoding; - return true; - } - - /** - * @return array - */ - function verifySignature($in, $sig) - { - for ($i = 0; $i < sizeof($sig); $i++) { - // check each possible signature in turn - $cursig = $sig[$i]; - if (sizeof($cursig) == $in->getNumParams() + 1) { - $itsOK = 1; - for ($n = 0; $n < $in->getNumParams(); $n++) { - $p = $in->getParam($n); - // print "<!-- $p -->\n"; - if ($p->kindOf() == 'scalar') { - $pt = $p->scalartyp(); - } else { - $pt = $p->kindOf(); - } - // $n+1 as first type of sig is return type - if ($pt != $cursig[$n+1]) { - $itsOK = 0; - $pno = $n+1; - $wanted = $cursig[$n+1]; - $got = $pt; - break; - } - } - if ($itsOK) { - return array(1); - } - } - } - if (isset($wanted)) { - return array(0, "Wanted ${wanted}, got ${got} at param ${pno}"); - } else { - $allowed = array(); - foreach ($sig as $val) { - end($val); - $allowed[] = key($val); - } - $allowed = array_unique($allowed); - $last = count($allowed) - 1; - if ($last > 0) { - $allowed[$last] = 'or ' . $allowed[$last]; - } - return array(0, - 'Signature permits ' . implode(', ', $allowed) - . ' parameters but the request had ' - . $in->getNumParams()); - } - } - - /** - * @return object a new XML_RPC_Response object - * - * @uses XML_RPC_Message::getEncoding(), XML_RPC_Server::$encoding - */ - function parseRequest($data = '') - { - global $XML_RPC_xh, $HTTP_RAW_POST_DATA, - $XML_RPC_err, $XML_RPC_str, $XML_RPC_errxml, - $XML_RPC_defencoding, $XML_RPC_Server_dmap; - - if ($data == '') { - $data = $HTTP_RAW_POST_DATA; - } - - $this->encoding = XML_RPC_Message::getEncoding($data); - $parser_resource = xml_parser_create($this->encoding); - $parser = (int) $parser_resource; - - $XML_RPC_xh[$parser] = array(); - $XML_RPC_xh[$parser]['cm'] = 0; - $XML_RPC_xh[$parser]['isf'] = 0; - $XML_RPC_xh[$parser]['params'] = array(); - $XML_RPC_xh[$parser]['method'] = ''; - $XML_RPC_xh[$parser]['stack'] = array(); - $XML_RPC_xh[$parser]['valuestack'] = array(); - - $plist = ''; - - // decompose incoming XML into request structure - - xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true); - xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee'); - xml_set_character_data_handler($parser_resource, 'XML_RPC_cd'); - if (!xml_parse($parser_resource, $data, 1)) { - // return XML error as a faultCode - $r = new XML_RPC_Response(0, - $XML_RPC_errxml+xml_get_error_code($parser_resource), - sprintf('XML error: %s at line %d', - xml_error_string(xml_get_error_code($parser_resource)), - xml_get_current_line_number($parser_resource))); - xml_parser_free($parser_resource); - } elseif ($XML_RPC_xh[$parser]['isf']>1) { - $r = new XML_RPC_Response(0, - $XML_RPC_err['invalid_request'], - $XML_RPC_str['invalid_request'] - . ': ' - . $XML_RPC_xh[$parser]['isf_reason']); - xml_parser_free($parser_resource); - } else { - xml_parser_free($parser_resource); - $m = new XML_RPC_Message($XML_RPC_xh[$parser]['method']); - // now add parameters in - for ($i = 0; $i < sizeof($XML_RPC_xh[$parser]['params']); $i++) { - // print '<!-- ' . $XML_RPC_xh[$parser]['params'][$i]. "-->\n"; - $plist .= "$i - " . var_export($XML_RPC_xh[$parser]['params'][$i], true) . " \n"; - $m->addParam($XML_RPC_xh[$parser]['params'][$i]); - } - XML_RPC_Server_debugmsg($plist); - - // now to deal with the method - $methName = $XML_RPC_xh[$parser]['method']; - if (strpos($methName, 'system.') === 0) { - $dmap = $XML_RPC_Server_dmap; - $sysCall = 1; - } else { - $dmap = $this->dmap; - $sysCall = 0; - } - - if (isset($dmap[$methName]['function']) - && is_string($dmap[$methName]['function']) - && strpos($dmap[$methName]['function'], '::') !== false) - { - $dmap[$methName]['function'] = - explode('::', $dmap[$methName]['function']); - } - - if (isset($dmap[$methName]['function']) - && is_callable($dmap[$methName]['function'])) - { - // dispatch if exists - if (isset($dmap[$methName]['signature'])) { - $sr = $this->verifySignature($m, - $dmap[$methName]['signature'] ); - } - if (!isset($dmap[$methName]['signature']) || $sr[0]) { - // if no signature or correct signature - if ($sysCall) { - $r = call_user_func($dmap[$methName]['function'], $this, $m); - } else { - $r = call_user_func($dmap[$methName]['function'], $m); - } - if (!is_a($r, 'XML_RPC_Response')) { - $r = new XML_RPC_Response(0, $XML_RPC_err['not_response_object'], - $XML_RPC_str['not_response_object']); - } - } else { - $r = new XML_RPC_Response(0, $XML_RPC_err['incorrect_params'], - $XML_RPC_str['incorrect_params'] - . ': ' . $sr[1]); - } - } else { - // else prepare error response - $r = new XML_RPC_Response(0, $XML_RPC_err['unknown_method'], - $XML_RPC_str['unknown_method']); - } - } - return $r; - } - - /** - * Echos back the input packet as a string value - * - * @return void - * - * Useful for debugging. - */ - function echoInput() - { - global $HTTP_RAW_POST_DATA; - - $r = new XML_RPC_Response(0); - $r->xv = new XML_RPC_Value("'Aha said I: '" . $HTTP_RAW_POST_DATA, 'string'); - print $r->serialize(); - } -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * c-hanging-comment-ender-p: nil - * End: - */ - -?> diff --git a/3rdparty/css/chosen-sprite.png b/3rdparty/css/chosen-sprite.png deleted file mode 100644 index f20db4439ea5c1038126bf326c8fd048b03a8226..0000000000000000000000000000000000000000 Binary files a/3rdparty/css/chosen-sprite.png and /dev/null differ diff --git a/3rdparty/css/chosen.css b/3rdparty/css/chosen.css deleted file mode 100644 index 96bae0fe95a380c0ac984920af40c45a9923bd2a..0000000000000000000000000000000000000000 --- a/3rdparty/css/chosen.css +++ /dev/null @@ -1,341 +0,0 @@ -/* @group Base */ -select.chzn-select { - visibility: hidden; - height: 28px !important; - min-height: 28px !important; -} -.chzn-container { - font-size: 13px; - position: relative; - display: inline-block; - zoom: 1; - *display: inline; - vertical-align: bottom; -} -.chzn-container .chzn-drop { - background: #fff; - border: 1px solid #aaa; - border-top: 0; - position: absolute; - top: 29px; - left: 0; - -webkit-box-shadow: 0 4px 5px rgba(0,0,0,.15); - -moz-box-shadow : 0 4px 5px rgba(0,0,0,.15); - -o-box-shadow : 0 4px 5px rgba(0,0,0,.15); - box-shadow : 0 4px 5px rgba(0,0,0,.15); - z-index: 999; -} -/* @end */ - -/* @group Single Chosen */ -.chzn-container-single .chzn-single { - background-color: #fff; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #eeeeee), color-stop(0.5, white)); - background-image: -webkit-linear-gradient(center bottom, #eeeeee 0%, white 50%); - background-image: -moz-linear-gradient(center bottom, #eeeeee 0%, white 50%); - background-image: -o-linear-gradient(top, #eeeeee 0%,#ffffff 50%); - background-image: -ms-linear-gradient(top, #eeeeee 0%,#ffffff 50%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#eeeeee', endColorstr='#ffffff',GradientType=0 ); - background-image: linear-gradient(top, #eeeeee 0%,#ffffff 50%); - -webkit-border-radius: 4px; - -moz-border-radius : 4px; - border-radius : 4px; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; - border: 1px solid #aaa; - display: block; - overflow: hidden; - white-space: nowrap; - position: relative; - height: 26px; - line-height: 26px; - padding: 0 0 0 8px; - color: #444; - text-decoration: none; -} -.chzn-container-single .chzn-single span { - margin-right: 26px; - display: block; - overflow: hidden; - white-space: nowrap; - -o-text-overflow: ellipsis; - -ms-text-overflow: ellipsis; - -moz-binding: url('/xml/ellipsis.xml#ellipsis'); - text-overflow: ellipsis; -} -.chzn-container-single .chzn-single div { - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius : 0 4px 4px 0; - border-radius : 0 4px 4px 0; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; - background: #ccc; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #ccc), color-stop(0.6, #eee)); - background-image: -webkit-linear-gradient(center bottom, #ccc 0%, #eee 60%); - background-image: -moz-linear-gradient(center bottom, #ccc 0%, #eee 60%); - background-image: -o-linear-gradient(bottom, #ccc 0%, #eee 60%); - background-image: -ms-linear-gradient(top, #cccccc 0%,#eeeeee 60%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#cccccc', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #cccccc 0%,#eeeeee 60%); - border-left: 1px solid #aaa; - position: absolute; - right: 0; - top: 0; - display: block; - height: 100%; - width: 18px; -} -.chzn-container-single .chzn-single div b { - background: url('chosen-sprite.png') no-repeat 0 1px; - display: block; - width: 100%; - height: 100%; -} -.chzn-container-single .chzn-search { - padding: 3px 4px; - margin: 0; - white-space: nowrap; -} -.chzn-container-single .chzn-search input { - background: #fff url('chosen-sprite.png') no-repeat 100% -20px; - background: url('chosen-sprite.png') no-repeat 100% -20px, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); - background: url('chosen-sprite.png') no-repeat 100% -20px, -webkit-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -20px, -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -20px, -o-linear-gradient(bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -20px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -20px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -20px, linear-gradient(top, #ffffff 85%,#eeeeee 99%); - margin: 1px 0; - padding: 4px 20px 4px 5px; - outline: 0; - border: 1px solid #aaa; - font-family: sans-serif; - font-size: 1em; -} -.chzn-container-single .chzn-drop { - -webkit-border-radius: 0 0 4px 4px; - -moz-border-radius : 0 0 4px 4px; - border-radius : 0 0 4px 4px; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; -} -/* @end */ - -/* @group Multi Chosen */ -.chzn-container-multi .chzn-choices { - background-color: #fff; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); - background-image: -webkit-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background-image: -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background-image: -o-linear-gradient(bottom, white 85%, #eeeeee 99%); - background-image: -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #ffffff 85%,#eeeeee 99%); - border: 1px solid #aaa; - margin: 0; - padding: 0; - cursor: text; - overflow: hidden; - height: auto !important; - height: 1%; - position: relative; -} -.chzn-container-multi .chzn-choices li { - float: left; - list-style: none; -} -.chzn-container-multi .chzn-choices .search-field { - white-space: nowrap; - margin: 0; - padding: 0; -} -.chzn-container-multi .chzn-choices .search-field input { - color: #666; - background: transparent !important; - border: 0 !important; - padding: 5px; - margin: 1px 0; - outline: 0; - -webkit-box-shadow: none; - -moz-box-shadow : none; - -o-box-shadow : none; - box-shadow : none; -} -.chzn-container-multi .chzn-choices .search-field .default { - color: #999; -} -.chzn-container-multi .chzn-choices .search-choice { - -webkit-border-radius: 3px; - -moz-border-radius : 3px; - border-radius : 3px; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; - background-color: #e4e4e4; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #e4e4e4), color-stop(0.7, #eeeeee)); - background-image: -webkit-linear-gradient(center bottom, #e4e4e4 0%, #eeeeee 70%); - background-image: -moz-linear-gradient(center bottom, #e4e4e4 0%, #eeeeee 70%); - background-image: -o-linear-gradient(bottom, #e4e4e4 0%, #eeeeee 70%); - background-image: -ms-linear-gradient(top, #e4e4e4 0%,#eeeeee 70%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e4e4e4', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #e4e4e4 0%,#eeeeee 70%); - color: #333; - border: 1px solid #b4b4b4; - line-height: 13px; - padding: 3px 19px 3px 6px; - margin: 3px 0 3px 5px; - position: relative; -} -.chzn-container-multi .chzn-choices .search-choice span { - cursor: default; -} -.chzn-container-multi .chzn-choices .search-choice-focus { - background: #d4d4d4; -} -.chzn-container-multi .chzn-choices .search-choice .search-choice-close { - display: block; - position: absolute; - right: 5px; - top: 6px; - width: 8px; - height: 9px; - font-size: 1px; - background: url(chosen-sprite.png) right top no-repeat; -} -.chzn-container-multi .chzn-choices .search-choice .search-choice-close:hover { - background-position: right -9px; -} -.chzn-container-multi .chzn-choices .search-choice-focus .search-choice-close { - background-position: right -9px; -} -/* @end */ - -/* @group Results */ -.chzn-container .chzn-results { - margin: 0 4px 4px 0; - max-height: 190px; - padding: 0 0 0 4px; - position: relative; - overflow-x: hidden; - overflow-y: auto; -} -.chzn-container-multi .chzn-results { - margin: -1px 0 0; - padding: 0; -} -.chzn-container .chzn-results li { - line-height: 80%; - padding: 7px 7px 8px; - margin: 0; - list-style: none; -} -.chzn-container .chzn-results .active-result { - cursor: pointer; -} -.chzn-container .chzn-results .highlighted { - background: #3875d7; - color: #fff; -} -.chzn-container .chzn-results li em { - background: #feffde; - font-style: normal; -} -.chzn-container .chzn-results .highlighted em { - background: transparent; -} -.chzn-container .chzn-results .no-results { - background: #f4f4f4; -} -.chzn-container .chzn-results .group-result { - cursor: default; - color: #999; - font-weight: bold; -} -.chzn-container .chzn-results .group-option { - padding-left: 20px; -} -.chzn-container-multi .chzn-drop .result-selected { - display: none; -} -/* @end */ - -/* @group Active */ -.chzn-container-active .chzn-single { - -webkit-box-shadow: 0 0 5px rgba(0,0,0,.3); - -moz-box-shadow : 0 0 5px rgba(0,0,0,.3); - -o-box-shadow : 0 0 5px rgba(0,0,0,.3); - box-shadow : 0 0 5px rgba(0,0,0,.3); - border: 1px solid #5897fb; -} -.chzn-container-active .chzn-single-with-drop { - border: 1px solid #aaa; - -webkit-box-shadow: 0 1px 0 #fff inset; - -moz-box-shadow : 0 1px 0 #fff inset; - -o-box-shadow : 0 1px 0 #fff inset; - box-shadow : 0 1px 0 #fff inset; - background-color: #eee; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, white), color-stop(0.5, #eeeeee)); - background-image: -webkit-linear-gradient(center bottom, white 0%, #eeeeee 50%); - background-image: -moz-linear-gradient(center bottom, white 0%, #eeeeee 50%); - background-image: -o-linear-gradient(bottom, white 0%, #eeeeee 50%); - background-image: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 50%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #ffffff 0%,#eeeeee 50%); - -webkit-border-bottom-left-radius : 0; - -webkit-border-bottom-right-radius: 0; - -moz-border-radius-bottomleft : 0; - -moz-border-radius-bottomright: 0; - border-bottom-left-radius : 0; - border-bottom-right-radius: 0; -} -.chzn-container-active .chzn-single-with-drop div { - background: transparent; - border-left: none; -} -.chzn-container-active .chzn-single-with-drop div b { - background-position: -18px 1px; -} -.chzn-container-active .chzn-choices { - -webkit-box-shadow: 0 0 5px rgba(0,0,0,.3); - -moz-box-shadow : 0 0 5px rgba(0,0,0,.3); - -o-box-shadow : 0 0 5px rgba(0,0,0,.3); - box-shadow : 0 0 5px rgba(0,0,0,.3); - border: 1px solid #5897fb; -} -.chzn-container-active .chzn-choices .search-field input { - color: #111 !important; -} -/* @end */ - -/* @group Right to Left */ -.chzn-rtl { direction:rtl;text-align: right; } -.chzn-rtl .chzn-single { padding-left: 0; padding-right: 8px; } -.chzn-rtl .chzn-single span { margin-left: 26px; margin-right: 0; } -.chzn-rtl .chzn-single div { - left: 0; right: auto; - border-left: none; border-right: 1px solid #aaaaaa; - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius : 4px 0 0 4px; - border-radius : 4px 0 0 4px; -} -.chzn-rtl .chzn-choices li { float: right; } -.chzn-rtl .chzn-choices .search-choice { padding: 3px 6px 3px 19px; margin: 3px 5px 3px 0; } -.chzn-rtl .chzn-choices .search-choice .search-choice-close { left: 5px; right: auto; background-position: right top;} -.chzn-rtl.chzn-container-single .chzn-results { margin-left: 4px; margin-right: 0; padding-left: 0; padding-right: 4px; } -.chzn-rtl .chzn-results .group-option { padding-left: 0; padding-right: 20px; } -.chzn-rtl.chzn-container-active .chzn-single-with-drop div { border-right: none; } -.chzn-rtl .chzn-search input { - background: url('chosen-sprite.png') no-repeat -38px -20px, #ffffff; - background: url('chosen-sprite.png') no-repeat -38px -20px, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); - background: url('chosen-sprite.png') no-repeat -38px -20px, -webkit-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -20px, -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -20px, -o-linear-gradient(bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -20px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -20px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -20px, linear-gradient(top, #ffffff 85%,#eeeeee 99%); - padding: 4px 5px 4px 20px; -} -/* @end */ \ No newline at end of file diff --git a/3rdparty/css/chosen/chosen-sprite.png b/3rdparty/css/chosen/chosen-sprite.png deleted file mode 100644 index 9edce05a6a899eaf98481d12dddbc433331a01ee..0000000000000000000000000000000000000000 Binary files a/3rdparty/css/chosen/chosen-sprite.png and /dev/null differ diff --git a/3rdparty/css/chosen/chosen.css b/3rdparty/css/chosen/chosen.css deleted file mode 100644 index b9c6d88028fc03ae712339d57e80b2a566eab862..0000000000000000000000000000000000000000 --- a/3rdparty/css/chosen/chosen.css +++ /dev/null @@ -1,368 +0,0 @@ -/* @group Base */ -.chzn-container { - font-size: 13px; - position: relative; - display: inline-block; - zoom: 1; - *display: inline; -} -.chzn-container .chzn-drop { - background: #fff; - border: 1px solid #aaa; - border-top: 0; - position: absolute; - top: 29px; - left: 0; - -webkit-box-shadow: 0 4px 5px rgba(0,0,0,.15); - -moz-box-shadow : 0 4px 5px rgba(0,0,0,.15); - -o-box-shadow : 0 4px 5px rgba(0,0,0,.15); - box-shadow : 0 4px 5px rgba(0,0,0,.15); - z-index: 999; -} -/* @end */ - -/* @group Single Chosen */ -.chzn-container-single .chzn-single { - background-color: #fff; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #eeeeee), color-stop(0.5, white)); - background-image: -webkit-linear-gradient(center bottom, #eeeeee 0%, white 50%); - background-image: -moz-linear-gradient(center bottom, #eeeeee 0%, white 50%); - background-image: -o-linear-gradient(top, #eeeeee 0%,#ffffff 50%); - background-image: -ms-linear-gradient(top, #eeeeee 0%,#ffffff 50%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#eeeeee', endColorstr='#ffffff',GradientType=0 ); - background-image: linear-gradient(top, #eeeeee 0%,#ffffff 50%); - -webkit-border-radius: 4px; - -moz-border-radius : 4px; - border-radius : 4px; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; - border: 1px solid #aaa; - display: block; - overflow: hidden; - white-space: nowrap; - position: relative; - height: 26px; - line-height: 26px; - padding: 0 0 0 8px; - color: #444; - text-decoration: none; -} -.chzn-container-single .chzn-single span { - margin-right: 26px; - display: block; - overflow: hidden; - white-space: nowrap; - -o-text-overflow: ellipsis; - -ms-text-overflow: ellipsis; - text-overflow: ellipsis; -} -.chzn-container-single .chzn-single abbr { - display: block; - position: absolute; - right: 26px; - top: 8px; - width: 12px; - height: 13px; - font-size: 1px; - background: url(chosen-sprite.png) right top no-repeat; -} -.chzn-container-single .chzn-single abbr:hover { - background-position: right -11px; -} -.chzn-container-single .chzn-single div { - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius : 0 4px 4px 0; - border-radius : 0 4px 4px 0; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; - background: #ccc; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #ccc), color-stop(0.6, #eee)); - background-image: -webkit-linear-gradient(center bottom, #ccc 0%, #eee 60%); - background-image: -moz-linear-gradient(center bottom, #ccc 0%, #eee 60%); - background-image: -o-linear-gradient(bottom, #ccc 0%, #eee 60%); - background-image: -ms-linear-gradient(top, #cccccc 0%,#eeeeee 60%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#cccccc', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #cccccc 0%,#eeeeee 60%); - border-left: 1px solid #aaa; - position: absolute; - right: 0; - top: 0; - display: block; - height: 100%; - width: 18px; -} -.chzn-container-single .chzn-single div b { - background: url('chosen-sprite.png') no-repeat 0 1px; - display: block; - width: 100%; - height: 100%; -} -.chzn-container-single .chzn-search { - padding: 3px 4px; - position: relative; - margin: 0; - white-space: nowrap; -} -.chzn-container-single .chzn-search input { - background: #fff url('chosen-sprite.png') no-repeat 100% -22px; - background: url('chosen-sprite.png') no-repeat 100% -22px, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); - background: url('chosen-sprite.png') no-repeat 100% -22px, -webkit-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -22px, -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -22px, -o-linear-gradient(bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -22px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -22px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat 100% -22px, linear-gradient(top, #ffffff 85%,#eeeeee 99%); - margin: 1px 0; - padding: 4px 20px 4px 5px; - outline: 0; - border: 1px solid #aaa; - font-family: sans-serif; - font-size: 1em; -} -.chzn-container-single .chzn-drop { - -webkit-border-radius: 0 0 4px 4px; - -moz-border-radius : 0 0 4px 4px; - border-radius : 0 0 4px 4px; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; -} -/* @end */ - -.chzn-container-single-nosearch .chzn-search input { - position: absolute; - left: -9000px; -} - -/* @group Multi Chosen */ -.chzn-container-multi .chzn-choices { - background-color: #fff; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); - background-image: -webkit-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background-image: -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background-image: -o-linear-gradient(bottom, white 85%, #eeeeee 99%); - background-image: -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #ffffff 85%,#eeeeee 99%); - border: 1px solid #aaa; - margin: 0; - padding: 0; - cursor: text; - overflow: hidden; - height: auto !important; - height: 1%; - position: relative; -} -.chzn-container-multi .chzn-choices li { - float: left; - list-style: none; -} -.chzn-container-multi .chzn-choices .search-field { - white-space: nowrap; - margin: 0; - padding: 0; -} -.chzn-container-multi .chzn-choices .search-field input { - color: #666; - background: transparent !important; - border: 0 !important; - padding: 5px; - margin: 1px 0; - outline: 0; - -webkit-box-shadow: none; - -moz-box-shadow : none; - -o-box-shadow : none; - box-shadow : none; -} -.chzn-container-multi .chzn-choices .search-field .default { - color: #999; -} -.chzn-container-multi .chzn-choices .search-choice { - -webkit-border-radius: 3px; - -moz-border-radius : 3px; - border-radius : 3px; - -moz-background-clip : padding; - -webkit-background-clip: padding-box; - background-clip : padding-box; - background-color: #e4e4e4; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #e4e4e4), color-stop(0.7, #eeeeee)); - background-image: -webkit-linear-gradient(center bottom, #e4e4e4 0%, #eeeeee 70%); - background-image: -moz-linear-gradient(center bottom, #e4e4e4 0%, #eeeeee 70%); - background-image: -o-linear-gradient(bottom, #e4e4e4 0%, #eeeeee 70%); - background-image: -ms-linear-gradient(top, #e4e4e4 0%,#eeeeee 70%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e4e4e4', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #e4e4e4 0%,#eeeeee 70%); - color: #333; - border: 1px solid #b4b4b4; - line-height: 13px; - padding: 3px 19px 3px 6px; - margin: 3px 0 3px 5px; - position: relative; -} -.chzn-container-multi .chzn-choices .search-choice span { - cursor: default; -} -.chzn-container-multi .chzn-choices .search-choice-focus { - background: #d4d4d4; -} -.chzn-container-multi .chzn-choices .search-choice .search-choice-close { - display: block; - position: absolute; - right: 3px; - top: 4px; - width: 12px; - height: 13px; - font-size: 1px; - background: url(chosen-sprite.png) right top no-repeat; -} -.chzn-container-multi .chzn-choices .search-choice .search-choice-close:hover { - background-position: right -11px; -} -.chzn-container-multi .chzn-choices .search-choice-focus .search-choice-close { - background-position: right -11px; -} -/* @end */ - -/* @group Results */ -.chzn-container .chzn-results { - margin: 0 4px 4px 0; - max-height: 190px; - padding: 0 0 0 4px; - position: relative; - overflow-x: hidden; - overflow-y: auto; -} -.chzn-container-multi .chzn-results { - margin: -1px 0 0; - padding: 0; -} -.chzn-container .chzn-results li { - display: none; - line-height: 80%; - padding: 7px 7px 8px; - margin: 0; - list-style: none; -} -.chzn-container .chzn-results .active-result { - cursor: pointer; - display: list-item; -} -.chzn-container .chzn-results .highlighted { - background: #3875d7; - color: #fff; -} -.chzn-container .chzn-results li em { - background: #feffde; - font-style: normal; -} -.chzn-container .chzn-results .highlighted em { - background: transparent; -} -.chzn-container .chzn-results .no-results { - background: #f4f4f4; - display: list-item; -} -.chzn-container .chzn-results .group-result { - cursor: default; - color: #999; - font-weight: bold; -} -.chzn-container .chzn-results .group-option { - padding-left: 20px; -} -.chzn-container-multi .chzn-drop .result-selected { - display: none; -} -/* @end */ - -/* @group Active */ -.chzn-container-active .chzn-single { - -webkit-box-shadow: 0 0 5px rgba(0,0,0,.3); - -moz-box-shadow : 0 0 5px rgba(0,0,0,.3); - -o-box-shadow : 0 0 5px rgba(0,0,0,.3); - box-shadow : 0 0 5px rgba(0,0,0,.3); - border: 1px solid #5897fb; -} -.chzn-container-active .chzn-single-with-drop { - border: 1px solid #aaa; - -webkit-box-shadow: 0 1px 0 #fff inset; - -moz-box-shadow : 0 1px 0 #fff inset; - -o-box-shadow : 0 1px 0 #fff inset; - box-shadow : 0 1px 0 #fff inset; - background-color: #eee; - background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, white), color-stop(0.5, #eeeeee)); - background-image: -webkit-linear-gradient(center bottom, white 0%, #eeeeee 50%); - background-image: -moz-linear-gradient(center bottom, white 0%, #eeeeee 50%); - background-image: -o-linear-gradient(bottom, white 0%, #eeeeee 50%); - background-image: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 50%); - filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); - background-image: linear-gradient(top, #ffffff 0%,#eeeeee 50%); - -webkit-border-bottom-left-radius : 0; - -webkit-border-bottom-right-radius: 0; - -moz-border-radius-bottomleft : 0; - -moz-border-radius-bottomright: 0; - border-bottom-left-radius : 0; - border-bottom-right-radius: 0; -} -.chzn-container-active .chzn-single-with-drop div { - background: transparent; - border-left: none; -} -.chzn-container-active .chzn-single-with-drop div b { - background-position: -18px 1px; -} -.chzn-container-active .chzn-choices { - -webkit-box-shadow: 0 0 5px rgba(0,0,0,.3); - -moz-box-shadow : 0 0 5px rgba(0,0,0,.3); - -o-box-shadow : 0 0 5px rgba(0,0,0,.3); - box-shadow : 0 0 5px rgba(0,0,0,.3); - border: 1px solid #5897fb; -} -.chzn-container-active .chzn-choices .search-field input { - color: #111 !important; -} -/* @end */ - -/* @group Disabled Support */ -.chzn-disabled { - cursor: default; - opacity:0.5 !important; -} -.chzn-disabled .chzn-single { - cursor: default; -} -.chzn-disabled .chzn-choices .search-choice .search-choice-close { - cursor: default; -} - -/* @group Right to Left */ -.chzn-rtl { direction:rtl;text-align: right; } -.chzn-rtl .chzn-single { padding-left: 0; padding-right: 8px; } -.chzn-rtl .chzn-single span { margin-left: 26px; margin-right: 0; } -.chzn-rtl .chzn-single div { - left: 0; right: auto; - border-left: none; border-right: 1px solid #aaaaaa; - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius : 4px 0 0 4px; - border-radius : 4px 0 0 4px; -} -.chzn-rtl .chzn-choices li { float: right; } -.chzn-rtl .chzn-choices .search-choice { padding: 3px 6px 3px 19px; margin: 3px 5px 3px 0; } -.chzn-rtl .chzn-choices .search-choice .search-choice-close { left: 5px; right: auto; background-position: right top;} -.chzn-rtl.chzn-container-single .chzn-results { margin-left: 4px; margin-right: 0; padding-left: 0; padding-right: 4px; } -.chzn-rtl .chzn-results .group-option { padding-left: 0; padding-right: 20px; } -.chzn-rtl.chzn-container-active .chzn-single-with-drop div { border-right: none; } -.chzn-rtl .chzn-search input { - background: url('chosen-sprite.png') no-repeat -38px -22px, #ffffff; - background: url('chosen-sprite.png') no-repeat -38px -22px, -webkit-gradient(linear, left bottom, left top, color-stop(0.85, white), color-stop(0.99, #eeeeee)); - background: url('chosen-sprite.png') no-repeat -38px -22px, -webkit-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -22px, -moz-linear-gradient(center bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -22px, -o-linear-gradient(bottom, white 85%, #eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -22px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -22px, -ms-linear-gradient(top, #ffffff 85%,#eeeeee 99%); - background: url('chosen-sprite.png') no-repeat -38px -22px, linear-gradient(top, #ffffff 85%,#eeeeee 99%); - padding: 4px 5px 4px 20px; -} -/* @end */ \ No newline at end of file diff --git a/3rdparty/fullcalendar/GPL-LICENSE.txt b/3rdparty/fullcalendar/GPL-LICENSE.txt deleted file mode 100644 index 11dddd00ef0e91a0bce53b034d6b5b318a84e690..0000000000000000000000000000000000000000 --- a/3rdparty/fullcalendar/GPL-LICENSE.txt +++ /dev/null @@ -1,278 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. diff --git a/3rdparty/fullcalendar/MIT-LICENSE.txt b/3rdparty/fullcalendar/MIT-LICENSE.txt deleted file mode 100644 index 46d475449640479223cb5d7eb6e8c18e9ae7c6b7..0000000000000000000000000000000000000000 --- a/3rdparty/fullcalendar/MIT-LICENSE.txt +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009 Adam Shaw - -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. diff --git a/3rdparty/fullcalendar/changelog.txt b/3rdparty/fullcalendar/changelog.txt deleted file mode 100644 index 50d0880fd7a3dd4e827c57152f3532b4f8a15dcb..0000000000000000000000000000000000000000 --- a/3rdparty/fullcalendar/changelog.txt +++ /dev/null @@ -1,313 +0,0 @@ - -version 1.5.2 (8/21/11) - - correctly process UTC "Z" ISO8601 date strings (issue 750) - -version 1.5.1 (4/9/11) - - more flexible ISO8601 date parsing (issue 814) - - more flexible parsing of UNIX timestamps (issue 826) - - FullCalendar now buildable from source on a Mac (issue 795) - - FullCalendar QA'd in FF4 (issue 883) - - upgraded to jQuery 1.5.2 (which supports IE9) and jQuery UI 1.8.11 - -version 1.5 (3/19/11) - - slicker default styling for buttons - - reworked a lot of the calendar's HTML and accompanying CSS - (solves issues 327 and 395) - - more printer-friendly (fullcalendar-print.css) - - fullcalendar now inherits styles from jquery-ui themes differently. - styles for buttons are distinct from styles for calendar cells. - (solves issue 299) - - can now color events through FullCalendar options and Event-Object properties (issue 117) - THIS IS NOW THE PREFERRED METHOD OF COLORING EVENTS (as opposed to using className and CSS) - - FullCalendar options: - - eventColor (changes both background and border) - - eventBackgroundColor - - eventBorderColor - - eventTextColor - - Event-Object options: - - color (changes both background and border) - - backgroundColor - - borderColor - - textColor - - can now specify an event source as an *object* with a `url` property (json feed) or - an `events` property (function or array) with additional properties that will - be applied to the entire event source: - - color (changes both background and border) - - backgroudColor - - borderColor - - textColor - - className - - editable - - allDayDefault - - ignoreTimezone - - startParam (for a feed) - - endParam (for a feed) - - ANY OF THE JQUERY $.ajax OPTIONS - allows for easily changing from GET to POST and sending additional parameters (issue 386) - allows for easily attaching ajax handlers such as `error` (issue 754) - allows for turning caching on (issue 355) - - Google Calendar feeds are now specified differently: - - specify a simple string of your feed's URL - - specify an *object* with a `url` property of your feed's URL. - you can include any of the new Event-Source options in this object. - - the old `$.fullCalendar.gcalFeed` method still works - - no more IE7 SSL popup (issue 504) - - remove `cacheParam` - use json event source `cache` option instead - - latest jquery/jquery-ui - -version 1.4.11 (2/22/11) - - fixed rerenderEvents bug (issue 790) - - fixed bug with faulty dragging of events from all-day slot in agenda views - - bundled with jquery 1.5 and jquery-ui 1.8.9 - -version 1.4.10 (1/2/11) - - fixed bug with resizing event to different week in 5-day month view (issue 740) - - fixed bug with events not sticking after a removeEvents call (issue 757) - - fixed bug with underlying parseTime method, and other uses of parseInt (issue 688) - -version 1.4.9 (11/16/10) - - new algorithm for vertically stacking events (issue 111) - - resizing an event to a different week (issue 306) - - bug: some events not rendered with consecutive calls to addEventSource (issue 679) - -version 1.4.8 (10/16/10) - - ignoreTimezone option (set to `false` to process UTC offsets in ISO8601 dates) - - bugfixes - - event refetching not being called under certain conditions (issues 417, 554) - - event refetching being called multiple times under certain conditions (issues 586, 616) - - selection cannot be triggered by right mouse button (issue 558) - - agenda view left axis sized incorrectly (issue 465) - - IE js error when calendar is too narrow (issue 517) - - agenda view looks strange when no scrollbars (issue 235) - - improved parsing of ISO8601 dates with UTC offsets - - $.fullCalendar.version - - an internal refactor of the code, for easier future development and modularity - -version 1.4.7 (7/5/10) - - "dropping" external objects onto the calendar - - droppable (boolean, to turn on/off) - - dropAccept (to filter which events the calendar will accept) - - drop (trigger) - - selectable options can now be specified with a View Option Hash - - bugfixes - - dragged & reverted events having wrong time text (issue 406) - - bug rendering events that have an endtime with seconds, but no hours/minutes (issue 477) - - gotoDate date overflow bug (issue 429) - - wrong date reported when clicking on edge of last column in agenda views (412) - - support newlines in event titles - - select/unselect callbacks now passes native js event - -version 1.4.6 (5/31/10) - - "selecting" days or timeslots - - options: selectable, selectHelper, unselectAuto, unselectCancel - - callbacks: select, unselect - - methods: select, unselect - - when dragging an event, the highlighting reflects the duration of the event - - code compressing by Google Closure Compiler - - bundled with jQuery 1.4.2 and jQuery UI 1.8.1 - -version 1.4.5 (2/21/10) - - lazyFetching option, which can force the calendar to fetch events on every view/date change - - scroll state of agenda views are preserved when switching back to view - - bugfixes - - calling methods on an uninitialized fullcalendar throws error - - IE6/7 bug where an entire view becomes invisible (issue 320) - - error when rendering a hidden calendar (in jquery ui tabs for example) in IE (issue 340) - - interconnected bugs related to calendar resizing and scrollbars - - when switching views or clicking prev/next, calendar would "blink" (issue 333) - - liquid-width calendar's events shifted (depending on initial height of browser) (issue 341) - - more robust underlying algorithm for calendar resizing - -version 1.4.4 (2/3/10) - - optimized event rendering in all views (events render in 1/10 the time) - - gotoDate() does not force the calendar to unnecessarily rerender - - render() method now correctly readjusts height - -version 1.4.3 (12/22/09) - - added destroy method - - Google Calendar event pages respect currentTimezone - - caching now handled by jQuery's ajax - - protection from setting aspectRatio to zero - - bugfixes - - parseISO8601 and DST caused certain events to display day before - - button positioning problem in IE6 - - ajax event source removed after recently being added, events still displayed - - event not displayed when end is an empty string - - dynamically setting calendar height when no events have been fetched, throws error - -version 1.4.2 (12/02/09) - - eventAfterRender trigger - - getDate & getView methods - - height & contentHeight options (explicitly sets the pixel height) - - minTime & maxTime options (restricts shown hours in agenda view) - - getters [for all options] and setters [for height, contentHeight, and aspectRatio ONLY! stay tuned..] - - render method now readjusts calendar's size - - bugfixes - - lightbox scripts that use iframes (like fancybox) - - day-of-week classNames were off when firstDay=1 - - guaranteed space on right side of agenda events (even when stacked) - - accepts ISO8601 dates with a space (instead of 'T') - -version 1.4.1 (10/31/09) - - can exclude weekends with new 'weekends' option - - gcal feed 'currentTimezone' option - - bugfixes - - year/month/date option sometimes wouldn't set correctly (depending on current date) - - daylight savings issue caused agenda views to start at 1am (for BST users) - - cleanup of gcal.js code - -version 1.4 (10/19/09) - - agendaWeek and agendaDay views - - added some options for agenda views: - - allDaySlot - - allDayText - - firstHour - - slotMinutes - - defaultEventMinutes - - axisFormat - - modified some existing options/triggers to work with agenda views: - - dragOpacity and timeFormat can now accept a "View Hash" (a new concept) - - dayClick now has an allDay parameter - - eventDrop now has an an allDay parameter - (this will affect those who use revertFunc, adjust parameter list) - - added 'prevYear' and 'nextYear' for buttons in header - - minor change for theme users, ui-state-hover not applied to active/inactive buttons - - added event-color-changing example in docs - - better defaults for right-to-left themed button icons - -version 1.3.2 (10/13/09) - - Bugfixes (please upgrade from 1.3.1!) - - squashed potential infinite loop when addMonths and addDays - is called with an invalid date - - $.fullCalendar.parseDate() now correctly parses IETF format - - when switching views, the 'today' button sticks inactive, fixed - - gotoDate now can accept a single Date argument - - documentation for changes in 1.3.1 and 1.3.2 now on website - -version 1.3.1 (9/30/09) - - Important Bugfixes (please upgrade from 1.3!) - - When current date was late in the month, for long months, and prev/next buttons - were clicked in month-view, some months would be skipped/repeated - - In certain time zones, daylight savings time would cause certain days - to be misnumbered in month-view - - Subtle change in way week interval is chosen when switching from month to basicWeek/basicDay view - - Added 'allDayDefault' option - - Added 'changeView' and 'render' methods - -version 1.3 (9/21/09) - - different 'views': month/basicWeek/basicDay - - more flexible 'header' system for buttons - - themable by jQuery UI themes - - resizable events (require jQuery UI resizable plugin) - - rescoped & rewritten CSS, enhanced default look - - cleaner css & rendering techniques for right-to-left - - reworked options & API to support multiple views / be consistent with jQuery UI - - refactoring of entire codebase - - broken into different JS & CSS files, assembled w/ build scripts - - new test suite for new features, uses firebug-lite - - refactored docs - - Options - + date - + defaultView - + aspectRatio - + disableResizing - + monthNames (use instead of $.fullCalendar.monthNames) - + monthNamesShort (use instead of $.fullCalendar.monthAbbrevs) - + dayNames (use instead of $.fullCalendar.dayNames) - + dayNamesShort (use instead of $.fullCalendar.dayAbbrevs) - + theme - + buttonText - + buttonIcons - x draggable -> editable/disableDragging - x fixedWeeks -> weekMode - x abbrevDayHeadings -> columnFormat - x buttons/title -> header - x eventDragOpacity -> dragOpacity - x eventRevertDuration -> dragRevertDuration - x weekStart -> firstDay - x rightToLeft -> isRTL - x showTime (use 'allDay' CalEvent property instead) - - Triggered Actions - + eventResizeStart - + eventResizeStop - + eventResize - x monthDisplay -> viewDisplay - x resize -> windowResize - 'eventDrop' params changed, can revert if ajax cuts out - - CalEvent Properties - x showTime -> allDay - x draggable -> editable - 'end' is now INCLUSIVE when allDay=true - 'url' now produces a real <a> tag, more native clicking/tab behavior - - Methods: - + renderEvent - x prevMonth -> prev - x nextMonth -> next - x prevYear/nextYear -> moveDate - x refresh -> rerenderEvents/refetchEvents - x removeEvent -> removeEvents - x getEventsByID -> clientEvents - - Utilities: - 'formatDate' format string completely changed (inspired by jQuery UI datepicker + datejs) - 'formatDates' added to support date-ranges - - Google Calendar Options: - x draggable -> editable - - Bugfixes - - gcal extension fetched 25 results max, now fetches all - -version 1.2.1 (6/29/09) - - bugfixes - - allows and corrects invalid end dates for events - - doesn't throw an error in IE while rendering when display:none - - fixed 'loading' callback when used w/ multiple addEventSource calls - - gcal className can now be an array - -version 1.2 (5/31/09) - - expanded API - - 'className' CalEvent attribute - - 'source' CalEvent attribute - - dynamically get/add/remove/update events of current month - - locale improvements: change month/day name text - - better date formatting ($.fullCalendar.formatDate) - - multiple 'event sources' allowed - - dynamically add/remove event sources - - options for prevYear and nextYear buttons - - docs have been reworked (include addition of Google Calendar docs) - - changed behavior of parseDate for number strings - (now interpets as unix timestamp, not MS times) - - bugfixes - - rightToLeft month start bug - - off-by-one errors with month formatting commands - - events from previous months sticking when clicking prev/next quickly - - Google Calendar API changed to work w/ multiple event sources - - can also provide 'className' and 'draggable' options - - date utilties moved from $ to $.fullCalendar - - more documentation in source code - - minified version of fullcalendar.js - - test suit (available from svn) - - top buttons now use <button> w/ an inner <span> for better css cusomization - - thus CSS has changed. IF UPGRADING FROM PREVIOUS VERSIONS, - UPGRADE YOUR FULLCALENDAR.CSS FILE!!! - -version 1.1 (5/10/09) - - Added the following options: - - weekStart - - rightToLeft - - titleFormat - - timeFormat - - cacheParam - - resize - - Fixed rendering bugs - - Opera 9.25 (events placement & window resizing) - - IE6 (window resizing) - - Optimized window resizing for ALL browsers - - Events on same day now sorted by start time (but first by timespan) - - Correct z-index when dragging - - Dragging contained in overflow DIV for IE6 - - Modified fullcalendar.css - - for right-to-left support - - for variable start-of-week - - for IE6 resizing bug - - for THEAD and TBODY (in 1.0, just used TBODY, restructured in 1.1) - - IF UPGRADING FROM FULLCALENDAR 1.0, YOU MUST UPGRADE FULLCALENDAR.CSS - !!!!!!!!!!! diff --git a/3rdparty/fullcalendar/css/fullcalendar.css b/3rdparty/fullcalendar/css/fullcalendar.css deleted file mode 100644 index 4e9e95e894f7732cc0e47f11a1864150dcd2389d..0000000000000000000000000000000000000000 --- a/3rdparty/fullcalendar/css/fullcalendar.css +++ /dev/null @@ -1,616 +0,0 @@ -/* - * FullCalendar v1.5.2 Stylesheet - * - * Copyright (c) 2011 Adam Shaw - * Dual licensed under the MIT and GPL licenses, located in - * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. - * - * Date: Sun Aug 21 22:06:09 2011 -0700 - * - */ - - -.fc { - direction: ltr; - text-align: left; - } - -.fc table { - border-collapse: collapse; - border-spacing: 0; - } - -html .fc, -.fc table { - font-size: 1em; - } - -.fc td, -.fc th { - padding: 0; - vertical-align: top; - } - - - -/* Header -------------------------------------------------------------------------*/ - -.fc-header td { - white-space: nowrap; - } - -.fc-header-left { - width: 25%; - text-align: left; - } - -.fc-header-center { - text-align: center; - } - -.fc-header-right { - width: 25%; - text-align: right; - } - -.fc-header-title { - display: inline-block; - vertical-align: top; - } - -.fc-header-title h2 { - margin-top: 0; - white-space: nowrap; - } - -.fc .fc-header-space { - padding-left: 10px; - } - -.fc-header .fc-button { - margin-bottom: 1em; - vertical-align: top; - } - -/* buttons edges butting together */ - -.fc-header .fc-button { - margin-right: -1px; - } - -.fc-header .fc-corner-right { - margin-right: 1px; /* back to normal */ - } - -.fc-header .ui-corner-right { - margin-right: 0; /* back to normal */ - } - -/* button layering (for border precedence) */ - -.fc-header .fc-state-hover, -.fc-header .ui-state-hover { - z-index: 2; - } - -.fc-header .fc-state-down { - z-index: 3; - } - -.fc-header .fc-state-active, -.fc-header .ui-state-active { - z-index: 4; - } - - - -/* Content -------------------------------------------------------------------------*/ - -.fc-content { - clear: both; - } - -.fc-view { - width: 100%; /* needed for view switching (when view is absolute) */ - overflow: hidden; - } - - - -/* Cell Styles -------------------------------------------------------------------------*/ - -.fc-widget-header, /* <th>, usually */ -.fc-widget-content { /* <td>, usually */ - border: 1px solid #ccc; - } - -.fc-state-highlight { /* <td> today cell */ /* TODO: add .fc-today to <th> */ - background: #ffc; - } - -.fc-cell-overlay { /* semi-transparent rectangle while dragging */ - background: #9cf; - opacity: .2; - filter: alpha(opacity=20); /* for IE */ - } - - - -/* Buttons -------------------------------------------------------------------------*/ - -.fc-button { - position: relative; - display: inline-block; - cursor: pointer; - } - -.fc-state-default { /* non-theme */ - border-style: solid; - border-width: 1px 0; - } - -.fc-button-inner { - position: relative; - float: left; - overflow: hidden; - } - -.fc-state-default .fc-button-inner { /* non-theme */ - border-style: solid; - border-width: 0 1px; - } - -.fc-button-content { - position: relative; - float: left; - height: 1.9em; - line-height: 1.9em; - padding: 0 .6em; - white-space: nowrap; - } - -/* icon (for jquery ui) */ - -.fc-button-content .fc-icon-wrap { - position: relative; - float: left; - top: 50%; - } - -.fc-button-content .ui-icon { - position: relative; - float: left; - margin-top: -50%; - *margin-top: 0; - *top: -50%; - } - -/* gloss effect */ - -.fc-state-default .fc-button-effect { - position: absolute; - top: 50%; - left: 0; - } - -.fc-state-default .fc-button-effect span { - position: absolute; - top: -100px; - left: 0; - width: 500px; - height: 100px; - border-width: 100px 0 0 1px; - border-style: solid; - border-color: #fff; - background: #444; - opacity: .09; - filter: alpha(opacity=9); - } - -/* button states (determines colors) */ - -.fc-state-default, -.fc-state-default .fc-button-inner { - border-style: solid; - border-color: #ccc #bbb #aaa; - background: #F3F3F3; - color: #000; - } - -.fc-state-hover, -.fc-state-hover .fc-button-inner { - border-color: #999; - } - -.fc-state-down, -.fc-state-down .fc-button-inner { - border-color: #555; - background: #777; - } - -.fc-state-active, -.fc-state-active .fc-button-inner { - border-color: #555; - background: #777; - color: #fff; - } - -.fc-state-disabled, -.fc-state-disabled .fc-button-inner { - color: #999; - border-color: #ddd; - } - -.fc-state-disabled { - cursor: default; - } - -.fc-state-disabled .fc-button-effect { - display: none; - } - - - -/* Global Event Styles -------------------------------------------------------------------------*/ - -.fc-event { - border-style: solid; - border-width: 0; - font-size: .85em; - cursor: default; - } - -a.fc-event, -.fc-event-draggable { - cursor: pointer; - } - -a.fc-event { - text-decoration: none; - } - -.fc-rtl .fc-event { - text-align: right; - } - -.fc-event-skin { - border-color: #36c; /* default BORDER color */ - background-color: #36c; /* default BACKGROUND color */ - color: #fff; /* default TEXT color */ - } - -.fc-event-inner { - position: relative; - width: 100%; - height: 100%; - border-style: solid; - border-width: 0; - overflow: hidden; - } - -.fc-event-time, -.fc-event-title { - padding: 0 1px; - } - -.fc .ui-resizable-handle { /*** TODO: don't use ui-resizable anymore, change class ***/ - display: block; - position: absolute; - z-index: 99999; - overflow: hidden; /* hacky spaces (IE6/7) */ - font-size: 300%; /* */ - line-height: 50%; /* */ - } - - - -/* Horizontal Events -------------------------------------------------------------------------*/ - -.fc-event-hori { - border-width: 1px 0; - margin-bottom: 1px; - } - -/* resizable */ - -.fc-event-hori .ui-resizable-e { - top: 0 !important; /* importants override pre jquery ui 1.7 styles */ - right: -3px !important; - width: 7px !important; - height: 100% !important; - cursor: e-resize; - } - -.fc-event-hori .ui-resizable-w { - top: 0 !important; - left: -3px !important; - width: 7px !important; - height: 100% !important; - cursor: w-resize; - } - -.fc-event-hori .ui-resizable-handle { - _padding-bottom: 14px; /* IE6 had 0 height */ - } - - - -/* Fake Rounded Corners (for buttons and events) -------------------------------------------------------------*/ - -.fc-corner-left { - margin-left: 1px; - } - -.fc-corner-left .fc-button-inner, -.fc-corner-left .fc-event-inner { - margin-left: -1px; - } - -.fc-corner-right { - margin-right: 1px; - } - -.fc-corner-right .fc-button-inner, -.fc-corner-right .fc-event-inner { - margin-right: -1px; - } - -.fc-corner-top { - margin-top: 1px; - } - -.fc-corner-top .fc-event-inner { - margin-top: -1px; - } - -.fc-corner-bottom { - margin-bottom: 1px; - } - -.fc-corner-bottom .fc-event-inner { - margin-bottom: -1px; - } - - - -/* Fake Rounded Corners SPECIFICALLY FOR EVENTS ------------------------------------------------------------------*/ - -.fc-corner-left .fc-event-inner { - border-left-width: 1px; - } - -.fc-corner-right .fc-event-inner { - border-right-width: 1px; - } - -.fc-corner-top .fc-event-inner { - border-top-width: 1px; - } - -.fc-corner-bottom .fc-event-inner { - border-bottom-width: 1px; - } - - - -/* Reusable Separate-border Table -------------------------------------------------------------*/ - -table.fc-border-separate { - border-collapse: separate; - } - -.fc-border-separate th, -.fc-border-separate td { - border-width: 1px 0 0 1px; - } - -.fc-border-separate th.fc-last, -.fc-border-separate td.fc-last { - border-right-width: 1px; - } - -.fc-border-separate tr.fc-last th, -.fc-border-separate tr.fc-last td { - border-bottom-width: 1px; - } - -.fc-border-separate tbody tr.fc-first td, -.fc-border-separate tbody tr.fc-first th { - border-top-width: 0; - } - - - -/* Month View, Basic Week View, Basic Day View -------------------------------------------------------------------------*/ - -.fc-grid th { - text-align: center; - } - -.fc-grid .fc-day-number { - float: right; - padding: 0 2px; - } - -.fc-grid .fc-other-month .fc-day-number { - opacity: 0.3; - filter: alpha(opacity=30); /* for IE */ - /* opacity with small font can sometimes look too faded - might want to set the 'color' property instead - making day-numbers bold also fixes the problem */ - } - -.fc-grid .fc-day-content { - clear: both; - padding: 2px 2px 1px; /* distance between events and day edges */ - } - -/* event styles */ - -.fc-grid .fc-event-time { - font-weight: bold; - } - -/* right-to-left */ - -.fc-rtl .fc-grid .fc-day-number { - float: left; - } - -.fc-rtl .fc-grid .fc-event-time { - float: right; - } - - - -/* Agenda Week View, Agenda Day View -------------------------------------------------------------------------*/ - -.fc-agenda table { - border-collapse: separate; - } - -.fc-agenda-days th { - text-align: center; - } - -.fc-agenda .fc-agenda-axis { - width: 50px; - padding: 0 4px; - vertical-align: middle; - text-align: right; - white-space: nowrap; - font-weight: normal; - } - -.fc-agenda .fc-day-content { - padding: 2px 2px 1px; - } - -/* make axis border take precedence */ - -.fc-agenda-days .fc-agenda-axis { - border-right-width: 1px; - } - -.fc-agenda-days .fc-col0 { - border-left-width: 0; - } - -/* all-day area */ - -.fc-agenda-allday th { - border-width: 0 1px; - } - -.fc-agenda-allday .fc-day-content { - min-height: 34px; /* TODO: doesnt work well in quirksmode */ - _height: 34px; - } - -/* divider (between all-day and slots) */ - -.fc-agenda-divider-inner { - height: 2px; - overflow: hidden; - } - -.fc-widget-header .fc-agenda-divider-inner { - background: #eee; - } - -/* slot rows */ - -.fc-agenda-slots th { - border-width: 1px 1px 0; - } - -.fc-agenda-slots td { - border-width: 1px 0 0; - background: none; - } - -.fc-agenda-slots td div { - height: 20px; - } - -.fc-agenda-slots tr.fc-slot0 th, -.fc-agenda-slots tr.fc-slot0 td { - border-top-width: 0; - } - -.fc-agenda-slots tr.fc-minor th, -.fc-agenda-slots tr.fc-minor td { - border-top-style: dotted; - } - -.fc-agenda-slots tr.fc-minor th.ui-widget-header { - *border-top-style: solid; /* doesn't work with background in IE6/7 */ - } - - - -/* Vertical Events -------------------------------------------------------------------------*/ - -.fc-event-vert { - border-width: 0 1px; - } - -.fc-event-vert .fc-event-head, -.fc-event-vert .fc-event-content { - position: relative; - z-index: 2; - width: 100%; - overflow: hidden; - } - -.fc-event-vert .fc-event-time { - white-space: nowrap; - font-size: 10px; - } - -.fc-event-vert .fc-event-bg { /* makes the event lighter w/ a semi-transparent overlay */ - position: absolute; - z-index: 1; - top: 0; - left: 0; - width: 100%; - height: 100%; - background: #fff; - opacity: .3; - filter: alpha(opacity=30); - } - -.fc .ui-draggable-dragging .fc-event-bg, /* TODO: something nicer like .fc-opacity */ -.fc-select-helper .fc-event-bg { - display: none\9; /* for IE6/7/8. nested opacity filters while dragging don't work */ - } - -/* resizable */ - -.fc-event-vert .ui-resizable-s { - bottom: 0 !important; /* importants override pre jquery ui 1.7 styles */ - width: 100% !important; - height: 8px !important; - overflow: hidden !important; - line-height: 8px !important; - font-size: 11px !important; - font-family: monospace; - text-align: center; - cursor: s-resize; - } - -.fc-agenda .ui-resizable-resizing { /* TODO: better selector */ - _overflow: hidden; - } diff --git a/3rdparty/fullcalendar/css/fullcalendar.print.css b/3rdparty/fullcalendar/css/fullcalendar.print.css deleted file mode 100644 index 18c7c9b10af0e0ac0caae846249fb4b1d1fec3af..0000000000000000000000000000000000000000 --- a/3rdparty/fullcalendar/css/fullcalendar.print.css +++ /dev/null @@ -1,59 +0,0 @@ -/* - * FullCalendar v1.5.2 Print Stylesheet - * - * Include this stylesheet on your page to get a more printer-friendly calendar. - * When including this stylesheet, use the media='print' attribute of the <link> tag. - * Make sure to include this stylesheet IN ADDITION to the regular fullcalendar.css. - * - * Copyright (c) 2011 Adam Shaw - * Dual licensed under the MIT and GPL licenses, located in - * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. - * - * Date: Sun Aug 21 22:06:09 2011 -0700 - * - */ - - - /* Events ------------------------------------------------------*/ - -.fc-event-skin { - background: none !important; - color: #000 !important; - } - -/* horizontal events */ - -.fc-event-hori { - border-width: 0 0 1px 0 !important; - border-bottom-style: dotted !important; - border-bottom-color: #000 !important; - padding: 1px 0 0 0 !important; - } - -.fc-event-hori .fc-event-inner { - border-width: 0 !important; - padding: 0 1px !important; - } - -/* vertical events */ - -.fc-event-vert { - border-width: 0 0 0 1px !important; - border-left-style: dotted !important; - border-left-color: #000 !important; - padding: 0 1px 0 0 !important; - } - -.fc-event-vert .fc-event-inner { - border-width: 0 !important; - padding: 1px 0 !important; - } - -.fc-event-bg { - display: none !important; - } - -.fc-event .ui-resizable-handle { - display: none !important; - } diff --git a/3rdparty/fullcalendar/js/fullcalendar.js b/3rdparty/fullcalendar/js/fullcalendar.js deleted file mode 100644 index fcdafbfca49712aaba9a07a9206b48aba4cb3536..0000000000000000000000000000000000000000 --- a/3rdparty/fullcalendar/js/fullcalendar.js +++ /dev/null @@ -1,5210 +0,0 @@ -/** - * @preserve - * FullCalendar v1.5.2 - * http://arshaw.com/fullcalendar/ - * - * Use fullcalendar.css for basic styling. - * For event drag & drop, requires jQuery UI draggable. - * For event resizing, requires jQuery UI resizable. - * - * Copyright (c) 2011 Adam Shaw - * Dual licensed under the MIT and GPL licenses, located in - * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. - * - * Date: Sun Aug 21 22:06:09 2011 -0700 - * - */ - -(function($, undefined) { - - -var defaults = { - - // display - defaultView: 'month', - aspectRatio: 1.35, - header: { - left: 'title', - center: '', - right: 'today prev,next' - }, - weekends: true, - - // editing - //editable: false, - //disableDragging: false, - //disableResizing: false, - - allDayDefault: true, - ignoreTimezone: true, - - // event ajax - lazyFetching: true, - startParam: 'start', - endParam: 'end', - - // time formats - titleFormat: { - month: 'MMMM yyyy', - week: "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", - day: 'dddd, MMM d, yyyy' - }, - columnFormat: { - month: 'ddd', - week: 'ddd M/d', - day: 'dddd M/d' - }, - timeFormat: { // for event elements - '': 'h(:mm)t' // default - }, - - // locale - isRTL: false, - firstDay: 0, - monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'], - monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], - dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'], - dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'], - buttonText: { - prev: ' ◄ ', - next: ' ► ', - prevYear: ' << ', - nextYear: ' >> ', - today: 'today', - month: 'month', - week: 'week', - day: 'day' - }, - - // jquery-ui theming - theme: false, - buttonIcons: { - prev: 'circle-triangle-w', - next: 'circle-triangle-e' - }, - - //selectable: false, - unselectAuto: true, - - dropAccept: '*' - -}; - -// right-to-left defaults -var rtlDefaults = { - header: { - left: 'next,prev today', - center: '', - right: 'title' - }, - buttonText: { - prev: ' ► ', - next: ' ◄ ', - prevYear: ' >> ', - nextYear: ' << ' - }, - buttonIcons: { - prev: 'circle-triangle-e', - next: 'circle-triangle-w' - } -}; - - - -var fc = $.fullCalendar = { version: "1.5.2" }; -var fcViews = fc.views = {}; - - -$.fn.fullCalendar = function(options) { - - - // method calling - if (typeof options == 'string') { - var args = Array.prototype.slice.call(arguments, 1); - var res; - this.each(function() { - var calendar = $.data(this, 'fullCalendar'); - if (calendar && $.isFunction(calendar[options])) { - var r = calendar[options].apply(calendar, args); - if (res === undefined) { - res = r; - } - if (options == 'destroy') { - $.removeData(this, 'fullCalendar'); - } - } - }); - if (res !== undefined) { - return res; - } - return this; - } - - - // would like to have this logic in EventManager, but needs to happen before options are recursively extended - var eventSources = options.eventSources || []; - delete options.eventSources; - if (options.events) { - eventSources.push(options.events); - delete options.events; - } - - - options = $.extend(true, {}, - defaults, - (options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {}, - options - ); - - - this.each(function(i, _element) { - var element = $(_element); - var calendar = new Calendar(element, options, eventSources); - element.data('fullCalendar', calendar); // TODO: look into memory leak implications - calendar.render(); - }); - - - return this; - -}; - - -// function for adding/overriding defaults -function setDefaults(d) { - $.extend(true, defaults, d); -} - - - - -function Calendar(element, options, eventSources) { - var t = this; - - - // exports - t.options = options; - t.render = render; - t.destroy = destroy; - t.refetchEvents = refetchEvents; - t.reportEvents = reportEvents; - t.reportEventChange = reportEventChange; - t.rerenderEvents = rerenderEvents; - t.changeView = changeView; - t.select = select; - t.unselect = unselect; - t.prev = prev; - t.next = next; - t.prevYear = prevYear; - t.nextYear = nextYear; - t.today = today; - t.gotoDate = gotoDate; - t.incrementDate = incrementDate; - t.formatDate = function(format, date) { return formatDate(format, date, options) }; - t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) }; - t.getDate = getDate; - t.getView = getView; - t.option = option; - t.trigger = trigger; - - - // imports - EventManager.call(t, options, eventSources); - var isFetchNeeded = t.isFetchNeeded; - var fetchEvents = t.fetchEvents; - - - // locals - var _element = element[0]; - var header; - var headerElement; - var content; - var tm; // for making theme classes - var currentView; - var viewInstances = {}; - var elementOuterWidth; - var suggestedViewHeight; - var absoluteViewElement; - var resizeUID = 0; - var ignoreWindowResize = 0; - var date = new Date(); - var events = []; - var _dragElement; - - - - /* Main Rendering - -----------------------------------------------------------------------------*/ - - - setYMD(date, options.year, options.month, options.date); - - - function render(inc) { - if (!content) { - initialRender(); - }else{ - calcSize(); - markSizesDirty(); - markEventsDirty(); - renderView(inc); - } - } - - - function initialRender() { - tm = options.theme ? 'ui' : 'fc'; - element.addClass('fc'); - if (options.isRTL) { - element.addClass('fc-rtl'); - } - if (options.theme) { - element.addClass('ui-widget'); - } - content = $("<div class='fc-content' style='position:relative'/>") - .prependTo(element); - header = new Header(t, options); - headerElement = header.render(); - if (headerElement) { - element.prepend(headerElement); - } - changeView(options.defaultView); - $(window).resize(windowResize); - // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize - if (!bodyVisible()) { - lateRender(); - } - } - - - // called when we know the calendar couldn't be rendered when it was initialized, - // but we think it's ready now - function lateRender() { - setTimeout(function() { // IE7 needs this so dimensions are calculated correctly - if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once - renderView(); - } - },0); - } - - - function destroy() { - $(window).unbind('resize', windowResize); - header.destroy(); - content.remove(); - element.removeClass('fc fc-rtl ui-widget'); - } - - - - function elementVisible() { - return _element.offsetWidth !== 0; - } - - - function bodyVisible() { - return $('body')[0].offsetWidth !== 0; - } - - - - /* View Rendering - -----------------------------------------------------------------------------*/ - - // TODO: improve view switching (still weird transition in IE, and FF has whiteout problem) - - function changeView(newViewName) { - if (!currentView || newViewName != currentView.name) { - ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached - - unselect(); - - var oldView = currentView; - var newViewElement; - - if (oldView) { - (oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera) - setMinHeight(content, content.height()); - oldView.element.hide(); - }else{ - setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated - } - content.css('overflow', 'hidden'); - - currentView = viewInstances[newViewName]; - if (currentView) { - currentView.element.show(); - }else{ - currentView = viewInstances[newViewName] = new fcViews[newViewName]( - newViewElement = absoluteViewElement = - $("<div class='fc-view fc-view-" + newViewName + "' style='position:absolute'/>") - .appendTo(content), - t // the calendar object - ); - } - - if (oldView) { - header.deactivateButton(oldView.name); - } - header.activateButton(newViewName); - - renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null - - content.css('overflow', ''); - if (oldView) { - setMinHeight(content, 1); - } - - if (!newViewElement) { - (currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera) - } - - ignoreWindowResize--; - } - } - - - - function renderView(inc) { - if (elementVisible()) { - ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached - - unselect(); - - if (suggestedViewHeight === undefined) { - calcSize(); - } - - var forceEventRender = false; - if (!currentView.start || inc || date < currentView.start || date >= currentView.end) { - // view must render an entire new date range (and refetch/render events) - currentView.render(date, inc || 0); // responsible for clearing events - setSize(true); - forceEventRender = true; - } - else if (currentView.sizeDirty) { - // view must resize (and rerender events) - currentView.clearEvents(); - setSize(); - forceEventRender = true; - } - else if (currentView.eventsDirty) { - currentView.clearEvents(); - forceEventRender = true; - } - currentView.sizeDirty = false; - currentView.eventsDirty = false; - updateEvents(forceEventRender); - - elementOuterWidth = element.outerWidth(); - - header.updateTitle(currentView.title); - var today = new Date(); - if (today >= currentView.start && today < currentView.end) { - header.disableButton('today'); - }else{ - header.enableButton('today'); - } - - ignoreWindowResize--; - currentView.trigger('viewDisplay', _element); - } - } - - - - /* Resizing - -----------------------------------------------------------------------------*/ - - - function updateSize() { - markSizesDirty(); - if (elementVisible()) { - calcSize(); - setSize(); - unselect(); - currentView.clearEvents(); - currentView.renderEvents(events); - currentView.sizeDirty = false; - } - } - - - function markSizesDirty() { - $.each(viewInstances, function(i, inst) { - inst.sizeDirty = true; - }); - } - - - function calcSize() { - if (options.contentHeight) { - suggestedViewHeight = options.contentHeight; - } - else if (options.height) { - suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content); - } - else { - suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5)); - } - } - - - function setSize(dateChanged) { // todo: dateChanged? - ignoreWindowResize++; - currentView.setHeight(suggestedViewHeight, dateChanged); - if (absoluteViewElement) { - absoluteViewElement.css('position', 'relative'); - absoluteViewElement = null; - } - currentView.setWidth(content.width(), dateChanged); - ignoreWindowResize--; - } - - - function windowResize() { - if (!ignoreWindowResize) { - if (currentView.start) { // view has already been rendered - var uid = ++resizeUID; - setTimeout(function() { // add a delay - if (uid == resizeUID && !ignoreWindowResize && elementVisible()) { - if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) { - ignoreWindowResize++; // in case the windowResize callback changes the height - updateSize(); - currentView.trigger('windowResize', _element); - ignoreWindowResize--; - } - } - }, 200); - }else{ - // calendar must have been initialized in a 0x0 iframe that has just been resized - lateRender(); - } - } - } - - - - /* Event Fetching/Rendering - -----------------------------------------------------------------------------*/ - - - // fetches events if necessary, rerenders events if necessary (or if forced) - function updateEvents(forceRender) { - if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) { - refetchEvents(); - } - else if (forceRender) { - rerenderEvents(); - } - } - - - function refetchEvents() { - fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents - } - - - // called when event data arrives - function reportEvents(_events) { - events = _events; - rerenderEvents(); - } - - - // called when a single event's data has been changed - function reportEventChange(eventID) { - rerenderEvents(eventID); - } - - - // attempts to rerenderEvents - function rerenderEvents(modifiedEventID) { - markEventsDirty(); - if (elementVisible()) { - currentView.clearEvents(); - currentView.renderEvents(events, modifiedEventID); - currentView.eventsDirty = false; - } - } - - - function markEventsDirty() { - $.each(viewInstances, function(i, inst) { - inst.eventsDirty = true; - }); - } - - - - /* Selection - -----------------------------------------------------------------------------*/ - - - function select(start, end, allDay) { - currentView.select(start, end, allDay===undefined ? true : allDay); - } - - - function unselect() { // safe to be called before renderView - if (currentView) { - currentView.unselect(); - } - } - - - - /* Date - -----------------------------------------------------------------------------*/ - - - function prev() { - renderView(-1); - } - - - function next() { - renderView(1); - } - - - function prevYear() { - addYears(date, -1); - renderView(); - } - - - function nextYear() { - addYears(date, 1); - renderView(); - } - - - function today() { - date = new Date(); - renderView(); - } - - - function gotoDate(year, month, dateOfMonth) { - if (year instanceof Date) { - date = cloneDate(year); // provided 1 argument, a Date - }else{ - setYMD(date, year, month, dateOfMonth); - } - renderView(); - } - - - function incrementDate(years, months, days) { - if (years !== undefined) { - addYears(date, years); - } - if (months !== undefined) { - addMonths(date, months); - } - if (days !== undefined) { - addDays(date, days); - } - renderView(); - } - - - function getDate() { - return cloneDate(date); - } - - - - /* Misc - -----------------------------------------------------------------------------*/ - - - function getView() { - return currentView; - } - - - function option(name, value) { - if (value === undefined) { - return options[name]; - } - if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') { - options[name] = value; - updateSize(); - } - } - - - function trigger(name, thisObj) { - if (options[name]) { - return options[name].apply( - thisObj || _element, - Array.prototype.slice.call(arguments, 2) - ); - } - } - - - - /* External Dragging - ------------------------------------------------------------------------*/ - - if (options.droppable) { - $(document) - .bind('dragstart', function(ev, ui) { - var _e = ev.target; - var e = $(_e); - if (!e.parents('.fc').length) { // not already inside a calendar - var accept = options.dropAccept; - if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) { - _dragElement = _e; - currentView.dragStart(_dragElement, ev, ui); - } - } - }) - .bind('dragstop', function(ev, ui) { - if (_dragElement) { - currentView.dragStop(_dragElement, ev, ui); - _dragElement = null; - } - }); - } - - -} - -function Header(calendar, options) { - var t = this; - - - // exports - t.render = render; - t.destroy = destroy; - t.updateTitle = updateTitle; - t.activateButton = activateButton; - t.deactivateButton = deactivateButton; - t.disableButton = disableButton; - t.enableButton = enableButton; - - - // locals - var element = $([]); - var tm; - - - - function render() { - tm = options.theme ? 'ui' : 'fc'; - var sections = options.header; - if (sections) { - element = $("<table class='fc-header' style='width:100%'/>") - .append( - $("<tr/>") - .append(renderSection('left')) - .append(renderSection('center')) - .append(renderSection('right')) - ); - return element; - } - } - - - function destroy() { - element.remove(); - } - - - function renderSection(position) { - var e = $("<td class='fc-header-" + position + "'/>"); - var buttonStr = options.header[position]; - if (buttonStr) { - $.each(buttonStr.split(' '), function(i) { - if (i > 0) { - e.append("<span class='fc-header-space'/>"); - } - var prevButton; - $.each(this.split(','), function(j, buttonName) { - if (buttonName == 'title') { - e.append("<span class='fc-header-title'><h2> </h2></span>"); - if (prevButton) { - prevButton.addClass(tm + '-corner-right'); - } - prevButton = null; - }else{ - var buttonClick; - if (calendar[buttonName]) { - buttonClick = calendar[buttonName]; // calendar method - } - else if (fcViews[buttonName]) { - buttonClick = function() { - button.removeClass(tm + '-state-hover'); // forget why - calendar.changeView(buttonName); - }; - } - if (buttonClick) { - var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here? - var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here? - var button = $( - "<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" + - "<span class='fc-button-inner'>" + - "<span class='fc-button-content'>" + - (icon ? - "<span class='fc-icon-wrap'>" + - "<span class='ui-icon ui-icon-" + icon + "'/>" + - "</span>" : - text - ) + - "</span>" + - "<span class='fc-button-effect'><span></span></span>" + - "</span>" + - "</span>" - ); - if (button) { - button - .click(function() { - if (!button.hasClass(tm + '-state-disabled')) { - buttonClick(); - } - }) - .mousedown(function() { - button - .not('.' + tm + '-state-active') - .not('.' + tm + '-state-disabled') - .addClass(tm + '-state-down'); - }) - .mouseup(function() { - button.removeClass(tm + '-state-down'); - }) - .hover( - function() { - button - .not('.' + tm + '-state-active') - .not('.' + tm + '-state-disabled') - .addClass(tm + '-state-hover'); - }, - function() { - button - .removeClass(tm + '-state-hover') - .removeClass(tm + '-state-down'); - } - ) - .appendTo(e); - if (!prevButton) { - button.addClass(tm + '-corner-left'); - } - prevButton = button; - } - } - } - }); - if (prevButton) { - prevButton.addClass(tm + '-corner-right'); - } - }); - } - return e; - } - - - function updateTitle(html) { - element.find('h2') - .html(html); - } - - - function activateButton(buttonName) { - element.find('span.fc-button-' + buttonName) - .addClass(tm + '-state-active'); - } - - - function deactivateButton(buttonName) { - element.find('span.fc-button-' + buttonName) - .removeClass(tm + '-state-active'); - } - - - function disableButton(buttonName) { - element.find('span.fc-button-' + buttonName) - .addClass(tm + '-state-disabled'); - } - - - function enableButton(buttonName) { - element.find('span.fc-button-' + buttonName) - .removeClass(tm + '-state-disabled'); - } - - -} - -fc.sourceNormalizers = []; -fc.sourceFetchers = []; - -var ajaxDefaults = { - dataType: 'json', - cache: false -}; - -var eventGUID = 1; - - -function EventManager(options, _sources) { - var t = this; - - - // exports - t.isFetchNeeded = isFetchNeeded; - t.fetchEvents = fetchEvents; - t.addEventSource = addEventSource; - t.removeEventSource = removeEventSource; - t.updateEvent = updateEvent; - t.renderEvent = renderEvent; - t.removeEvents = removeEvents; - t.clientEvents = clientEvents; - t.normalizeEvent = normalizeEvent; - - - // imports - var trigger = t.trigger; - var getView = t.getView; - var reportEvents = t.reportEvents; - - - // locals - var stickySource = { events: [] }; - var sources = [ stickySource ]; - var rangeStart, rangeEnd; - var currentFetchID = 0; - var pendingSourceCnt = 0; - var loadingLevel = 0; - var cache = []; - - - for (var i=0; i<_sources.length; i++) { - _addEventSource(_sources[i]); - } - - - - /* Fetching - -----------------------------------------------------------------------------*/ - - - function isFetchNeeded(start, end) { - return !rangeStart || start < rangeStart || end > rangeEnd; - } - - - function fetchEvents(start, end) { - rangeStart = start; - rangeEnd = end; - cache = []; - var fetchID = ++currentFetchID; - var len = sources.length; - pendingSourceCnt = len; - for (var i=0; i<len; i++) { - fetchEventSource(sources[i], fetchID); - } - } - - - function fetchEventSource(source, fetchID) { - _fetchEventSource(source, function(events) { - if (fetchID == currentFetchID) { - if (events) { - for (var i=0; i<events.length; i++) { - events[i].source = source; - normalizeEvent(events[i]); - } - cache = cache.concat(events); - } - pendingSourceCnt--; - if (!pendingSourceCnt) { - reportEvents(cache); - } - } - }); - } - - - function _fetchEventSource(source, callback) { - var i; - var fetchers = fc.sourceFetchers; - var res; - for (i=0; i<fetchers.length; i++) { - res = fetchers[i](source, rangeStart, rangeEnd, callback); - if (res === true) { - // the fetcher is in charge. made its own async request - return; - } - else if (typeof res == 'object') { - // the fetcher returned a new source. process it - _fetchEventSource(res, callback); - return; - } - } - var events = source.events; - if (events) { - if ($.isFunction(events)) { - pushLoading(); - events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) { - callback(events); - popLoading(); - }); - } - else if ($.isArray(events)) { - callback(events); - } - else { - callback(); - } - }else{ - var url = source.url; - if (url) { - var success = source.success; - var error = source.error; - var complete = source.complete; - var data = $.extend({}, source.data || {}); - var startParam = firstDefined(source.startParam, options.startParam); - var endParam = firstDefined(source.endParam, options.endParam); - if (startParam) { - data[startParam] = Math.round(+rangeStart / 1000); - } - if (endParam) { - data[endParam] = Math.round(+rangeEnd / 1000); - } - pushLoading(); - $.ajax($.extend({}, ajaxDefaults, source, { - data: data, - success: function(events) { - events = events || []; - var res = applyAll(success, this, arguments); - if ($.isArray(res)) { - events = res; - } - callback(events); - }, - error: function() { - applyAll(error, this, arguments); - callback(); - }, - complete: function() { - applyAll(complete, this, arguments); - popLoading(); - } - })); - }else{ - callback(); - } - } - } - - - - /* Sources - -----------------------------------------------------------------------------*/ - - - function addEventSource(source) { - source = _addEventSource(source); - if (source) { - pendingSourceCnt++; - fetchEventSource(source, currentFetchID); // will eventually call reportEvents - } - } - - - function _addEventSource(source) { - if ($.isFunction(source) || $.isArray(source)) { - source = { events: source }; - } - else if (typeof source == 'string') { - source = { url: source }; - } - if (typeof source == 'object') { - normalizeSource(source); - sources.push(source); - return source; - } - } - - - function removeEventSource(source) { - sources = $.grep(sources, function(src) { - return !isSourcesEqual(src, source); - }); - // remove all client events from that source - cache = $.grep(cache, function(e) { - return !isSourcesEqual(e.source, source); - }); - reportEvents(cache); - } - - - - /* Manipulation - -----------------------------------------------------------------------------*/ - - - function updateEvent(event) { // update an existing event - var i, len = cache.length, e, - defaultEventEnd = getView().defaultEventEnd, // getView??? - startDelta = event.start - event._start, - endDelta = event.end ? - (event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end - : 0; // was null and event was just resized - for (i=0; i<len; i++) { - e = cache[i]; - if (e._id == event._id && e != event) { - e.start = new Date(+e.start + startDelta); - if (event.end) { - if (e.end) { - e.end = new Date(+e.end + endDelta); - }else{ - e.end = new Date(+defaultEventEnd(e) + endDelta); - } - }else{ - e.end = null; - } - e.title = event.title; - e.url = event.url; - e.allDay = event.allDay; - e.className = event.className; - e.editable = event.editable; - e.color = event.color; - e.backgroudColor = event.backgroudColor; - e.borderColor = event.borderColor; - e.textColor = event.textColor; - normalizeEvent(e); - } - } - normalizeEvent(event); - reportEvents(cache); - } - - - function renderEvent(event, stick) { - normalizeEvent(event); - if (!event.source) { - if (stick) { - stickySource.events.push(event); - event.source = stickySource; - } - cache.push(event); - } - reportEvents(cache); - } - - - function removeEvents(filter) { - if (!filter) { // remove all - cache = []; - // clear all array sources - for (var i=0; i<sources.length; i++) { - if ($.isArray(sources[i].events)) { - sources[i].events = []; - } - } - }else{ - if (!$.isFunction(filter)) { // an event ID - var id = filter + ''; - filter = function(e) { - return e._id == id; - }; - } - cache = $.grep(cache, filter, true); - // remove events from array sources - for (var i=0; i<sources.length; i++) { - if ($.isArray(sources[i].events)) { - sources[i].events = $.grep(sources[i].events, filter, true); - } - } - } - reportEvents(cache); - } - - - function clientEvents(filter) { - if ($.isFunction(filter)) { - return $.grep(cache, filter); - } - else if (filter) { // an event ID - filter += ''; - return $.grep(cache, function(e) { - return e._id == filter; - }); - } - return cache; // else, return all - } - - - - /* Loading State - -----------------------------------------------------------------------------*/ - - - function pushLoading() { - if (!loadingLevel++) { - trigger('loading', null, true); - } - } - - - function popLoading() { - if (!--loadingLevel) { - trigger('loading', null, false); - } - } - - - - /* Event Normalization - -----------------------------------------------------------------------------*/ - - - function normalizeEvent(event) { - var source = event.source || {}; - var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone); - event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + ''); - if (event.date) { - if (!event.start) { - event.start = event.date; - } - delete event.date; - } - event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone)); - event.end = parseDate(event.end, ignoreTimezone); - if (event.end && event.end <= event.start) { - event.end = null; - } - event._end = event.end ? cloneDate(event.end) : null; - if (event.allDay === undefined) { - event.allDay = firstDefined(source.allDayDefault, options.allDayDefault); - } - if (event.className) { - if (typeof event.className == 'string') { - event.className = event.className.split(/\s+/); - } - }else{ - event.className = []; - } - // TODO: if there is no start date, return false to indicate an invalid event - } - - - - /* Utils - ------------------------------------------------------------------------------*/ - - - function normalizeSource(source) { - if (source.className) { - // TODO: repeat code, same code for event classNames - if (typeof source.className == 'string') { - source.className = source.className.split(/\s+/); - } - }else{ - source.className = []; - } - var normalizers = fc.sourceNormalizers; - for (var i=0; i<normalizers.length; i++) { - normalizers[i](source); - } - } - - - function isSourcesEqual(source1, source2) { - return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2); - } - - - function getSourcePrimitive(source) { - return ((typeof source == 'object') ? (source.events || source.url) : '') || source; - } - - -} - - -fc.addDays = addDays; -fc.cloneDate = cloneDate; -fc.parseDate = parseDate; -fc.parseISO8601 = parseISO8601; -fc.parseTime = parseTime; -fc.formatDate = formatDate; -fc.formatDates = formatDates; - - - -/* Date Math ------------------------------------------------------------------------------*/ - -var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'], - DAY_MS = 86400000, - HOUR_MS = 3600000, - MINUTE_MS = 60000; - - -function addYears(d, n, keepTime) { - d.setFullYear(d.getFullYear() + n); - if (!keepTime) { - clearTime(d); - } - return d; -} - - -function addMonths(d, n, keepTime) { // prevents day overflow/underflow - if (+d) { // prevent infinite looping on invalid dates - var m = d.getMonth() + n, - check = cloneDate(d); - check.setDate(1); - check.setMonth(m); - d.setMonth(m); - if (!keepTime) { - clearTime(d); - } - while (d.getMonth() != check.getMonth()) { - d.setDate(d.getDate() + (d < check ? 1 : -1)); - } - } - return d; -} - - -function addDays(d, n, keepTime) { // deals with daylight savings - if (+d) { - var dd = d.getDate() + n, - check = cloneDate(d); - check.setHours(9); // set to middle of day - check.setDate(dd); - d.setDate(dd); - if (!keepTime) { - clearTime(d); - } - fixDate(d, check); - } - return d; -} - - -function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes - if (+d) { // prevent infinite looping on invalid dates - while (d.getDate() != check.getDate()) { - d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS); - } - } -} - - -function addMinutes(d, n) { - d.setMinutes(d.getMinutes() + n); - return d; -} - - -function clearTime(d) { - d.setHours(0); - d.setMinutes(0); - d.setSeconds(0); - d.setMilliseconds(0); - return d; -} - - -function cloneDate(d, dontKeepTime) { - if (dontKeepTime) { - return clearTime(new Date(+d)); - } - return new Date(+d); -} - - -function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1 - var i=0, d; - do { - d = new Date(1970, i++, 1); - } while (d.getHours()); // != 0 - return d; -} - - -function skipWeekend(date, inc, excl) { - inc = inc || 1; - while (!date.getDay() || (excl && date.getDay()==1 || !excl && date.getDay()==6)) { - addDays(date, inc); - } - return date; -} - - -function dayDiff(d1, d2) { // d1 - d2 - return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS); -} - - -function setYMD(date, y, m, d) { - if (y !== undefined && y != date.getFullYear()) { - date.setDate(1); - date.setMonth(0); - date.setFullYear(y); - } - if (m !== undefined && m != date.getMonth()) { - date.setDate(1); - date.setMonth(m); - } - if (d !== undefined) { - date.setDate(d); - } -} - - - -/* Date Parsing ------------------------------------------------------------------------------*/ - - -function parseDate(s, ignoreTimezone) { // ignoreTimezone defaults to true - if (typeof s == 'object') { // already a Date object - return s; - } - if (typeof s == 'number') { // a UNIX timestamp - return new Date(s * 1000); - } - if (typeof s == 'string') { - if (s.match(/^\d+(\.\d+)?$/)) { // a UNIX timestamp - return new Date(parseFloat(s) * 1000); - } - if (ignoreTimezone === undefined) { - ignoreTimezone = true; - } - return parseISO8601(s, ignoreTimezone) || (s ? new Date(s) : null); - } - // TODO: never return invalid dates (like from new Date(<string>)), return null instead - return null; -} - - -function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false - // derived from http://delete.me.uk/2005/03/iso8601.html - // TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html - var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/); - if (!m) { - return null; - } - var date = new Date(m[1], 0, 1); - if (ignoreTimezone || !m[13]) { - var check = new Date(m[1], 0, 1, 9, 0); - if (m[3]) { - date.setMonth(m[3] - 1); - check.setMonth(m[3] - 1); - } - if (m[5]) { - date.setDate(m[5]); - check.setDate(m[5]); - } - fixDate(date, check); - if (m[7]) { - date.setHours(m[7]); - } - if (m[8]) { - date.setMinutes(m[8]); - } - if (m[10]) { - date.setSeconds(m[10]); - } - if (m[12]) { - date.setMilliseconds(Number("0." + m[12]) * 1000); - } - fixDate(date, check); - }else{ - date.setUTCFullYear( - m[1], - m[3] ? m[3] - 1 : 0, - m[5] || 1 - ); - date.setUTCHours( - m[7] || 0, - m[8] || 0, - m[10] || 0, - m[12] ? Number("0." + m[12]) * 1000 : 0 - ); - if (m[14]) { - var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0); - offset *= m[15] == '-' ? 1 : -1; - date = new Date(+date + (offset * 60 * 1000)); - } - } - return date; -} - - -function parseTime(s) { // returns minutes since start of day - if (typeof s == 'number') { // an hour - return s * 60; - } - if (typeof s == 'object') { // a Date object - return s.getHours() * 60 + s.getMinutes(); - } - var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/); - if (m) { - var h = parseInt(m[1], 10); - if (m[3]) { - h %= 12; - if (m[3].toLowerCase().charAt(0) == 'p') { - h += 12; - } - } - return h * 60 + (m[2] ? parseInt(m[2], 10) : 0); - } -} - - - -/* Date Formatting ------------------------------------------------------------------------------*/ -// TODO: use same function formatDate(date, [date2], format, [options]) - - -function formatDate(date, format, options) { - return formatDates(date, null, format, options); -} - - -function formatDates(date1, date2, format, options) { - options = options || defaults; - var date = date1, - otherDate = date2, - i, len = format.length, c, - i2, formatter, - res = ''; - for (i=0; i<len; i++) { - c = format.charAt(i); - if (c == "'") { - for (i2=i+1; i2<len; i2++) { - if (format.charAt(i2) == "'") { - if (date) { - if (i2 == i+1) { - res += "'"; - }else{ - res += format.substring(i+1, i2); - } - i = i2; - } - break; - } - } - } - else if (c == '(') { - for (i2=i+1; i2<len; i2++) { - if (format.charAt(i2) == ')') { - var subres = formatDate(date, format.substring(i+1, i2), options); - if (parseInt(subres.replace(/\D/, ''), 10)) { - res += subres; - } - i = i2; - break; - } - } - } - else if (c == '[') { - for (i2=i+1; i2<len; i2++) { - if (format.charAt(i2) == ']') { - var subformat = format.substring(i+1, i2); - var subres = formatDate(date, subformat, options); - if (subres != formatDate(otherDate, subformat, options)) { - res += subres; - } - i = i2; - break; - } - } - } - else if (c == '{') { - date = date2; - otherDate = date1; - } - else if (c == '}') { - date = date1; - otherDate = date2; - } - else { - for (i2=len; i2>i; i2--) { - if (formatter = dateFormatters[format.substring(i, i2)]) { - if (date) { - res += formatter(date, options); - } - i = i2 - 1; - break; - } - } - if (i2 == i) { - if (date) { - res += c; - } - } - } - } - return res; -}; - - -var dateFormatters = { - s : function(d) { return d.getSeconds() }, - ss : function(d) { return zeroPad(d.getSeconds()) }, - m : function(d) { return d.getMinutes() }, - mm : function(d) { return zeroPad(d.getMinutes()) }, - h : function(d) { return d.getHours() % 12 || 12 }, - hh : function(d) { return zeroPad(d.getHours() % 12 || 12) }, - H : function(d) { return d.getHours() }, - HH : function(d) { return zeroPad(d.getHours()) }, - d : function(d) { return d.getDate() }, - dd : function(d) { return zeroPad(d.getDate()) }, - ddd : function(d,o) { return o.dayNamesShort[d.getDay()] }, - dddd: function(d,o) { return o.dayNames[d.getDay()] }, - M : function(d) { return d.getMonth() + 1 }, - MM : function(d) { return zeroPad(d.getMonth() + 1) }, - MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] }, - MMMM: function(d,o) { return o.monthNames[d.getMonth()] }, - yy : function(d) { return (d.getFullYear()+'').substring(2) }, - yyyy: function(d) { return d.getFullYear() }, - t : function(d) { return d.getHours() < 12 ? 'a' : 'p' }, - tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' }, - T : function(d) { return d.getHours() < 12 ? 'A' : 'P' }, - TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' }, - u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") }, - S : function(d) { - var date = d.getDate(); - if (date > 10 && date < 20) { - return 'th'; - } - return ['st', 'nd', 'rd'][date%10-1] || 'th'; - } -}; - - - -fc.applyAll = applyAll; - - -/* Event Date Math ------------------------------------------------------------------------------*/ - - -function exclEndDay(event) { - if (event.end) { - return _exclEndDay(event.end, event.allDay); - }else{ - return addDays(cloneDate(event.start), 1); - } -} - - -function _exclEndDay(end, allDay) { - end = cloneDate(end); - return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end); -} - - -function segCmp(a, b) { - return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start); -} - - -function segsCollide(seg1, seg2) { - return seg1.end > seg2.start && seg1.start < seg2.end; -} - - - -/* Event Sorting ------------------------------------------------------------------------------*/ - - -// event rendering utilities -function sliceSegs(events, visEventEnds, start, end) { - var segs = [], - i, len=events.length, event, - eventStart, eventEnd, - segStart, segEnd, - isStart, isEnd; - for (i=0; i<len; i++) { - event = events[i]; - eventStart = event.start; - eventEnd = visEventEnds[i]; - if (eventEnd > start && eventStart < end) { - if (eventStart < start) { - segStart = cloneDate(start); - isStart = false; - }else{ - segStart = eventStart; - isStart = true; - } - if (eventEnd > end) { - segEnd = cloneDate(end); - isEnd = false; - }else{ - segEnd = eventEnd; - isEnd = true; - } - segs.push({ - event: event, - start: segStart, - end: segEnd, - isStart: isStart, - isEnd: isEnd, - msLength: segEnd - segStart - }); - } - } - return segs.sort(segCmp); -} - - -// event rendering calculation utilities -function stackSegs(segs) { - var levels = [], - i, len = segs.length, seg, - j, collide, k; - for (i=0; i<len; i++) { - seg = segs[i]; - j = 0; // the level index where seg should belong - while (true) { - collide = false; - if (levels[j]) { - for (k=0; k<levels[j].length; k++) { - if (segsCollide(levels[j][k], seg)) { - collide = true; - break; - } - } - } - if (collide) { - j++; - }else{ - break; - } - } - if (levels[j]) { - levels[j].push(seg); - }else{ - levels[j] = [seg]; - } - } - return levels; -} - - - -/* Event Element Binding ------------------------------------------------------------------------------*/ - - -function lazySegBind(container, segs, bindHandlers) { - container.unbind('mouseover').mouseover(function(ev) { - var parent=ev.target, e, - i, seg; - while (parent != this) { - e = parent; - parent = parent.parentNode; - } - if ((i = e._fci) !== undefined) { - e._fci = undefined; - seg = segs[i]; - bindHandlers(seg.event, seg.element, seg); - $(ev.target).trigger(ev); - } - ev.stopPropagation(); - }); -} - - - -/* Element Dimensions ------------------------------------------------------------------------------*/ - - -function setOuterWidth(element, width, includeMargins) { - for (var i=0, e; i<element.length; i++) { - e = $(element[i]); - e.width(Math.max(0, width - hsides(e, includeMargins))); - } -} - - -function setOuterHeight(element, height, includeMargins) { - for (var i=0, e; i<element.length; i++) { - e = $(element[i]); - e.height(Math.max(0, height - vsides(e, includeMargins))); - } -} - - -// TODO: curCSS has been deprecated (jQuery 1.4.3 - 10/16/2010) - - -function hsides(element, includeMargins) { - return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0); -} - - -function hpadding(element) { - return (parseFloat($.curCSS(element[0], 'paddingLeft', true)) || 0) + - (parseFloat($.curCSS(element[0], 'paddingRight', true)) || 0); -} - - -function hmargins(element) { - return (parseFloat($.curCSS(element[0], 'marginLeft', true)) || 0) + - (parseFloat($.curCSS(element[0], 'marginRight', true)) || 0); -} - - -function hborders(element) { - return (parseFloat($.curCSS(element[0], 'borderLeftWidth', true)) || 0) + - (parseFloat($.curCSS(element[0], 'borderRightWidth', true)) || 0); -} - - -function vsides(element, includeMargins) { - return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0); -} - - -function vpadding(element) { - return (parseFloat($.curCSS(element[0], 'paddingTop', true)) || 0) + - (parseFloat($.curCSS(element[0], 'paddingBottom', true)) || 0); -} - - -function vmargins(element) { - return (parseFloat($.curCSS(element[0], 'marginTop', true)) || 0) + - (parseFloat($.curCSS(element[0], 'marginBottom', true)) || 0); -} - - -function vborders(element) { - return (parseFloat($.curCSS(element[0], 'borderTopWidth', true)) || 0) + - (parseFloat($.curCSS(element[0], 'borderBottomWidth', true)) || 0); -} - - -function setMinHeight(element, height) { - height = (typeof height == 'number' ? height + 'px' : height); - element.each(function(i, _element) { - _element.style.cssText += ';min-height:' + height + ';_height:' + height; - // why can't we just use .css() ? i forget - }); -} - - - -/* Misc Utils ------------------------------------------------------------------------------*/ - - -//TODO: arraySlice -//TODO: isFunction, grep ? - - -function noop() { } - - -function cmp(a, b) { - return a - b; -} - - -function arrayMax(a) { - return Math.max.apply(Math, a); -} - - -function zeroPad(n) { - return (n < 10 ? '0' : '') + n; -} - - -function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object - if (obj[name] !== undefined) { - return obj[name]; - } - var parts = name.split(/(?=[A-Z])/), - i=parts.length-1, res; - for (; i>=0; i--) { - res = obj[parts[i].toLowerCase()]; - if (res !== undefined) { - return res; - } - } - return obj['']; -} - - -function htmlEscape(s) { - return s.replace(/&/g, '&') - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/'/g, ''') - .replace(/"/g, '"') - .replace(/\n/g, '<br />'); -} - - -function cssKey(_element) { - return _element.id + '/' + _element.className + '/' + _element.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig, ''); -} - - -function disableTextSelection(element) { - element - .attr('unselectable', 'on') - .css('MozUserSelect', 'none') - .bind('selectstart.ui', function() { return false; }); -} - - -/* -function enableTextSelection(element) { - element - .attr('unselectable', 'off') - .css('MozUserSelect', '') - .unbind('selectstart.ui'); -} -*/ - - -function markFirstLast(e) { - e.children() - .removeClass('fc-first fc-last') - .filter(':first-child') - .addClass('fc-first') - .end() - .filter(':last-child') - .addClass('fc-last'); -} - - -function setDayID(cell, date) { - cell.each(function(i, _cell) { - _cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]); - // TODO: make a way that doesn't rely on order of classes - }); -} - - -function getSkinCss(event, opt) { - var source = event.source || {}; - var eventColor = event.color; - var sourceColor = source.color; - var optionColor = opt('eventColor'); - var backgroundColor = - event.backgroundColor || - eventColor || - source.backgroundColor || - sourceColor || - opt('eventBackgroundColor') || - optionColor; - var borderColor = - event.borderColor || - eventColor || - source.borderColor || - sourceColor || - opt('eventBorderColor') || - optionColor; - var textColor = - event.textColor || - source.textColor || - opt('eventTextColor'); - var statements = []; - if (backgroundColor) { - statements.push('background-color:' + backgroundColor); - } - if (borderColor) { - statements.push('border-color:' + borderColor); - } - if (textColor) { - statements.push('color:' + textColor); - } - return statements.join(';'); -} - - -function applyAll(functions, thisObj, args) { - if ($.isFunction(functions)) { - functions = [ functions ]; - } - if (functions) { - var i; - var ret; - for (i=0; i<functions.length; i++) { - ret = functions[i].apply(thisObj, args) || ret; - } - return ret; - } -} - - -function firstDefined() { - for (var i=0; i<arguments.length; i++) { - if (arguments[i] !== undefined) { - return arguments[i]; - } - } -} - - - -fcViews.month = MonthView; - -function MonthView(element, calendar) { - var t = this; - - - // exports - t.render = render; - - - // imports - BasicView.call(t, element, calendar, 'month'); - var opt = t.opt; - var renderBasic = t.renderBasic; - var formatDate = calendar.formatDate; - - - - function render(date, delta) { - if (delta) { - addMonths(date, delta); - date.setDate(1); - } - var start = cloneDate(date, true); - start.setDate(1); - var end = addMonths(cloneDate(start), 1); - var visStart = cloneDate(start); - var visEnd = cloneDate(end); - var firstDay = opt('firstDay'); - var nwe = opt('weekends') ? 0 : 1; - if (nwe) { - skipWeekend(visStart); - skipWeekend(visEnd, -1, true); - } - addDays(visStart, -((visStart.getDay() - Math.max(firstDay, nwe) + 7) % 7)); - addDays(visEnd, (7 - visEnd.getDay() + Math.max(firstDay, nwe)) % 7); - var rowCnt = Math.round((visEnd - visStart) / (DAY_MS * 7)); - if (opt('weekMode') == 'fixed') { - addDays(visEnd, (6 - rowCnt) * 7); - rowCnt = 6; - } - t.title = formatDate(start, opt('titleFormat')); - t.start = start; - t.end = end; - t.visStart = visStart; - t.visEnd = visEnd; - renderBasic(6, rowCnt, nwe ? 5 : 7, true); - } - - -} - -fcViews.basicWeek = BasicWeekView; - -function BasicWeekView(element, calendar) { - var t = this; - - - // exports - t.render = render; - - - // imports - BasicView.call(t, element, calendar, 'basicWeek'); - var opt = t.opt; - var renderBasic = t.renderBasic; - var formatDates = calendar.formatDates; - - - - function render(date, delta) { - if (delta) { - addDays(date, delta * 7); - } - var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7)); - var end = addDays(cloneDate(start), 7); - var visStart = cloneDate(start); - var visEnd = cloneDate(end); - var weekends = opt('weekends'); - if (!weekends) { - skipWeekend(visStart); - skipWeekend(visEnd, -1, true); - } - t.title = formatDates( - visStart, - addDays(cloneDate(visEnd), -1), - opt('titleFormat') - ); - t.start = start; - t.end = end; - t.visStart = visStart; - t.visEnd = visEnd; - renderBasic(1, 1, weekends ? 7 : 5, false); - } - - -} - -fcViews.basicDay = BasicDayView; - -//TODO: when calendar's date starts out on a weekend, shouldn't happen - - -function BasicDayView(element, calendar) { - var t = this; - - - // exports - t.render = render; - - - // imports - BasicView.call(t, element, calendar, 'basicDay'); - var opt = t.opt; - var renderBasic = t.renderBasic; - var formatDate = calendar.formatDate; - - - - function render(date, delta) { - if (delta) { - addDays(date, delta); - if (!opt('weekends')) { - skipWeekend(date, delta < 0 ? -1 : 1); - } - } - t.title = formatDate(date, opt('titleFormat')); - t.start = t.visStart = cloneDate(date, true); - t.end = t.visEnd = addDays(cloneDate(t.start), 1); - renderBasic(1, 1, 1, false); - } - - -} - -setDefaults({ - weekMode: 'fixed' -}); - - -function BasicView(element, calendar, viewName) { - var t = this; - - - // exports - t.renderBasic = renderBasic; - t.setHeight = setHeight; - t.setWidth = setWidth; - t.renderDayOverlay = renderDayOverlay; - t.defaultSelectionEnd = defaultSelectionEnd; - t.renderSelection = renderSelection; - t.clearSelection = clearSelection; - t.reportDayClick = reportDayClick; // for selection (kinda hacky) - t.dragStart = dragStart; - t.dragStop = dragStop; - t.defaultEventEnd = defaultEventEnd; - t.getHoverListener = function() { return hoverListener }; - t.colContentLeft = colContentLeft; - t.colContentRight = colContentRight; - t.dayOfWeekCol = dayOfWeekCol; - t.dateCell = dateCell; - t.cellDate = cellDate; - t.cellIsAllDay = function() { return true }; - t.allDayRow = allDayRow; - t.allDayBounds = allDayBounds; - t.getRowCnt = function() { return rowCnt }; - t.getColCnt = function() { return colCnt }; - t.getColWidth = function() { return colWidth }; - t.getDaySegmentContainer = function() { return daySegmentContainer }; - - - // imports - View.call(t, element, calendar, viewName); - OverlayManager.call(t); - SelectionManager.call(t); - BasicEventRenderer.call(t); - var opt = t.opt; - var trigger = t.trigger; - var clearEvents = t.clearEvents; - var renderOverlay = t.renderOverlay; - var clearOverlays = t.clearOverlays; - var daySelectionMousedown = t.daySelectionMousedown; - var formatDate = calendar.formatDate; - - - // locals - - var head; - var headCells; - var body; - var bodyRows; - var bodyCells; - var bodyFirstCells; - var bodyCellTopInners; - var daySegmentContainer; - - var viewWidth; - var viewHeight; - var colWidth; - - var rowCnt, colCnt; - var coordinateGrid; - var hoverListener; - var colContentPositions; - - var rtl, dis, dit; - var firstDay; - var nwe; - var tm; - var colFormat; - - - - /* Rendering - ------------------------------------------------------------*/ - - - disableTextSelection(element.addClass('fc-grid')); - - - function renderBasic(maxr, r, c, showNumbers) { - rowCnt = r; - colCnt = c; - updateOptions(); - var firstTime = !body; - if (firstTime) { - buildSkeleton(maxr, showNumbers); - }else{ - clearEvents(); - } - updateCells(firstTime); - } - - - - function updateOptions() { - rtl = opt('isRTL'); - if (rtl) { - dis = -1; - dit = colCnt - 1; - }else{ - dis = 1; - dit = 0; - } - firstDay = opt('firstDay'); - nwe = opt('weekends') ? 0 : 1; - tm = opt('theme') ? 'ui' : 'fc'; - colFormat = opt('columnFormat'); - } - - - - function buildSkeleton(maxRowCnt, showNumbers) { - var s; - var headerClass = tm + "-widget-header"; - var contentClass = tm + "-widget-content"; - var i, j; - var table; - - s = - "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" + - "<thead>" + - "<tr>"; - for (i=0; i<colCnt; i++) { - s += - "<th class='fc- " + headerClass + "'/>"; // need fc- for setDayID - } - s += - "</tr>" + - "</thead>" + - "<tbody>"; - for (i=0; i<maxRowCnt; i++) { - s += - "<tr class='fc-week" + i + "'>"; - for (j=0; j<colCnt; j++) { - s += - "<td class='fc- " + contentClass + " fc-day" + (i*colCnt+j) + "'>" + // need fc- for setDayID - "<div>" + - (showNumbers ? - "<div class='fc-day-number'/>" : - '' - ) + - "<div class='fc-day-content'>" + - "<div style='position:relative'> </div>" + - "</div>" + - "</div>" + - "</td>"; - } - s += - "</tr>"; - } - s += - "</tbody>" + - "</table>"; - table = $(s).appendTo(element); - - head = table.find('thead'); - headCells = head.find('th'); - body = table.find('tbody'); - bodyRows = body.find('tr'); - bodyCells = body.find('td'); - bodyFirstCells = bodyCells.filter(':first-child'); - bodyCellTopInners = bodyRows.eq(0).find('div.fc-day-content div'); - - markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's - markFirstLast(bodyRows); // marks first+last td's - bodyRows.eq(0).addClass('fc-first'); // fc-last is done in updateCells - - dayBind(bodyCells); - - daySegmentContainer = - $("<div style='position:absolute;z-index:8;top:0;left:0'/>") - .appendTo(element); - } - - - - function updateCells(firstTime) { - var dowDirty = firstTime || rowCnt == 1; // could the cells' day-of-weeks need updating? - var month = t.start.getMonth(); - var today = clearTime(new Date()); - var cell; - var date; - var row; - - if (dowDirty) { - headCells.each(function(i, _cell) { - cell = $(_cell); - date = indexDate(i); - cell.html(formatDate(date, colFormat)); - setDayID(cell, date); - }); - } - - bodyCells.each(function(i, _cell) { - cell = $(_cell); - date = indexDate(i); - if (date.getMonth() == month) { - cell.removeClass('fc-other-month'); - }else{ - cell.addClass('fc-other-month'); - } - if (+date == +today) { - cell.addClass(tm + '-state-highlight fc-today'); - }else{ - cell.removeClass(tm + '-state-highlight fc-today'); - } - cell.find('div.fc-day-number').text(date.getDate()); - if (dowDirty) { - setDayID(cell, date); - } - }); - - bodyRows.each(function(i, _row) { - row = $(_row); - if (i < rowCnt) { - row.show(); - if (i == rowCnt-1) { - row.addClass('fc-last'); - }else{ - row.removeClass('fc-last'); - } - }else{ - row.hide(); - } - }); - } - - - - function setHeight(height) { - viewHeight = height; - - var bodyHeight = viewHeight - head.height(); - var rowHeight; - var rowHeightLast; - var cell; - - if (opt('weekMode') == 'variable') { - rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6)); - }else{ - rowHeight = Math.floor(bodyHeight / rowCnt); - rowHeightLast = bodyHeight - rowHeight * (rowCnt-1); - } - - bodyFirstCells.each(function(i, _cell) { - if (i < rowCnt) { - cell = $(_cell); - setMinHeight( - cell.find('> div'), - (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell) - ); - } - }); - - } - - - function setWidth(width) { - viewWidth = width; - colContentPositions.clear(); - colWidth = Math.floor(viewWidth / colCnt); - setOuterWidth(headCells.slice(0, -1), colWidth); - } - - - - /* Day clicking and binding - -----------------------------------------------------------*/ - - - function dayBind(days) { - days.click(dayClick) - .mousedown(daySelectionMousedown); - } - - - function dayClick(ev) { - if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick - var index = parseInt(this.className.match(/fc\-day(\d+)/)[1]); // TODO: maybe use .data - var date = indexDate(index); - trigger('dayClick', this, date, true, ev); - } - } - - - - /* Semi-transparent Overlay Helpers - ------------------------------------------------------*/ - - - function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive - if (refreshCoordinateGrid) { - coordinateGrid.build(); - } - var rowStart = cloneDate(t.visStart); - var rowEnd = addDays(cloneDate(rowStart), colCnt); - for (var i=0; i<rowCnt; i++) { - var stretchStart = new Date(Math.max(rowStart, overlayStart)); - var stretchEnd = new Date(Math.min(rowEnd, overlayEnd)); - if (stretchStart < stretchEnd) { - var colStart, colEnd; - if (rtl) { - colStart = dayDiff(stretchEnd, rowStart)*dis+dit+1; - colEnd = dayDiff(stretchStart, rowStart)*dis+dit+1; - }else{ - colStart = dayDiff(stretchStart, rowStart); - colEnd = dayDiff(stretchEnd, rowStart); - } - dayBind( - renderCellOverlay(i, colStart, i, colEnd-1) - ); - } - addDays(rowStart, 7); - addDays(rowEnd, 7); - } - } - - - function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive - var rect = coordinateGrid.rect(row0, col0, row1, col1, element); - return renderOverlay(rect, element); - } - - - - /* Selection - -----------------------------------------------------------------------*/ - - - function defaultSelectionEnd(startDate, allDay) { - return cloneDate(startDate); - } - - - function renderSelection(startDate, endDate, allDay) { - renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); // rebuild every time??? - } - - - function clearSelection() { - clearOverlays(); - } - - - function reportDayClick(date, allDay, ev) { - var cell = dateCell(date); - var _element = bodyCells[cell.row*colCnt + cell.col]; - trigger('dayClick', _element, date, allDay, ev); - } - - - - /* External Dragging - -----------------------------------------------------------------------*/ - - - function dragStart(_dragElement, ev, ui) { - hoverListener.start(function(cell) { - clearOverlays(); - if (cell) { - renderCellOverlay(cell.row, cell.col, cell.row, cell.col); - } - }, ev); - } - - - function dragStop(_dragElement, ev, ui) { - var cell = hoverListener.stop(); - clearOverlays(); - if (cell) { - var d = cellDate(cell); - trigger('drop', _dragElement, d, true, ev, ui); - } - } - - - - /* Utilities - --------------------------------------------------------*/ - - - function defaultEventEnd(event) { - return cloneDate(event.start); - } - - - coordinateGrid = new CoordinateGrid(function(rows, cols) { - var e, n, p; - headCells.each(function(i, _e) { - e = $(_e); - n = e.offset().left; - if (i) { - p[1] = n; - } - p = [n]; - cols[i] = p; - }); - p[1] = n + e.outerWidth(); - bodyRows.each(function(i, _e) { - if (i < rowCnt) { - e = $(_e); - n = e.offset().top; - if (i) { - p[1] = n; - } - p = [n]; - rows[i] = p; - } - }); - p[1] = n + e.outerHeight(); - }); - - - hoverListener = new HoverListener(coordinateGrid); - - - colContentPositions = new HorizontalPositionCache(function(col) { - return bodyCellTopInners.eq(col); - }); - - - function colContentLeft(col) { - return colContentPositions.left(col); - } - - - function colContentRight(col) { - return colContentPositions.right(col); - } - - - - - function dateCell(date) { - return { - row: Math.floor(dayDiff(date, t.visStart) / 7), - col: dayOfWeekCol(date.getDay()) - }; - } - - - function cellDate(cell) { - return _cellDate(cell.row, cell.col); - } - - - function _cellDate(row, col) { - return addDays(cloneDate(t.visStart), row*7 + col*dis+dit); - // what about weekends in middle of week? - } - - - function indexDate(index) { - return _cellDate(Math.floor(index/colCnt), index%colCnt); - } - - - function dayOfWeekCol(dayOfWeek) { - return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt) * dis + dit; - } - - - - - function allDayRow(i) { - return bodyRows.eq(i); - } - - - function allDayBounds(i) { - return { - left: 0, - right: viewWidth - }; - } - - -} - -function BasicEventRenderer() { - var t = this; - - - // exports - t.renderEvents = renderEvents; - t.compileDaySegs = compileSegs; // for DayEventRenderer - t.clearEvents = clearEvents; - t.bindDaySeg = bindDaySeg; - - - // imports - DayEventRenderer.call(t); - var opt = t.opt; - var trigger = t.trigger; - //var setOverflowHidden = t.setOverflowHidden; - var isEventDraggable = t.isEventDraggable; - var isEventResizable = t.isEventResizable; - var reportEvents = t.reportEvents; - var reportEventClear = t.reportEventClear; - var eventElementHandlers = t.eventElementHandlers; - var showEvents = t.showEvents; - var hideEvents = t.hideEvents; - var eventDrop = t.eventDrop; - var getDaySegmentContainer = t.getDaySegmentContainer; - var getHoverListener = t.getHoverListener; - var renderDayOverlay = t.renderDayOverlay; - var clearOverlays = t.clearOverlays; - var getRowCnt = t.getRowCnt; - var getColCnt = t.getColCnt; - var renderDaySegs = t.renderDaySegs; - var resizableDayEvent = t.resizableDayEvent; - - - - /* Rendering - --------------------------------------------------------------------*/ - - - function renderEvents(events, modifiedEventId) { - reportEvents(events); - renderDaySegs(compileSegs(events), modifiedEventId); - } - - - function clearEvents() { - reportEventClear(); - getDaySegmentContainer().empty(); - } - - - function compileSegs(events) { - var rowCnt = getRowCnt(), - colCnt = getColCnt(), - d1 = cloneDate(t.visStart), - d2 = addDays(cloneDate(d1), colCnt), - visEventsEnds = $.map(events, exclEndDay), - i, row, - j, level, - k, seg, - segs=[]; - for (i=0; i<rowCnt; i++) { - row = stackSegs(sliceSegs(events, visEventsEnds, d1, d2)); - for (j=0; j<row.length; j++) { - level = row[j]; - for (k=0; k<level.length; k++) { - seg = level[k]; - seg.row = i; - seg.level = j; // not needed anymore - segs.push(seg); - } - } - addDays(d1, 7); - addDays(d2, 7); - } - return segs; - } - - - function bindDaySeg(event, eventElement, seg) { - if (isEventDraggable(event)) { - draggableDayEvent(event, eventElement); - } - if (seg.isEnd && isEventResizable(event)) { - resizableDayEvent(event, eventElement, seg); - } - eventElementHandlers(event, eventElement); - // needs to be after, because resizableDayEvent might stopImmediatePropagation on click - } - - - - /* Dragging - ----------------------------------------------------------------------------*/ - - - function draggableDayEvent(event, eventElement) { - var hoverListener = getHoverListener(); - var dayDelta; - eventElement.draggable({ - zIndex: 9, - delay: 50, - opacity: opt('dragOpacity'), - revertDuration: opt('dragRevertDuration'), - start: function(ev, ui) { - trigger('eventDragStart', eventElement, event, ev, ui); - hideEvents(event, eventElement); - hoverListener.start(function(cell, origCell, rowDelta, colDelta) { - eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta); - clearOverlays(); - if (cell) { - //setOverflowHidden(true); - dayDelta = rowDelta*7 + colDelta * (opt('isRTL') ? -1 : 1); - renderDayOverlay( - addDays(cloneDate(event.start), dayDelta), - addDays(exclEndDay(event), dayDelta) - ); - }else{ - //setOverflowHidden(false); - dayDelta = 0; - } - }, ev, 'drag'); - }, - stop: function(ev, ui) { - hoverListener.stop(); - clearOverlays(); - trigger('eventDragStop', eventElement, event, ev, ui); - if (dayDelta) { - eventDrop(this, event, dayDelta, 0, event.allDay, ev, ui); - }else{ - eventElement.css('filter', ''); // clear IE opacity side-effects - showEvents(event, eventElement); - } - //setOverflowHidden(false); - } - }); - } - - -} - -fcViews.agendaWeek = AgendaWeekView; - -function AgendaWeekView(element, calendar) { - var t = this; - - - // exports - t.render = render; - - - // imports - AgendaView.call(t, element, calendar, 'agendaWeek'); - var opt = t.opt; - var renderAgenda = t.renderAgenda; - var formatDates = calendar.formatDates; - - - - function render(date, delta) { - if (delta) { - addDays(date, delta * 7); - } - var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7)); - var end = addDays(cloneDate(start), 7); - var visStart = cloneDate(start); - var visEnd = cloneDate(end); - var weekends = opt('weekends'); - if (!weekends) { - skipWeekend(visStart); - skipWeekend(visEnd, -1, true); - } - t.title = formatDates( - visStart, - addDays(cloneDate(visEnd), -1), - opt('titleFormat') - ); - t.start = start; - t.end = end; - t.visStart = visStart; - t.visEnd = visEnd; - renderAgenda(weekends ? 7 : 5); - } - - -} - -fcViews.agendaDay = AgendaDayView; - -function AgendaDayView(element, calendar) { - var t = this; - - - // exports - t.render = render; - - - // imports - AgendaView.call(t, element, calendar, 'agendaDay'); - var opt = t.opt; - var renderAgenda = t.renderAgenda; - var formatDate = calendar.formatDate; - - - - function render(date, delta) { - if (delta) { - addDays(date, delta); - if (!opt('weekends')) { - skipWeekend(date, delta < 0 ? -1 : 1); - } - } - var start = cloneDate(date, true); - var end = addDays(cloneDate(start), 1); - t.title = formatDate(date, opt('titleFormat')); - t.start = t.visStart = start; - t.end = t.visEnd = end; - renderAgenda(1); - } - - -} - -setDefaults({ - allDaySlot: true, - allDayText: 'all-day', - firstHour: 6, - slotMinutes: 30, - defaultEventMinutes: 120, - axisFormat: 'h(:mm)tt', - timeFormat: { - agenda: 'h:mm{ - h:mm}' - }, - dragOpacity: { - agenda: .5 - }, - minTime: 0, - maxTime: 24 -}); - - -// TODO: make it work in quirks mode (event corners, all-day height) -// TODO: test liquid width, especially in IE6 - - -function AgendaView(element, calendar, viewName) { - var t = this; - - - // exports - t.renderAgenda = renderAgenda; - t.setWidth = setWidth; - t.setHeight = setHeight; - t.beforeHide = beforeHide; - t.afterShow = afterShow; - t.defaultEventEnd = defaultEventEnd; - t.timePosition = timePosition; - t.dayOfWeekCol = dayOfWeekCol; - t.dateCell = dateCell; - t.cellDate = cellDate; - t.cellIsAllDay = cellIsAllDay; - t.allDayRow = getAllDayRow; - t.allDayBounds = allDayBounds; - t.getHoverListener = function() { return hoverListener }; - t.colContentLeft = colContentLeft; - t.colContentRight = colContentRight; - t.getDaySegmentContainer = function() { return daySegmentContainer }; - t.getSlotSegmentContainer = function() { return slotSegmentContainer }; - t.getMinMinute = function() { return minMinute }; - t.getMaxMinute = function() { return maxMinute }; - t.getBodyContent = function() { return slotContent }; // !!?? - t.getRowCnt = function() { return 1 }; - t.getColCnt = function() { return colCnt }; - t.getColWidth = function() { return colWidth }; - t.getSlotHeight = function() { return slotHeight }; - t.defaultSelectionEnd = defaultSelectionEnd; - t.renderDayOverlay = renderDayOverlay; - t.renderSelection = renderSelection; - t.clearSelection = clearSelection; - t.reportDayClick = reportDayClick; // selection mousedown hack - t.dragStart = dragStart; - t.dragStop = dragStop; - - - // imports - View.call(t, element, calendar, viewName); - OverlayManager.call(t); - SelectionManager.call(t); - AgendaEventRenderer.call(t); - var opt = t.opt; - var trigger = t.trigger; - var clearEvents = t.clearEvents; - var renderOverlay = t.renderOverlay; - var clearOverlays = t.clearOverlays; - var reportSelection = t.reportSelection; - var unselect = t.unselect; - var daySelectionMousedown = t.daySelectionMousedown; - var slotSegHtml = t.slotSegHtml; - var formatDate = calendar.formatDate; - - - // locals - - var dayTable; - var dayHead; - var dayHeadCells; - var dayBody; - var dayBodyCells; - var dayBodyCellInners; - var dayBodyFirstCell; - var dayBodyFirstCellStretcher; - var slotLayer; - var daySegmentContainer; - var allDayTable; - var allDayRow; - var slotScroller; - var slotContent; - var slotSegmentContainer; - var slotTable; - var slotTableFirstInner; - var axisFirstCells; - var gutterCells; - var selectionHelper; - - var viewWidth; - var viewHeight; - var axisWidth; - var colWidth; - var gutterWidth; - var slotHeight; // TODO: what if slotHeight changes? (see issue 650) - var savedScrollTop; - - var colCnt; - var slotCnt; - var coordinateGrid; - var hoverListener; - var colContentPositions; - var slotTopCache = {}; - - var tm; - var firstDay; - var nwe; // no weekends (int) - var rtl, dis, dit; // day index sign / translate - var minMinute, maxMinute; - var colFormat; - - - - /* Rendering - -----------------------------------------------------------------------------*/ - - - disableTextSelection(element.addClass('fc-agenda')); - - - function renderAgenda(c) { - colCnt = c; - updateOptions(); - if (!dayTable) { - buildSkeleton(); - }else{ - clearEvents(); - } - updateCells(); - } - - - - function updateOptions() { - tm = opt('theme') ? 'ui' : 'fc'; - nwe = opt('weekends') ? 0 : 1; - firstDay = opt('firstDay'); - if (rtl = opt('isRTL')) { - dis = -1; - dit = colCnt - 1; - }else{ - dis = 1; - dit = 0; - } - minMinute = parseTime(opt('minTime')); - maxMinute = parseTime(opt('maxTime')); - colFormat = opt('columnFormat'); - } - - - - function buildSkeleton() { - var headerClass = tm + "-widget-header"; - var contentClass = tm + "-widget-content"; - var s; - var i; - var d; - var maxd; - var minutes; - var slotNormal = opt('slotMinutes') % 15 == 0; - - s = - "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" + - "<thead>" + - "<tr>" + - "<th class='fc-agenda-axis " + headerClass + "'> </th>"; - for (i=0; i<colCnt; i++) { - s += - "<th class='fc- fc-col" + i + ' ' + headerClass + "'/>"; // fc- needed for setDayID - } - s += - "<th class='fc-agenda-gutter " + headerClass + "'> </th>" + - "</tr>" + - "</thead>" + - "<tbody>" + - "<tr>" + - "<th class='fc-agenda-axis " + headerClass + "'> </th>"; - for (i=0; i<colCnt; i++) { - s += - "<td class='fc- fc-col" + i + ' ' + contentClass + "'>" + // fc- needed for setDayID - "<div>" + - "<div class='fc-day-content'>" + - "<div style='position:relative'> </div>" + - "</div>" + - "</div>" + - "</td>"; - } - s += - "<td class='fc-agenda-gutter " + contentClass + "'> </td>" + - "</tr>" + - "</tbody>" + - "</table>"; - dayTable = $(s).appendTo(element); - dayHead = dayTable.find('thead'); - dayHeadCells = dayHead.find('th').slice(1, -1); - dayBody = dayTable.find('tbody'); - dayBodyCells = dayBody.find('td').slice(0, -1); - dayBodyCellInners = dayBodyCells.find('div.fc-day-content div'); - dayBodyFirstCell = dayBodyCells.eq(0); - dayBodyFirstCellStretcher = dayBodyFirstCell.find('> div'); - - markFirstLast(dayHead.add(dayHead.find('tr'))); - markFirstLast(dayBody.add(dayBody.find('tr'))); - - axisFirstCells = dayHead.find('th:first'); - gutterCells = dayTable.find('.fc-agenda-gutter'); - - slotLayer = - $("<div style='position:absolute;z-index:2;left:0;width:100%'/>") - .appendTo(element); - - if (opt('allDaySlot')) { - - daySegmentContainer = - $("<div style='position:absolute;z-index:8;top:0;left:0'/>") - .appendTo(slotLayer); - - s = - "<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" + - "<tr>" + - "<th class='" + headerClass + " fc-agenda-axis'>" + opt('allDayText') + "</th>" + - "<td>" + - "<div class='fc-day-content'><div style='position:relative'/></div>" + - "</td>" + - "<th class='" + headerClass + " fc-agenda-gutter'> </th>" + - "</tr>" + - "</table>"; - allDayTable = $(s).appendTo(slotLayer); - allDayRow = allDayTable.find('tr'); - - dayBind(allDayRow.find('td')); - - axisFirstCells = axisFirstCells.add(allDayTable.find('th:first')); - gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter')); - - slotLayer.append( - "<div class='fc-agenda-divider " + headerClass + "'>" + - "<div class='fc-agenda-divider-inner'/>" + - "</div>" - ); - - }else{ - - daySegmentContainer = $([]); // in jQuery 1.4, we can just do $() - - } - - slotScroller = - $("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>") - .appendTo(slotLayer); - - slotContent = - $("<div style='position:relative;width:100%;overflow:hidden'/>") - .appendTo(slotScroller); - - slotSegmentContainer = - $("<div style='position:absolute;z-index:8;top:0;left:0'/>") - .appendTo(slotContent); - - s = - "<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" + - "<tbody>"; - d = zeroDate(); - maxd = addMinutes(cloneDate(d), maxMinute); - addMinutes(d, minMinute); - slotCnt = 0; - for (i=0; d < maxd; i++) { - minutes = d.getMinutes(); - s += - "<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" + - "<th class='fc-agenda-axis " + headerClass + "'>" + - ((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : ' ') + - "</th>" + - "<td class='" + contentClass + "'>" + - "<div style='position:relative'> </div>" + - "</td>" + - "</tr>"; - addMinutes(d, opt('slotMinutes')); - slotCnt++; - } - s += - "</tbody>" + - "</table>"; - slotTable = $(s).appendTo(slotContent); - slotTableFirstInner = slotTable.find('div:first'); - - slotBind(slotTable.find('td')); - - axisFirstCells = axisFirstCells.add(slotTable.find('th:first')); - } - - - - function updateCells() { - var i; - var headCell; - var bodyCell; - var date; - var today = clearTime(new Date()); - for (i=0; i<colCnt; i++) { - date = colDate(i); - headCell = dayHeadCells.eq(i); - headCell.html(formatDate(date, colFormat)); - bodyCell = dayBodyCells.eq(i); - if (+date == +today) { - bodyCell.addClass(tm + '-state-highlight fc-today'); - }else{ - bodyCell.removeClass(tm + '-state-highlight fc-today'); - } - setDayID(headCell.add(bodyCell), date); - } - } - - - - function setHeight(height, dateChanged) { - if (height === undefined) { - height = viewHeight; - } - viewHeight = height; - slotTopCache = {}; - - var headHeight = dayBody.position().top; - var allDayHeight = slotScroller.position().top; // including divider - var bodyHeight = Math.min( // total body height, including borders - height - headHeight, // when scrollbars - slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border - ); - - dayBodyFirstCellStretcher - .height(bodyHeight - vsides(dayBodyFirstCell)); - - slotLayer.css('top', headHeight); - - slotScroller.height(bodyHeight - allDayHeight - 1); - - slotHeight = slotTableFirstInner.height() + 1; // +1 for border - - if (dateChanged) { - resetScroll(); - } - } - - - - function setWidth(width) { - viewWidth = width; - colContentPositions.clear(); - - axisWidth = 0; - setOuterWidth( - axisFirstCells - .width('') - .each(function(i, _cell) { - axisWidth = Math.max(axisWidth, $(_cell).outerWidth()); - }), - axisWidth - ); - - var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7) - //slotTable.width(slotTableWidth); - - gutterWidth = slotScroller.width() - slotTableWidth; - if (gutterWidth) { - setOuterWidth(gutterCells, gutterWidth); - gutterCells - .show() - .prev() - .removeClass('fc-last'); - }else{ - gutterCells - .hide() - .prev() - .addClass('fc-last'); - } - - colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt); - setOuterWidth(dayHeadCells.slice(0, -1), colWidth); - } - - - - function resetScroll() { - var d0 = zeroDate(); - var scrollDate = cloneDate(d0); - scrollDate.setHours(opt('firstHour')); - var top = timePosition(d0, scrollDate) + 1; // +1 for the border - function scroll() { - slotScroller.scrollTop(top); - } - scroll(); - setTimeout(scroll, 0); // overrides any previous scroll state made by the browser - } - - - function beforeHide() { - savedScrollTop = slotScroller.scrollTop(); - } - - - function afterShow() { - slotScroller.scrollTop(savedScrollTop); - } - - - - /* Slot/Day clicking and binding - -----------------------------------------------------------------------*/ - - - function dayBind(cells) { - cells.click(slotClick) - .mousedown(daySelectionMousedown); - } - - - function slotBind(cells) { - cells.click(slotClick) - .mousedown(slotSelectionMousedown); - } - - - function slotClick(ev) { - if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick - var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth)); - var date = colDate(col); - var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data - if (rowMatch) { - var mins = parseInt(rowMatch[1]) * opt('slotMinutes'); - var hours = Math.floor(mins/60); - date.setHours(hours); - date.setMinutes(mins%60 + minMinute); - trigger('dayClick', dayBodyCells[col], date, false, ev); - }else{ - trigger('dayClick', dayBodyCells[col], date, true, ev); - } - } - } - - - - /* Semi-transparent Overlay Helpers - -----------------------------------------------------*/ - - - function renderDayOverlay(startDate, endDate, refreshCoordinateGrid) { // endDate is exclusive - if (refreshCoordinateGrid) { - coordinateGrid.build(); - } - var visStart = cloneDate(t.visStart); - var startCol, endCol; - if (rtl) { - startCol = dayDiff(endDate, visStart)*dis+dit+1; - endCol = dayDiff(startDate, visStart)*dis+dit+1; - }else{ - startCol = dayDiff(startDate, visStart); - endCol = dayDiff(endDate, visStart); - } - startCol = Math.max(0, startCol); - endCol = Math.min(colCnt, endCol); - if (startCol < endCol) { - dayBind( - renderCellOverlay(0, startCol, 0, endCol-1) - ); - } - } - - - function renderCellOverlay(row0, col0, row1, col1) { // only for all-day? - var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer); - return renderOverlay(rect, slotLayer); - } - - - function renderSlotOverlay(overlayStart, overlayEnd) { - var dayStart = cloneDate(t.visStart); - var dayEnd = addDays(cloneDate(dayStart), 1); - for (var i=0; i<colCnt; i++) { - var stretchStart = new Date(Math.max(dayStart, overlayStart)); - var stretchEnd = new Date(Math.min(dayEnd, overlayEnd)); - if (stretchStart < stretchEnd) { - var col = i*dis+dit; - var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only use it for horizontal coords - var top = timePosition(dayStart, stretchStart); - var bottom = timePosition(dayStart, stretchEnd); - rect.top = top; - rect.height = bottom - top; - slotBind( - renderOverlay(rect, slotContent) - ); - } - addDays(dayStart, 1); - addDays(dayEnd, 1); - } - } - - - - /* Coordinate Utilities - -----------------------------------------------------------------------------*/ - - - coordinateGrid = new CoordinateGrid(function(rows, cols) { - var e, n, p; - dayHeadCells.each(function(i, _e) { - e = $(_e); - n = e.offset().left; - if (i) { - p[1] = n; - } - p = [n]; - cols[i] = p; - }); - p[1] = n + e.outerWidth(); - if (opt('allDaySlot')) { - e = allDayRow; - n = e.offset().top; - rows[0] = [n, n+e.outerHeight()]; - } - var slotTableTop = slotContent.offset().top; - var slotScrollerTop = slotScroller.offset().top; - var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight(); - function constrain(n) { - return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n)); - } - for (var i=0; i<slotCnt; i++) { - rows.push([ - constrain(slotTableTop + slotHeight*i), - constrain(slotTableTop + slotHeight*(i+1)) - ]); - } - }); - - - hoverListener = new HoverListener(coordinateGrid); - - - colContentPositions = new HorizontalPositionCache(function(col) { - return dayBodyCellInners.eq(col); - }); - - - function colContentLeft(col) { - return colContentPositions.left(col); - } - - - function colContentRight(col) { - return colContentPositions.right(col); - } - - - - - function dateCell(date) { // "cell" terminology is now confusing - return { - row: Math.floor(dayDiff(date, t.visStart) / 7), - col: dayOfWeekCol(date.getDay()) - }; - } - - - function cellDate(cell) { - var d = colDate(cell.col); - var slotIndex = cell.row; - if (opt('allDaySlot')) { - slotIndex--; - } - if (slotIndex >= 0) { - addMinutes(d, minMinute + slotIndex * opt('slotMinutes')); - } - return d; - } - - - function colDate(col) { // returns dates with 00:00:00 - return addDays(cloneDate(t.visStart), col*dis+dit); - } - - - function cellIsAllDay(cell) { - return opt('allDaySlot') && !cell.row; - } - - - function dayOfWeekCol(dayOfWeek) { - return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt)*dis+dit; - } - - - - - // get the Y coordinate of the given time on the given day (both Date objects) - function timePosition(day, time) { // both date objects. day holds 00:00 of current day - day = cloneDate(day, true); - if (time < addMinutes(cloneDate(day), minMinute)) { - return 0; - } - if (time >= addMinutes(cloneDate(day), maxMinute)) { - return slotTable.height(); - } - var slotMinutes = opt('slotMinutes'), - minutes = time.getHours()*60 + time.getMinutes() - minMinute, - slotI = Math.floor(minutes / slotMinutes), - slotTop = slotTopCache[slotI]; - if (slotTop === undefined) { - slotTop = slotTopCache[slotI] = slotTable.find('tr:eq(' + slotI + ') td div')[0].offsetTop; //.position().top; // need this optimization??? - } - return Math.max(0, Math.round( - slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes) - )); - } - - - function allDayBounds() { - return { - left: axisWidth, - right: viewWidth - gutterWidth - } - } - - - function getAllDayRow(index) { - return allDayRow; - } - - - function defaultEventEnd(event) { - var start = cloneDate(event.start); - if (event.allDay) { - return start; - } - return addMinutes(start, opt('defaultEventMinutes')); - } - - - - /* Selection - ---------------------------------------------------------------------------------*/ - - - function defaultSelectionEnd(startDate, allDay) { - if (allDay) { - return cloneDate(startDate); - } - return addMinutes(cloneDate(startDate), opt('slotMinutes')); - } - - - function renderSelection(startDate, endDate, allDay) { // only for all-day - if (allDay) { - if (opt('allDaySlot')) { - renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); - } - }else{ - renderSlotSelection(startDate, endDate); - } - } - - - function renderSlotSelection(startDate, endDate) { - var helperOption = opt('selectHelper'); - coordinateGrid.build(); - if (helperOption) { - var col = dayDiff(startDate, t.visStart) * dis + dit; - if (col >= 0 && col < colCnt) { // only works when times are on same day - var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only for horizontal coords - var top = timePosition(startDate, startDate); - var bottom = timePosition(startDate, endDate); - if (bottom > top) { // protect against selections that are entirely before or after visible range - rect.top = top; - rect.height = bottom - top; - rect.left += 2; - rect.width -= 5; - if ($.isFunction(helperOption)) { - var helperRes = helperOption(startDate, endDate); - if (helperRes) { - rect.position = 'absolute'; - rect.zIndex = 8; - selectionHelper = $(helperRes) - .css(rect) - .appendTo(slotContent); - } - }else{ - rect.isStart = true; // conside rect a "seg" now - rect.isEnd = true; // - selectionHelper = $(slotSegHtml( - { - title: '', - start: startDate, - end: endDate, - className: ['fc-select-helper'], - editable: false - }, - rect - )); - selectionHelper.css('opacity', opt('dragOpacity')); - } - if (selectionHelper) { - slotBind(selectionHelper); - slotContent.append(selectionHelper); - setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended - setOuterHeight(selectionHelper, rect.height, true); - } - } - } - }else{ - renderSlotOverlay(startDate, endDate); - } - } - - - function clearSelection() { - clearOverlays(); - if (selectionHelper) { - selectionHelper.remove(); - selectionHelper = null; - } - } - - - function slotSelectionMousedown(ev) { - if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button - unselect(ev); - var dates; - hoverListener.start(function(cell, origCell) { - clearSelection(); - if (cell && cell.col == origCell.col && !cellIsAllDay(cell)) { - var d1 = cellDate(origCell); - var d2 = cellDate(cell); - dates = [ - d1, - addMinutes(cloneDate(d1), opt('slotMinutes')), - d2, - addMinutes(cloneDate(d2), opt('slotMinutes')) - ].sort(cmp); - renderSlotSelection(dates[0], dates[3]); - }else{ - dates = null; - } - }, ev); - $(document).one('mouseup', function(ev) { - hoverListener.stop(); - if (dates) { - if (+dates[0] == +dates[1]) { - reportDayClick(dates[0], false, ev); - } - reportSelection(dates[0], dates[3], false, ev); - } - }); - } - } - - - function reportDayClick(date, allDay, ev) { - trigger('dayClick', dayBodyCells[dayOfWeekCol(date.getDay())], date, allDay, ev); - } - - - - /* External Dragging - --------------------------------------------------------------------------------*/ - - - function dragStart(_dragElement, ev, ui) { - hoverListener.start(function(cell) { - clearOverlays(); - if (cell) { - if (cellIsAllDay(cell)) { - renderCellOverlay(cell.row, cell.col, cell.row, cell.col); - }else{ - var d1 = cellDate(cell); - var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes')); - renderSlotOverlay(d1, d2); - } - } - }, ev); - } - - - function dragStop(_dragElement, ev, ui) { - var cell = hoverListener.stop(); - clearOverlays(); - if (cell) { - trigger('drop', _dragElement, cellDate(cell), cellIsAllDay(cell), ev, ui); - } - } - - -} - -function AgendaEventRenderer() { - var t = this; - - - // exports - t.renderEvents = renderEvents; - t.compileDaySegs = compileDaySegs; // for DayEventRenderer - t.clearEvents = clearEvents; - t.slotSegHtml = slotSegHtml; - t.bindDaySeg = bindDaySeg; - - - // imports - DayEventRenderer.call(t); - var opt = t.opt; - var trigger = t.trigger; - //var setOverflowHidden = t.setOverflowHidden; - var isEventDraggable = t.isEventDraggable; - var isEventResizable = t.isEventResizable; - var eventEnd = t.eventEnd; - var reportEvents = t.reportEvents; - var reportEventClear = t.reportEventClear; - var eventElementHandlers = t.eventElementHandlers; - var setHeight = t.setHeight; - var getDaySegmentContainer = t.getDaySegmentContainer; - var getSlotSegmentContainer = t.getSlotSegmentContainer; - var getHoverListener = t.getHoverListener; - var getMaxMinute = t.getMaxMinute; - var getMinMinute = t.getMinMinute; - var timePosition = t.timePosition; - var colContentLeft = t.colContentLeft; - var colContentRight = t.colContentRight; - var renderDaySegs = t.renderDaySegs; - var resizableDayEvent = t.resizableDayEvent; // TODO: streamline binding architecture - var getColCnt = t.getColCnt; - var getColWidth = t.getColWidth; - var getSlotHeight = t.getSlotHeight; - var getBodyContent = t.getBodyContent; - var reportEventElement = t.reportEventElement; - var showEvents = t.showEvents; - var hideEvents = t.hideEvents; - var eventDrop = t.eventDrop; - var eventResize = t.eventResize; - var renderDayOverlay = t.renderDayOverlay; - var clearOverlays = t.clearOverlays; - var calendar = t.calendar; - var formatDate = calendar.formatDate; - var formatDates = calendar.formatDates; - - - - /* Rendering - ----------------------------------------------------------------------------*/ - - - function renderEvents(events, modifiedEventId) { - reportEvents(events); - var i, len=events.length, - dayEvents=[], - slotEvents=[]; - for (i=0; i<len; i++) { - if (events[i].allDay) { - dayEvents.push(events[i]); - }else{ - slotEvents.push(events[i]); - } - } - if (opt('allDaySlot')) { - renderDaySegs(compileDaySegs(dayEvents), modifiedEventId); - setHeight(); // no params means set to viewHeight - } - renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId); - } - - - function clearEvents() { - reportEventClear(); - getDaySegmentContainer().empty(); - getSlotSegmentContainer().empty(); - } - - - function compileDaySegs(events) { - var levels = stackSegs(sliceSegs(events, $.map(events, exclEndDay), t.visStart, t.visEnd)), - i, levelCnt=levels.length, level, - j, seg, - segs=[]; - for (i=0; i<levelCnt; i++) { - level = levels[i]; - for (j=0; j<level.length; j++) { - seg = level[j]; - seg.row = 0; - seg.level = i; // not needed anymore - segs.push(seg); - } - } - return segs; - } - - - function compileSlotSegs(events) { - var colCnt = getColCnt(), - minMinute = getMinMinute(), - maxMinute = getMaxMinute(), - d = addMinutes(cloneDate(t.visStart), minMinute), - visEventEnds = $.map(events, slotEventEnd), - i, col, - j, level, - k, seg, - segs=[]; - for (i=0; i<colCnt; i++) { - col = stackSegs(sliceSegs(events, visEventEnds, d, addMinutes(cloneDate(d), maxMinute-minMinute))); - countForwardSegs(col); - for (j=0; j<col.length; j++) { - level = col[j]; - for (k=0; k<level.length; k++) { - seg = level[k]; - seg.col = i; - seg.level = j; - segs.push(seg); - } - } - addDays(d, 1, true); - } - return segs; - } - - - function slotEventEnd(event) { - if (event.end) { - return cloneDate(event.end); - }else{ - return addMinutes(cloneDate(event.start), opt('defaultEventMinutes')); - } - } - - - // renders events in the 'time slots' at the bottom - - function renderSlotSegs(segs, modifiedEventId) { - - var i, segCnt=segs.length, seg, - event, - classes, - top, bottom, - colI, levelI, forward, - leftmost, - availWidth, - outerWidth, - left, - html='', - eventElements, - eventElement, - triggerRes, - vsideCache={}, - hsideCache={}, - key, val, - contentElement, - height, - slotSegmentContainer = getSlotSegmentContainer(), - rtl, dis, dit, - colCnt = getColCnt(); - - if (rtl = opt('isRTL')) { - dis = -1; - dit = colCnt - 1; - }else{ - dis = 1; - dit = 0; - } - - // calculate position/dimensions, create html - for (i=0; i<segCnt; i++) { - seg = segs[i]; - event = seg.event; - top = timePosition(seg.start, seg.start); - bottom = timePosition(seg.start, seg.end); - colI = seg.col; - levelI = seg.level; - forward = seg.forward || 0; - leftmost = colContentLeft(colI*dis + dit); - availWidth = colContentRight(colI*dis + dit) - leftmost; - availWidth = Math.min(availWidth-6, availWidth*.95); // TODO: move this to CSS - if (levelI) { - // indented and thin - outerWidth = availWidth / (levelI + forward + 1); - }else{ - if (forward) { - // moderately wide, aligned left still - outerWidth = ((availWidth / (forward + 1)) - (12/2)) * 2; // 12 is the predicted width of resizer = - }else{ - // can be entire width, aligned left - outerWidth = availWidth; - } - } - left = leftmost + // leftmost possible - (availWidth / (levelI + forward + 1) * levelI) // indentation - * dis + (rtl ? availWidth - outerWidth : 0); // rtl - seg.top = top; - seg.left = left; - seg.outerWidth = outerWidth; - seg.outerHeight = bottom - top; - html += slotSegHtml(event, seg); - } - slotSegmentContainer[0].innerHTML = html; // faster than html() - eventElements = slotSegmentContainer.children(); - - // retrieve elements, run through eventRender callback, bind event handlers - for (i=0; i<segCnt; i++) { - seg = segs[i]; - event = seg.event; - eventElement = $(eventElements[i]); // faster than eq() - triggerRes = trigger('eventRender', event, event, eventElement); - if (triggerRes === false) { - eventElement.remove(); - }else{ - if (triggerRes && triggerRes !== true) { - eventElement.remove(); - eventElement = $(triggerRes) - .css({ - position: 'absolute', - top: seg.top, - left: seg.left - }) - .appendTo(slotSegmentContainer); - } - seg.element = eventElement; - if (event._id === modifiedEventId) { - bindSlotSeg(event, eventElement, seg); - }else{ - eventElement[0]._fci = i; // for lazySegBind - } - reportEventElement(event, eventElement); - } - } - - lazySegBind(slotSegmentContainer, segs, bindSlotSeg); - - // record event sides and title positions - for (i=0; i<segCnt; i++) { - seg = segs[i]; - if (eventElement = seg.element) { - val = vsideCache[key = seg.key = cssKey(eventElement[0])]; - seg.vsides = val === undefined ? (vsideCache[key] = vsides(eventElement, true)) : val; - val = hsideCache[key]; - seg.hsides = val === undefined ? (hsideCache[key] = hsides(eventElement, true)) : val; - contentElement = eventElement.find('div.fc-event-content'); - if (contentElement.length) { - seg.contentTop = contentElement[0].offsetTop; - } - } - } - - // set all positions/dimensions at once - for (i=0; i<segCnt; i++) { - seg = segs[i]; - if (eventElement = seg.element) { - eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px'; - height = Math.max(0, seg.outerHeight - seg.vsides); - eventElement[0].style.height = height + 'px'; - event = seg.event; - if (seg.contentTop !== undefined && height - seg.contentTop < 10) { - // not enough room for title, put it in the time header - eventElement.find('div.fc-event-time') - .text(formatDate(event.start, opt('timeFormat')) + ' - ' + event.title); - eventElement.find('div.fc-event-title') - .remove(); - } - trigger('eventAfterRender', event, event, eventElement); - } - } - - } - - - function slotSegHtml(event, seg) { - var html = "<"; - var url = event.url; - var skinCss = getSkinCss(event, opt); - var skinCssAttr = (skinCss ? " style='" + skinCss + "'" : ''); - var classes = ['fc-event', 'fc-event-skin', 'fc-event-vert']; - if (isEventDraggable(event)) { - classes.push('fc-event-draggable'); - } - if (seg.isStart) { - classes.push('fc-corner-top'); - } - if (seg.isEnd) { - classes.push('fc-corner-bottom'); - } - classes = classes.concat(event.className); - if (event.source) { - classes = classes.concat(event.source.className || []); - } - if (url) { - html += "a href='" + htmlEscape(event.url) + "'"; - }else{ - html += "div"; - } - html += - " class='" + classes.join(' ') + "'" + - " style='position:absolute;z-index:8;top:" + seg.top + "px;left:" + seg.left + "px;" + skinCss + "'" + - ">" + - "<div class='fc-event-inner fc-event-skin'" + skinCssAttr + ">" + - "<div class='fc-event-head fc-event-skin'" + skinCssAttr + ">" + - "<div class='fc-event-time'>" + - htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + - "</div>" + - "</div>" + - "<div class='fc-event-content'>" + - "<div class='fc-event-title'>" + - htmlEscape(event.title) + - "</div>" + - "</div>" + - "<div class='fc-event-bg'></div>" + - "</div>"; // close inner - if (seg.isEnd && isEventResizable(event)) { - html += - "<div class='ui-resizable-handle ui-resizable-s'>=</div>"; - } - html += - "</" + (url ? "a" : "div") + ">"; - return html; - } - - - function bindDaySeg(event, eventElement, seg) { - if (isEventDraggable(event)) { - draggableDayEvent(event, eventElement, seg.isStart); - } - if (seg.isEnd && isEventResizable(event)) { - resizableDayEvent(event, eventElement, seg); - } - eventElementHandlers(event, eventElement); - // needs to be after, because resizableDayEvent might stopImmediatePropagation on click - } - - - function bindSlotSeg(event, eventElement, seg) { - var timeElement = eventElement.find('div.fc-event-time'); - if (isEventDraggable(event)) { - draggableSlotEvent(event, eventElement, timeElement); - } - if (seg.isEnd && isEventResizable(event)) { - resizableSlotEvent(event, eventElement, timeElement); - } - eventElementHandlers(event, eventElement); - } - - - - /* Dragging - -----------------------------------------------------------------------------------*/ - - - // when event starts out FULL-DAY - - function draggableDayEvent(event, eventElement, isStart) { - var origWidth; - var revert; - var allDay=true; - var dayDelta; - var dis = opt('isRTL') ? -1 : 1; - var hoverListener = getHoverListener(); - var colWidth = getColWidth(); - var slotHeight = getSlotHeight(); - var minMinute = getMinMinute(); - eventElement.draggable({ - zIndex: 9, - opacity: opt('dragOpacity', 'month'), // use whatever the month view was using - revertDuration: opt('dragRevertDuration'), - start: function(ev, ui) { - trigger('eventDragStart', eventElement, event, ev, ui); - hideEvents(event, eventElement); - origWidth = eventElement.width(); - hoverListener.start(function(cell, origCell, rowDelta, colDelta) { - clearOverlays(); - if (cell) { - //setOverflowHidden(true); - revert = false; - dayDelta = colDelta * dis; - if (!cell.row) { - // on full-days - renderDayOverlay( - addDays(cloneDate(event.start), dayDelta), - addDays(exclEndDay(event), dayDelta) - ); - resetElement(); - }else{ - // mouse is over bottom slots - if (isStart) { - if (allDay) { - // convert event to temporary slot-event - eventElement.width(colWidth - 10); // don't use entire width - setOuterHeight( - eventElement, - slotHeight * Math.round( - (event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) - / opt('slotMinutes') - ) - ); - eventElement.draggable('option', 'grid', [colWidth, 1]); - allDay = false; - } - }else{ - revert = true; - } - } - revert = revert || (allDay && !dayDelta); - }else{ - resetElement(); - //setOverflowHidden(false); - revert = true; - } - eventElement.draggable('option', 'revert', revert); - }, ev, 'drag'); - }, - stop: function(ev, ui) { - hoverListener.stop(); - clearOverlays(); - trigger('eventDragStop', eventElement, event, ev, ui); - if (revert) { - // hasn't moved or is out of bounds (draggable has already reverted) - resetElement(); - eventElement.css('filter', ''); // clear IE opacity side-effects - showEvents(event, eventElement); - }else{ - // changed! - var minuteDelta = 0; - if (!allDay) { - minuteDelta = Math.round((eventElement.offset().top - getBodyContent().offset().top) / slotHeight) - * opt('slotMinutes') - + minMinute - - (event.start.getHours() * 60 + event.start.getMinutes()); - } - eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui); - } - //setOverflowHidden(false); - } - }); - function resetElement() { - if (!allDay) { - eventElement - .width(origWidth) - .height('') - .draggable('option', 'grid', null); - allDay = true; - } - } - } - - - // when event starts out IN TIMESLOTS - - function draggableSlotEvent(event, eventElement, timeElement) { - var origPosition; - var allDay=false; - var dayDelta; - var minuteDelta; - var prevMinuteDelta; - var dis = opt('isRTL') ? -1 : 1; - var hoverListener = getHoverListener(); - var colCnt = getColCnt(); - var colWidth = getColWidth(); - var slotHeight = getSlotHeight(); - eventElement.draggable({ - zIndex: 9, - scroll: false, - grid: [colWidth, slotHeight], - axis: colCnt==1 ? 'y' : false, - opacity: opt('dragOpacity'), - revertDuration: opt('dragRevertDuration'), - start: function(ev, ui) { - trigger('eventDragStart', eventElement, event, ev, ui); - hideEvents(event, eventElement); - origPosition = eventElement.position(); - minuteDelta = prevMinuteDelta = 0; - hoverListener.start(function(cell, origCell, rowDelta, colDelta) { - eventElement.draggable('option', 'revert', !cell); - clearOverlays(); - if (cell) { - dayDelta = colDelta * dis; - if (opt('allDaySlot') && !cell.row) { - // over full days - if (!allDay) { - // convert to temporary all-day event - allDay = true; - timeElement.hide(); - eventElement.draggable('option', 'grid', null); - } - renderDayOverlay( - addDays(cloneDate(event.start), dayDelta), - addDays(exclEndDay(event), dayDelta) - ); - }else{ - // on slots - resetElement(); - } - } - }, ev, 'drag'); - }, - drag: function(ev, ui) { - minuteDelta = Math.round((ui.position.top - origPosition.top) / slotHeight) * opt('slotMinutes'); - if (minuteDelta != prevMinuteDelta) { - if (!allDay) { - updateTimeText(minuteDelta); - } - prevMinuteDelta = minuteDelta; - } - }, - stop: function(ev, ui) { - var cell = hoverListener.stop(); - clearOverlays(); - trigger('eventDragStop', eventElement, event, ev, ui); - if (cell && (dayDelta || minuteDelta || allDay)) { - // changed! - eventDrop(this, event, dayDelta, allDay ? 0 : minuteDelta, allDay, ev, ui); - }else{ - // either no change or out-of-bounds (draggable has already reverted) - resetElement(); - eventElement.css('filter', ''); // clear IE opacity side-effects - eventElement.css(origPosition); // sometimes fast drags make event revert to wrong position - updateTimeText(0); - showEvents(event, eventElement); - } - } - }); - function updateTimeText(minuteDelta) { - var newStart = addMinutes(cloneDate(event.start), minuteDelta); - var newEnd; - if (event.end) { - newEnd = addMinutes(cloneDate(event.end), minuteDelta); - } - timeElement.text(formatDates(newStart, newEnd, opt('timeFormat'))); - } - function resetElement() { - // convert back to original slot-event - if (allDay) { - timeElement.css('display', ''); // show() was causing display=inline - eventElement.draggable('option', 'grid', [colWidth, slotHeight]); - allDay = false; - } - } - } - - - - /* Resizing - --------------------------------------------------------------------------------------*/ - - - function resizableSlotEvent(event, eventElement, timeElement) { - var slotDelta, prevSlotDelta; - var slotHeight = getSlotHeight(); - eventElement.resizable({ - handles: { - s: 'div.ui-resizable-s' - }, - grid: slotHeight, - start: function(ev, ui) { - slotDelta = prevSlotDelta = 0; - hideEvents(event, eventElement); - eventElement.css('z-index', 9); - trigger('eventResizeStart', this, event, ev, ui); - }, - resize: function(ev, ui) { - // don't rely on ui.size.height, doesn't take grid into account - slotDelta = Math.round((Math.max(slotHeight, eventElement.height()) - ui.originalSize.height) / slotHeight); - if (slotDelta != prevSlotDelta) { - timeElement.text( - formatDates( - event.start, - (!slotDelta && !event.end) ? null : // no change, so don't display time range - addMinutes(eventEnd(event), opt('slotMinutes')*slotDelta), - opt('timeFormat') - ) - ); - prevSlotDelta = slotDelta; - } - }, - stop: function(ev, ui) { - trigger('eventResizeStop', this, event, ev, ui); - if (slotDelta) { - eventResize(this, event, 0, opt('slotMinutes')*slotDelta, ev, ui); - }else{ - eventElement.css('z-index', 8); - showEvents(event, eventElement); - // BUG: if event was really short, need to put title back in span - } - } - }); - } - - -} - - -function countForwardSegs(levels) { - var i, j, k, level, segForward, segBack; - for (i=levels.length-1; i>0; i--) { - level = levels[i]; - for (j=0; j<level.length; j++) { - segForward = level[j]; - for (k=0; k<levels[i-1].length; k++) { - segBack = levels[i-1][k]; - if (segsCollide(segForward, segBack)) { - segBack.forward = Math.max(segBack.forward||0, (segForward.forward||0)+1); - } - } - } - } -} - - - - -function View(element, calendar, viewName) { - var t = this; - - - // exports - t.element = element; - t.calendar = calendar; - t.name = viewName; - t.opt = opt; - t.trigger = trigger; - //t.setOverflowHidden = setOverflowHidden; - t.isEventDraggable = isEventDraggable; - t.isEventResizable = isEventResizable; - t.reportEvents = reportEvents; - t.eventEnd = eventEnd; - t.reportEventElement = reportEventElement; - t.reportEventClear = reportEventClear; - t.eventElementHandlers = eventElementHandlers; - t.showEvents = showEvents; - t.hideEvents = hideEvents; - t.eventDrop = eventDrop; - t.eventResize = eventResize; - // t.title - // t.start, t.end - // t.visStart, t.visEnd - - - // imports - var defaultEventEnd = t.defaultEventEnd; - var normalizeEvent = calendar.normalizeEvent; // in EventManager - var reportEventChange = calendar.reportEventChange; - - - // locals - var eventsByID = {}; - var eventElements = []; - var eventElementsByID = {}; - var options = calendar.options; - - - - function opt(name, viewNameOverride) { - var v = options[name]; - if (typeof v == 'object') { - return smartProperty(v, viewNameOverride || viewName); - } - return v; - } - - - function trigger(name, thisObj) { - return calendar.trigger.apply( - calendar, - [name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t]) - ); - } - - - /* - function setOverflowHidden(bool) { - element.css('overflow', bool ? 'hidden' : ''); - } - */ - - - function isEventDraggable(event) { - return isEventEditable(event) && !opt('disableDragging'); - } - - - function isEventResizable(event) { // but also need to make sure the seg.isEnd == true - return isEventEditable(event) && !opt('disableResizing'); - } - - - function isEventEditable(event) { - return firstDefined(event.editable, (event.source || {}).editable, opt('editable')); - } - - - - /* Event Data - ------------------------------------------------------------------------------*/ - - - // report when view receives new events - function reportEvents(events) { // events are already normalized at this point - eventsByID = {}; - var i, len=events.length, event; - for (i=0; i<len; i++) { - event = events[i]; - if (eventsByID[event._id]) { - eventsByID[event._id].push(event); - }else{ - eventsByID[event._id] = [event]; - } - } - } - - - // returns a Date object for an event's end - function eventEnd(event) { - return event.end ? cloneDate(event.end) : defaultEventEnd(event); - } - - - - /* Event Elements - ------------------------------------------------------------------------------*/ - - - // report when view creates an element for an event - function reportEventElement(event, element) { - eventElements.push(element); - if (eventElementsByID[event._id]) { - eventElementsByID[event._id].push(element); - }else{ - eventElementsByID[event._id] = [element]; - } - } - - - function reportEventClear() { - eventElements = []; - eventElementsByID = {}; - } - - - // attaches eventClick, eventMouseover, eventMouseout - function eventElementHandlers(event, eventElement) { - eventElement - .click(function(ev) { - if (!eventElement.hasClass('ui-draggable-dragging') && - !eventElement.hasClass('ui-resizable-resizing')) { - return trigger('eventClick', this, event, ev); - } - }) - .hover( - function(ev) { - trigger('eventMouseover', this, event, ev); - }, - function(ev) { - trigger('eventMouseout', this, event, ev); - } - ); - // TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element) - // TODO: same for resizing - } - - - function showEvents(event, exceptElement) { - eachEventElement(event, exceptElement, 'show'); - } - - - function hideEvents(event, exceptElement) { - eachEventElement(event, exceptElement, 'hide'); - } - - - function eachEventElement(event, exceptElement, funcName) { - var elements = eventElementsByID[event._id], - i, len = elements.length; - for (i=0; i<len; i++) { - if (!exceptElement || elements[i][0] != exceptElement[0]) { - elements[i][funcName](); - } - } - } - - - - /* Event Modification Reporting - ---------------------------------------------------------------------------------*/ - - - function eventDrop(e, event, dayDelta, minuteDelta, allDay, ev, ui) { - var oldAllDay = event.allDay; - var eventId = event._id; - moveEvents(eventsByID[eventId], dayDelta, minuteDelta, allDay); - trigger( - 'eventDrop', - e, - event, - dayDelta, - minuteDelta, - allDay, - function() { - // TODO: investigate cases where this inverse technique might not work - moveEvents(eventsByID[eventId], -dayDelta, -minuteDelta, oldAllDay); - reportEventChange(eventId); - }, - ev, - ui - ); - reportEventChange(eventId); - } - - - function eventResize(e, event, dayDelta, minuteDelta, ev, ui) { - var eventId = event._id; - elongateEvents(eventsByID[eventId], dayDelta, minuteDelta); - trigger( - 'eventResize', - e, - event, - dayDelta, - minuteDelta, - function() { - // TODO: investigate cases where this inverse technique might not work - elongateEvents(eventsByID[eventId], -dayDelta, -minuteDelta); - reportEventChange(eventId); - }, - ev, - ui - ); - reportEventChange(eventId); - } - - - - /* Event Modification Math - ---------------------------------------------------------------------------------*/ - - - function moveEvents(events, dayDelta, minuteDelta, allDay) { - minuteDelta = minuteDelta || 0; - for (var e, len=events.length, i=0; i<len; i++) { - e = events[i]; - if (allDay !== undefined) { - e.allDay = allDay; - } - addMinutes(addDays(e.start, dayDelta, true), minuteDelta); - if (e.end) { - e.end = addMinutes(addDays(e.end, dayDelta, true), minuteDelta); - } - normalizeEvent(e, options); - } - } - - - function elongateEvents(events, dayDelta, minuteDelta) { - minuteDelta = minuteDelta || 0; - for (var e, len=events.length, i=0; i<len; i++) { - e = events[i]; - e.end = addMinutes(addDays(eventEnd(e), dayDelta, true), minuteDelta); - normalizeEvent(e, options); - } - } - - -} - -function DayEventRenderer() { - var t = this; - - - // exports - t.renderDaySegs = renderDaySegs; - t.resizableDayEvent = resizableDayEvent; - - - // imports - var opt = t.opt; - var trigger = t.trigger; - var isEventDraggable = t.isEventDraggable; - var isEventResizable = t.isEventResizable; - var eventEnd = t.eventEnd; - var reportEventElement = t.reportEventElement; - var showEvents = t.showEvents; - var hideEvents = t.hideEvents; - var eventResize = t.eventResize; - var getRowCnt = t.getRowCnt; - var getColCnt = t.getColCnt; - var getColWidth = t.getColWidth; - var allDayRow = t.allDayRow; - var allDayBounds = t.allDayBounds; - var colContentLeft = t.colContentLeft; - var colContentRight = t.colContentRight; - var dayOfWeekCol = t.dayOfWeekCol; - var dateCell = t.dateCell; - var compileDaySegs = t.compileDaySegs; - var getDaySegmentContainer = t.getDaySegmentContainer; - var bindDaySeg = t.bindDaySeg; //TODO: streamline this - var formatDates = t.calendar.formatDates; - var renderDayOverlay = t.renderDayOverlay; - var clearOverlays = t.clearOverlays; - var clearSelection = t.clearSelection; - - - - /* Rendering - -----------------------------------------------------------------------------*/ - - - function renderDaySegs(segs, modifiedEventId) { - var segmentContainer = getDaySegmentContainer(); - var rowDivs; - var rowCnt = getRowCnt(); - var colCnt = getColCnt(); - var i = 0; - var rowI; - var levelI; - var colHeights; - var j; - var segCnt = segs.length; - var seg; - var top; - var k; - segmentContainer[0].innerHTML = daySegHTML(segs); // faster than .html() - daySegElementResolve(segs, segmentContainer.children()); - daySegElementReport(segs); - daySegHandlers(segs, segmentContainer, modifiedEventId); - daySegCalcHSides(segs); - daySegSetWidths(segs); - daySegCalcHeights(segs); - rowDivs = getRowDivs(); - // set row heights, calculate event tops (in relation to row top) - for (rowI=0; rowI<rowCnt; rowI++) { - levelI = 0; - colHeights = []; - for (j=0; j<colCnt; j++) { - colHeights[j] = 0; - } - while (i<segCnt && (seg = segs[i]).row == rowI) { - // loop through segs in a row - top = arrayMax(colHeights.slice(seg.startCol, seg.endCol)); - seg.top = top; - top += seg.outerHeight; - for (k=seg.startCol; k<seg.endCol; k++) { - colHeights[k] = top; - } - i++; - } - rowDivs[rowI].height(arrayMax(colHeights)); - } - daySegSetTops(segs, getRowTops(rowDivs)); - } - - - function renderTempDaySegs(segs, adjustRow, adjustTop) { - var tempContainer = $("<div/>"); - var elements; - var segmentContainer = getDaySegmentContainer(); - var i; - var segCnt = segs.length; - var element; - tempContainer[0].innerHTML = daySegHTML(segs); // faster than .html() - elements = tempContainer.children(); - segmentContainer.append(elements); - daySegElementResolve(segs, elements); - daySegCalcHSides(segs); - daySegSetWidths(segs); - daySegCalcHeights(segs); - daySegSetTops(segs, getRowTops(getRowDivs())); - elements = []; - for (i=0; i<segCnt; i++) { - element = segs[i].element; - if (element) { - if (segs[i].row === adjustRow) { - element.css('top', adjustTop); - } - elements.push(element[0]); - } - } - return $(elements); - } - - - function daySegHTML(segs) { // also sets seg.left and seg.outerWidth - var rtl = opt('isRTL'); - var i; - var segCnt=segs.length; - var seg; - var event; - var url; - var classes; - var bounds = allDayBounds(); - var minLeft = bounds.left; - var maxLeft = bounds.right; - var leftCol; - var rightCol; - var left; - var right; - var skinCss; - var html = ''; - // calculate desired position/dimensions, create html - for (i=0; i<segCnt; i++) { - seg = segs[i]; - event = seg.event; - classes = ['fc-event', 'fc-event-skin', 'fc-event-hori']; - if (isEventDraggable(event)) { - classes.push('fc-event-draggable'); - } - if (rtl) { - if (seg.isStart) { - classes.push('fc-corner-right'); - } - if (seg.isEnd) { - classes.push('fc-corner-left'); - } - leftCol = dayOfWeekCol(seg.end.getDay()-1); - rightCol = dayOfWeekCol(seg.start.getDay()); - left = seg.isEnd ? colContentLeft(leftCol) : minLeft; - right = seg.isStart ? colContentRight(rightCol) : maxLeft; - }else{ - if (seg.isStart) { - classes.push('fc-corner-left'); - } - if (seg.isEnd) { - classes.push('fc-corner-right'); - } - leftCol = dayOfWeekCol(seg.start.getDay()); - rightCol = dayOfWeekCol(seg.end.getDay()-1); - left = seg.isStart ? colContentLeft(leftCol) : minLeft; - right = seg.isEnd ? colContentRight(rightCol) : maxLeft; - } - classes = classes.concat(event.className); - if (event.source) { - classes = classes.concat(event.source.className || []); - } - url = event.url; - skinCss = getSkinCss(event, opt); - if (url) { - html += "<a href='" + htmlEscape(url) + "'"; - }else{ - html += "<div"; - } - html += - " class='" + classes.join(' ') + "'" + - " style='position:absolute;z-index:8;left:"+left+"px;" + skinCss + "'" + - ">" + - "<div" + - " class='fc-event-inner fc-event-skin'" + - (skinCss ? " style='" + skinCss + "'" : '') + - ">"; - if (!event.allDay && seg.isStart) { - html += - "<span class='fc-event-time'>" + - htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + - "</span>"; - } - html += - "<span class='fc-event-title'>" + htmlEscape(event.title) + "</span>" + - "</div>"; - if (seg.isEnd && isEventResizable(event)) { - html += - "<div class='ui-resizable-handle ui-resizable-" + (rtl ? 'w' : 'e') + "'>" + - " " + // makes hit area a lot better for IE6/7 - "</div>"; - } - html += - "</" + (url ? "a" : "div" ) + ">"; - seg.left = left; - seg.outerWidth = right - left; - seg.startCol = leftCol; - seg.endCol = rightCol + 1; // needs to be exclusive - } - return html; - } - - - function daySegElementResolve(segs, elements) { // sets seg.element - var i; - var segCnt = segs.length; - var seg; - var event; - var element; - var triggerRes; - for (i=0; i<segCnt; i++) { - seg = segs[i]; - event = seg.event; - element = $(elements[i]); // faster than .eq() - triggerRes = trigger('eventRender', event, event, element); - if (triggerRes === false) { - element.remove(); - }else{ - if (triggerRes && triggerRes !== true) { - triggerRes = $(triggerRes) - .css({ - position: 'absolute', - left: seg.left - }); - element.replaceWith(triggerRes); - element = triggerRes; - } - seg.element = element; - } - } - } - - - function daySegElementReport(segs) { - var i; - var segCnt = segs.length; - var seg; - var element; - for (i=0; i<segCnt; i++) { - seg = segs[i]; - element = seg.element; - if (element) { - reportEventElement(seg.event, element); - } - } - } - - - function daySegHandlers(segs, segmentContainer, modifiedEventId) { - var i; - var segCnt = segs.length; - var seg; - var element; - var event; - // retrieve elements, run through eventRender callback, bind handlers - for (i=0; i<segCnt; i++) { - seg = segs[i]; - element = seg.element; - if (element) { - event = seg.event; - if (event._id === modifiedEventId) { - bindDaySeg(event, element, seg); - }else{ - element[0]._fci = i; // for lazySegBind - } - } - } - lazySegBind(segmentContainer, segs, bindDaySeg); - } - - - function daySegCalcHSides(segs) { // also sets seg.key - var i; - var segCnt = segs.length; - var seg; - var element; - var key, val; - var hsideCache = {}; - // record event horizontal sides - for (i=0; i<segCnt; i++) { - seg = segs[i]; - element = seg.element; - if (element) { - key = seg.key = cssKey(element[0]); - val = hsideCache[key]; - if (val === undefined) { - val = hsideCache[key] = hsides(element, true); - } - seg.hsides = val; - } - } - } - - - function daySegSetWidths(segs) { - var i; - var segCnt = segs.length; - var seg; - var element; - for (i=0; i<segCnt; i++) { - seg = segs[i]; - element = seg.element; - if (element) { - element[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px'; - } - } - } - - - function daySegCalcHeights(segs) { - var i; - var segCnt = segs.length; - var seg; - var element; - var key, val; - var vmarginCache = {}; - // record event heights - for (i=0; i<segCnt; i++) { - seg = segs[i]; - element = seg.element; - if (element) { - key = seg.key; // created in daySegCalcHSides - val = vmarginCache[key]; - if (val === undefined) { - val = vmarginCache[key] = vmargins(element); - } - seg.outerHeight = element[0].offsetHeight + val; - } - } - } - - - function getRowDivs() { - var i; - var rowCnt = getRowCnt(); - var rowDivs = []; - for (i=0; i<rowCnt; i++) { - rowDivs[i] = allDayRow(i) - .find('td:first div.fc-day-content > div'); // optimal selector? - } - return rowDivs; - } - - - function getRowTops(rowDivs) { - var i; - var rowCnt = rowDivs.length; - var tops = []; - for (i=0; i<rowCnt; i++) { - tops[i] = rowDivs[i][0].offsetTop; // !!?? but this means the element needs position:relative if in a table cell!!!! - } - return tops; - } - - - function daySegSetTops(segs, rowTops) { // also triggers eventAfterRender - var i; - var segCnt = segs.length; - var seg; - var element; - var event; - for (i=0; i<segCnt; i++) { - seg = segs[i]; - element = seg.element; - if (element) { - element[0].style.top = rowTops[seg.row] + (seg.top||0) + 'px'; - event = seg.event; - trigger('eventAfterRender', event, event, element); - } - } - } - - - - /* Resizing - -----------------------------------------------------------------------------------*/ - - - function resizableDayEvent(event, element, seg) { - var rtl = opt('isRTL'); - var direction = rtl ? 'w' : 'e'; - var handle = element.find('div.ui-resizable-' + direction); - var isResizing = false; - - // TODO: look into using jquery-ui mouse widget for this stuff - disableTextSelection(element); // prevent native <a> selection for IE - element - .mousedown(function(ev) { // prevent native <a> selection for others - ev.preventDefault(); - }) - .click(function(ev) { - if (isResizing) { - ev.preventDefault(); // prevent link from being visited (only method that worked in IE6) - ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called - // (eventElementHandlers needs to be bound after resizableDayEvent) - } - }); - - handle.mousedown(function(ev) { - if (ev.which != 1) { - return; // needs to be left mouse button - } - isResizing = true; - var hoverListener = t.getHoverListener(); - var rowCnt = getRowCnt(); - var colCnt = getColCnt(); - var dis = rtl ? -1 : 1; - var dit = rtl ? colCnt-1 : 0; - var elementTop = element.css('top'); - var dayDelta; - var helpers; - var eventCopy = $.extend({}, event); - var minCell = dateCell(event.start); - clearSelection(); - $('body') - .css('cursor', direction + '-resize') - .one('mouseup', mouseup); - trigger('eventResizeStart', this, event, ev); - hoverListener.start(function(cell, origCell) { - if (cell) { - var r = Math.max(minCell.row, cell.row); - var c = cell.col; - if (rowCnt == 1) { - r = 0; // hack for all-day area in agenda views - } - if (r == minCell.row) { - if (rtl) { - c = Math.min(minCell.col, c); - }else{ - c = Math.max(minCell.col, c); - } - } - dayDelta = (r*7 + c*dis+dit) - (origCell.row*7 + origCell.col*dis+dit); - var newEnd = addDays(eventEnd(event), dayDelta, true); - if (dayDelta) { - eventCopy.end = newEnd; - var oldHelpers = helpers; - helpers = renderTempDaySegs(compileDaySegs([eventCopy]), seg.row, elementTop); - helpers.find('*').css('cursor', direction + '-resize'); - if (oldHelpers) { - oldHelpers.remove(); - } - hideEvents(event); - }else{ - if (helpers) { - showEvents(event); - helpers.remove(); - helpers = null; - } - } - clearOverlays(); - renderDayOverlay(event.start, addDays(cloneDate(newEnd), 1)); // coordinate grid already rebuild at hoverListener.start - } - }, ev); - - function mouseup(ev) { - trigger('eventResizeStop', this, event, ev); - $('body').css('cursor', ''); - hoverListener.stop(); - clearOverlays(); - if (dayDelta) { - eventResize(this, event, dayDelta, 0, ev); - // event redraw will clear helpers - } - // otherwise, the drag handler already restored the old events - - setTimeout(function() { // make this happen after the element's click event - isResizing = false; - },0); - } - - }); - } - - -} - -//BUG: unselect needs to be triggered when events are dragged+dropped - -function SelectionManager() { - var t = this; - - - // exports - t.select = select; - t.unselect = unselect; - t.reportSelection = reportSelection; - t.daySelectionMousedown = daySelectionMousedown; - - - // imports - var opt = t.opt; - var trigger = t.trigger; - var defaultSelectionEnd = t.defaultSelectionEnd; - var renderSelection = t.renderSelection; - var clearSelection = t.clearSelection; - - - // locals - var selected = false; - - - - // unselectAuto - if (opt('selectable') && opt('unselectAuto')) { - $(document).mousedown(function(ev) { - var ignore = opt('unselectCancel'); - if (ignore) { - if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match - return; - } - } - unselect(ev); - }); - } - - - function select(startDate, endDate, allDay) { - unselect(); - if (!endDate) { - endDate = defaultSelectionEnd(startDate, allDay); - } - renderSelection(startDate, endDate, allDay); - reportSelection(startDate, endDate, allDay); - } - - - function unselect(ev) { - if (selected) { - selected = false; - clearSelection(); - trigger('unselect', null, ev); - } - } - - - function reportSelection(startDate, endDate, allDay, ev) { - selected = true; - trigger('select', null, startDate, endDate, allDay, ev); - } - - - function daySelectionMousedown(ev) { // not really a generic manager method, oh well - var cellDate = t.cellDate; - var cellIsAllDay = t.cellIsAllDay; - var hoverListener = t.getHoverListener(); - var reportDayClick = t.reportDayClick; // this is hacky and sort of weird - if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button - unselect(ev); - var _mousedownElement = this; - var dates; - hoverListener.start(function(cell, origCell) { // TODO: maybe put cellDate/cellIsAllDay info in cell - clearSelection(); - if (cell && cellIsAllDay(cell)) { - dates = [ cellDate(origCell), cellDate(cell) ].sort(cmp); - renderSelection(dates[0], dates[1], true); - }else{ - dates = null; - } - }, ev); - $(document).one('mouseup', function(ev) { - hoverListener.stop(); - if (dates) { - if (+dates[0] == +dates[1]) { - reportDayClick(dates[0], true, ev); - } - reportSelection(dates[0], dates[1], true, ev); - } - }); - } - } - - -} - -function OverlayManager() { - var t = this; - - - // exports - t.renderOverlay = renderOverlay; - t.clearOverlays = clearOverlays; - - - // locals - var usedOverlays = []; - var unusedOverlays = []; - - - function renderOverlay(rect, parent) { - var e = unusedOverlays.shift(); - if (!e) { - e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>"); - } - if (e[0].parentNode != parent[0]) { - e.appendTo(parent); - } - usedOverlays.push(e.css(rect).show()); - return e; - } - - - function clearOverlays() { - var e; - while (e = usedOverlays.shift()) { - unusedOverlays.push(e.hide().unbind()); - } - } - - -} - -function CoordinateGrid(buildFunc) { - - var t = this; - var rows; - var cols; - - - t.build = function() { - rows = []; - cols = []; - buildFunc(rows, cols); - }; - - - t.cell = function(x, y) { - var rowCnt = rows.length; - var colCnt = cols.length; - var i, r=-1, c=-1; - for (i=0; i<rowCnt; i++) { - if (y >= rows[i][0] && y < rows[i][1]) { - r = i; - break; - } - } - for (i=0; i<colCnt; i++) { - if (x >= cols[i][0] && x < cols[i][1]) { - c = i; - break; - } - } - return (r>=0 && c>=0) ? { row:r, col:c } : null; - }; - - - t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive - var origin = originElement.offset(); - return { - top: rows[row0][0] - origin.top, - left: cols[col0][0] - origin.left, - width: cols[col1][1] - cols[col0][0], - height: rows[row1][1] - rows[row0][0] - }; - }; - -} - -function HoverListener(coordinateGrid) { - - - var t = this; - var bindType; - var change; - var firstCell; - var cell; - - - t.start = function(_change, ev, _bindType) { - change = _change; - firstCell = cell = null; - coordinateGrid.build(); - mouse(ev); - bindType = _bindType || 'mousemove'; - $(document).bind(bindType, mouse); - }; - - - function mouse(ev) { - var newCell = coordinateGrid.cell(ev.pageX, ev.pageY); - if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col)) { - if (newCell) { - if (!firstCell) { - firstCell = newCell; - } - change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col); - }else{ - change(newCell, firstCell); - } - cell = newCell; - } - } - - - t.stop = function() { - $(document).unbind(bindType, mouse); - return cell; - }; - - -} - -function HorizontalPositionCache(getElement) { - - var t = this, - elements = {}, - lefts = {}, - rights = {}; - - function e(i) { - return elements[i] = elements[i] || getElement(i); - } - - t.left = function(i) { - return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i]; - }; - - t.right = function(i) { - return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i]; - }; - - t.clear = function() { - elements = {}; - lefts = {}; - rights = {}; - }; - -} - -})(jQuery); diff --git a/3rdparty/fullcalendar/js/fullcalendar.min.js b/3rdparty/fullcalendar/js/fullcalendar.min.js deleted file mode 100644 index fc06a89a6106dd2e5a7380f87290cb86a21b8a70..0000000000000000000000000000000000000000 --- a/3rdparty/fullcalendar/js/fullcalendar.min.js +++ /dev/null @@ -1,113 +0,0 @@ -/* - - FullCalendar v1.5.2 - http://arshaw.com/fullcalendar/ - - Use fullcalendar.css for basic styling. - For event drag & drop, requires jQuery UI draggable. - For event resizing, requires jQuery UI resizable. - - Copyright (c) 2011 Adam Shaw - Dual licensed under the MIT and GPL licenses, located in - MIT-LICENSE.txt and GPL-LICENSE.txt respectively. - - Date: Sun Aug 21 22:06:09 2011 -0700 - -*/ -(function(m,oa){function wb(a){m.extend(true,Ya,a)}function Yb(a,b,e){function d(k){if(E){u();q();ma();S(k)}else f()}function f(){B=b.theme?"ui":"fc";a.addClass("fc");b.isRTL&&a.addClass("fc-rtl");b.theme&&a.addClass("ui-widget");E=m("<div class='fc-content' style='position:relative'/>").prependTo(a);C=new Zb(X,b);(P=C.render())&&a.prepend(P);y(b.defaultView);m(window).resize(na);t()||g()}function g(){setTimeout(function(){!n.start&&t()&&S()},0)}function l(){m(window).unbind("resize",na);C.destroy(); -E.remove();a.removeClass("fc fc-rtl ui-widget")}function j(){return i.offsetWidth!==0}function t(){return m("body")[0].offsetWidth!==0}function y(k){if(!n||k!=n.name){F++;pa();var D=n,Z;if(D){(D.beforeHide||xb)();Za(E,E.height());D.element.hide()}else Za(E,1);E.css("overflow","hidden");if(n=Y[k])n.element.show();else n=Y[k]=new Ja[k](Z=s=m("<div class='fc-view fc-view-"+k+"' style='position:absolute'/>").appendTo(E),X);D&&C.deactivateButton(D.name);C.activateButton(k);S();E.css("overflow","");D&& -Za(E,1);Z||(n.afterShow||xb)();F--}}function S(k){if(j()){F++;pa();o===oa&&u();var D=false;if(!n.start||k||r<n.start||r>=n.end){n.render(r,k||0);fa(true);D=true}else if(n.sizeDirty){n.clearEvents();fa();D=true}else if(n.eventsDirty){n.clearEvents();D=true}n.sizeDirty=false;n.eventsDirty=false;ga(D);W=a.outerWidth();C.updateTitle(n.title);k=new Date;k>=n.start&&k<n.end?C.disableButton("today"):C.enableButton("today");F--;n.trigger("viewDisplay",i)}}function Q(){q();if(j()){u();fa();pa();n.clearEvents(); -n.renderEvents(J);n.sizeDirty=false}}function q(){m.each(Y,function(k,D){D.sizeDirty=true})}function u(){o=b.contentHeight?b.contentHeight:b.height?b.height-(P?P.height():0)-Sa(E):Math.round(E.width()/Math.max(b.aspectRatio,0.5))}function fa(k){F++;n.setHeight(o,k);if(s){s.css("position","relative");s=null}n.setWidth(E.width(),k);F--}function na(){if(!F)if(n.start){var k=++v;setTimeout(function(){if(k==v&&!F&&j())if(W!=(W=a.outerWidth())){F++;Q();n.trigger("windowResize",i);F--}},200)}else g()}function ga(k){if(!b.lazyFetching|| -ya(n.visStart,n.visEnd))ra();else k&&da()}function ra(){K(n.visStart,n.visEnd)}function sa(k){J=k;da()}function ha(k){da(k)}function da(k){ma();if(j()){n.clearEvents();n.renderEvents(J,k);n.eventsDirty=false}}function ma(){m.each(Y,function(k,D){D.eventsDirty=true})}function ua(k,D,Z){n.select(k,D,Z===oa?true:Z)}function pa(){n&&n.unselect()}function U(){S(-1)}function ca(){S(1)}function ka(){gb(r,-1);S()}function qa(){gb(r,1);S()}function G(){r=new Date;S()}function p(k,D,Z){if(k instanceof Date)r= -N(k);else yb(r,k,D,Z);S()}function L(k,D,Z){k!==oa&&gb(r,k);D!==oa&&hb(r,D);Z!==oa&&ba(r,Z);S()}function c(){return N(r)}function z(){return n}function H(k,D){if(D===oa)return b[k];if(k=="height"||k=="contentHeight"||k=="aspectRatio"){b[k]=D;Q()}}function T(k,D){if(b[k])return b[k].apply(D||i,Array.prototype.slice.call(arguments,2))}var X=this;X.options=b;X.render=d;X.destroy=l;X.refetchEvents=ra;X.reportEvents=sa;X.reportEventChange=ha;X.rerenderEvents=da;X.changeView=y;X.select=ua;X.unselect=pa; -X.prev=U;X.next=ca;X.prevYear=ka;X.nextYear=qa;X.today=G;X.gotoDate=p;X.incrementDate=L;X.formatDate=function(k,D){return Oa(k,D,b)};X.formatDates=function(k,D,Z){return ib(k,D,Z,b)};X.getDate=c;X.getView=z;X.option=H;X.trigger=T;$b.call(X,b,e);var ya=X.isFetchNeeded,K=X.fetchEvents,i=a[0],C,P,E,B,n,Y={},W,o,s,v=0,F=0,r=new Date,J=[],M;yb(r,b.year,b.month,b.date);b.droppable&&m(document).bind("dragstart",function(k,D){var Z=k.target,ja=m(Z);if(!ja.parents(".fc").length){var ia=b.dropAccept;if(m.isFunction(ia)? -ia.call(Z,ja):ja.is(ia)){M=Z;n.dragStart(M,k,D)}}}).bind("dragstop",function(k,D){if(M){n.dragStop(M,k,D);M=null}})}function Zb(a,b){function e(){q=b.theme?"ui":"fc";if(b.header)return Q=m("<table class='fc-header' style='width:100%'/>").append(m("<tr/>").append(f("left")).append(f("center")).append(f("right")))}function d(){Q.remove()}function f(u){var fa=m("<td class='fc-header-"+u+"'/>");(u=b.header[u])&&m.each(u.split(" "),function(na){na>0&&fa.append("<span class='fc-header-space'/>");var ga; -m.each(this.split(","),function(ra,sa){if(sa=="title"){fa.append("<span class='fc-header-title'><h2> </h2></span>");ga&&ga.addClass(q+"-corner-right");ga=null}else{var ha;if(a[sa])ha=a[sa];else if(Ja[sa])ha=function(){ma.removeClass(q+"-state-hover");a.changeView(sa)};if(ha){ra=b.theme?jb(b.buttonIcons,sa):null;var da=jb(b.buttonText,sa),ma=m("<span class='fc-button fc-button-"+sa+" "+q+"-state-default'><span class='fc-button-inner'><span class='fc-button-content'>"+(ra?"<span class='fc-icon-wrap'><span class='ui-icon ui-icon-"+ -ra+"'/></span>":da)+"</span><span class='fc-button-effect'><span></span></span></span></span>");if(ma){ma.click(function(){ma.hasClass(q+"-state-disabled")||ha()}).mousedown(function(){ma.not("."+q+"-state-active").not("."+q+"-state-disabled").addClass(q+"-state-down")}).mouseup(function(){ma.removeClass(q+"-state-down")}).hover(function(){ma.not("."+q+"-state-active").not("."+q+"-state-disabled").addClass(q+"-state-hover")},function(){ma.removeClass(q+"-state-hover").removeClass(q+"-state-down")}).appendTo(fa); -ga||ma.addClass(q+"-corner-left");ga=ma}}}});ga&&ga.addClass(q+"-corner-right")});return fa}function g(u){Q.find("h2").html(u)}function l(u){Q.find("span.fc-button-"+u).addClass(q+"-state-active")}function j(u){Q.find("span.fc-button-"+u).removeClass(q+"-state-active")}function t(u){Q.find("span.fc-button-"+u).addClass(q+"-state-disabled")}function y(u){Q.find("span.fc-button-"+u).removeClass(q+"-state-disabled")}var S=this;S.render=e;S.destroy=d;S.updateTitle=g;S.activateButton=l;S.deactivateButton= -j;S.disableButton=t;S.enableButton=y;var Q=m([]),q}function $b(a,b){function e(c,z){return!ca||c<ca||z>ka}function d(c,z){ca=c;ka=z;L=[];c=++qa;G=z=U.length;for(var H=0;H<z;H++)f(U[H],c)}function f(c,z){g(c,function(H){if(z==qa){if(H){for(var T=0;T<H.length;T++){H[T].source=c;na(H[T])}L=L.concat(H)}G--;G||ua(L)}})}function g(c,z){var H,T=Aa.sourceFetchers,X;for(H=0;H<T.length;H++){X=T[H](c,ca,ka,z);if(X===true)return;else if(typeof X=="object"){g(X,z);return}}if(H=c.events)if(m.isFunction(H)){u(); -H(N(ca),N(ka),function(C){z(C);fa()})}else m.isArray(H)?z(H):z();else if(c.url){var ya=c.success,K=c.error,i=c.complete;H=m.extend({},c.data||{});T=Ta(c.startParam,a.startParam);X=Ta(c.endParam,a.endParam);if(T)H[T]=Math.round(+ca/1E3);if(X)H[X]=Math.round(+ka/1E3);u();m.ajax(m.extend({},ac,c,{data:H,success:function(C){C=C||[];var P=$a(ya,this,arguments);if(m.isArray(P))C=P;z(C)},error:function(){$a(K,this,arguments);z()},complete:function(){$a(i,this,arguments);fa()}}))}else z()}function l(c){if(c= -j(c)){G++;f(c,qa)}}function j(c){if(m.isFunction(c)||m.isArray(c))c={events:c};else if(typeof c=="string")c={url:c};if(typeof c=="object"){ga(c);U.push(c);return c}}function t(c){U=m.grep(U,function(z){return!ra(z,c)});L=m.grep(L,function(z){return!ra(z.source,c)});ua(L)}function y(c){var z,H=L.length,T,X=ma().defaultEventEnd,ya=c.start-c._start,K=c.end?c.end-(c._end||X(c)):0;for(z=0;z<H;z++){T=L[z];if(T._id==c._id&&T!=c){T.start=new Date(+T.start+ya);T.end=c.end?T.end?new Date(+T.end+K):new Date(+X(T)+ -K):null;T.title=c.title;T.url=c.url;T.allDay=c.allDay;T.className=c.className;T.editable=c.editable;T.color=c.color;T.backgroudColor=c.backgroudColor;T.borderColor=c.borderColor;T.textColor=c.textColor;na(T)}}na(c);ua(L)}function S(c,z){na(c);if(!c.source){if(z){pa.events.push(c);c.source=pa}L.push(c)}ua(L)}function Q(c){if(c){if(!m.isFunction(c)){var z=c+"";c=function(T){return T._id==z}}L=m.grep(L,c,true);for(H=0;H<U.length;H++)if(m.isArray(U[H].events))U[H].events=m.grep(U[H].events,c,true)}else{L= -[];for(var H=0;H<U.length;H++)if(m.isArray(U[H].events))U[H].events=[]}ua(L)}function q(c){if(m.isFunction(c))return m.grep(L,c);else if(c){c+="";return m.grep(L,function(z){return z._id==c})}return L}function u(){p++||da("loading",null,true)}function fa(){--p||da("loading",null,false)}function na(c){var z=c.source||{},H=Ta(z.ignoreTimezone,a.ignoreTimezone);c._id=c._id||(c.id===oa?"_fc"+bc++:c.id+"");if(c.date){if(!c.start)c.start=c.date;delete c.date}c._start=N(c.start=kb(c.start,H));c.end=kb(c.end, -H);if(c.end&&c.end<=c.start)c.end=null;c._end=c.end?N(c.end):null;if(c.allDay===oa)c.allDay=Ta(z.allDayDefault,a.allDayDefault);if(c.className){if(typeof c.className=="string")c.className=c.className.split(/\s+/)}else c.className=[]}function ga(c){if(c.className){if(typeof c.className=="string")c.className=c.className.split(/\s+/)}else c.className=[];for(var z=Aa.sourceNormalizers,H=0;H<z.length;H++)z[H](c)}function ra(c,z){return c&&z&&sa(c)==sa(z)}function sa(c){return(typeof c=="object"?c.events|| -c.url:"")||c}var ha=this;ha.isFetchNeeded=e;ha.fetchEvents=d;ha.addEventSource=l;ha.removeEventSource=t;ha.updateEvent=y;ha.renderEvent=S;ha.removeEvents=Q;ha.clientEvents=q;ha.normalizeEvent=na;var da=ha.trigger,ma=ha.getView,ua=ha.reportEvents,pa={events:[]},U=[pa],ca,ka,qa=0,G=0,p=0,L=[];for(ha=0;ha<b.length;ha++)j(b[ha])}function gb(a,b,e){a.setFullYear(a.getFullYear()+b);e||Ka(a);return a}function hb(a,b,e){if(+a){b=a.getMonth()+b;var d=N(a);d.setDate(1);d.setMonth(b);a.setMonth(b);for(e||Ka(a);a.getMonth()!= -d.getMonth();)a.setDate(a.getDate()+(a<d?1:-1))}return a}function ba(a,b,e){if(+a){b=a.getDate()+b;var d=N(a);d.setHours(9);d.setDate(b);a.setDate(b);e||Ka(a);lb(a,d)}return a}function lb(a,b){if(+a)for(;a.getDate()!=b.getDate();)a.setTime(+a+(a<b?1:-1)*cc)}function xa(a,b){a.setMinutes(a.getMinutes()+b);return a}function Ka(a){a.setHours(0);a.setMinutes(0);a.setSeconds(0);a.setMilliseconds(0);return a}function N(a,b){if(b)return Ka(new Date(+a));return new Date(+a)}function zb(){var a=0,b;do b=new Date(1970, -a++,1);while(b.getHours());return b}function Fa(a,b,e){for(b=b||1;!a.getDay()||e&&a.getDay()==1||!e&&a.getDay()==6;)ba(a,b);return a}function Ca(a,b){return Math.round((N(a,true)-N(b,true))/Ab)}function yb(a,b,e,d){if(b!==oa&&b!=a.getFullYear()){a.setDate(1);a.setMonth(0);a.setFullYear(b)}if(e!==oa&&e!=a.getMonth()){a.setDate(1);a.setMonth(e)}d!==oa&&a.setDate(d)}function kb(a,b){if(typeof a=="object")return a;if(typeof a=="number")return new Date(a*1E3);if(typeof a=="string"){if(a.match(/^\d+(\.\d+)?$/))return new Date(parseFloat(a)* -1E3);if(b===oa)b=true;return Bb(a,b)||(a?new Date(a):null)}return null}function Bb(a,b){a=a.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/);if(!a)return null;var e=new Date(a[1],0,1);if(b||!a[13]){b=new Date(a[1],0,1,9,0);if(a[3]){e.setMonth(a[3]-1);b.setMonth(a[3]-1)}if(a[5]){e.setDate(a[5]);b.setDate(a[5])}lb(e,b);a[7]&&e.setHours(a[7]);a[8]&&e.setMinutes(a[8]);a[10]&&e.setSeconds(a[10]);a[12]&&e.setMilliseconds(Number("0."+ -a[12])*1E3);lb(e,b)}else{e.setUTCFullYear(a[1],a[3]?a[3]-1:0,a[5]||1);e.setUTCHours(a[7]||0,a[8]||0,a[10]||0,a[12]?Number("0."+a[12])*1E3:0);if(a[14]){b=Number(a[16])*60+(a[18]?Number(a[18]):0);b*=a[15]=="-"?1:-1;e=new Date(+e+b*60*1E3)}}return e}function mb(a){if(typeof a=="number")return a*60;if(typeof a=="object")return a.getHours()*60+a.getMinutes();if(a=a.match(/(\d+)(?::(\d+))?\s*(\w+)?/)){var b=parseInt(a[1],10);if(a[3]){b%=12;if(a[3].toLowerCase().charAt(0)=="p")b+=12}return b*60+(a[2]?parseInt(a[2], -10):0)}}function Oa(a,b,e){return ib(a,null,b,e)}function ib(a,b,e,d){d=d||Ya;var f=a,g=b,l,j=e.length,t,y,S,Q="";for(l=0;l<j;l++){t=e.charAt(l);if(t=="'")for(y=l+1;y<j;y++){if(e.charAt(y)=="'"){if(f){Q+=y==l+1?"'":e.substring(l+1,y);l=y}break}}else if(t=="(")for(y=l+1;y<j;y++){if(e.charAt(y)==")"){l=Oa(f,e.substring(l+1,y),d);if(parseInt(l.replace(/\D/,""),10))Q+=l;l=y;break}}else if(t=="[")for(y=l+1;y<j;y++){if(e.charAt(y)=="]"){t=e.substring(l+1,y);l=Oa(f,t,d);if(l!=Oa(g,t,d))Q+=l;l=y;break}}else if(t== -"{"){f=b;g=a}else if(t=="}"){f=a;g=b}else{for(y=j;y>l;y--)if(S=dc[e.substring(l,y)]){if(f)Q+=S(f,d);l=y-1;break}if(y==l)if(f)Q+=t}}return Q}function Ua(a){return a.end?ec(a.end,a.allDay):ba(N(a.start),1)}function ec(a,b){a=N(a);return b||a.getHours()||a.getMinutes()?ba(a,1):Ka(a)}function fc(a,b){return(b.msLength-a.msLength)*100+(a.event.start-b.event.start)}function Cb(a,b){return a.end>b.start&&a.start<b.end}function nb(a,b,e,d){var f=[],g,l=a.length,j,t,y,S,Q;for(g=0;g<l;g++){j=a[g];t=j.start; -y=b[g];if(y>e&&t<d){if(t<e){t=N(e);S=false}else{t=t;S=true}if(y>d){y=N(d);Q=false}else{y=y;Q=true}f.push({event:j,start:t,end:y,isStart:S,isEnd:Q,msLength:y-t})}}return f.sort(fc)}function ob(a){var b=[],e,d=a.length,f,g,l,j;for(e=0;e<d;e++){f=a[e];for(g=0;;){l=false;if(b[g])for(j=0;j<b[g].length;j++)if(Cb(b[g][j],f)){l=true;break}if(l)g++;else break}if(b[g])b[g].push(f);else b[g]=[f]}return b}function Db(a,b,e){a.unbind("mouseover").mouseover(function(d){for(var f=d.target,g;f!=this;){g=f;f=f.parentNode}if((f= -g._fci)!==oa){g._fci=oa;g=b[f];e(g.event,g.element,g);m(d.target).trigger(d)}d.stopPropagation()})}function Va(a,b,e){for(var d=0,f;d<a.length;d++){f=m(a[d]);f.width(Math.max(0,b-pb(f,e)))}}function Eb(a,b,e){for(var d=0,f;d<a.length;d++){f=m(a[d]);f.height(Math.max(0,b-Sa(f,e)))}}function pb(a,b){return gc(a)+hc(a)+(b?ic(a):0)}function gc(a){return(parseFloat(m.curCSS(a[0],"paddingLeft",true))||0)+(parseFloat(m.curCSS(a[0],"paddingRight",true))||0)}function ic(a){return(parseFloat(m.curCSS(a[0], -"marginLeft",true))||0)+(parseFloat(m.curCSS(a[0],"marginRight",true))||0)}function hc(a){return(parseFloat(m.curCSS(a[0],"borderLeftWidth",true))||0)+(parseFloat(m.curCSS(a[0],"borderRightWidth",true))||0)}function Sa(a,b){return jc(a)+kc(a)+(b?Fb(a):0)}function jc(a){return(parseFloat(m.curCSS(a[0],"paddingTop",true))||0)+(parseFloat(m.curCSS(a[0],"paddingBottom",true))||0)}function Fb(a){return(parseFloat(m.curCSS(a[0],"marginTop",true))||0)+(parseFloat(m.curCSS(a[0],"marginBottom",true))||0)} -function kc(a){return(parseFloat(m.curCSS(a[0],"borderTopWidth",true))||0)+(parseFloat(m.curCSS(a[0],"borderBottomWidth",true))||0)}function Za(a,b){b=typeof b=="number"?b+"px":b;a.each(function(e,d){d.style.cssText+=";min-height:"+b+";_height:"+b})}function xb(){}function Gb(a,b){return a-b}function Hb(a){return Math.max.apply(Math,a)}function Pa(a){return(a<10?"0":"")+a}function jb(a,b){if(a[b]!==oa)return a[b];b=b.split(/(?=[A-Z])/);for(var e=b.length-1,d;e>=0;e--){d=a[b[e].toLowerCase()];if(d!== -oa)return d}return a[""]}function Qa(a){return a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/"/g,""").replace(/\n/g,"<br />")}function Ib(a){return a.id+"/"+a.className+"/"+a.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig,"")}function qb(a){a.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})}function ab(a){a.children().removeClass("fc-first fc-last").filter(":first-child").addClass("fc-first").end().filter(":last-child").addClass("fc-last")} -function rb(a,b){a.each(function(e,d){d.className=d.className.replace(/^fc-\w*/,"fc-"+lc[b.getDay()])})}function Jb(a,b){var e=a.source||{},d=a.color,f=e.color,g=b("eventColor"),l=a.backgroundColor||d||e.backgroundColor||f||b("eventBackgroundColor")||g;d=a.borderColor||d||e.borderColor||f||b("eventBorderColor")||g;a=a.textColor||e.textColor||b("eventTextColor");b=[];l&&b.push("background-color:"+l);d&&b.push("border-color:"+d);a&&b.push("color:"+a);return b.join(";")}function $a(a,b,e){if(m.isFunction(a))a= -[a];if(a){var d,f;for(d=0;d<a.length;d++)f=a[d].apply(b,e)||f;return f}}function Ta(){for(var a=0;a<arguments.length;a++)if(arguments[a]!==oa)return arguments[a]}function mc(a,b){function e(j,t){if(t){hb(j,t);j.setDate(1)}j=N(j,true);j.setDate(1);t=hb(N(j),1);var y=N(j),S=N(t),Q=f("firstDay"),q=f("weekends")?0:1;if(q){Fa(y);Fa(S,-1,true)}ba(y,-((y.getDay()-Math.max(Q,q)+7)%7));ba(S,(7-S.getDay()+Math.max(Q,q))%7);Q=Math.round((S-y)/(Ab*7));if(f("weekMode")=="fixed"){ba(S,(6-Q)*7);Q=6}d.title=l(j, -f("titleFormat"));d.start=j;d.end=t;d.visStart=y;d.visEnd=S;g(6,Q,q?5:7,true)}var d=this;d.render=e;sb.call(d,a,b,"month");var f=d.opt,g=d.renderBasic,l=b.formatDate}function nc(a,b){function e(j,t){t&&ba(j,t*7);j=ba(N(j),-((j.getDay()-f("firstDay")+7)%7));t=ba(N(j),7);var y=N(j),S=N(t),Q=f("weekends");if(!Q){Fa(y);Fa(S,-1,true)}d.title=l(y,ba(N(S),-1),f("titleFormat"));d.start=j;d.end=t;d.visStart=y;d.visEnd=S;g(1,1,Q?7:5,false)}var d=this;d.render=e;sb.call(d,a,b,"basicWeek");var f=d.opt,g=d.renderBasic, -l=b.formatDates}function oc(a,b){function e(j,t){if(t){ba(j,t);f("weekends")||Fa(j,t<0?-1:1)}d.title=l(j,f("titleFormat"));d.start=d.visStart=N(j,true);d.end=d.visEnd=ba(N(d.start),1);g(1,1,1,false)}var d=this;d.render=e;sb.call(d,a,b,"basicDay");var f=d.opt,g=d.renderBasic,l=b.formatDate}function sb(a,b,e){function d(w,I,R,V){v=I;F=R;f();(I=!C)?g(w,V):z();l(I)}function f(){if(k=L("isRTL")){D=-1;Z=F-1}else{D=1;Z=0}ja=L("firstDay");ia=L("weekends")?0:1;la=L("theme")?"ui":"fc";$=L("columnFormat")}function g(w, -I){var R,V=la+"-widget-header",ea=la+"-widget-content",aa;R="<table class='fc-border-separate' style='width:100%' cellspacing='0'><thead><tr>";for(aa=0;aa<F;aa++)R+="<th class='fc- "+V+"'/>";R+="</tr></thead><tbody>";for(aa=0;aa<w;aa++){R+="<tr class='fc-week"+aa+"'>";for(V=0;V<F;V++)R+="<td class='fc- "+ea+" fc-day"+(aa*F+V)+"'><div>"+(I?"<div class='fc-day-number'/>":"")+"<div class='fc-day-content'><div style='position:relative'> </div></div></div></td>";R+="</tr>"}R+="</tbody></table>";w= -m(R).appendTo(a);K=w.find("thead");i=K.find("th");C=w.find("tbody");P=C.find("tr");E=C.find("td");B=E.filter(":first-child");n=P.eq(0).find("div.fc-day-content div");ab(K.add(K.find("tr")));ab(P);P.eq(0).addClass("fc-first");y(E);Y=m("<div style='position:absolute;z-index:8;top:0;left:0'/>").appendTo(a)}function l(w){var I=w||v==1,R=p.start.getMonth(),V=Ka(new Date),ea,aa,va;I&&i.each(function(wa,Ga){ea=m(Ga);aa=ca(wa);ea.html(ya(aa,$));rb(ea,aa)});E.each(function(wa,Ga){ea=m(Ga);aa=ca(wa);aa.getMonth()== -R?ea.removeClass("fc-other-month"):ea.addClass("fc-other-month");+aa==+V?ea.addClass(la+"-state-highlight fc-today"):ea.removeClass(la+"-state-highlight fc-today");ea.find("div.fc-day-number").text(aa.getDate());I&&rb(ea,aa)});P.each(function(wa,Ga){va=m(Ga);if(wa<v){va.show();wa==v-1?va.addClass("fc-last"):va.removeClass("fc-last")}else va.hide()})}function j(w){o=w;w=o-K.height();var I,R,V;if(L("weekMode")=="variable")I=R=Math.floor(w/(v==1?2:6));else{I=Math.floor(w/v);R=w-I*(v-1)}B.each(function(ea, -aa){if(ea<v){V=m(aa);Za(V.find("> div"),(ea==v-1?R:I)-Sa(V))}})}function t(w){W=w;M.clear();s=Math.floor(W/F);Va(i.slice(0,-1),s)}function y(w){w.click(S).mousedown(X)}function S(w){if(!L("selectable")){var I=parseInt(this.className.match(/fc\-day(\d+)/)[1]);I=ca(I);c("dayClick",this,I,true,w)}}function Q(w,I,R){R&&r.build();R=N(p.visStart);for(var V=ba(N(R),F),ea=0;ea<v;ea++){var aa=new Date(Math.max(R,w)),va=new Date(Math.min(V,I));if(aa<va){var wa;if(k){wa=Ca(va,R)*D+Z+1;aa=Ca(aa,R)*D+Z+1}else{wa= -Ca(aa,R);aa=Ca(va,R)}y(q(ea,wa,ea,aa-1))}ba(R,7);ba(V,7)}}function q(w,I,R,V){w=r.rect(w,I,R,V,a);return H(w,a)}function u(w){return N(w)}function fa(w,I){Q(w,ba(N(I),1),true)}function na(){T()}function ga(w,I,R){var V=ua(w);c("dayClick",E[V.row*F+V.col],w,I,R)}function ra(w,I){J.start(function(R){T();R&&q(R.row,R.col,R.row,R.col)},I)}function sa(w,I,R){var V=J.stop();T();if(V){V=pa(V);c("drop",w,V,true,I,R)}}function ha(w){return N(w.start)}function da(w){return M.left(w)}function ma(w){return M.right(w)} -function ua(w){return{row:Math.floor(Ca(w,p.visStart)/7),col:ka(w.getDay())}}function pa(w){return U(w.row,w.col)}function U(w,I){return ba(N(p.visStart),w*7+I*D+Z)}function ca(w){return U(Math.floor(w/F),w%F)}function ka(w){return(w-Math.max(ja,ia)+F)%F*D+Z}function qa(w){return P.eq(w)}function G(){return{left:0,right:W}}var p=this;p.renderBasic=d;p.setHeight=j;p.setWidth=t;p.renderDayOverlay=Q;p.defaultSelectionEnd=u;p.renderSelection=fa;p.clearSelection=na;p.reportDayClick=ga;p.dragStart=ra;p.dragStop= -sa;p.defaultEventEnd=ha;p.getHoverListener=function(){return J};p.colContentLeft=da;p.colContentRight=ma;p.dayOfWeekCol=ka;p.dateCell=ua;p.cellDate=pa;p.cellIsAllDay=function(){return true};p.allDayRow=qa;p.allDayBounds=G;p.getRowCnt=function(){return v};p.getColCnt=function(){return F};p.getColWidth=function(){return s};p.getDaySegmentContainer=function(){return Y};Kb.call(p,a,b,e);Lb.call(p);Mb.call(p);pc.call(p);var L=p.opt,c=p.trigger,z=p.clearEvents,H=p.renderOverlay,T=p.clearOverlays,X=p.daySelectionMousedown, -ya=b.formatDate,K,i,C,P,E,B,n,Y,W,o,s,v,F,r,J,M,k,D,Z,ja,ia,la,$;qb(a.addClass("fc-grid"));r=new Nb(function(w,I){var R,V,ea;i.each(function(aa,va){R=m(va);V=R.offset().left;if(aa)ea[1]=V;ea=[V];I[aa]=ea});ea[1]=V+R.outerWidth();P.each(function(aa,va){if(aa<v){R=m(va);V=R.offset().top;if(aa)ea[1]=V;ea=[V];w[aa]=ea}});ea[1]=V+R.outerHeight()});J=new Ob(r);M=new Pb(function(w){return n.eq(w)})}function pc(){function a(U,ca){S(U);ua(e(U),ca)}function b(){Q();ga().empty()}function e(U){var ca=da(),ka= -ma(),qa=N(g.visStart);ka=ba(N(qa),ka);var G=m.map(U,Ua),p,L,c,z,H,T,X=[];for(p=0;p<ca;p++){L=ob(nb(U,G,qa,ka));for(c=0;c<L.length;c++){z=L[c];for(H=0;H<z.length;H++){T=z[H];T.row=p;T.level=c;X.push(T)}}ba(qa,7);ba(ka,7)}return X}function d(U,ca,ka){t(U)&&f(U,ca);ka.isEnd&&y(U)&&pa(U,ca,ka);q(U,ca)}function f(U,ca){var ka=ra(),qa;ca.draggable({zIndex:9,delay:50,opacity:l("dragOpacity"),revertDuration:l("dragRevertDuration"),start:function(G,p){j("eventDragStart",ca,U,G,p);fa(U,ca);ka.start(function(L, -c,z,H){ca.draggable("option","revert",!L||!z&&!H);ha();if(L){qa=z*7+H*(l("isRTL")?-1:1);sa(ba(N(U.start),qa),ba(Ua(U),qa))}else qa=0},G,"drag")},stop:function(G,p){ka.stop();ha();j("eventDragStop",ca,U,G,p);if(qa)na(this,U,qa,0,U.allDay,G,p);else{ca.css("filter","");u(U,ca)}}})}var g=this;g.renderEvents=a;g.compileDaySegs=e;g.clearEvents=b;g.bindDaySeg=d;Qb.call(g);var l=g.opt,j=g.trigger,t=g.isEventDraggable,y=g.isEventResizable,S=g.reportEvents,Q=g.reportEventClear,q=g.eventElementHandlers,u=g.showEvents, -fa=g.hideEvents,na=g.eventDrop,ga=g.getDaySegmentContainer,ra=g.getHoverListener,sa=g.renderDayOverlay,ha=g.clearOverlays,da=g.getRowCnt,ma=g.getColCnt,ua=g.renderDaySegs,pa=g.resizableDayEvent}function qc(a,b){function e(j,t){t&&ba(j,t*7);j=ba(N(j),-((j.getDay()-f("firstDay")+7)%7));t=ba(N(j),7);var y=N(j),S=N(t),Q=f("weekends");if(!Q){Fa(y);Fa(S,-1,true)}d.title=l(y,ba(N(S),-1),f("titleFormat"));d.start=j;d.end=t;d.visStart=y;d.visEnd=S;g(Q?7:5)}var d=this;d.render=e;Rb.call(d,a,b,"agendaWeek"); -var f=d.opt,g=d.renderAgenda,l=b.formatDates}function rc(a,b){function e(j,t){if(t){ba(j,t);f("weekends")||Fa(j,t<0?-1:1)}t=N(j,true);var y=ba(N(t),1);d.title=l(j,f("titleFormat"));d.start=d.visStart=t;d.end=d.visEnd=y;g(1)}var d=this;d.render=e;Rb.call(d,a,b,"agendaDay");var f=d.opt,g=d.renderAgenda,l=b.formatDate}function Rb(a,b,e){function d(h){Ba=h;f();v?P():g();l()}function f(){Wa=i("theme")?"ui":"fc";Sb=i("weekends")?0:1;Tb=i("firstDay");if(Ub=i("isRTL")){Ha=-1;Ia=Ba-1}else{Ha=1;Ia=0}La=mb(i("minTime")); -bb=mb(i("maxTime"));Vb=i("columnFormat")}function g(){var h=Wa+"-widget-header",O=Wa+"-widget-content",x,A,ta,za,Da,Ea=i("slotMinutes")%15==0;x="<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'><thead><tr><th class='fc-agenda-axis "+h+"'> </th>";for(A=0;A<Ba;A++)x+="<th class='fc- fc-col"+A+" "+h+"'/>";x+="<th class='fc-agenda-gutter "+h+"'> </th></tr></thead><tbody><tr><th class='fc-agenda-axis "+h+"'> </th>";for(A=0;A<Ba;A++)x+="<td class='fc- fc-col"+ -A+" "+O+"'><div><div class='fc-day-content'><div style='position:relative'> </div></div></div></td>";x+="<td class='fc-agenda-gutter "+O+"'> </td></tr></tbody></table>";v=m(x).appendTo(a);F=v.find("thead");r=F.find("th").slice(1,-1);J=v.find("tbody");M=J.find("td").slice(0,-1);k=M.find("div.fc-day-content div");D=M.eq(0);Z=D.find("> div");ab(F.add(F.find("tr")));ab(J.add(J.find("tr")));aa=F.find("th:first");va=v.find(".fc-agenda-gutter");ja=m("<div style='position:absolute;z-index:2;left:0;width:100%'/>").appendTo(a); -if(i("allDaySlot")){ia=m("<div style='position:absolute;z-index:8;top:0;left:0'/>").appendTo(ja);x="<table style='width:100%' class='fc-agenda-allday' cellspacing='0'><tr><th class='"+h+" fc-agenda-axis'>"+i("allDayText")+"</th><td><div class='fc-day-content'><div style='position:relative'/></div></td><th class='"+h+" fc-agenda-gutter'> </th></tr></table>";la=m(x).appendTo(ja);$=la.find("tr");q($.find("td"));aa=aa.add(la.find("th:first"));va=va.add(la.find("th.fc-agenda-gutter"));ja.append("<div class='fc-agenda-divider "+ -h+"'><div class='fc-agenda-divider-inner'/></div>")}else ia=m([]);w=m("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>").appendTo(ja);I=m("<div style='position:relative;width:100%;overflow:hidden'/>").appendTo(w);R=m("<div style='position:absolute;z-index:8;top:0;left:0'/>").appendTo(I);x="<table class='fc-agenda-slots' style='width:100%' cellspacing='0'><tbody>";ta=zb();za=xa(N(ta),bb);xa(ta,La);for(A=tb=0;ta<za;A++){Da=ta.getMinutes();x+="<tr class='fc-slot"+A+" "+ -(!Da?"":"fc-minor")+"'><th class='fc-agenda-axis "+h+"'>"+(!Ea||!Da?s(ta,i("axisFormat")):" ")+"</th><td class='"+O+"'><div style='position:relative'> </div></td></tr>";xa(ta,i("slotMinutes"));tb++}x+="</tbody></table>";V=m(x).appendTo(I);ea=V.find("div:first");u(V.find("td"));aa=aa.add(V.find("th:first"))}function l(){var h,O,x,A,ta=Ka(new Date);for(h=0;h<Ba;h++){A=ua(h);O=r.eq(h);O.html(s(A,Vb));x=M.eq(h);+A==+ta?x.addClass(Wa+"-state-highlight fc-today"):x.removeClass(Wa+"-state-highlight fc-today"); -rb(O.add(x),A)}}function j(h,O){if(h===oa)h=Wb;Wb=h;ub={};var x=J.position().top,A=w.position().top;h=Math.min(h-x,V.height()+A+1);Z.height(h-Sa(D));ja.css("top",x);w.height(h-A-1);Xa=ea.height()+1;O&&y()}function t(h){Ga=h;cb.clear();Ma=0;Va(aa.width("").each(function(O,x){Ma=Math.max(Ma,m(x).outerWidth())}),Ma);h=w[0].clientWidth;if(vb=w.width()-h){Va(va,vb);va.show().prev().removeClass("fc-last")}else va.hide().prev().addClass("fc-last");db=Math.floor((h-Ma)/Ba);Va(r.slice(0,-1),db)}function y(){function h(){w.scrollTop(A)} -var O=zb(),x=N(O);x.setHours(i("firstHour"));var A=ca(O,x)+1;h();setTimeout(h,0)}function S(){Xb=w.scrollTop()}function Q(){w.scrollTop(Xb)}function q(h){h.click(fa).mousedown(W)}function u(h){h.click(fa).mousedown(H)}function fa(h){if(!i("selectable")){var O=Math.min(Ba-1,Math.floor((h.pageX-v.offset().left-Ma)/db)),x=ua(O),A=this.parentNode.className.match(/fc-slot(\d+)/);if(A){A=parseInt(A[1])*i("slotMinutes");var ta=Math.floor(A/60);x.setHours(ta);x.setMinutes(A%60+La);C("dayClick",M[O],x,false, -h)}else C("dayClick",M[O],x,true,h)}}function na(h,O,x){x&&Na.build();var A=N(K.visStart);if(Ub){x=Ca(O,A)*Ha+Ia+1;h=Ca(h,A)*Ha+Ia+1}else{x=Ca(h,A);h=Ca(O,A)}x=Math.max(0,x);h=Math.min(Ba,h);x<h&&q(ga(0,x,0,h-1))}function ga(h,O,x,A){h=Na.rect(h,O,x,A,ja);return E(h,ja)}function ra(h,O){for(var x=N(K.visStart),A=ba(N(x),1),ta=0;ta<Ba;ta++){var za=new Date(Math.max(x,h)),Da=new Date(Math.min(A,O));if(za<Da){var Ea=ta*Ha+Ia;Ea=Na.rect(0,Ea,0,Ea,I);za=ca(x,za);Da=ca(x,Da);Ea.top=za;Ea.height=Da-za;u(E(Ea, -I))}ba(x,1);ba(A,1)}}function sa(h){return cb.left(h)}function ha(h){return cb.right(h)}function da(h){return{row:Math.floor(Ca(h,K.visStart)/7),col:U(h.getDay())}}function ma(h){var O=ua(h.col);h=h.row;i("allDaySlot")&&h--;h>=0&&xa(O,La+h*i("slotMinutes"));return O}function ua(h){return ba(N(K.visStart),h*Ha+Ia)}function pa(h){return i("allDaySlot")&&!h.row}function U(h){return(h-Math.max(Tb,Sb)+Ba)%Ba*Ha+Ia}function ca(h,O){h=N(h,true);if(O<xa(N(h),La))return 0;if(O>=xa(N(h),bb))return V.height(); -h=i("slotMinutes");O=O.getHours()*60+O.getMinutes()-La;var x=Math.floor(O/h),A=ub[x];if(A===oa)A=ub[x]=V.find("tr:eq("+x+") td div")[0].offsetTop;return Math.max(0,Math.round(A-1+Xa*(O%h/h)))}function ka(){return{left:Ma,right:Ga-vb}}function qa(){return $}function G(h){var O=N(h.start);if(h.allDay)return O;return xa(O,i("defaultEventMinutes"))}function p(h,O){if(O)return N(h);return xa(N(h),i("slotMinutes"))}function L(h,O,x){if(x)i("allDaySlot")&&na(h,ba(N(O),1),true);else c(h,O)}function c(h,O){var x= -i("selectHelper");Na.build();if(x){var A=Ca(h,K.visStart)*Ha+Ia;if(A>=0&&A<Ba){A=Na.rect(0,A,0,A,I);var ta=ca(h,h),za=ca(h,O);if(za>ta){A.top=ta;A.height=za-ta;A.left+=2;A.width-=5;if(m.isFunction(x)){if(h=x(h,O)){A.position="absolute";A.zIndex=8;wa=m(h).css(A).appendTo(I)}}else{A.isStart=true;A.isEnd=true;wa=m(o({title:"",start:h,end:O,className:["fc-select-helper"],editable:false},A));wa.css("opacity",i("dragOpacity"))}if(wa){u(wa);I.append(wa);Va(wa,A.width,true);Eb(wa,A.height,true)}}}}else ra(h, -O)}function z(){B();if(wa){wa.remove();wa=null}}function H(h){if(h.which==1&&i("selectable")){Y(h);var O;Ra.start(function(x,A){z();if(x&&x.col==A.col&&!pa(x)){A=ma(A);x=ma(x);O=[A,xa(N(A),i("slotMinutes")),x,xa(N(x),i("slotMinutes"))].sort(Gb);c(O[0],O[3])}else O=null},h);m(document).one("mouseup",function(x){Ra.stop();if(O){+O[0]==+O[1]&&T(O[0],false,x);n(O[0],O[3],false,x)}})}}function T(h,O,x){C("dayClick",M[U(h.getDay())],h,O,x)}function X(h,O){Ra.start(function(x){B();if(x)if(pa(x))ga(x.row, -x.col,x.row,x.col);else{x=ma(x);var A=xa(N(x),i("defaultEventMinutes"));ra(x,A)}},O)}function ya(h,O,x){var A=Ra.stop();B();A&&C("drop",h,ma(A),pa(A),O,x)}var K=this;K.renderAgenda=d;K.setWidth=t;K.setHeight=j;K.beforeHide=S;K.afterShow=Q;K.defaultEventEnd=G;K.timePosition=ca;K.dayOfWeekCol=U;K.dateCell=da;K.cellDate=ma;K.cellIsAllDay=pa;K.allDayRow=qa;K.allDayBounds=ka;K.getHoverListener=function(){return Ra};K.colContentLeft=sa;K.colContentRight=ha;K.getDaySegmentContainer=function(){return ia}; -K.getSlotSegmentContainer=function(){return R};K.getMinMinute=function(){return La};K.getMaxMinute=function(){return bb};K.getBodyContent=function(){return I};K.getRowCnt=function(){return 1};K.getColCnt=function(){return Ba};K.getColWidth=function(){return db};K.getSlotHeight=function(){return Xa};K.defaultSelectionEnd=p;K.renderDayOverlay=na;K.renderSelection=L;K.clearSelection=z;K.reportDayClick=T;K.dragStart=X;K.dragStop=ya;Kb.call(K,a,b,e);Lb.call(K);Mb.call(K);sc.call(K);var i=K.opt,C=K.trigger, -P=K.clearEvents,E=K.renderOverlay,B=K.clearOverlays,n=K.reportSelection,Y=K.unselect,W=K.daySelectionMousedown,o=K.slotSegHtml,s=b.formatDate,v,F,r,J,M,k,D,Z,ja,ia,la,$,w,I,R,V,ea,aa,va,wa,Ga,Wb,Ma,db,vb,Xa,Xb,Ba,tb,Na,Ra,cb,ub={},Wa,Tb,Sb,Ub,Ha,Ia,La,bb,Vb;qb(a.addClass("fc-agenda"));Na=new Nb(function(h,O){function x(eb){return Math.max(Ea,Math.min(tc,eb))}var A,ta,za;r.each(function(eb,uc){A=m(uc);ta=A.offset().left;if(eb)za[1]=ta;za=[ta];O[eb]=za});za[1]=ta+A.outerWidth();if(i("allDaySlot")){A= -$;ta=A.offset().top;h[0]=[ta,ta+A.outerHeight()]}for(var Da=I.offset().top,Ea=w.offset().top,tc=Ea+w.outerHeight(),fb=0;fb<tb;fb++)h.push([x(Da+Xa*fb),x(Da+Xa*(fb+1))])});Ra=new Ob(Na);cb=new Pb(function(h){return k.eq(h)})}function sc(){function a(o,s){sa(o);var v,F=o.length,r=[],J=[];for(v=0;v<F;v++)o[v].allDay?r.push(o[v]):J.push(o[v]);if(u("allDaySlot")){L(e(r),s);ma()}g(d(J),s)}function b(){ha();ua().empty();pa().empty()}function e(o){o=ob(nb(o,m.map(o,Ua),q.visStart,q.visEnd));var s,v=o.length, -F,r,J,M=[];for(s=0;s<v;s++){F=o[s];for(r=0;r<F.length;r++){J=F[r];J.row=0;J.level=s;M.push(J)}}return M}function d(o){var s=z(),v=ka(),F=ca(),r=xa(N(q.visStart),v),J=m.map(o,f),M,k,D,Z,ja,ia,la=[];for(M=0;M<s;M++){k=ob(nb(o,J,r,xa(N(r),F-v)));vc(k);for(D=0;D<k.length;D++){Z=k[D];for(ja=0;ja<Z.length;ja++){ia=Z[ja];ia.col=M;ia.level=D;la.push(ia)}}ba(r,1,true)}return la}function f(o){return o.end?N(o.end):xa(N(o.start),u("defaultEventMinutes"))}function g(o,s){var v,F=o.length,r,J,M,k,D,Z,ja,ia,la, -$="",w,I,R={},V={},ea=pa(),aa;v=z();if(w=u("isRTL")){I=-1;aa=v-1}else{I=1;aa=0}for(v=0;v<F;v++){r=o[v];J=r.event;M=qa(r.start,r.start);k=qa(r.start,r.end);D=r.col;Z=r.level;ja=r.forward||0;ia=G(D*I+aa);la=p(D*I+aa)-ia;la=Math.min(la-6,la*0.95);D=Z?la/(Z+ja+1):ja?(la/(ja+1)-6)*2:la;Z=ia+la/(Z+ja+1)*Z*I+(w?la-D:0);r.top=M;r.left=Z;r.outerWidth=D;r.outerHeight=k-M;$+=l(J,r)}ea[0].innerHTML=$;w=ea.children();for(v=0;v<F;v++){r=o[v];J=r.event;$=m(w[v]);I=fa("eventRender",J,J,$);if(I===false)$.remove(); -else{if(I&&I!==true){$.remove();$=m(I).css({position:"absolute",top:r.top,left:r.left}).appendTo(ea)}r.element=$;if(J._id===s)t(J,$,r);else $[0]._fci=v;ya(J,$)}}Db(ea,o,t);for(v=0;v<F;v++){r=o[v];if($=r.element){J=R[s=r.key=Ib($[0])];r.vsides=J===oa?(R[s]=Sa($,true)):J;J=V[s];r.hsides=J===oa?(V[s]=pb($,true)):J;s=$.find("div.fc-event-content");if(s.length)r.contentTop=s[0].offsetTop}}for(v=0;v<F;v++){r=o[v];if($=r.element){$[0].style.width=Math.max(0,r.outerWidth-r.hsides)+"px";R=Math.max(0,r.outerHeight- -r.vsides);$[0].style.height=R+"px";J=r.event;if(r.contentTop!==oa&&R-r.contentTop<10){$.find("div.fc-event-time").text(Y(J.start,u("timeFormat"))+" - "+J.title);$.find("div.fc-event-title").remove()}fa("eventAfterRender",J,J,$)}}}function l(o,s){var v="<",F=o.url,r=Jb(o,u),J=r?" style='"+r+"'":"",M=["fc-event","fc-event-skin","fc-event-vert"];na(o)&&M.push("fc-event-draggable");s.isStart&&M.push("fc-corner-top");s.isEnd&&M.push("fc-corner-bottom");M=M.concat(o.className);if(o.source)M=M.concat(o.source.className|| -[]);v+=F?"a href='"+Qa(o.url)+"'":"div";v+=" class='"+M.join(" ")+"' style='position:absolute;z-index:8;top:"+s.top+"px;left:"+s.left+"px;"+r+"'><div class='fc-event-inner fc-event-skin'"+J+"><div class='fc-event-head fc-event-skin'"+J+"><div class='fc-event-time'>"+Qa(W(o.start,o.end,u("timeFormat")))+"</div></div><div class='fc-event-content'><div class='fc-event-title'>"+Qa(o.title)+"</div></div><div class='fc-event-bg'></div></div>";if(s.isEnd&&ga(o))v+="<div class='ui-resizable-handle ui-resizable-s'>=</div>"; -v+="</"+(F?"a":"div")+">";return v}function j(o,s,v){na(o)&&y(o,s,v.isStart);v.isEnd&&ga(o)&&c(o,s,v);da(o,s)}function t(o,s,v){var F=s.find("div.fc-event-time");na(o)&&S(o,s,F);v.isEnd&&ga(o)&&Q(o,s,F);da(o,s)}function y(o,s,v){function F(){if(!M){s.width(r).height("").draggable("option","grid",null);M=true}}var r,J,M=true,k,D=u("isRTL")?-1:1,Z=U(),ja=H(),ia=T(),la=ka();s.draggable({zIndex:9,opacity:u("dragOpacity","month"),revertDuration:u("dragRevertDuration"),start:function($,w){fa("eventDragStart", -s,o,$,w);i(o,s);r=s.width();Z.start(function(I,R,V,ea){B();if(I){J=false;k=ea*D;if(I.row)if(v){if(M){s.width(ja-10);Eb(s,ia*Math.round((o.end?(o.end-o.start)/wc:u("defaultEventMinutes"))/u("slotMinutes")));s.draggable("option","grid",[ja,1]);M=false}}else J=true;else{E(ba(N(o.start),k),ba(Ua(o),k));F()}J=J||M&&!k}else{F();J=true}s.draggable("option","revert",J)},$,"drag")},stop:function($,w){Z.stop();B();fa("eventDragStop",s,o,$,w);if(J){F();s.css("filter","");K(o,s)}else{var I=0;M||(I=Math.round((s.offset().top- -X().offset().top)/ia)*u("slotMinutes")+la-(o.start.getHours()*60+o.start.getMinutes()));C(this,o,k,I,M,$,w)}}})}function S(o,s,v){function F(I){var R=xa(N(o.start),I),V;if(o.end)V=xa(N(o.end),I);v.text(W(R,V,u("timeFormat")))}function r(){if(M){v.css("display","");s.draggable("option","grid",[$,w]);M=false}}var J,M=false,k,D,Z,ja=u("isRTL")?-1:1,ia=U(),la=z(),$=H(),w=T();s.draggable({zIndex:9,scroll:false,grid:[$,w],axis:la==1?"y":false,opacity:u("dragOpacity"),revertDuration:u("dragRevertDuration"), -start:function(I,R){fa("eventDragStart",s,o,I,R);i(o,s);J=s.position();D=Z=0;ia.start(function(V,ea,aa,va){s.draggable("option","revert",!V);B();if(V){k=va*ja;if(u("allDaySlot")&&!V.row){if(!M){M=true;v.hide();s.draggable("option","grid",null)}E(ba(N(o.start),k),ba(Ua(o),k))}else r()}},I,"drag")},drag:function(I,R){D=Math.round((R.position.top-J.top)/w)*u("slotMinutes");if(D!=Z){M||F(D);Z=D}},stop:function(I,R){var V=ia.stop();B();fa("eventDragStop",s,o,I,R);if(V&&(k||D||M))C(this,o,k,M?0:D,M,I,R); -else{r();s.css("filter","");s.css(J);F(0);K(o,s)}}})}function Q(o,s,v){var F,r,J=T();s.resizable({handles:{s:"div.ui-resizable-s"},grid:J,start:function(M,k){F=r=0;i(o,s);s.css("z-index",9);fa("eventResizeStart",this,o,M,k)},resize:function(M,k){F=Math.round((Math.max(J,s.height())-k.originalSize.height)/J);if(F!=r){v.text(W(o.start,!F&&!o.end?null:xa(ra(o),u("slotMinutes")*F),u("timeFormat")));r=F}},stop:function(M,k){fa("eventResizeStop",this,o,M,k);if(F)P(this,o,0,u("slotMinutes")*F,M,k);else{s.css("z-index", -8);K(o,s)}}})}var q=this;q.renderEvents=a;q.compileDaySegs=e;q.clearEvents=b;q.slotSegHtml=l;q.bindDaySeg=j;Qb.call(q);var u=q.opt,fa=q.trigger,na=q.isEventDraggable,ga=q.isEventResizable,ra=q.eventEnd,sa=q.reportEvents,ha=q.reportEventClear,da=q.eventElementHandlers,ma=q.setHeight,ua=q.getDaySegmentContainer,pa=q.getSlotSegmentContainer,U=q.getHoverListener,ca=q.getMaxMinute,ka=q.getMinMinute,qa=q.timePosition,G=q.colContentLeft,p=q.colContentRight,L=q.renderDaySegs,c=q.resizableDayEvent,z=q.getColCnt, -H=q.getColWidth,T=q.getSlotHeight,X=q.getBodyContent,ya=q.reportEventElement,K=q.showEvents,i=q.hideEvents,C=q.eventDrop,P=q.eventResize,E=q.renderDayOverlay,B=q.clearOverlays,n=q.calendar,Y=n.formatDate,W=n.formatDates}function vc(a){var b,e,d,f,g,l;for(b=a.length-1;b>0;b--){f=a[b];for(e=0;e<f.length;e++){g=f[e];for(d=0;d<a[b-1].length;d++){l=a[b-1][d];if(Cb(g,l))l.forward=Math.max(l.forward||0,(g.forward||0)+1)}}}}function Kb(a,b,e){function d(G,p){G=qa[G];if(typeof G=="object")return jb(G,p||e); -return G}function f(G,p){return b.trigger.apply(b,[G,p||da].concat(Array.prototype.slice.call(arguments,2),[da]))}function g(G){return j(G)&&!d("disableDragging")}function l(G){return j(G)&&!d("disableResizing")}function j(G){return Ta(G.editable,(G.source||{}).editable,d("editable"))}function t(G){U={};var p,L=G.length,c;for(p=0;p<L;p++){c=G[p];if(U[c._id])U[c._id].push(c);else U[c._id]=[c]}}function y(G){return G.end?N(G.end):ma(G)}function S(G,p){ca.push(p);if(ka[G._id])ka[G._id].push(p);else ka[G._id]= -[p]}function Q(){ca=[];ka={}}function q(G,p){p.click(function(L){if(!p.hasClass("ui-draggable-dragging")&&!p.hasClass("ui-resizable-resizing"))return f("eventClick",this,G,L)}).hover(function(L){f("eventMouseover",this,G,L)},function(L){f("eventMouseout",this,G,L)})}function u(G,p){na(G,p,"show")}function fa(G,p){na(G,p,"hide")}function na(G,p,L){G=ka[G._id];var c,z=G.length;for(c=0;c<z;c++)if(!p||G[c][0]!=p[0])G[c][L]()}function ga(G,p,L,c,z,H,T){var X=p.allDay,ya=p._id;sa(U[ya],L,c,z);f("eventDrop", -G,p,L,c,z,function(){sa(U[ya],-L,-c,X);pa(ya)},H,T);pa(ya)}function ra(G,p,L,c,z,H){var T=p._id;ha(U[T],L,c);f("eventResize",G,p,L,c,function(){ha(U[T],-L,-c);pa(T)},z,H);pa(T)}function sa(G,p,L,c){L=L||0;for(var z,H=G.length,T=0;T<H;T++){z=G[T];if(c!==oa)z.allDay=c;xa(ba(z.start,p,true),L);if(z.end)z.end=xa(ba(z.end,p,true),L);ua(z,qa)}}function ha(G,p,L){L=L||0;for(var c,z=G.length,H=0;H<z;H++){c=G[H];c.end=xa(ba(y(c),p,true),L);ua(c,qa)}}var da=this;da.element=a;da.calendar=b;da.name=e;da.opt= -d;da.trigger=f;da.isEventDraggable=g;da.isEventResizable=l;da.reportEvents=t;da.eventEnd=y;da.reportEventElement=S;da.reportEventClear=Q;da.eventElementHandlers=q;da.showEvents=u;da.hideEvents=fa;da.eventDrop=ga;da.eventResize=ra;var ma=da.defaultEventEnd,ua=b.normalizeEvent,pa=b.reportEventChange,U={},ca=[],ka={},qa=b.options}function Qb(){function a(i,C){var P=z(),E=pa(),B=U(),n=0,Y,W,o=i.length,s,v;P[0].innerHTML=e(i);d(i,P.children());f(i);g(i,P,C);l(i);j(i);t(i);C=y();for(P=0;P<E;P++){Y=[];for(W= -0;W<B;W++)Y[W]=0;for(;n<o&&(s=i[n]).row==P;){W=Hb(Y.slice(s.startCol,s.endCol));s.top=W;W+=s.outerHeight;for(v=s.startCol;v<s.endCol;v++)Y[v]=W;n++}C[P].height(Hb(Y))}Q(i,S(C))}function b(i,C,P){var E=m("<div/>"),B=z(),n=i.length,Y;E[0].innerHTML=e(i);E=E.children();B.append(E);d(i,E);l(i);j(i);t(i);Q(i,S(y()));E=[];for(B=0;B<n;B++)if(Y=i[B].element){i[B].row===C&&Y.css("top",P);E.push(Y[0])}return m(E)}function e(i){var C=fa("isRTL"),P,E=i.length,B,n,Y,W;P=ka();var o=P.left,s=P.right,v,F,r,J,M,k= -"";for(P=0;P<E;P++){B=i[P];n=B.event;W=["fc-event","fc-event-skin","fc-event-hori"];ga(n)&&W.push("fc-event-draggable");if(C){B.isStart&&W.push("fc-corner-right");B.isEnd&&W.push("fc-corner-left");v=p(B.end.getDay()-1);F=p(B.start.getDay());r=B.isEnd?qa(v):o;J=B.isStart?G(F):s}else{B.isStart&&W.push("fc-corner-left");B.isEnd&&W.push("fc-corner-right");v=p(B.start.getDay());F=p(B.end.getDay()-1);r=B.isStart?qa(v):o;J=B.isEnd?G(F):s}W=W.concat(n.className);if(n.source)W=W.concat(n.source.className|| -[]);Y=n.url;M=Jb(n,fa);k+=Y?"<a href='"+Qa(Y)+"'":"<div";k+=" class='"+W.join(" ")+"' style='position:absolute;z-index:8;left:"+r+"px;"+M+"'><div class='fc-event-inner fc-event-skin'"+(M?" style='"+M+"'":"")+">";if(!n.allDay&&B.isStart)k+="<span class='fc-event-time'>"+Qa(T(n.start,n.end,fa("timeFormat")))+"</span>";k+="<span class='fc-event-title'>"+Qa(n.title)+"</span></div>";if(B.isEnd&&ra(n))k+="<div class='ui-resizable-handle ui-resizable-"+(C?"w":"e")+"'> </div>";k+="</"+(Y? -"a":"div")+">";B.left=r;B.outerWidth=J-r;B.startCol=v;B.endCol=F+1}return k}function d(i,C){var P,E=i.length,B,n,Y;for(P=0;P<E;P++){B=i[P];n=B.event;Y=m(C[P]);n=na("eventRender",n,n,Y);if(n===false)Y.remove();else{if(n&&n!==true){n=m(n).css({position:"absolute",left:B.left});Y.replaceWith(n);Y=n}B.element=Y}}}function f(i){var C,P=i.length,E,B;for(C=0;C<P;C++){E=i[C];(B=E.element)&&ha(E.event,B)}}function g(i,C,P){var E,B=i.length,n,Y,W;for(E=0;E<B;E++){n=i[E];if(Y=n.element){W=n.event;if(W._id=== -P)H(W,Y,n);else Y[0]._fci=E}}Db(C,i,H)}function l(i){var C,P=i.length,E,B,n,Y,W={};for(C=0;C<P;C++){E=i[C];if(B=E.element){n=E.key=Ib(B[0]);Y=W[n];if(Y===oa)Y=W[n]=pb(B,true);E.hsides=Y}}}function j(i){var C,P=i.length,E,B;for(C=0;C<P;C++){E=i[C];if(B=E.element)B[0].style.width=Math.max(0,E.outerWidth-E.hsides)+"px"}}function t(i){var C,P=i.length,E,B,n,Y,W={};for(C=0;C<P;C++){E=i[C];if(B=E.element){n=E.key;Y=W[n];if(Y===oa)Y=W[n]=Fb(B);E.outerHeight=B[0].offsetHeight+Y}}}function y(){var i,C=pa(), -P=[];for(i=0;i<C;i++)P[i]=ca(i).find("td:first div.fc-day-content > div");return P}function S(i){var C,P=i.length,E=[];for(C=0;C<P;C++)E[C]=i[C][0].offsetTop;return E}function Q(i,C){var P,E=i.length,B,n;for(P=0;P<E;P++){B=i[P];if(n=B.element){n[0].style.top=C[B.row]+(B.top||0)+"px";B=B.event;na("eventAfterRender",B,B,n)}}}function q(i,C,P){var E=fa("isRTL"),B=E?"w":"e",n=C.find("div.ui-resizable-"+B),Y=false;qb(C);C.mousedown(function(W){W.preventDefault()}).click(function(W){if(Y){W.preventDefault(); -W.stopImmediatePropagation()}});n.mousedown(function(W){function o(ia){na("eventResizeStop",this,i,ia);m("body").css("cursor","");s.stop();ya();k&&ua(this,i,k,0,ia);setTimeout(function(){Y=false},0)}if(W.which==1){Y=true;var s=u.getHoverListener(),v=pa(),F=U(),r=E?-1:1,J=E?F-1:0,M=C.css("top"),k,D,Z=m.extend({},i),ja=L(i.start);K();m("body").css("cursor",B+"-resize").one("mouseup",o);na("eventResizeStart",this,i,W);s.start(function(ia,la){if(ia){var $=Math.max(ja.row,ia.row);ia=ia.col;if(v==1)$=0; -if($==ja.row)ia=E?Math.min(ja.col,ia):Math.max(ja.col,ia);k=$*7+ia*r+J-(la.row*7+la.col*r+J);la=ba(sa(i),k,true);if(k){Z.end=la;$=D;D=b(c([Z]),P.row,M);D.find("*").css("cursor",B+"-resize");$&&$.remove();ma(i)}else if(D){da(i);D.remove();D=null}ya();X(i.start,ba(N(la),1))}},W)}})}var u=this;u.renderDaySegs=a;u.resizableDayEvent=q;var fa=u.opt,na=u.trigger,ga=u.isEventDraggable,ra=u.isEventResizable,sa=u.eventEnd,ha=u.reportEventElement,da=u.showEvents,ma=u.hideEvents,ua=u.eventResize,pa=u.getRowCnt, -U=u.getColCnt,ca=u.allDayRow,ka=u.allDayBounds,qa=u.colContentLeft,G=u.colContentRight,p=u.dayOfWeekCol,L=u.dateCell,c=u.compileDaySegs,z=u.getDaySegmentContainer,H=u.bindDaySeg,T=u.calendar.formatDates,X=u.renderDayOverlay,ya=u.clearOverlays,K=u.clearSelection}function Mb(){function a(Q,q,u){b();q||(q=j(Q,u));t(Q,q,u);e(Q,q,u)}function b(Q){if(S){S=false;y();l("unselect",null,Q)}}function e(Q,q,u,fa){S=true;l("select",null,Q,q,u,fa)}function d(Q){var q=f.cellDate,u=f.cellIsAllDay,fa=f.getHoverListener(), -na=f.reportDayClick;if(Q.which==1&&g("selectable")){b(Q);var ga;fa.start(function(ra,sa){y();if(ra&&u(ra)){ga=[q(sa),q(ra)].sort(Gb);t(ga[0],ga[1],true)}else ga=null},Q);m(document).one("mouseup",function(ra){fa.stop();if(ga){+ga[0]==+ga[1]&&na(ga[0],true,ra);e(ga[0],ga[1],true,ra)}})}}var f=this;f.select=a;f.unselect=b;f.reportSelection=e;f.daySelectionMousedown=d;var g=f.opt,l=f.trigger,j=f.defaultSelectionEnd,t=f.renderSelection,y=f.clearSelection,S=false;g("selectable")&&g("unselectAuto")&&m(document).mousedown(function(Q){var q= -g("unselectCancel");if(q)if(m(Q.target).parents(q).length)return;b(Q)})}function Lb(){function a(g,l){var j=f.shift();j||(j=m("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>"));j[0].parentNode!=l[0]&&j.appendTo(l);d.push(j.css(g).show());return j}function b(){for(var g;g=d.shift();)f.push(g.hide().unbind())}var e=this;e.renderOverlay=a;e.clearOverlays=b;var d=[],f=[]}function Nb(a){var b=this,e,d;b.build=function(){e=[];d=[];a(e,d)};b.cell=function(f,g){var l=e.length,j=d.length, -t,y=-1,S=-1;for(t=0;t<l;t++)if(g>=e[t][0]&&g<e[t][1]){y=t;break}for(t=0;t<j;t++)if(f>=d[t][0]&&f<d[t][1]){S=t;break}return y>=0&&S>=0?{row:y,col:S}:null};b.rect=function(f,g,l,j,t){t=t.offset();return{top:e[f][0]-t.top,left:d[g][0]-t.left,width:d[j][1]-d[g][0],height:e[l][1]-e[f][0]}}}function Ob(a){function b(j){j=a.cell(j.pageX,j.pageY);if(!j!=!l||j&&(j.row!=l.row||j.col!=l.col)){if(j){g||(g=j);f(j,g,j.row-g.row,j.col-g.col)}else f(j,g);l=j}}var e=this,d,f,g,l;e.start=function(j,t,y){f=j;g=l=null; -a.build();b(t);d=y||"mousemove";m(document).bind(d,b)};e.stop=function(){m(document).unbind(d,b);return l}}function Pb(a){function b(l){return d[l]=d[l]||a(l)}var e=this,d={},f={},g={};e.left=function(l){return f[l]=f[l]===oa?b(l).position().left:f[l]};e.right=function(l){return g[l]=g[l]===oa?e.left(l)+b(l).width():g[l]};e.clear=function(){d={};f={};g={}}}var Ya={defaultView:"month",aspectRatio:1.35,header:{left:"title",center:"",right:"today prev,next"},weekends:true,allDayDefault:true,ignoreTimezone:true, -lazyFetching:true,startParam:"start",endParam:"end",titleFormat:{month:"MMMM yyyy",week:"MMM d[ yyyy]{ '—'[ MMM] d yyyy}",day:"dddd, MMM d, yyyy"},columnFormat:{month:"ddd",week:"ddd M/d",day:"dddd M/d"},timeFormat:{"":"h(:mm)t"},isRTL:false,firstDay:0,monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday", -"Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],buttonText:{prev:" ◄ ",next:" ► ",prevYear:" << ",nextYear:" >> ",today:"today",month:"month",week:"week",day:"day"},theme:false,buttonIcons:{prev:"circle-triangle-w",next:"circle-triangle-e"},unselectAuto:true,dropAccept:"*"},xc={header:{left:"next,prev today",center:"",right:"title"},buttonText:{prev:" ► ",next:" ◄ ", -prevYear:" >> ",nextYear:" << "},buttonIcons:{prev:"circle-triangle-e",next:"circle-triangle-w"}},Aa=m.fullCalendar={version:"1.5.2"},Ja=Aa.views={};m.fn.fullCalendar=function(a){if(typeof a=="string"){var b=Array.prototype.slice.call(arguments,1),e;this.each(function(){var f=m.data(this,"fullCalendar");if(f&&m.isFunction(f[a])){f=f[a].apply(f,b);if(e===oa)e=f;a=="destroy"&&m.removeData(this,"fullCalendar")}});if(e!==oa)return e;return this}var d=a.eventSources||[]; -delete a.eventSources;if(a.events){d.push(a.events);delete a.events}a=m.extend(true,{},Ya,a.isRTL||a.isRTL===oa&&Ya.isRTL?xc:{},a);this.each(function(f,g){f=m(g);g=new Yb(f,a,d);f.data("fullCalendar",g);g.render()});return this};Aa.sourceNormalizers=[];Aa.sourceFetchers=[];var ac={dataType:"json",cache:false},bc=1;Aa.addDays=ba;Aa.cloneDate=N;Aa.parseDate=kb;Aa.parseISO8601=Bb;Aa.parseTime=mb;Aa.formatDate=Oa;Aa.formatDates=ib;var lc=["sun","mon","tue","wed","thu","fri","sat"],Ab=864E5,cc=36E5,wc= -6E4,dc={s:function(a){return a.getSeconds()},ss:function(a){return Pa(a.getSeconds())},m:function(a){return a.getMinutes()},mm:function(a){return Pa(a.getMinutes())},h:function(a){return a.getHours()%12||12},hh:function(a){return Pa(a.getHours()%12||12)},H:function(a){return a.getHours()},HH:function(a){return Pa(a.getHours())},d:function(a){return a.getDate()},dd:function(a){return Pa(a.getDate())},ddd:function(a,b){return b.dayNamesShort[a.getDay()]},dddd:function(a,b){return b.dayNames[a.getDay()]}, -M:function(a){return a.getMonth()+1},MM:function(a){return Pa(a.getMonth()+1)},MMM:function(a,b){return b.monthNamesShort[a.getMonth()]},MMMM:function(a,b){return b.monthNames[a.getMonth()]},yy:function(a){return(a.getFullYear()+"").substring(2)},yyyy:function(a){return a.getFullYear()},t:function(a){return a.getHours()<12?"a":"p"},tt:function(a){return a.getHours()<12?"am":"pm"},T:function(a){return a.getHours()<12?"A":"P"},TT:function(a){return a.getHours()<12?"AM":"PM"},u:function(a){return Oa(a, -"yyyy-MM-dd'T'HH:mm:ss'Z'")},S:function(a){a=a.getDate();if(a>10&&a<20)return"th";return["st","nd","rd"][a%10-1]||"th"}};Aa.applyAll=$a;Ja.month=mc;Ja.basicWeek=nc;Ja.basicDay=oc;wb({weekMode:"fixed"});Ja.agendaWeek=qc;Ja.agendaDay=rc;wb({allDaySlot:true,allDayText:"all-day",firstHour:6,slotMinutes:30,defaultEventMinutes:120,axisFormat:"h(:mm)tt",timeFormat:{agenda:"h:mm{ - h:mm}"},dragOpacity:{agenda:0.5},minTime:0,maxTime:24})})(jQuery); diff --git a/3rdparty/fullcalendar/js/gcal.js b/3rdparty/fullcalendar/js/gcal.js deleted file mode 100644 index 709e25cb2622ae889488739f1543e5fc1e1bd4c2..0000000000000000000000000000000000000000 --- a/3rdparty/fullcalendar/js/gcal.js +++ /dev/null @@ -1,112 +0,0 @@ -/* - * FullCalendar v1.5.2 Google Calendar Plugin - * - * Copyright (c) 2011 Adam Shaw - * Dual licensed under the MIT and GPL licenses, located in - * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. - * - * Date: Sun Aug 21 22:06:09 2011 -0700 - * - */ - -(function($) { - - -var fc = $.fullCalendar; -var formatDate = fc.formatDate; -var parseISO8601 = fc.parseISO8601; -var addDays = fc.addDays; -var applyAll = fc.applyAll; - - -fc.sourceNormalizers.push(function(sourceOptions) { - if (sourceOptions.dataType == 'gcal' || - sourceOptions.dataType === undefined && - (sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) { - sourceOptions.dataType = 'gcal'; - if (sourceOptions.editable === undefined) { - sourceOptions.editable = false; - } - } -}); - - -fc.sourceFetchers.push(function(sourceOptions, start, end) { - if (sourceOptions.dataType == 'gcal') { - return transformOptions(sourceOptions, start, end); - } -}); - - -function transformOptions(sourceOptions, start, end) { - - var success = sourceOptions.success; - var data = $.extend({}, sourceOptions.data || {}, { - 'start-min': formatDate(start, 'u'), - 'start-max': formatDate(end, 'u'), - 'singleevents': true, - 'max-results': 9999 - }); - - var ctz = sourceOptions.currentTimezone; - if (ctz) { - data.ctz = ctz = ctz.replace(' ', '_'); - } - - return $.extend({}, sourceOptions, { - url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?', - dataType: 'jsonp', - data: data, - startParam: false, - endParam: false, - success: function(data) { - var events = []; - if (data.feed.entry) { - $.each(data.feed.entry, function(i, entry) { - var startStr = entry['gd$when'][0]['startTime']; - var start = parseISO8601(startStr, true); - var end = parseISO8601(entry['gd$when'][0]['endTime'], true); - var allDay = startStr.indexOf('T') == -1; - var url; - $.each(entry.link, function(i, link) { - if (link.type == 'text/html') { - url = link.href; - if (ctz) { - url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz; - } - } - }); - if (allDay) { - addDays(end, -1); // make inclusive - } - events.push({ - id: entry['gCal$uid']['value'], - title: entry['title']['$t'], - url: url, - start: start, - end: end, - allDay: allDay, - location: entry['gd$where'][0]['valueString'], - description: entry['content']['$t'] - }); - }); - } - var args = [events].concat(Array.prototype.slice.call(arguments, 1)); - var res = applyAll(success, this, args); - if ($.isArray(res)) { - return res; - } - return events; - } - }); - -} - - -// legacy -fc.gcalFeed = function(url, sourceOptions) { - return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' }); -}; - - -})(jQuery); diff --git a/3rdparty/js/chosen/LICENSE.md b/3rdparty/js/chosen/LICENSE.md deleted file mode 100644 index 80109bba80284211160f8c23f2c0d84cade96c34..0000000000000000000000000000000000000000 --- a/3rdparty/js/chosen/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -# Chosen, a Select Box Enhancer for jQuery and Protoype -## by Patrick Filler for [Harvest](http://getharvest.com) - -Available for use under the [MIT License](http://en.wikipedia.org/wiki/MIT_License) - -Copyright (c) 2011 by Harvest - -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. \ No newline at end of file diff --git a/3rdparty/js/chosen/README.md b/3rdparty/js/chosen/README.md deleted file mode 100644 index cee8ed1cc08839b0a8f05bd3547bf879fc190e7d..0000000000000000000000000000000000000000 --- a/3rdparty/js/chosen/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# Chosen - -Chosen is a library for making long, unwieldy select boxes more user friendly. - -- jQuery support: 1.4+ -- Prototype support: 1.7+ - -For documentation, usage, and examples, see: -http://harvesthq.github.com/chosen - -### Contributing to Chosen - -Contributions and pull requests are very welcome. Please follow these guidelines when submitting new code. - -1. Make all changes in Coffeescript files, **not** JavaScript files. -2. For feature changes, update both jQuery *and* Prototype versions -3. Use 'cake build' to generate Chosen's JavaScript file and minified version. -4. Don't touch the VERSION file -5. Submit a Pull Request using GitHub. - -### Using CoffeeScript & Cake - -First, make sure you have the proper CoffeeScript / Cake set-up in place. - -1. Install Coffeescript: the [CoffeeScript documentation](http://jashkenas.github.com/coffee-script/) provides easy-to-follow instructions. -2. Install UglifyJS: <code>npm -g install uglify-js</code> -3. Verify that your $NODE_PATH is properly configured using <code>echo $NODE_PATH</code> - -Once you're configured, building the JavasScript from the command line is easy: - - cake build # build Chosen from source - cake watch # watch coffee/ for changes and build Chosen - -If you're interested, you can find the recipes in Cakefile. - - -### Chosen Credits - -- Built by [Harvest](http://www.getharvest.com/) -- Concept and development by [Patrick Filler](http://www.patrickfiller.com/) -- Design and CSS by [Matthew Lettini](http://matthewlettini.com/) - -### Notable Forks - -- [Chosen for MooTools](https://github.com/julesjanssen/chosen), by Jules Janssen -- [Chosen Drupal 7 Module](https://github.com/Polzme/chosen), by Pol Dell'Aiera \ No newline at end of file diff --git a/3rdparty/js/chosen/VERSION b/3rdparty/js/chosen/VERSION deleted file mode 100644 index b0bb878545dc6dc410a02b0df8b7ea9fd5705960..0000000000000000000000000000000000000000 --- a/3rdparty/js/chosen/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.9.5 diff --git a/3rdparty/js/chosen/chosen.jquery.js b/3rdparty/js/chosen/chosen.jquery.js deleted file mode 100644 index e7e661c09628db219577ae9c6848716b3aac4daa..0000000000000000000000000000000000000000 --- a/3rdparty/js/chosen/chosen.jquery.js +++ /dev/null @@ -1,857 +0,0 @@ -// Chosen, a Select Box Enhancer for jQuery and Protoype -// by Patrick Filler for Harvest, http://getharvest.com -// -// Version 0.9.5 -// Full source at https://github.com/harvesthq/chosen -// Copyright (c) 2011 Harvest http://getharvest.com - -// MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md -// This file is generated by `cake build`, do not edit it by hand. -(function() { - /* - Chosen source: generate output using 'cake build' - Copyright (c) 2011 by Harvest - */ var $, Chosen, get_side_border_padding, root; - var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; - root = this; - $ = jQuery; - $.fn.extend({ - chosen: function(options) { - if ($.browser === "msie" && ($.browser.version === "6.0" || $.browser.version === "7.0")) { - return this; - } - return $(this).each(function(input_field) { - if (!($(this)).hasClass("chzn-done")) { - return new Chosen(this, options); - } - }); - } - }); - Chosen = (function() { - function Chosen(form_field, options) { - this.form_field = form_field; - this.options = options != null ? options : {}; - this.set_default_values(); - this.form_field_jq = $(this.form_field); - this.is_multiple = this.form_field.multiple; - this.is_rtl = this.form_field_jq.hasClass("chzn-rtl"); - this.default_text_default = this.form_field.multiple ? "Select Some Options" : "Select an Option"; - this.set_up_html(); - this.register_observers(); - this.form_field_jq.addClass("chzn-done"); - } - Chosen.prototype.set_default_values = function() { - this.click_test_action = __bind(function(evt) { - return this.test_active_click(evt); - }, this); - this.activate_action = __bind(function(evt) { - return this.activate_field(evt); - }, this); - this.active_field = false; - this.mouse_on_container = false; - this.results_showing = false; - this.result_highlighted = null; - this.result_single_selected = null; - this.allow_single_deselect = (this.options.allow_single_deselect != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false; - this.disable_search_threshold = this.options.disable_search_threshold || 0; - this.choices = 0; - return this.results_none_found = this.options.no_results_text || "No results match"; - }; - Chosen.prototype.set_up_html = function() { - var container_div, dd_top, dd_width, sf_width; - this.container_id = this.form_field.id.length ? this.form_field.id.replace(/(:|\.)/g, '_') : this.generate_field_id(); - this.container_id += "_chzn"; - this.f_width = this.form_field_jq.outerWidth(); - this.default_text = this.form_field_jq.data('placeholder') ? this.form_field_jq.data('placeholder') : this.default_text_default; - container_div = $("<div />", { - id: this.container_id, - "class": "chzn-container" + (this.is_rtl ? ' chzn-rtl' : ''), - style: 'width: ' + this.f_width + 'px;' - }); - if (this.is_multiple) { - container_div.html('<ul class="chzn-choices"><li class="search-field"><input type="text" value="' + this.default_text + '" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chzn-drop" style="left:-9000px;"><ul class="chzn-results"></ul></div>'); - } else { - container_div.html('<a href="javascript:void(0)" class="chzn-single"><span>' + this.default_text + '</span><div><b></b></div></a><div class="chzn-drop" style="left:-9000px;"><div class="chzn-search"><input type="text" autocomplete="off" /></div><ul class="chzn-results"></ul></div>'); - } - this.form_field_jq.hide().after(container_div); - this.container = $('#' + this.container_id); - this.container.addClass("chzn-container-" + (this.is_multiple ? "multi" : "single")); - if (!this.is_multiple && this.form_field.options.length <= this.disable_search_threshold) { - this.container.addClass("chzn-container-single-nosearch"); - } - this.dropdown = this.container.find('div.chzn-drop').first(); - dd_top = this.container.height(); - dd_width = this.f_width - get_side_border_padding(this.dropdown); - this.dropdown.css({ - "width": dd_width + "px", - "top": dd_top + "px" - }); - this.search_field = this.container.find('input').first(); - this.search_results = this.container.find('ul.chzn-results').first(); - this.search_field_scale(); - this.search_no_results = this.container.find('li.no-results').first(); - if (this.is_multiple) { - this.search_choices = this.container.find('ul.chzn-choices').first(); - this.search_container = this.container.find('li.search-field').first(); - } else { - this.search_container = this.container.find('div.chzn-search').first(); - this.selected_item = this.container.find('.chzn-single').first(); - sf_width = dd_width - get_side_border_padding(this.search_container) - get_side_border_padding(this.search_field); - this.search_field.css({ - "width": sf_width + "px" - }); - } - this.results_build(); - return this.set_tab_index(); - }; - Chosen.prototype.register_observers = function() { - this.container.mousedown(__bind(function(evt) { - return this.container_mousedown(evt); - }, this)); - this.container.mouseup(__bind(function(evt) { - return this.container_mouseup(evt); - }, this)); - this.container.mouseenter(__bind(function(evt) { - return this.mouse_enter(evt); - }, this)); - this.container.mouseleave(__bind(function(evt) { - return this.mouse_leave(evt); - }, this)); - this.search_results.mouseup(__bind(function(evt) { - return this.search_results_mouseup(evt); - }, this)); - this.search_results.mouseover(__bind(function(evt) { - return this.search_results_mouseover(evt); - }, this)); - this.search_results.mouseout(__bind(function(evt) { - return this.search_results_mouseout(evt); - }, this)); - this.form_field_jq.bind("liszt:updated", __bind(function(evt) { - return this.results_update_field(evt); - }, this)); - this.search_field.blur(__bind(function(evt) { - return this.input_blur(evt); - }, this)); - this.search_field.keyup(__bind(function(evt) { - return this.keyup_checker(evt); - }, this)); - this.search_field.keydown(__bind(function(evt) { - return this.keydown_checker(evt); - }, this)); - if (this.is_multiple) { - this.search_choices.click(__bind(function(evt) { - return this.choices_click(evt); - }, this)); - return this.search_field.focus(__bind(function(evt) { - return this.input_focus(evt); - }, this)); - } - }; - Chosen.prototype.search_field_disabled = function() { - this.is_disabled = this.form_field_jq.attr('disabled'); - if (this.is_disabled) { - this.container.addClass('chzn-disabled'); - this.search_field.attr('disabled', true); - if (!this.is_multiple) { - this.selected_item.unbind("focus", this.activate_action); - } - return this.close_field(); - } else { - this.container.removeClass('chzn-disabled'); - this.search_field.attr('disabled', false); - if (!this.is_multiple) { - return this.selected_item.bind("focus", this.activate_action); - } - } - }; - Chosen.prototype.container_mousedown = function(evt) { - var target_closelink; - if (!this.is_disabled) { - target_closelink = evt != null ? ($(evt.target)).hasClass("search-choice-close") : false; - if (evt && evt.type === "mousedown") { - evt.stopPropagation(); - } - if (!this.pending_destroy_click && !target_closelink) { - if (!this.active_field) { - if (this.is_multiple) { - this.search_field.val(""); - } - $(document).click(this.click_test_action); - this.results_show(); - } else if (!this.is_multiple && evt && ($(evt.target) === this.selected_item || $(evt.target).parents("a.chzn-single").length)) { - evt.preventDefault(); - this.results_toggle(); - } - return this.activate_field(); - } else { - return this.pending_destroy_click = false; - } - } - }; - Chosen.prototype.container_mouseup = function(evt) { - if (evt.target.nodeName === "ABBR") { - return this.results_reset(evt); - } - }; - Chosen.prototype.mouse_enter = function() { - return this.mouse_on_container = true; - }; - Chosen.prototype.mouse_leave = function() { - return this.mouse_on_container = false; - }; - Chosen.prototype.input_focus = function(evt) { - if (!this.active_field) { - return setTimeout((__bind(function() { - return this.container_mousedown(); - }, this)), 50); - } - }; - Chosen.prototype.input_blur = function(evt) { - if (!this.mouse_on_container) { - this.active_field = false; - return setTimeout((__bind(function() { - return this.blur_test(); - }, this)), 100); - } - }; - Chosen.prototype.blur_test = function(evt) { - if (!this.active_field && this.container.hasClass("chzn-container-active")) { - return this.close_field(); - } - }; - Chosen.prototype.close_field = function() { - $(document).unbind("click", this.click_test_action); - if (!this.is_multiple) { - this.selected_item.attr("tabindex", this.search_field.attr("tabindex")); - this.search_field.attr("tabindex", -1); - } - this.active_field = false; - this.results_hide(); - this.container.removeClass("chzn-container-active"); - this.winnow_results_clear(); - this.clear_backstroke(); - this.show_search_field_default(); - return this.search_field_scale(); - }; - Chosen.prototype.activate_field = function() { - if (!this.is_multiple && !this.active_field) { - this.search_field.attr("tabindex", this.selected_item.attr("tabindex")); - this.selected_item.attr("tabindex", -1); - } - this.container.addClass("chzn-container-active"); - this.active_field = true; - this.search_field.val(this.search_field.val()); - return this.search_field.focus(); - }; - Chosen.prototype.test_active_click = function(evt) { - if ($(evt.target).parents('#' + this.container_id).length) { - return this.active_field = true; - } else { - return this.close_field(); - } - }; - Chosen.prototype.results_build = function() { - var content, data, startTime, _i, _len, _ref; - startTime = new Date(); - this.parsing = true; - this.results_data = root.SelectParser.select_to_array(this.form_field); - if (this.is_multiple && this.choices > 0) { - this.search_choices.find("li.search-choice").remove(); - this.choices = 0; - } else if (!this.is_multiple) { - this.selected_item.find("span").text(this.default_text); - } - content = ''; - _ref = this.results_data; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - data = _ref[_i]; - if (data.group) { - content += this.result_add_group(data); - } else if (!data.empty) { - content += this.result_add_option(data); - if (data.selected && this.is_multiple) { - this.choice_build(data); - } else if (data.selected && !this.is_multiple) { - this.selected_item.find("span").text(data.text); - if (this.allow_single_deselect) { - this.selected_item.find("span").first().after("<abbr class=\"search-choice-close\"></abbr>"); - } - } - } - } - this.search_field_disabled(); - this.show_search_field_default(); - this.search_field_scale(); - this.search_results.html(content); - return this.parsing = false; - }; - Chosen.prototype.result_add_group = function(group) { - if (!group.disabled) { - group.dom_id = this.container_id + "_g_" + group.array_index; - return '<li id="' + group.dom_id + '" class="group-result">' + $("<div />").text(group.label).html() + '</li>'; - } else { - return ""; - } - }; - Chosen.prototype.result_add_option = function(option) { - var classes, style; - if (!option.disabled) { - option.dom_id = this.container_id + "_o_" + option.array_index; - classes = option.selected && this.is_multiple ? [] : ["active-result"]; - if (option.selected) { - classes.push("result-selected"); - } - if (option.group_array_index != null) { - classes.push("group-option"); - } - if (option.classes !== "") { - classes.push(option.classes); - } - style = option.style.cssText !== "" ? " style=\"" + option.style + "\"" : ""; - return '<li id="' + option.dom_id + '" class="' + classes.join(' ') + '"' + style + '>' + option.html + '</li>'; - } else { - return ""; - } - }; - Chosen.prototype.results_update_field = function() { - this.result_clear_highlight(); - this.result_single_selected = null; - return this.results_build(); - }; - Chosen.prototype.result_do_highlight = function(el) { - var high_bottom, high_top, maxHeight, visible_bottom, visible_top; - if (el.length) { - this.result_clear_highlight(); - this.result_highlight = el; - this.result_highlight.addClass("highlighted"); - maxHeight = parseInt(this.search_results.css("maxHeight"), 10); - visible_top = this.search_results.scrollTop(); - visible_bottom = maxHeight + visible_top; - high_top = this.result_highlight.position().top + this.search_results.scrollTop(); - high_bottom = high_top + this.result_highlight.outerHeight(); - if (high_bottom >= visible_bottom) { - return this.search_results.scrollTop((high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0); - } else if (high_top < visible_top) { - return this.search_results.scrollTop(high_top); - } - } - }; - Chosen.prototype.result_clear_highlight = function() { - if (this.result_highlight) { - this.result_highlight.removeClass("highlighted"); - } - return this.result_highlight = null; - }; - Chosen.prototype.results_toggle = function() { - if (this.results_showing) { - return this.results_hide(); - } else { - return this.results_show(); - } - }; - Chosen.prototype.results_show = function() { - var dd_top; - if (!this.is_multiple) { - this.selected_item.addClass("chzn-single-with-drop"); - if (this.result_single_selected) { - this.result_do_highlight(this.result_single_selected); - } - } - dd_top = this.is_multiple ? this.container.height() : this.container.height() - 1; - this.dropdown.css({ - "top": dd_top + "px", - "left": 0 - }); - this.results_showing = true; - this.search_field.focus(); - this.search_field.val(this.search_field.val()); - return this.winnow_results(); - }; - Chosen.prototype.results_hide = function() { - if (!this.is_multiple) { - this.selected_item.removeClass("chzn-single-with-drop"); - } - this.result_clear_highlight(); - this.dropdown.css({ - "left": "-9000px" - }); - return this.results_showing = false; - }; - Chosen.prototype.set_tab_index = function(el) { - var ti; - if (this.form_field_jq.attr("tabindex")) { - ti = this.form_field_jq.attr("tabindex"); - this.form_field_jq.attr("tabindex", -1); - if (this.is_multiple) { - return this.search_field.attr("tabindex", ti); - } else { - this.selected_item.attr("tabindex", ti); - return this.search_field.attr("tabindex", -1); - } - } - }; - Chosen.prototype.show_search_field_default = function() { - if (this.is_multiple && this.choices < 1 && !this.active_field) { - this.search_field.val(this.default_text); - return this.search_field.addClass("default"); - } else { - this.search_field.val(""); - return this.search_field.removeClass("default"); - } - }; - Chosen.prototype.search_results_mouseup = function(evt) { - var target; - target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first(); - if (target.length) { - this.result_highlight = target; - return this.result_select(evt); - } - }; - Chosen.prototype.search_results_mouseover = function(evt) { - var target; - target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first(); - if (target) { - return this.result_do_highlight(target); - } - }; - Chosen.prototype.search_results_mouseout = function(evt) { - if ($(evt.target).hasClass("active-result" || $(evt.target).parents('.active-result').first())) { - return this.result_clear_highlight(); - } - }; - Chosen.prototype.choices_click = function(evt) { - evt.preventDefault(); - if (this.active_field && !($(evt.target).hasClass("search-choice" || $(evt.target).parents('.search-choice').first)) && !this.results_showing) { - return this.results_show(); - } - }; - Chosen.prototype.choice_build = function(item) { - var choice_id, link; - choice_id = this.container_id + "_c_" + item.array_index; - this.choices += 1; - this.search_container.before('<li class="search-choice" id="' + choice_id + '"><span>' + item.html + '</span><a href="javascript:void(0)" class="search-choice-close" rel="' + item.array_index + '"></a></li>'); - link = $('#' + choice_id).find("a").first(); - return link.click(__bind(function(evt) { - return this.choice_destroy_link_click(evt); - }, this)); - }; - Chosen.prototype.choice_destroy_link_click = function(evt) { - evt.preventDefault(); - if (!this.is_disabled) { - this.pending_destroy_click = true; - return this.choice_destroy($(evt.target)); - } else { - return evt.stopPropagation; - } - }; - Chosen.prototype.choice_destroy = function(link) { - this.choices -= 1; - this.show_search_field_default(); - if (this.is_multiple && this.choices > 0 && this.search_field.val().length < 1) { - this.results_hide(); - } - this.result_deselect(link.attr("rel")); - return link.parents('li').first().remove(); - }; - Chosen.prototype.results_reset = function(evt) { - this.form_field.options[0].selected = true; - this.selected_item.find("span").text(this.default_text); - this.show_search_field_default(); - $(evt.target).remove(); - this.form_field_jq.trigger("change"); - if (this.active_field) { - return this.results_hide(); - } - }; - Chosen.prototype.result_select = function(evt) { - var high, high_id, item, position; - if (this.result_highlight) { - high = this.result_highlight; - high_id = high.attr("id"); - this.result_clear_highlight(); - if (this.is_multiple) { - this.result_deactivate(high); - } else { - this.search_results.find(".result-selected").removeClass("result-selected"); - this.result_single_selected = high; - } - high.addClass("result-selected"); - position = high_id.substr(high_id.lastIndexOf("_") + 1); - item = this.results_data[position]; - item.selected = true; - this.form_field.options[item.options_index].selected = true; - if (this.is_multiple) { - this.choice_build(item); - } else { - this.selected_item.find("span").first().text(item.text); - if (this.allow_single_deselect) { - this.selected_item.find("span").first().after("<abbr class=\"search-choice-close\"></abbr>"); - } - } - if (!(evt.metaKey && this.is_multiple)) { - this.results_hide(); - } - this.search_field.val(""); - this.form_field_jq.trigger("change"); - return this.search_field_scale(); - } - }; - Chosen.prototype.result_activate = function(el) { - return el.addClass("active-result"); - }; - Chosen.prototype.result_deactivate = function(el) { - return el.removeClass("active-result"); - }; - Chosen.prototype.result_deselect = function(pos) { - var result, result_data; - result_data = this.results_data[pos]; - result_data.selected = false; - this.form_field.options[result_data.options_index].selected = false; - result = $("#" + this.container_id + "_o_" + pos); - result.removeClass("result-selected").addClass("active-result").show(); - this.result_clear_highlight(); - this.winnow_results(); - this.form_field_jq.trigger("change"); - return this.search_field_scale(); - }; - Chosen.prototype.results_search = function(evt) { - if (this.results_showing) { - return this.winnow_results(); - } else { - return this.results_show(); - } - }; - Chosen.prototype.winnow_results = function() { - var found, option, part, parts, regex, result_id, results, searchText, startTime, startpos, text, zregex, _i, _j, _len, _len2, _ref; - startTime = new Date(); - this.no_results_clear(); - results = 0; - searchText = this.search_field.val() === this.default_text ? "" : $('<div/>').text($.trim(this.search_field.val())).html(); - regex = new RegExp('^' + searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i'); - zregex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i'); - _ref = this.results_data; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - option = _ref[_i]; - if (!option.disabled && !option.empty) { - if (option.group) { - $('#' + option.dom_id).hide(); - } else if (!(this.is_multiple && option.selected)) { - found = false; - result_id = option.dom_id; - if (regex.test(option.html)) { - found = true; - results += 1; - } else if (option.html.indexOf(" ") >= 0 || option.html.indexOf("[") === 0) { - parts = option.html.replace(/\[|\]/g, "").split(" "); - if (parts.length) { - for (_j = 0, _len2 = parts.length; _j < _len2; _j++) { - part = parts[_j]; - if (regex.test(part)) { - found = true; - results += 1; - } - } - } - } - if (found) { - if (searchText.length) { - startpos = option.html.search(zregex); - text = option.html.substr(0, startpos + searchText.length) + '</em>' + option.html.substr(startpos + searchText.length); - text = text.substr(0, startpos) + '<em>' + text.substr(startpos); - } else { - text = option.html; - } - if ($("#" + result_id).html !== text) { - $("#" + result_id).html(text); - } - this.result_activate($("#" + result_id)); - if (option.group_array_index != null) { - $("#" + this.results_data[option.group_array_index].dom_id).show(); - } - } else { - if (this.result_highlight && result_id === this.result_highlight.attr('id')) { - this.result_clear_highlight(); - } - this.result_deactivate($("#" + result_id)); - } - } - } - } - if (results < 1 && searchText.length) { - return this.no_results(searchText); - } else { - return this.winnow_results_set_highlight(); - } - }; - Chosen.prototype.winnow_results_clear = function() { - var li, lis, _i, _len, _results; - this.search_field.val(""); - lis = this.search_results.find("li"); - _results = []; - for (_i = 0, _len = lis.length; _i < _len; _i++) { - li = lis[_i]; - li = $(li); - _results.push(li.hasClass("group-result") ? li.show() : !this.is_multiple || !li.hasClass("result-selected") ? this.result_activate(li) : void 0); - } - return _results; - }; - Chosen.prototype.winnow_results_set_highlight = function() { - var do_high, selected_results; - if (!this.result_highlight) { - selected_results = !this.is_multiple ? this.search_results.find(".result-selected.active-result") : []; - do_high = selected_results.length ? selected_results.first() : this.search_results.find(".active-result").first(); - if (do_high != null) { - return this.result_do_highlight(do_high); - } - } - }; - Chosen.prototype.no_results = function(terms) { - var no_results_html; - no_results_html = $('<li class="no-results">' + this.results_none_found + ' "<span></span>"</li>'); - no_results_html.find("span").first().html(terms); - return this.search_results.append(no_results_html); - }; - Chosen.prototype.no_results_clear = function() { - return this.search_results.find(".no-results").remove(); - }; - Chosen.prototype.keydown_arrow = function() { - var first_active, next_sib; - if (!this.result_highlight) { - first_active = this.search_results.find("li.active-result").first(); - if (first_active) { - this.result_do_highlight($(first_active)); - } - } else if (this.results_showing) { - next_sib = this.result_highlight.nextAll("li.active-result").first(); - if (next_sib) { - this.result_do_highlight(next_sib); - } - } - if (!this.results_showing) { - return this.results_show(); - } - }; - Chosen.prototype.keyup_arrow = function() { - var prev_sibs; - if (!this.results_showing && !this.is_multiple) { - return this.results_show(); - } else if (this.result_highlight) { - prev_sibs = this.result_highlight.prevAll("li.active-result"); - if (prev_sibs.length) { - return this.result_do_highlight(prev_sibs.first()); - } else { - if (this.choices > 0) { - this.results_hide(); - } - return this.result_clear_highlight(); - } - } - }; - Chosen.prototype.keydown_backstroke = function() { - if (this.pending_backstroke) { - this.choice_destroy(this.pending_backstroke.find("a").first()); - return this.clear_backstroke(); - } else { - this.pending_backstroke = this.search_container.siblings("li.search-choice").last(); - return this.pending_backstroke.addClass("search-choice-focus"); - } - }; - Chosen.prototype.clear_backstroke = function() { - if (this.pending_backstroke) { - this.pending_backstroke.removeClass("search-choice-focus"); - } - return this.pending_backstroke = null; - }; - Chosen.prototype.keyup_checker = function(evt) { - var stroke, _ref; - stroke = (_ref = evt.which) != null ? _ref : evt.keyCode; - this.search_field_scale(); - switch (stroke) { - case 8: - if (this.is_multiple && this.backstroke_length < 1 && this.choices > 0) { - return this.keydown_backstroke(); - } else if (!this.pending_backstroke) { - this.result_clear_highlight(); - return this.results_search(); - } - break; - case 13: - evt.preventDefault(); - if (this.results_showing) { - return this.result_select(evt); - } - break; - case 27: - if (this.results_showing) { - return this.results_hide(); - } - break; - case 9: - case 38: - case 40: - case 16: - case 91: - case 17: - break; - default: - return this.results_search(); - } - }; - Chosen.prototype.keydown_checker = function(evt) { - var stroke, _ref; - stroke = (_ref = evt.which) != null ? _ref : evt.keyCode; - this.search_field_scale(); - if (stroke !== 8 && this.pending_backstroke) { - this.clear_backstroke(); - } - switch (stroke) { - case 8: - this.backstroke_length = this.search_field.val().length; - break; - case 9: - this.mouse_on_container = false; - break; - case 13: - evt.preventDefault(); - break; - case 38: - evt.preventDefault(); - this.keyup_arrow(); - break; - case 40: - this.keydown_arrow(); - break; - } - }; - Chosen.prototype.search_field_scale = function() { - var dd_top, div, h, style, style_block, styles, w, _i, _len; - if (this.is_multiple) { - h = 0; - w = 0; - style_block = "position:absolute; left: -1000px; top: -1000px; display:none;"; - styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing']; - for (_i = 0, _len = styles.length; _i < _len; _i++) { - style = styles[_i]; - style_block += style + ":" + this.search_field.css(style) + ";"; - } - div = $('<div />', { - 'style': style_block - }); - div.text(this.search_field.val()); - $('body').append(div); - w = div.width() + 25; - div.remove(); - if (w > this.f_width - 10) { - w = this.f_width - 10; - } - this.search_field.css({ - 'width': w + 'px' - }); - dd_top = this.container.height(); - return this.dropdown.css({ - "top": dd_top + "px" - }); - } - }; - Chosen.prototype.generate_field_id = function() { - var new_id; - new_id = this.generate_random_id(); - this.form_field.id = new_id; - return new_id; - }; - Chosen.prototype.generate_random_id = function() { - var string; - string = "sel" + this.generate_random_char() + this.generate_random_char() + this.generate_random_char(); - while ($("#" + string).length > 0) { - string += this.generate_random_char(); - } - return string; - }; - Chosen.prototype.generate_random_char = function() { - var chars, newchar, rand; - chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ"; - rand = Math.floor(Math.random() * chars.length); - return newchar = chars.substring(rand, rand + 1); - }; - return Chosen; - })(); - get_side_border_padding = function(elmt) { - var side_border_padding; - return side_border_padding = elmt.outerWidth() - elmt.width(); - }; - root.get_side_border_padding = get_side_border_padding; -}).call(this); -(function() { - var SelectParser; - SelectParser = (function() { - function SelectParser() { - this.options_index = 0; - this.parsed = []; - } - SelectParser.prototype.add_node = function(child) { - if (child.nodeName === "OPTGROUP") { - return this.add_group(child); - } else { - return this.add_option(child); - } - }; - SelectParser.prototype.add_group = function(group) { - var group_position, option, _i, _len, _ref, _results; - group_position = this.parsed.length; - this.parsed.push({ - array_index: group_position, - group: true, - label: group.label, - children: 0, - disabled: group.disabled - }); - _ref = group.childNodes; - _results = []; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - option = _ref[_i]; - _results.push(this.add_option(option, group_position, group.disabled)); - } - return _results; - }; - SelectParser.prototype.add_option = function(option, group_position, group_disabled) { - if (option.nodeName === "OPTION") { - if (option.text !== "") { - if (group_position != null) { - this.parsed[group_position].children += 1; - } - this.parsed.push({ - array_index: this.parsed.length, - options_index: this.options_index, - value: option.value, - text: option.text, - html: option.innerHTML, - selected: option.selected, - disabled: group_disabled === true ? group_disabled : option.disabled, - group_array_index: group_position, - classes: option.className, - style: option.style.cssText - }); - } else { - this.parsed.push({ - array_index: this.parsed.length, - options_index: this.options_index, - empty: true - }); - } - return this.options_index += 1; - } - }; - return SelectParser; - })(); - SelectParser.select_to_array = function(select) { - var child, parser, _i, _len, _ref; - parser = new SelectParser(); - _ref = select.childNodes; - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - child = _ref[_i]; - parser.add_node(child); - } - return parser.parsed; - }; - this.SelectParser = SelectParser; -}).call(this); diff --git a/3rdparty/js/chosen/chosen.jquery.min.js b/3rdparty/js/chosen/chosen.jquery.min.js deleted file mode 100644 index 371ee53e7a352edec5313ec4912d9dccb3160e29..0000000000000000000000000000000000000000 --- a/3rdparty/js/chosen/chosen.jquery.min.js +++ /dev/null @@ -1,10 +0,0 @@ -// Chosen, a Select Box Enhancer for jQuery and Protoype -// by Patrick Filler for Harvest, http://getharvest.com -// -// Version 0.9.5 -// Full source at https://github.com/harvesthq/chosen -// Copyright (c) 2011 Harvest http://getharvest.com - -// MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md -// This file is generated by `cake build`, do not edit it by hand. -(function(){var a,b,c,d,e=function(a,b){return function(){return a.apply(b,arguments)}};d=this,a=jQuery,a.fn.extend({chosen:function(c){return a.browser!=="msie"||a.browser.version!=="6.0"&&a.browser.version!=="7.0"?a(this).each(function(d){if(!a(this).hasClass("chzn-done"))return new b(this,c)}):this}}),b=function(){function b(b,c){this.form_field=b,this.options=c!=null?c:{},this.set_default_values(),this.form_field_jq=a(this.form_field),this.is_multiple=this.form_field.multiple,this.is_rtl=this.form_field_jq.hasClass("chzn-rtl"),this.default_text_default=this.form_field.multiple?"Select Some Options":"Select an Option",this.set_up_html(),this.register_observers(),this.form_field_jq.addClass("chzn-done")}b.prototype.set_default_values=function(){this.click_test_action=e(function(a){return this.test_active_click(a)},this),this.activate_action=e(function(a){return this.activate_field(a)},this),this.active_field=!1,this.mouse_on_container=!1,this.results_showing=!1,this.result_highlighted=null,this.result_single_selected=null,this.allow_single_deselect=this.options.allow_single_deselect!=null&&this.form_field.options[0].text===""?this.options.allow_single_deselect:!1,this.disable_search_threshold=this.options.disable_search_threshold||0,this.choices=0;return this.results_none_found=this.options.no_results_text||"No results match"},b.prototype.set_up_html=function(){var b,d,e,f;this.container_id=this.form_field.id.length?this.form_field.id.replace(/(:|\.)/g,"_"):this.generate_field_id(),this.container_id+="_chzn",this.f_width=this.form_field_jq.outerWidth(),this.default_text=this.form_field_jq.data("placeholder")?this.form_field_jq.data("placeholder"):this.default_text_default,b=a("<div />",{id:this.container_id,"class":"chzn-container"+(this.is_rtl?" chzn-rtl":""),style:"width: "+this.f_width+"px;"}),this.is_multiple?b.html('<ul class="chzn-choices"><li class="search-field"><input type="text" value="'+this.default_text+'" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chzn-drop" style="left:-9000px;"><ul class="chzn-results"></ul></div>'):b.html('<a href="javascript:void(0)" class="chzn-single"><span>'+this.default_text+'</span><div><b></b></div></a><div class="chzn-drop" style="left:-9000px;"><div class="chzn-search"><input type="text" autocomplete="off" /></div><ul class="chzn-results"></ul></div>'),this.form_field_jq.hide().after(b),this.container=a("#"+this.container_id),this.container.addClass("chzn-container-"+(this.is_multiple?"multi":"single")),!this.is_multiple&&this.form_field.options.length<=this.disable_search_threshold&&this.container.addClass("chzn-container-single-nosearch"),this.dropdown=this.container.find("div.chzn-drop").first(),d=this.container.height(),e=this.f_width-c(this.dropdown),this.dropdown.css({width:e+"px",top:d+"px"}),this.search_field=this.container.find("input").first(),this.search_results=this.container.find("ul.chzn-results").first(),this.search_field_scale(),this.search_no_results=this.container.find("li.no-results").first(),this.is_multiple?(this.search_choices=this.container.find("ul.chzn-choices").first(),this.search_container=this.container.find("li.search-field").first()):(this.search_container=this.container.find("div.chzn-search").first(),this.selected_item=this.container.find(".chzn-single").first(),f=e-c(this.search_container)-c(this.search_field),this.search_field.css({width:f+"px"})),this.results_build();return this.set_tab_index()},b.prototype.register_observers=function(){this.container.mousedown(e(function(a){return this.container_mousedown(a)},this)),this.container.mouseup(e(function(a){return this.container_mouseup(a)},this)),this.container.mouseenter(e(function(a){return this.mouse_enter(a)},this)),this.container.mouseleave(e(function(a){return this.mouse_leave(a)},this)),this.search_results.mouseup(e(function(a){return this.search_results_mouseup(a)},this)),this.search_results.mouseover(e(function(a){return this.search_results_mouseover(a)},this)),this.search_results.mouseout(e(function(a){return this.search_results_mouseout(a)},this)),this.form_field_jq.bind("liszt:updated",e(function(a){return this.results_update_field(a)},this)),this.search_field.blur(e(function(a){return this.input_blur(a)},this)),this.search_field.keyup(e(function(a){return this.keyup_checker(a)},this)),this.search_field.keydown(e(function(a){return this.keydown_checker(a)},this));if(this.is_multiple){this.search_choices.click(e(function(a){return this.choices_click(a)},this));return this.search_field.focus(e(function(a){return this.input_focus(a)},this))}},b.prototype.search_field_disabled=function(){this.is_disabled=this.form_field_jq.attr("disabled");if(this.is_disabled){this.container.addClass("chzn-disabled"),this.search_field.attr("disabled",!0),this.is_multiple||this.selected_item.unbind("focus",this.activate_action);return this.close_field()}this.container.removeClass("chzn-disabled"),this.search_field.attr("disabled",!1);if(!this.is_multiple)return this.selected_item.bind("focus",this.activate_action)},b.prototype.container_mousedown=function(b){var c;if(!this.is_disabled){c=b!=null?a(b.target).hasClass("search-choice-close"):!1,b&&b.type==="mousedown"&&b.stopPropagation();if(!this.pending_destroy_click&&!c){this.active_field?!this.is_multiple&&b&&(a(b.target)===this.selected_item||a(b.target).parents("a.chzn-single").length)&&(b.preventDefault(),this.results_toggle()):(this.is_multiple&&this.search_field.val(""),a(document).click(this.click_test_action),this.results_show());return this.activate_field()}return this.pending_destroy_click=!1}},b.prototype.container_mouseup=function(a){if(a.target.nodeName==="ABBR")return this.results_reset(a)},b.prototype.mouse_enter=function(){return this.mouse_on_container=!0},b.prototype.mouse_leave=function(){return this.mouse_on_container=!1},b.prototype.input_focus=function(a){if(!this.active_field)return setTimeout(e(function(){return this.container_mousedown()},this),50)},b.prototype.input_blur=function(a){if(!this.mouse_on_container){this.active_field=!1;return setTimeout(e(function(){return this.blur_test()},this),100)}},b.prototype.blur_test=function(a){if(!this.active_field&&this.container.hasClass("chzn-container-active"))return this.close_field()},b.prototype.close_field=function(){a(document).unbind("click",this.click_test_action),this.is_multiple||(this.selected_item.attr("tabindex",this.search_field.attr("tabindex")),this.search_field.attr("tabindex",-1)),this.active_field=!1,this.results_hide(),this.container.removeClass("chzn-container-active"),this.winnow_results_clear(),this.clear_backstroke(),this.show_search_field_default();return this.search_field_scale()},b.prototype.activate_field=function(){!this.is_multiple&&!this.active_field&&(this.search_field.attr("tabindex",this.selected_item.attr("tabindex")),this.selected_item.attr("tabindex",-1)),this.container.addClass("chzn-container-active"),this.active_field=!0,this.search_field.val(this.search_field.val());return this.search_field.focus()},b.prototype.test_active_click=function(b){return a(b.target).parents("#"+this.container_id).length?this.active_field=!0:this.close_field()},b.prototype.results_build=function(){var a,b,c,e,f,g;c=new Date,this.parsing=!0,this.results_data=d.SelectParser.select_to_array(this.form_field),this.is_multiple&&this.choices>0?(this.search_choices.find("li.search-choice").remove(),this.choices=0):this.is_multiple||this.selected_item.find("span").text(this.default_text),a="",g=this.results_data;for(e=0,f=g.length;e<f;e++)b=g[e],b.group?a+=this.result_add_group(b):b.empty||(a+=this.result_add_option(b),b.selected&&this.is_multiple?this.choice_build(b):b.selected&&!this.is_multiple&&(this.selected_item.find("span").text(b.text),this.allow_single_deselect&&this.selected_item.find("span").first().after('<abbr class="search-choice-close"></abbr>')));this.search_field_disabled(),this.show_search_field_default(),this.search_field_scale(),this.search_results.html(a);return this.parsing=!1},b.prototype.result_add_group=function(b){if(!b.disabled){b.dom_id=this.container_id+"_g_"+b.array_index;return'<li id="'+b.dom_id+'" class="group-result">'+a("<div />").text(b.label).html()+"</li>"}return""},b.prototype.result_add_option=function(a){var b,c;if(!a.disabled){a.dom_id=this.container_id+"_o_"+a.array_index,b=a.selected&&this.is_multiple?[]:["active-result"],a.selected&&b.push("result-selected"),a.group_array_index!=null&&b.push("group-option"),a.classes!==""&&b.push(a.classes),c=a.style.cssText!==""?' style="'+a.style+'"':"";return'<li id="'+a.dom_id+'" class="'+b.join(" ")+'"'+c+">"+a.html+"</li>"}return""},b.prototype.results_update_field=function(){this.result_clear_highlight(),this.result_single_selected=null;return this.results_build()},b.prototype.result_do_highlight=function(a){var b,c,d,e,f;if(a.length){this.result_clear_highlight(),this.result_highlight=a,this.result_highlight.addClass("highlighted"),d=parseInt(this.search_results.css("maxHeight"),10),f=this.search_results.scrollTop(),e=d+f,c=this.result_highlight.position().top+this.search_results.scrollTop(),b=c+this.result_highlight.outerHeight();if(b>=e)return this.search_results.scrollTop(b-d>0?b-d:0);if(c<f)return this.search_results.scrollTop(c)}},b.prototype.result_clear_highlight=function(){this.result_highlight&&this.result_highlight.removeClass("highlighted");return this.result_highlight=null},b.prototype.results_toggle=function(){return this.results_showing?this.results_hide():this.results_show()},b.prototype.results_show=function(){var a;this.is_multiple||(this.selected_item.addClass("chzn-single-with-drop"),this.result_single_selected&&this.result_do_highlight(this.result_single_selected)),a=this.is_multiple?this.container.height():this.container.height()-1,this.dropdown.css({top:a+"px",left:0}),this.results_showing=!0,this.search_field.focus(),this.search_field.val(this.search_field.val());return this.winnow_results()},b.prototype.results_hide=function(){this.is_multiple||this.selected_item.removeClass("chzn-single-with-drop"),this.result_clear_highlight(),this.dropdown.css({left:"-9000px"});return this.results_showing=!1},b.prototype.set_tab_index=function(a){var b;if(this.form_field_jq.attr("tabindex")){b=this.form_field_jq.attr("tabindex"),this.form_field_jq.attr("tabindex",-1);if(this.is_multiple)return this.search_field.attr("tabindex",b);this.selected_item.attr("tabindex",b);return this.search_field.attr("tabindex",-1)}},b.prototype.show_search_field_default=function(){if(this.is_multiple&&this.choices<1&&!this.active_field){this.search_field.val(this.default_text);return this.search_field.addClass("default")}this.search_field.val("");return this.search_field.removeClass("default")},b.prototype.search_results_mouseup=function(b){var c;c=a(b.target).hasClass("active-result")?a(b.target):a(b.target).parents(".active-result").first();if(c.length){this.result_highlight=c;return this.result_select(b)}},b.prototype.search_results_mouseover=function(b){var c;c=a(b.target).hasClass("active-result")?a(b.target):a(b.target).parents(".active-result").first();if(c)return this.result_do_highlight(c)},b.prototype.search_results_mouseout=function(b){if(a(b.target).hasClass("active-result"))return this.result_clear_highlight()},b.prototype.choices_click=function(b){b.preventDefault();if(this.active_field&&!a(b.target).hasClass("search-choice")&&!this.results_showing)return this.results_show()},b.prototype.choice_build=function(b){var c,d;c=this.container_id+"_c_"+b.array_index,this.choices+=1,this.search_container.before('<li class="search-choice" id="'+c+'"><span>'+b.html+'</span><a href="javascript:void(0)" class="search-choice-close" rel="'+b.array_index+'"></a></li>'),d=a("#"+c).find("a").first();return d.click(e(function(a){return this.choice_destroy_link_click(a)},this))},b.prototype.choice_destroy_link_click=function(b){b.preventDefault();if(!this.is_disabled){this.pending_destroy_click=!0;return this.choice_destroy(a(b.target))}return b.stopPropagation},b.prototype.choice_destroy=function(a){this.choices-=1,this.show_search_field_default(),this.is_multiple&&this.choices>0&&this.search_field.val().length<1&&this.results_hide(),this.result_deselect(a.attr("rel"));return a.parents("li").first().remove()},b.prototype.results_reset=function(b){this.form_field.options[0].selected=!0,this.selected_item.find("span").text(this.default_text),this.show_search_field_default(),a(b.target).remove(),this.form_field_jq.trigger("change");if(this.active_field)return this.results_hide()},b.prototype.result_select=function(a){var b,c,d,e;if(this.result_highlight){b=this.result_highlight,c=b.attr("id"),this.result_clear_highlight(),this.is_multiple?this.result_deactivate(b):(this.search_results.find(".result-selected").removeClass("result-selected"),this.result_single_selected=b),b.addClass("result-selected"),e=c.substr(c.lastIndexOf("_")+1),d=this.results_data[e],d.selected=!0,this.form_field.options[d.options_index].selected=!0,this.is_multiple?this.choice_build(d):(this.selected_item.find("span").first().text(d.text),this.allow_single_deselect&&this.selected_item.find("span").first().after('<abbr class="search-choice-close"></abbr>')),(!a.metaKey||!this.is_multiple)&&this.results_hide(),this.search_field.val(""),this.form_field_jq.trigger("change");return this.search_field_scale()}},b.prototype.result_activate=function(a){return a.addClass("active-result")},b.prototype.result_deactivate=function(a){return a.removeClass("active-result")},b.prototype.result_deselect=function(b){var c,d;d=this.results_data[b],d.selected=!1,this.form_field.options[d.options_index].selected=!1,c=a("#"+this.container_id+"_o_"+b),c.removeClass("result-selected").addClass("active-result").show(),this.result_clear_highlight(),this.winnow_results(),this.form_field_jq.trigger("change");return this.search_field_scale()},b.prototype.results_search=function(a){return this.results_showing?this.winnow_results():this.results_show()},b.prototype.winnow_results=function(){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r;j=new Date,this.no_results_clear(),h=0,i=this.search_field.val()===this.default_text?"":a("<div/>").text(a.trim(this.search_field.val())).html(),f=new RegExp("^"+i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"i"),m=new RegExp(i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"i"),r=this.results_data;for(n=0,p=r.length;n<p;n++){c=r[n];if(!c.disabled&&!c.empty)if(c.group)a("#"+c.dom_id).hide();else if(!this.is_multiple||!c.selected){b=!1,g=c.dom_id;if(f.test(c.html))b=!0,h+=1;else if(c.html.indexOf(" ")>=0||c.html.indexOf("[")===0){e=c.html.replace(/\[|\]/g,"").split(" ");if(e.length)for(o=0,q=e.length;o<q;o++)d=e[o],f.test(d)&&(b=!0,h+=1)}b?(i.length?(k=c.html.search(m),l=c.html.substr(0,k+i.length)+"</em>"+c.html.substr(k+i.length),l=l.substr(0,k)+"<em>"+l.substr(k)):l=c.html,a("#"+g).html!==l&&a("#"+g).html(l),this.result_activate(a("#"+g)),c.group_array_index!=null&&a("#"+this.results_data[c.group_array_index].dom_id).show()):(this.result_highlight&&g===this.result_highlight.attr("id")&&this.result_clear_highlight(),this.result_deactivate(a("#"+g)))}}return h<1&&i.length?this.no_results(i):this.winnow_results_set_highlight()},b.prototype.winnow_results_clear=function(){var b,c,d,e,f;this.search_field.val(""),c=this.search_results.find("li"),f=[];for(d=0,e=c.length;d<e;d++)b=c[d],b=a(b),f.push(b.hasClass("group-result")?b.show():!this.is_multiple||!b.hasClass("result-selected")?this.result_activate(b):void 0);return f},b.prototype.winnow_results_set_highlight=function(){var a,b;if(!this.result_highlight){b=this.is_multiple?[]:this.search_results.find(".result-selected.active-result"),a=b.length?b.first():this.search_results.find(".active-result").first();if(a!=null)return this.result_do_highlight(a)}},b.prototype.no_results=function(b){var c;c=a('<li class="no-results">'+this.results_none_found+' "<span></span>"</li>'),c.find("span").first().html(b);return this.search_results.append(c)},b.prototype.no_results_clear=function(){return this.search_results.find(".no-results").remove()},b.prototype.keydown_arrow=function(){var b,c;this.result_highlight?this.results_showing&&(c=this.result_highlight.nextAll("li.active-result").first(),c&&this.result_do_highlight(c)):(b=this.search_results.find("li.active-result").first(),b&&this.result_do_highlight(a(b)));if(!this.results_showing)return this.results_show()},b.prototype.keyup_arrow=function(){var a;if(!this.results_showing&&!this.is_multiple)return this.results_show();if(this.result_highlight){a=this.result_highlight.prevAll("li.active-result");if(a.length)return this.result_do_highlight(a.first());this.choices>0&&this.results_hide();return this.result_clear_highlight()}},b.prototype.keydown_backstroke=function(){if(this.pending_backstroke){this.choice_destroy(this.pending_backstroke.find("a").first());return this.clear_backstroke()}this.pending_backstroke=this.search_container.siblings("li.search-choice").last();return this.pending_backstroke.addClass("search-choice-focus")},b.prototype.clear_backstroke=function(){this.pending_backstroke&&this.pending_backstroke.removeClass("search-choice-focus");return this.pending_backstroke=null},b.prototype.keyup_checker=function(a){var b,c;b=(c=a.which)!=null?c:a.keyCode,this.search_field_scale();switch(b){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices>0)return this.keydown_backstroke();if(!this.pending_backstroke){this.result_clear_highlight();return this.results_search()}break;case 13:a.preventDefault();if(this.results_showing)return this.result_select(a);break;case 27:if(this.results_showing)return this.results_hide();break;case 9:case 38:case 40:case 16:case 91:case 17:break;default:return this.results_search()}},b.prototype.keydown_checker=function(a){var b,c;b=(c=a.which)!=null?c:a.keyCode,this.search_field_scale(),b!==8&&this.pending_backstroke&&this.clear_backstroke();switch(b){case 8:this.backstroke_length=this.search_field.val().length;break;case 9:this.mouse_on_container=!1;break;case 13:a.preventDefault();break;case 38:a.preventDefault(),this.keyup_arrow();break;case 40:this.keydown_arrow()}},b.prototype.search_field_scale=function(){var b,c,d,e,f,g,h,i,j;if(this.is_multiple){d=0,h=0,f="position:absolute; left: -1000px; top: -1000px; display:none;",g=["font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"];for(i=0,j=g.length;i<j;i++)e=g[i],f+=e+":"+this.search_field.css(e)+";";c=a("<div />",{style:f}),c.text(this.search_field.val()),a("body").append(c),h=c.width()+25,c.remove(),h>this.f_width-10&&(h=this.f_width-10),this.search_field.css({width:h+"px"}),b=this.container.height();return this.dropdown.css({top:b+"px"})}},b.prototype.generate_field_id=function(){var a;a=this.generate_random_id(),this.form_field.id=a;return a},b.prototype.generate_random_id=function(){var b;b="sel"+this.generate_random_char()+this.generate_random_char()+this.generate_random_char();while(a("#"+b).length>0)b+=this.generate_random_char();return b},b.prototype.generate_random_char=function(){var a,b,c;a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ",c=Math.floor(Math.random()*a.length);return b=a.substring(c,c+1)};return b}(),c=function(a){var b;return b=a.outerWidth()-a.width()},d.get_side_border_padding=c}).call(this),function(){var a;a=function(){function a(){this.options_index=0,this.parsed=[]}a.prototype.add_node=function(a){return a.nodeName==="OPTGROUP"?this.add_group(a):this.add_option(a)},a.prototype.add_group=function(a){var b,c,d,e,f,g;b=this.parsed.length,this.parsed.push({array_index:b,group:!0,label:a.label,children:0,disabled:a.disabled}),f=a.childNodes,g=[];for(d=0,e=f.length;d<e;d++)c=f[d],g.push(this.add_option(c,b,a.disabled));return g},a.prototype.add_option=function(a,b,c){if(a.nodeName==="OPTION"){a.text!==""?(b!=null&&(this.parsed[b].children+=1),this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:a.value,text:a.text,html:a.innerHTML,selected:a.selected,disabled:c===!0?c:a.disabled,group_array_index:b,classes:a.className,style:a.style.cssText})):this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:!0});return this.options_index+=1}};return a}(),a.select_to_array=function(b){var c,d,e,f,g;d=new a,g=b.childNodes;for(e=0,f=g.length;e<f;e++)c=g[e],d.add_node(c);return d.parsed},this.SelectParser=a}.call(this) \ No newline at end of file diff --git a/3rdparty/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE b/3rdparty/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE deleted file mode 100755 index a65e83e87628fbc7b03266e72e94aad5011b29fb..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/HELP_MY_TESTS_DONT_WORK_ANYMORE +++ /dev/null @@ -1,399 +0,0 @@ -Simple Test interface changes -============================= -Because the SimpleTest tool set is still evolving it is likely that tests -written with earlier versions will fail with the newest ones. The most -dramatic changes are in the alpha releases. Here is a list of possible -problems and their fixes... - -assertText() no longer finds a string inside a <script> tag ------------------------------------------------------------ -The assertText() method is intended to match only visible, -human-readable text on the web page. Therefore, the contents of script -tags should not be matched by this assertion. However there was a bug -in the text normalisation code of simpletest which meant that <script> -tags spanning multiple lines would not have their content stripped -out. If you want to check the content of a <script> tag, use -assertPattern(), or write a custom expectation. - -Overloaded method not working ------------------------------ -All protected and private methods had underscores -removed. This means that any private/protected methods that -you overloaded with those names need to be updated. - -Fatal error: Call to undefined method Classname::classname() ------------------------------------------------------------- -SimpleTest renamed all of its constructors from -Classname to __construct; derived classes invoking -their parent constructors should replace parent::Classname() -with parent::__construct(). - -Custom CSS in HtmlReporter not being applied --------------------------------------------- -Batch rename of protected and private methods -means that _getCss() was renamed to getCss(). -Please rename your method and it should work again. - -setReturnReference() throws errors in E_STRICT ----------------------------------------------- -Happens when an object is passed by reference. -This also happens with setReturnReferenceAt(). -If you want to return objects then replace these -with calls to returns() and returnsAt() with the -same arguments. This change was forced in the 1.1 -version for E_STRICT compatibility. - -assertReference() throws errors in E_STRICT -------------------------------------------- -Due to language restrictions you cannot compare -both variables and objects in E_STRICT mode. Use -assertSame() in this mode with objects. This change -was forced the 1.1 version. - -Cannot create GroupTest ------------------------ -The GroupTest has been renamed TestSuite (see below). -It was removed completely in 1.1 in favour of this -name. - -No method getRelativeUrls() or getAbsoluteUrls() ------------------------------------------------- -These methods were always a bit weird anyway, and -the new parsing of the base tag makes them more so. -They have been replaced with getUrls() instead. If -you want the old functionality then simply chop -off the current domain from getUrls(). - -Method setWildcard() removed in mocks -------------------------------------- -Even setWildcard() has been removed in 1.0.1beta now. -If you want to test explicitely for a '*' string, then -simply pass in new IdenticalExpectation('*') instead. - -No method _getTest() on mocks ------------------------------ -This has finally been removed. It was a pretty esoteric -flex point anyway. It was there to allow the mocks to -work with other test tools, but no one does this. - -No method assertError(), assertNoErrors(), swallowErrors() ----------------------------------------------------------- -These have been deprecated in 1.0.1beta in favour of -expectError() and expectException(). assertNoErrors() is -redundant if you use expectError() as failures are now reported -immediately. - -No method TestCase::signal() ----------------------------- -This has been deprecated in favour of triggering an error or -throwing an exception. Deprecated as of 1.0.1beta. - -No method TestCase::sendMessage() ---------------------------------- -This has been deprecated as of 1.0.1beta. - -Failure to connect now emits failures -------------------------------------- -It used to be that you would have to use the -getTransferError() call on the web tester to see if -there was a socket level error in a fetch. This check -is now always carried out by the WebTestCase unless -the fetch is prefaced with WebTestCase::ignoreErrors(). -The ignore directive only lasts for the next fetching -action such as get() and click(). - -No method SimpleTestOptions::ignore() -------------------------------------- -This is deprecated in version 1.0.1beta and has been moved -to SimpleTest::ignore() as that is more readable. In -addition, parent classes are also ignored automatically. -If you are using PHP5 you can skip this directive simply -by marking your test case as abstract. - -No method assertCopy() ----------------------- -This is deprecated in 1.0.1 in favour of assertClone(). -The assertClone() method is slightly different in that -the objects must be identical, but without being a -reference. It is thus not a strict inversion of -assertReference(). - -Constructor wildcard override has no effect in mocks ----------------------------------------------------- -As of 1.0.1beta this is now set with setWildcard() instead -of in the constructor. - -No methods setStubBaseClass()/getStubBaseClass() ------------------------------------------------- -As mocks are now used instead of stubs, these methods -stopped working and are now removed as of the 1.0.1beta -release. The mock objects may be freely used instead. - -No method addPartialMockCode() ------------------------------- -The ability to insert arbitrary partial mock code -has been removed. This was a low value feature -causing needless complications. It was removed -in the 1.0.1beta release. - -No method setMockBaseClass() ----------------------------- -The ability to change the mock base class has been -scheduled for removal and is deprecated since the -1.0.1beta version. This was a rarely used feature -except as a workaround for PHP5 limitations. As -these limitations are being resolved it's hoped -that the bundled mocks can be used directly. - -No class Stub -------------- -Server stubs are deprecated from 1.0.1 as the mocks now -have exactly the same interface. Just use mock objects -instead. - -No class SimpleTestOptions --------------------------- -This was replced by the shorter SimpleTest in 1.0.1beta1 -and is since deprecated. - -No file simple_test.php ------------------------ -This was renamed test_case.php in 1.0.1beta to more accurately -reflect it's purpose. This file should never be directly -included in test suites though, as it's part of the -underlying mechanics and has a tendency to be refactored. - -No class WantedPatternExpectation ---------------------------------- -This was deprecated in 1.0.1alpha in favour of the simpler -name PatternExpectation. - -No class NoUnwantedPatternExpectation -------------------------------------- -This was deprecated in 1.0.1alpha in favour of the simpler -name NoPatternExpectation. - -No method assertNoUnwantedPattern() ------------------------------------ -This has been renamed to assertNoPattern() in 1.0.1alpha and -the old form is deprecated. - -No method assertWantedPattern() -------------------------------- -This has been renamed to assertPattern() in 1.0.1alpha and -the old form is deprecated. - -No method assertExpectation() ------------------------------ -This was renamed as assert() in 1.0.1alpha and the old form -has been deprecated. - -No class WildcardExpectation ----------------------------- -This was a mostly internal class for the mock objects. It was -renamed AnythingExpectation to bring it closer to JMock and -NMock in version 1.0.1alpha. - -Missing UnitTestCase::assertErrorPattern() ------------------------------------------- -This method is deprecated for version 1.0.1 onwards. -This method has been subsumed by assertError() that can now -take an expectation. Simply pass a PatternExpectation -into assertError() to simulate the old behaviour. - -No HTML when matching page elements ------------------------------------ -This behaviour has been switched to using plain text as if it -were seen by the user of the browser. This means that HTML tags -are suppressed, entities are converted and whitespace is -normalised. This should make it easier to match items in forms. -Also images are replaced with their "alt" text so that they -can be matched as well. - -No method SimpleRunner::_getTestCase() --------------------------------------- -This was made public as getTestCase() in 1.0RC2. - -No method restartSession() --------------------------- -This was renamed to restart() in the WebTestCase, SimpleBrowser -and the underlying SimpleUserAgent in 1.0RC2. Because it was -undocumented anyway, no attempt was made at backward -compatibility. - -My custom test case ignored by tally() --------------------------------------- -The _assertTrue method has had it's signature changed due to a bug -in the PHP 5.0.1 release. You must now use getTest() from within -that method to get the test case. Mock compatibility with other -unit testers is now deprecated as of 1.0.1alpha as PEAR::PHPUnit2 -should soon have mock support of it's own. - -Broken code extending SimpleRunner ----------------------------------- -This was replaced with SimpleScorer so that I could use the runner -name in another class. This happened in RC1 development and there -is no easy backward compatibility fix. The solution is simply to -extend SimpleScorer instead. - -Missing method getBaseCookieValue() ------------------------------------ -This was renamed getCurrentCookieValue() in RC1. - -Missing files from the SimpleTest suite ---------------------------------------- -Versions of SimpleTest prior to Beta6 required a SIMPLE_TEST constant -to point at the SimpleTest folder location before any of the toolset -was loaded. This is no longer documented as it is now unnecessary -for later versions. If you are using an earlier version you may -need this constant. Consult the documentation that was bundled with -the release that you are using or upgrade to Beta6 or later. - -No method SimpleBrowser::getCurrentUrl() --------------------------------------- -This is replaced with the more versatile showRequest() for -debugging. It only existed in this context for version Beta5. -Later versions will have SimpleBrowser::getHistory() for tracking -paths through pages. It is renamed as getUrl() since 1.0RC1. - -No method Stub::setStubBaseClass() ----------------------------------- -This method has finally been removed in 1.0RC1. Use -SimpleTestOptions::setStubBaseClass() instead. - -No class CommandLineReporter ----------------------------- -This was renamed to TextReporter in Beta3 and the deprecated version -was removed in 1.0RC1. - -No method requireReturn() -------------------------- -This was deprecated in Beta3 and is now removed. - -No method expectCookie() ------------------------- -This method was abruptly removed in Beta4 so as to simplify the internals -until another mechanism can replace it. As a workaround it is necessary -to assert that the cookie has changed by setting it before the page -fetch and then assert the desired value. - -No method clickSubmitByFormId() -------------------------------- -This method had an incorrect name as no button was involved. It was -renamed to submitByFormId() in Beta4 and the old version deprecated. -Now removed. - -No method paintStart() or paintEnd() ------------------------------------- -You should only get this error if you have subclassed the lower level -reporting and test runner machinery. These methods have been broken -down into events for test methods, events for test cases and events -for group tests. The new methods are... - -paintStart() --> paintMethodStart(), paintCaseStart(), paintGroupStart() -paintEnd() --> paintMethodEnd(), paintCaseEnd(), paintGroupEnd() - -This change was made in Beta3, ironically to make it easier to subclass -the inner machinery. Simply duplicating the code you had in the previous -methods should provide a temporary fix. - -No class TestDisplay --------------------- -This has been folded into SimpleReporter in Beta3 and is now deprecated. -It was removed in RC1. - -No method WebTestCase::fetch() ------------------------------- -This was renamed get() in Alpha8. It is removed in Beta3. - -No method submit() ------------------- -This has been renamed clickSubmit() in Beta1. The old method was -removed in Beta2. - -No method clearHistory() ------------------------- -This method is deprecated in Beta2 and removed in RC1. - -No method getCallCount() ------------------------- -This method has been deprecated since Beta1 and has now been -removed. There are now more ways to set expectations on counts -and so this method should be unecessery. Removed in RC1. - -Cannot find file * ------------------- -The following public name changes have occoured... - -simple_html_test.php --> reporter.php -simple_mock.php --> mock_objects.php -simple_unit.php --> unit_tester.php -simple_web.php --> web_tester.php - -The old names were deprecated in Alpha8 and removed in Beta1. - -No method attachObserver() --------------------------- -Prior to the Alpha8 release the old internal observer pattern was -gutted and replaced with a visitor. This is to trade flexibility of -test case expansion against the ease of writing user interfaces. - -Code such as... - -$test = &new MyTestCase(); -$test->attachObserver(new TestHtmlDisplay()); -$test->run(); - -...should be rewritten as... - -$test = &new MyTestCase(); -$test->run(new HtmlReporter()); - -If you previously attached multiple observers then the workaround -is to run the tests twice, once with each, until they can be combined. -For one observer the old method is simulated in Alpha 8, but is -removed in Beta1. - -No class TestHtmlDisplay ------------------------- -This class has been renamed to HtmlReporter in Alpha8. It is supported, -but deprecated in Beta1 and removed in Beta2. If you have subclassed -the display for your own design, then you will have to extend this -class (HtmlReporter) instead. - -If you have accessed the event queue by overriding the notify() method -then I am afraid you are in big trouble :(. The reporter is now -carried around the test suite by the runner classes and the methods -called directly. In the unlikely event that this is a problem and -you don't want to upgrade the test tool then simplest is to write your -own runner class and invoke the tests with... - -$test->accept(new MyRunner(new MyReporter())); - -...rather than the run method. This should be easier to extend -anyway and gives much more control. Even this method is overhauled -in Beta3 where the runner class can be set within the test case. Really -the best thing to do is to upgrade to this version as whatever you were -trying to achieve before should now be very much easier. - -Missing set options method --------------------------- -All test suite options are now in one class called SimpleTestOptions. -This means that options are set differently... - -GroupTest::ignore() --> SimpleTestOptions::ignore() -Mock::setMockBaseClass() --> SimpleTestOptions::setMockBaseClass() - -These changed in Alpha8 and the old versions are now removed in RC1. - -No method setExpected*() ------------------------- -The mock expectations changed their names in Alpha4 and the old names -ceased to be supported in Alpha8. The changes are... - -setExpectedArguments() --> expectArguments() -setExpectedArgumentsSequence() --> expectArgumentsAt() -setExpectedCallCount() --> expectCallCount() -setMaximumCallCount() --> expectMaximumCallCount() - -The parameters remained the same. diff --git a/3rdparty/simpletest/LICENSE b/3rdparty/simpletest/LICENSE deleted file mode 100755 index 09f465ab703f79f8c7b509795d785b1124889f86..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/LICENSE +++ /dev/null @@ -1,502 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - <one line to give the library's name and a brief idea of what it does.> - Copyright (C) <year> <name of author> - - 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - <signature of Ty Coon>, 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! diff --git a/3rdparty/simpletest/README b/3rdparty/simpletest/README deleted file mode 100755 index 40f41666d4002bae933843e845eae095a436ed25..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/README +++ /dev/null @@ -1,102 +0,0 @@ -SimpleTest -========== - -You probably got this package from: - - http://simpletest.org/en/download.html - -If there is no licence agreement with this package please download -a version from the location above. You must read and accept that -licence to use this software. The file is titled simply LICENSE. - -What is it? It's a framework for unit testing, web site testing and -mock objects for PHP 5.0.5+. - -If you have used JUnit, you will find this PHP unit testing version very -similar. Also included is a mock objects and server stubs generator. -The stubs can have return values set for different arguments, can have -sequences set also by arguments and can return items by reference. -The mocks inherit all of this functionality and can also have -expectations set, again in sequences and for different arguments. - -A web tester similar in concept to JWebUnit is also included. There is no -JavaScript or tables support, but forms, authentication, cookies and -frames are handled. - -You can see a release schedule at http://simpletest.org/en/overview.html -which is also copied to the documentation folder with this release. -A full PHPDocumenter API documentation exists at -http://simpletest.org/api/. - -The user interface is minimal in the extreme, but a lot of information -flows from the test suite. After version 1.0 we will release a better -web UI, but we are leaving XUL and GTK versions to volunteers as -everybody has their own opinion on a good GUI, and we don't want to -discourage development by shipping one with the toolkit. You can -download an Eclipse plug-in separately. - -The unit tests for SimpleTest itself can be run here: - - test/unit_tests.php - -And tests involving live network connections as well are here: - - test/all_tests.php - -The full tests will typically overrun the 8Mb limit often allowed -to a PHP process. A workaround is to run the tests on the command -with a custom php.ini file or with the switch -dmemory_limit=-1 -if you do not have access to your server version. - -The full tests read some test data from simpletest.org. If the site -is down or has been modified for a later version then you will get -spurious errors. A unit_tests.php failure on the other hand would be -very serious. Please notify us if you find one. - -Even if all of the tests run please verify that your existing test suites -also function as expected. The file: - - HELP_MY_TESTS_DONT_WORK_ANYMORE - -...contains information on interface changes. It also points out -deprecated interfaces, so you should read this even if all of -your current tests appear to run. - -There is a documentation folder which contains the core reference information -in English and French, although this information is fairly basic. -You can find a tutorial on... - - http://simpletest.org/en/first_test_tutorial.html - -...to get you started and this material will eventually become included -with the project documentation. A French translation exists at: - - http://simpletest.org/fr/first_test_tutorial.html - -If you download and use, and possibly even extend this tool, please let us -know. Any feedback, even bad, is always welcome and we will work to get -your suggestions into the next release. Ideally please send your -comments to: - - simpletest-support@lists.sourceforge.net - -...so that others can read them too. We usually try to respond within 48 -hours. - -There is no change log except at Sourceforge. You can visit the -release notes to see the completed TODO list after each cycle and also the -status of any bugs, but if the bug is recent then it will be fixed in SVN only. -The SVN check-ins always have all the tests passing and so SVN snapshots should -be pretty usable, although the code may not look so good internally. - -Oh, and one last thing: SimpleTest is called "Simple" because it should -be simple to use. We intend to add a complete set of tools for a test -first and "test as you code" type of development. "Simple" does not mean -"Lite" in this context. - -Thanks to everyone who has sent comments and offered suggestions. They -really are invaluable, but sadly you are too many to mention in full. -Thanks to all on the advanced PHP forum on SitePoint, especially Harry -Fuecks. Early adopters are always an inspiration. - - -- Marcus Baker, Jason Sweat, Travis Swicegood, Perrick Penet and Edward Z. Yang. diff --git a/3rdparty/simpletest/VERSION b/3rdparty/simpletest/VERSION deleted file mode 100755 index 9084fa2f716a7117829f3f32a5f4cef400e02903..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/VERSION +++ /dev/null @@ -1 +0,0 @@ -1.1.0 diff --git a/3rdparty/simpletest/arguments.php b/3rdparty/simpletest/arguments.php deleted file mode 100755 index 89e7f9de6ef276651c834c97a9e6d3fb39998cf7..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/arguments.php +++ /dev/null @@ -1,224 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: dumper.php 1909 2009-07-29 15:58:11Z dgheath $ - */ - -/** - * Parses the command line arguments. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleArguments { - private $all = array(); - - /** - * Parses the command line arguments. The usual formats - * are supported: - * -f value - * -f=value - * --flag=value - * --flag value - * -f (true) - * --flag (true) - * @param array $arguments Normally the PHP $argv. - */ - function __construct($arguments) { - array_shift($arguments); - while (count($arguments) > 0) { - list($key, $value) = $this->parseArgument($arguments); - $this->assign($key, $value); - } - } - - /** - * Sets the value in the argments object. If multiple - * values are added under the same key, the key will - * give an array value in the order they were added. - * @param string $key The variable to assign to. - * @param string value The value that would norally - * be colected on the command line. - */ - function assign($key, $value) { - if ($this->$key === false) { - $this->all[$key] = $value; - } elseif (! is_array($this->$key)) { - $this->all[$key] = array($this->$key, $value); - } else { - $this->all[$key][] = $value; - } - } - - /** - * Extracts the next key and value from the argument list. - * @param array $arguments The remaining arguments to be parsed. - * The argument list will be reduced. - * @return array Two item array of key and value. - * If no value can be found it will - * have the value true assigned instead. - */ - private function parseArgument(&$arguments) { - $argument = array_shift($arguments); - if (preg_match('/^-(\w)=(.+)$/', $argument, $matches)) { - return array($matches[1], $matches[2]); - } elseif (preg_match('/^-(\w)$/', $argument, $matches)) { - return array($matches[1], $this->nextNonFlagElseTrue($arguments)); - } elseif (preg_match('/^--(\w+)=(.+)$/', $argument, $matches)) { - return array($matches[1], $matches[2]); - } elseif (preg_match('/^--(\w+)$/', $argument, $matches)) { - return array($matches[1], $this->nextNonFlagElseTrue($arguments)); - } - } - - /** - * Attempts to use the next argument as a value. It - * won't use what it thinks is a flag. - * @param array $arguments Remaining arguments to be parsed. - * This variable is modified if there - * is a value to be extracted. - * @return string/boolean The next value unless it's a flag. - */ - private function nextNonFlagElseTrue(&$arguments) { - return $this->valueIsNext($arguments) ? array_shift($arguments) : true; - } - - /** - * Test to see if the next available argument is a valid value. - * If it starts with "-" or "--" it's a flag and doesn't count. - * @param array $arguments Remaining arguments to be parsed. - * Not affected by this call. - * boolean True if valid value. - */ - function valueIsNext($arguments) { - return isset($arguments[0]) && ! $this->isFlag($arguments[0]); - } - - /** - * It's a flag if it starts with "-" or "--". - * @param string $argument Value to be tested. - * @return boolean True if it's a flag. - */ - function isFlag($argument) { - return strncmp($argument, '-', 1) == 0; - } - - /** - * The arguments are available as individual member - * variables on the object. - * @param string $key Argument name. - * @return string/array/boolean Either false for no value, - * the value as a string or - * a list of multiple values if - * the flag had been specified more - * than once. - */ - function __get($key) { - if (isset($this->all[$key])) { - return $this->all[$key]; - } - return false; - } - - /** - * The entire argument set as a hash. - * @return hash Each argument and it's value(s). - */ - function all() { - return $this->all; - } -} - -/** - * Renders the help for the command line arguments. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleHelp { - private $overview; - private $flag_sets = array(); - private $explanations = array(); - - /** - * Sets up the top level explanation for the program. - * @param string $overview Summary of program. - */ - function __construct($overview = '') { - $this->overview = $overview; - } - - /** - * Adds the explanation for a group of flags that all - * have the same function. - * @param string/array $flags Flag and alternates. Don't - * worry about leading dashes - * as these are inserted automatically. - * @param string $explanation What that flag group does. - */ - function explainFlag($flags, $explanation) { - $flags = is_array($flags) ? $flags : array($flags); - $this->flag_sets[] = $flags; - $this->explanations[] = $explanation; - } - - /** - * Generates the help text. - * @returns string The complete formatted text. - */ - function render() { - $tab_stop = $this->longestFlag($this->flag_sets) + 4; - $text = $this->overview . "\n"; - for ($i = 0; $i < count($this->flag_sets); $i++) { - $text .= $this->renderFlagSet($this->flag_sets[$i], $this->explanations[$i], $tab_stop); - } - return $this->noDuplicateNewLines($text); - } - - /** - * Works out the longest flag for formatting purposes. - * @param array $flag_sets The internal flag set list. - */ - private function longestFlag($flag_sets) { - $longest = 0; - foreach ($flag_sets as $flags) { - foreach ($flags as $flag) { - $longest = max($longest, strlen($this->renderFlag($flag))); - } - } - return $longest; - } - - /** - * Generates the text for a single flag and it's alternate flags. - * @returns string Help text for that flag group. - */ - private function renderFlagSet($flags, $explanation, $tab_stop) { - $flag = array_shift($flags); - $text = str_pad($this->renderFlag($flag), $tab_stop, ' ') . $explanation . "\n"; - foreach ($flags as $flag) { - $text .= ' ' . $this->renderFlag($flag) . "\n"; - } - return $text; - } - - /** - * Generates the flag name including leading dashes. - * @param string $flag Just the name. - * @returns Fag with apropriate dashes. - */ - private function renderFlag($flag) { - return (strlen($flag) == 1 ? '-' : '--') . $flag; - } - - /** - * Converts multiple new lines into a single new line. - * Just there to trap accidental duplicate new lines. - * @param string $text Text to clean up. - * @returns string Text with no blank lines. - */ - private function noDuplicateNewLines($text) { - return preg_replace('/(\n+)/', "\n", $text); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/authentication.php b/3rdparty/simpletest/authentication.php deleted file mode 100644 index fcd4efd3f0a285f43f27b8e8e28f07b52f3f97a2..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/authentication.php +++ /dev/null @@ -1,237 +0,0 @@ -<?php -/** - * Base include file for SimpleTest - * @package SimpleTest - * @subpackage WebTester - * @version $Id: authentication.php 2011 2011-04-29 08:22:48Z pp11 $ - */ -/** - * include http class - */ -require_once(dirname(__FILE__) . '/http.php'); - -/** - * Represents a single security realm's identity. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleRealm { - private $type; - private $root; - private $username; - private $password; - - /** - * Starts with the initial entry directory. - * @param string $type Authentication type for this - * realm. Only Basic authentication - * is currently supported. - * @param SimpleUrl $url Somewhere in realm. - * @access public - */ - function SimpleRealm($type, $url) { - $this->type = $type; - $this->root = $url->getBasePath(); - $this->username = false; - $this->password = false; - } - - /** - * Adds another location to the realm. - * @param SimpleUrl $url Somewhere in realm. - * @access public - */ - function stretch($url) { - $this->root = $this->getCommonPath($this->root, $url->getPath()); - } - - /** - * Finds the common starting path. - * @param string $first Path to compare. - * @param string $second Path to compare. - * @return string Common directories. - * @access private - */ - protected function getCommonPath($first, $second) { - $first = explode('/', $first); - $second = explode('/', $second); - for ($i = 0; $i < min(count($first), count($second)); $i++) { - if ($first[$i] != $second[$i]) { - return implode('/', array_slice($first, 0, $i)) . '/'; - } - } - return implode('/', $first) . '/'; - } - - /** - * Sets the identity to try within this realm. - * @param string $username Username in authentication dialog. - * @param string $username Password in authentication dialog. - * @access public - */ - function setIdentity($username, $password) { - $this->username = $username; - $this->password = $password; - } - - /** - * Accessor for current identity. - * @return string Last succesful username. - * @access public - */ - function getUsername() { - return $this->username; - } - - /** - * Accessor for current identity. - * @return string Last succesful password. - * @access public - */ - function getPassword() { - return $this->password; - } - - /** - * Test to see if the URL is within the directory - * tree of the realm. - * @param SimpleUrl $url URL to test. - * @return boolean True if subpath. - * @access public - */ - function isWithin($url) { - if ($this->isIn($this->root, $url->getBasePath())) { - return true; - } - if ($this->isIn($this->root, $url->getBasePath() . $url->getPage() . '/')) { - return true; - } - return false; - } - - /** - * Tests to see if one string is a substring of - * another. - * @param string $part Small bit. - * @param string $whole Big bit. - * @return boolean True if the small bit is - * in the big bit. - * @access private - */ - protected function isIn($part, $whole) { - return strpos($whole, $part) === 0; - } -} - -/** - * Manages security realms. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleAuthenticator { - private $realms; - - /** - * Clears the realms. - * @access public - */ - function SimpleAuthenticator() { - $this->restartSession(); - } - - /** - * Starts with no realms set up. - * @access public - */ - function restartSession() { - $this->realms = array(); - } - - /** - * Adds a new realm centered the current URL. - * Browsers privatey wildly on their behaviour in this - * regard. Mozilla ignores the realm and presents - * only when challenged, wasting bandwidth. IE - * just carries on presenting until a new challenge - * occours. SimpleTest tries to follow the spirit of - * the original standards committee and treats the - * base URL as the root of a file tree shaped realm. - * @param SimpleUrl $url Base of realm. - * @param string $type Authentication type for this - * realm. Only Basic authentication - * is currently supported. - * @param string $realm Name of realm. - * @access public - */ - function addRealm($url, $type, $realm) { - $this->realms[$url->getHost()][$realm] = new SimpleRealm($type, $url); - } - - /** - * Sets the current identity to be presented - * against that realm. - * @param string $host Server hosting realm. - * @param string $realm Name of realm. - * @param string $username Username for realm. - * @param string $password Password for realm. - * @access public - */ - function setIdentityForRealm($host, $realm, $username, $password) { - if (isset($this->realms[$host][$realm])) { - $this->realms[$host][$realm]->setIdentity($username, $password); - } - } - - /** - * Finds the name of the realm by comparing URLs. - * @param SimpleUrl $url URL to test. - * @return SimpleRealm Name of realm. - * @access private - */ - protected function findRealmFromUrl($url) { - if (! isset($this->realms[$url->getHost()])) { - return false; - } - foreach ($this->realms[$url->getHost()] as $name => $realm) { - if ($realm->isWithin($url)) { - return $realm; - } - } - return false; - } - - /** - * Presents the appropriate headers for this location. - * @param SimpleHttpRequest $request Request to modify. - * @param SimpleUrl $url Base of realm. - * @access public - */ - function addHeaders(&$request, $url) { - if ($url->getUsername() && $url->getPassword()) { - $username = $url->getUsername(); - $password = $url->getPassword(); - } elseif ($realm = $this->findRealmFromUrl($url)) { - $username = $realm->getUsername(); - $password = $realm->getPassword(); - } else { - return; - } - $this->addBasicHeaders($request, $username, $password); - } - - /** - * Presents the appropriate headers for this - * location for basic authentication. - * @param SimpleHttpRequest $request Request to modify. - * @param string $username Username for realm. - * @param string $password Password for realm. - * @access public - */ - static function addBasicHeaders(&$request, $username, $password) { - if ($username && $password) { - $request->addHeaderLine( - 'Authorization: Basic ' . base64_encode("$username:$password")); - } - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/autorun.php b/3rdparty/simpletest/autorun.php deleted file mode 100644 index 8faf84d3ceb0c49207798dbe78b575cf9ae28643..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/autorun.php +++ /dev/null @@ -1,101 +0,0 @@ -<?php -/** - * Autorunner which runs all tests cases found in a file - * that includes this module. - * @package SimpleTest - * @version $Id: autorun.php 2037 2011-11-30 17:58:21Z pp11 $ - */ - -/**#@+ - * include simpletest files - */ -require_once dirname(__FILE__) . '/unit_tester.php'; -require_once dirname(__FILE__) . '/mock_objects.php'; -require_once dirname(__FILE__) . '/collector.php'; -require_once dirname(__FILE__) . '/default_reporter.php'; -/**#@-*/ - -$GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_CLASSES'] = get_declared_classes(); -$GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_PATH'] = getcwd(); -register_shutdown_function('simpletest_autorun'); - -/** - * Exit handler to run all recent test cases and exit system if in CLI - */ -function simpletest_autorun() { - chdir($GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_PATH']); - if (tests_have_run()) { - return; - } - $result = run_local_tests(); - if (SimpleReporter::inCli()) { - exit($result ? 0 : 1); - } -} - -/** - * run all recent test cases if no test has - * so far been run. Uses the DefaultReporter which can have - * it's output controlled with SimpleTest::prefer(). - * @return boolean/null false if there were test failures, true if - * there were no failures, null if tests are - * already running - */ -function run_local_tests() { - try { - if (tests_have_run()) { - return; - } - $candidates = capture_new_classes(); - $loader = new SimpleFileLoader(); - $suite = $loader->createSuiteFromClasses( - basename(initial_file()), - $loader->selectRunnableTests($candidates)); - return $suite->run(new DefaultReporter()); - } catch (Exception $stack_frame_fix) { - print $stack_frame_fix->getMessage(); - return false; - } -} - -/** - * Checks the current test context to see if a test has - * ever been run. - * @return boolean True if tests have run. - */ -function tests_have_run() { - if ($context = SimpleTest::getContext()) { - return (boolean)$context->getTest(); - } - return false; -} - -/** - * The first autorun file. - * @return string Filename of first autorun script. - */ -function initial_file() { - static $file = false; - if (! $file) { - if (isset($_SERVER, $_SERVER['SCRIPT_FILENAME'])) { - $file = $_SERVER['SCRIPT_FILENAME']; - } else { - $included_files = get_included_files(); - $file = reset($included_files); - } - } - return $file; -} - -/** - * Every class since the first autorun include. This - * is safe enough if require_once() is always used. - * @return array Class names. - */ -function capture_new_classes() { - global $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES; - return array_map('strtolower', array_diff(get_declared_classes(), - $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES ? - $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES : array())); -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/browser.php b/3rdparty/simpletest/browser.php deleted file mode 100644 index 615e738d350a93e27cc0ede65d1c65c140ce71ae..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/browser.php +++ /dev/null @@ -1,1144 +0,0 @@ -<?php -/** - * Base include file for SimpleTest - * @package SimpleTest - * @subpackage WebTester - * @version $Id: browser.php 2013 2011-04-29 09:29:45Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/simpletest.php'); -require_once(dirname(__FILE__) . '/http.php'); -require_once(dirname(__FILE__) . '/encoding.php'); -require_once(dirname(__FILE__) . '/page.php'); -require_once(dirname(__FILE__) . '/php_parser.php'); -require_once(dirname(__FILE__) . '/tidy_parser.php'); -require_once(dirname(__FILE__) . '/selector.php'); -require_once(dirname(__FILE__) . '/frames.php'); -require_once(dirname(__FILE__) . '/user_agent.php'); -if (! SimpleTest::getParsers()) { - SimpleTest::setParsers(array(new SimpleTidyPageBuilder(), new SimplePHPPageBuilder())); - //SimpleTest::setParsers(array(new SimplePHPPageBuilder())); -} -/**#@-*/ - -if (! defined('DEFAULT_MAX_NESTED_FRAMES')) { - define('DEFAULT_MAX_NESTED_FRAMES', 3); -} - -/** - * Browser history list. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleBrowserHistory { - private $sequence = array(); - private $position = -1; - - /** - * Test for no entries yet. - * @return boolean True if empty. - * @access private - */ - protected function isEmpty() { - return ($this->position == -1); - } - - /** - * Test for being at the beginning. - * @return boolean True if first. - * @access private - */ - protected function atBeginning() { - return ($this->position == 0) && ! $this->isEmpty(); - } - - /** - * Test for being at the last entry. - * @return boolean True if last. - * @access private - */ - protected function atEnd() { - return ($this->position + 1 >= count($this->sequence)) && ! $this->isEmpty(); - } - - /** - * Adds a successfully fetched page to the history. - * @param SimpleUrl $url URL of fetch. - * @param SimpleEncoding $parameters Any post data with the fetch. - * @access public - */ - function recordEntry($url, $parameters) { - $this->dropFuture(); - array_push( - $this->sequence, - array('url' => $url, 'parameters' => $parameters)); - $this->position++; - } - - /** - * Last fully qualified URL for current history - * position. - * @return SimpleUrl URL for this position. - * @access public - */ - function getUrl() { - if ($this->isEmpty()) { - return false; - } - return $this->sequence[$this->position]['url']; - } - - /** - * Parameters of last fetch from current history - * position. - * @return SimpleFormEncoding Post parameters. - * @access public - */ - function getParameters() { - if ($this->isEmpty()) { - return false; - } - return $this->sequence[$this->position]['parameters']; - } - - /** - * Step back one place in the history. Stops at - * the first page. - * @return boolean True if any previous entries. - * @access public - */ - function back() { - if ($this->isEmpty() || $this->atBeginning()) { - return false; - } - $this->position--; - return true; - } - - /** - * Step forward one place. If already at the - * latest entry then nothing will happen. - * @return boolean True if any future entries. - * @access public - */ - function forward() { - if ($this->isEmpty() || $this->atEnd()) { - return false; - } - $this->position++; - return true; - } - - /** - * Ditches all future entries beyond the current - * point. - * @access private - */ - protected function dropFuture() { - if ($this->isEmpty()) { - return; - } - while (! $this->atEnd()) { - array_pop($this->sequence); - } - } -} - -/** - * Simulated web browser. This is an aggregate of - * the user agent, the HTML parsing, request history - * and the last header set. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleBrowser { - private $user_agent; - private $page; - private $history; - private $ignore_frames; - private $maximum_nested_frames; - private $parser; - - /** - * Starts with a fresh browser with no - * cookie or any other state information. The - * exception is that a default proxy will be - * set up if specified in the options. - * @access public - */ - function __construct() { - $this->user_agent = $this->createUserAgent(); - $this->user_agent->useProxy( - SimpleTest::getDefaultProxy(), - SimpleTest::getDefaultProxyUsername(), - SimpleTest::getDefaultProxyPassword()); - $this->page = new SimplePage(); - $this->history = $this->createHistory(); - $this->ignore_frames = false; - $this->maximum_nested_frames = DEFAULT_MAX_NESTED_FRAMES; - } - - /** - * Creates the underlying user agent. - * @return SimpleFetcher Content fetcher. - * @access protected - */ - protected function createUserAgent() { - return new SimpleUserAgent(); - } - - /** - * Creates a new empty history list. - * @return SimpleBrowserHistory New list. - * @access protected - */ - protected function createHistory() { - return new SimpleBrowserHistory(); - } - - /** - * Get the HTML parser to use. Can be overridden by - * setParser. Otherwise scans through the available parsers and - * uses the first one which is available. - * @return object SimplePHPPageBuilder or SimpleTidyPageBuilder - */ - protected function getParser() { - if ($this->parser) { - return $this->parser; - } - foreach (SimpleTest::getParsers() as $parser) { - if ($parser->can()) { - return $parser; - } - } - } - - /** - * Override the default HTML parser, allowing parsers to be plugged in. - * @param object A parser object instance. - */ - public function setParser($parser) { - $this->parser = $parser; - } - - /** - * Disables frames support. Frames will not be fetched - * and the frameset page will be used instead. - * @access public - */ - function ignoreFrames() { - $this->ignore_frames = true; - } - - /** - * Enables frames support. Frames will be fetched from - * now on. - * @access public - */ - function useFrames() { - $this->ignore_frames = false; - } - - /** - * Switches off cookie sending and recieving. - * @access public - */ - function ignoreCookies() { - $this->user_agent->ignoreCookies(); - } - - /** - * Switches back on the cookie sending and recieving. - * @access public - */ - function useCookies() { - $this->user_agent->useCookies(); - } - - /** - * Parses the raw content into a page. Will load further - * frame pages unless frames are disabled. - * @param SimpleHttpResponse $response Response from fetch. - * @param integer $depth Nested frameset depth. - * @return SimplePage Parsed HTML. - * @access private - */ - protected function parse($response, $depth = 0) { - $page = $this->buildPage($response); - if ($this->ignore_frames || ! $page->hasFrames() || ($depth > $this->maximum_nested_frames)) { - return $page; - } - $frameset = new SimpleFrameset($page); - foreach ($page->getFrameset() as $key => $url) { - $frame = $this->fetch($url, new SimpleGetEncoding(), $depth + 1); - $frameset->addFrame($frame, $key); - } - return $frameset; - } - - /** - * Assembles the parsing machinery and actually parses - * a single page. Frees all of the builder memory and so - * unjams the PHP memory management. - * @param SimpleHttpResponse $response Response from fetch. - * @return SimplePage Parsed top level page. - */ - protected function buildPage($response) { - return $this->getParser()->parse($response); - } - - /** - * Fetches a page. Jointly recursive with the parse() - * method as it descends a frameset. - * @param string/SimpleUrl $url Target to fetch. - * @param SimpleEncoding $encoding GET/POST parameters. - * @param integer $depth Nested frameset depth protection. - * @return SimplePage Parsed page. - * @access private - */ - protected function fetch($url, $encoding, $depth = 0) { - $response = $this->user_agent->fetchResponse($url, $encoding); - if ($response->isError()) { - return new SimplePage($response); - } - return $this->parse($response, $depth); - } - - /** - * Fetches a page or a single frame if that is the current - * focus. - * @param SimpleUrl $url Target to fetch. - * @param SimpleEncoding $parameters GET/POST parameters. - * @return string Raw content of page. - * @access private - */ - protected function load($url, $parameters) { - $frame = $url->getTarget(); - if (! $frame || ! $this->page->hasFrames() || (strtolower($frame) == '_top')) { - return $this->loadPage($url, $parameters); - } - return $this->loadFrame(array($frame), $url, $parameters); - } - - /** - * Fetches a page and makes it the current page/frame. - * @param string/SimpleUrl $url Target to fetch as string. - * @param SimplePostEncoding $parameters POST parameters. - * @return string Raw content of page. - * @access private - */ - protected function loadPage($url, $parameters) { - $this->page = $this->fetch($url, $parameters); - $this->history->recordEntry( - $this->page->getUrl(), - $this->page->getRequestData()); - return $this->page->getRaw(); - } - - /** - * Fetches a frame into the existing frameset replacing the - * original. - * @param array $frames List of names to drill down. - * @param string/SimpleUrl $url Target to fetch as string. - * @param SimpleFormEncoding $parameters POST parameters. - * @return string Raw content of page. - * @access private - */ - protected function loadFrame($frames, $url, $parameters) { - $page = $this->fetch($url, $parameters); - $this->page->setFrame($frames, $page); - return $page->getRaw(); - } - - /** - * Removes expired and temporary cookies as if - * the browser was closed and re-opened. - * @param string/integer $date Time when session restarted. - * If omitted then all persistent - * cookies are kept. - * @access public - */ - function restart($date = false) { - $this->user_agent->restart($date); - } - - /** - * Adds a header to every fetch. - * @param string $header Header line to add to every - * request until cleared. - * @access public - */ - function addHeader($header) { - $this->user_agent->addHeader($header); - } - - /** - * Ages the cookies by the specified time. - * @param integer $interval Amount in seconds. - * @access public - */ - function ageCookies($interval) { - $this->user_agent->ageCookies($interval); - } - - /** - * Sets an additional cookie. If a cookie has - * the same name and path it is replaced. - * @param string $name Cookie key. - * @param string $value Value of cookie. - * @param string $host Host upon which the cookie is valid. - * @param string $path Cookie path if not host wide. - * @param string $expiry Expiry date. - * @access public - */ - function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { - $this->user_agent->setCookie($name, $value, $host, $path, $expiry); - } - - /** - * Reads the most specific cookie value from the - * browser cookies. - * @param string $host Host to search. - * @param string $path Applicable path. - * @param string $name Name of cookie to read. - * @return string False if not present, else the - * value as a string. - * @access public - */ - function getCookieValue($host, $path, $name) { - return $this->user_agent->getCookieValue($host, $path, $name); - } - - /** - * Reads the current cookies for the current URL. - * @param string $name Key of cookie to find. - * @return string Null if there is no current URL, false - * if the cookie is not set. - * @access public - */ - function getCurrentCookieValue($name) { - return $this->user_agent->getBaseCookieValue($name, $this->page->getUrl()); - } - - /** - * Sets the maximum number of redirects before - * a page will be loaded anyway. - * @param integer $max Most hops allowed. - * @access public - */ - function setMaximumRedirects($max) { - $this->user_agent->setMaximumRedirects($max); - } - - /** - * Sets the maximum number of nesting of framed pages - * within a framed page to prevent loops. - * @param integer $max Highest depth allowed. - * @access public - */ - function setMaximumNestedFrames($max) { - $this->maximum_nested_frames = $max; - } - - /** - * Sets the socket timeout for opening a connection. - * @param integer $timeout Maximum time in seconds. - * @access public - */ - function setConnectionTimeout($timeout) { - $this->user_agent->setConnectionTimeout($timeout); - } - - /** - * Sets proxy to use on all requests for when - * testing from behind a firewall. Set URL - * to false to disable. - * @param string $proxy Proxy URL. - * @param string $username Proxy username for authentication. - * @param string $password Proxy password for authentication. - * @access public - */ - function useProxy($proxy, $username = false, $password = false) { - $this->user_agent->useProxy($proxy, $username, $password); - } - - /** - * Fetches the page content with a HEAD request. - * Will affect cookies, but will not change the base URL. - * @param string/SimpleUrl $url Target to fetch as string. - * @param hash/SimpleHeadEncoding $parameters Additional parameters for - * HEAD request. - * @return boolean True if successful. - * @access public - */ - function head($url, $parameters = false) { - if (! is_object($url)) { - $url = new SimpleUrl($url); - } - if ($this->getUrl()) { - $url = $url->makeAbsolute($this->getUrl()); - } - $response = $this->user_agent->fetchResponse($url, new SimpleHeadEncoding($parameters)); - $this->page = new SimplePage($response); - return ! $response->isError(); - } - - /** - * Fetches the page content with a simple GET request. - * @param string/SimpleUrl $url Target to fetch. - * @param hash/SimpleFormEncoding $parameters Additional parameters for - * GET request. - * @return string Content of page or false. - * @access public - */ - function get($url, $parameters = false) { - if (! is_object($url)) { - $url = new SimpleUrl($url); - } - if ($this->getUrl()) { - $url = $url->makeAbsolute($this->getUrl()); - } - return $this->load($url, new SimpleGetEncoding($parameters)); - } - - /** - * Fetches the page content with a POST request. - * @param string/SimpleUrl $url Target to fetch as string. - * @param hash/SimpleFormEncoding $parameters POST parameters or request body. - * @param string $content_type MIME Content-Type of the request body - * @return string Content of page. - * @access public - */ - function post($url, $parameters = false, $content_type = false) { - if (! is_object($url)) { - $url = new SimpleUrl($url); - } - if ($this->getUrl()) { - $url = $url->makeAbsolute($this->getUrl()); - } - return $this->load($url, new SimplePostEncoding($parameters, $content_type)); - } - - /** - * Fetches the page content with a PUT request. - * @param string/SimpleUrl $url Target to fetch as string. - * @param hash/SimpleFormEncoding $parameters PUT request body. - * @param string $content_type MIME Content-Type of the request body - * @return string Content of page. - * @access public - */ - function put($url, $parameters = false, $content_type = false) { - if (! is_object($url)) { - $url = new SimpleUrl($url); - } - return $this->load($url, new SimplePutEncoding($parameters, $content_type)); - } - - /** - * Sends a DELETE request and fetches the response. - * @param string/SimpleUrl $url Target to fetch. - * @param hash/SimpleFormEncoding $parameters Additional parameters for - * DELETE request. - * @return string Content of page or false. - * @access public - */ - function delete($url, $parameters = false) { - if (! is_object($url)) { - $url = new SimpleUrl($url); - } - return $this->load($url, new SimpleDeleteEncoding($parameters)); - } - - /** - * Equivalent to hitting the retry button on the - * browser. Will attempt to repeat the page fetch. If - * there is no history to repeat it will give false. - * @return string/boolean Content if fetch succeeded - * else false. - * @access public - */ - function retry() { - $frames = $this->page->getFrameFocus(); - if (count($frames) > 0) { - $this->loadFrame( - $frames, - $this->page->getUrl(), - $this->page->getRequestData()); - return $this->page->getRaw(); - } - if ($url = $this->history->getUrl()) { - $this->page = $this->fetch($url, $this->history->getParameters()); - return $this->page->getRaw(); - } - return false; - } - - /** - * Equivalent to hitting the back button on the - * browser. The browser history is unchanged on - * failure. The page content is refetched as there - * is no concept of content caching in SimpleTest. - * @return boolean True if history entry and - * fetch succeeded - * @access public - */ - function back() { - if (! $this->history->back()) { - return false; - } - $content = $this->retry(); - if (! $content) { - $this->history->forward(); - } - return $content; - } - - /** - * Equivalent to hitting the forward button on the - * browser. The browser history is unchanged on - * failure. The page content is refetched as there - * is no concept of content caching in SimpleTest. - * @return boolean True if history entry and - * fetch succeeded - * @access public - */ - function forward() { - if (! $this->history->forward()) { - return false; - } - $content = $this->retry(); - if (! $content) { - $this->history->back(); - } - return $content; - } - - /** - * Retries a request after setting the authentication - * for the current realm. - * @param string $username Username for realm. - * @param string $password Password for realm. - * @return boolean True if successful fetch. Note - * that authentication may still have - * failed. - * @access public - */ - function authenticate($username, $password) { - if (! $this->page->getRealm()) { - return false; - } - $url = $this->page->getUrl(); - if (! $url) { - return false; - } - $this->user_agent->setIdentity( - $url->getHost(), - $this->page->getRealm(), - $username, - $password); - return $this->retry(); - } - - /** - * Accessor for a breakdown of the frameset. - * @return array Hash tree of frames by name - * or index if no name. - * @access public - */ - function getFrames() { - return $this->page->getFrames(); - } - - /** - * Accessor for current frame focus. Will be - * false if no frame has focus. - * @return integer/string/boolean Label if any, otherwise - * the position in the frameset - * or false if none. - * @access public - */ - function getFrameFocus() { - return $this->page->getFrameFocus(); - } - - /** - * Sets the focus by index. The integer index starts from 1. - * @param integer $choice Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocusByIndex($choice) { - return $this->page->setFrameFocusByIndex($choice); - } - - /** - * Sets the focus by name. - * @param string $name Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocus($name) { - return $this->page->setFrameFocus($name); - } - - /** - * Clears the frame focus. All frames will be searched - * for content. - * @access public - */ - function clearFrameFocus() { - return $this->page->clearFrameFocus(); - } - - /** - * Accessor for last error. - * @return string Error from last response. - * @access public - */ - function getTransportError() { - return $this->page->getTransportError(); - } - - /** - * Accessor for current MIME type. - * @return string MIME type as string; e.g. 'text/html' - * @access public - */ - function getMimeType() { - return $this->page->getMimeType(); - } - - /** - * Accessor for last response code. - * @return integer Last HTTP response code received. - * @access public - */ - function getResponseCode() { - return $this->page->getResponseCode(); - } - - /** - * Accessor for last Authentication type. Only valid - * straight after a challenge (401). - * @return string Description of challenge type. - * @access public - */ - function getAuthentication() { - return $this->page->getAuthentication(); - } - - /** - * Accessor for last Authentication realm. Only valid - * straight after a challenge (401). - * @return string Name of security realm. - * @access public - */ - function getRealm() { - return $this->page->getRealm(); - } - - /** - * Accessor for current URL of page or frame if - * focused. - * @return string Location of current page or frame as - * a string. - */ - function getUrl() { - $url = $this->page->getUrl(); - return $url ? $url->asString() : false; - } - - /** - * Accessor for base URL of page if set via BASE tag - * @return string base URL - */ - function getBaseUrl() { - $url = $this->page->getBaseUrl(); - return $url ? $url->asString() : false; - } - - /** - * Accessor for raw bytes sent down the wire. - * @return string Original text sent. - * @access public - */ - function getRequest() { - return $this->page->getRequest(); - } - - /** - * Accessor for raw header information. - * @return string Header block. - * @access public - */ - function getHeaders() { - return $this->page->getHeaders(); - } - - /** - * Accessor for raw page information. - * @return string Original text content of web page. - * @access public - */ - function getContent() { - return $this->page->getRaw(); - } - - /** - * Accessor for plain text version of the page. - * @return string Normalised text representation. - * @access public - */ - function getContentAsText() { - return $this->page->getText(); - } - - /** - * Accessor for parsed title. - * @return string Title or false if no title is present. - * @access public - */ - function getTitle() { - return $this->page->getTitle(); - } - - /** - * Accessor for a list of all links in current page. - * @return array List of urls with scheme of - * http or https and hostname. - * @access public - */ - function getUrls() { - return $this->page->getUrls(); - } - - /** - * Sets all form fields with that name. - * @param string $label Name or label of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setField($label, $value, $position=false) { - return $this->page->setField(new SimpleByLabelOrName($label), $value, $position); - } - - /** - * Sets all form fields with that name. Will use label if - * one is available (not yet implemented). - * @param string $name Name of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setFieldByName($name, $value, $position=false) { - return $this->page->setField(new SimpleByName($name), $value, $position); - } - - /** - * Sets all form fields with that id attribute. - * @param string/integer $id Id of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setFieldById($id, $value) { - return $this->page->setField(new SimpleById($id), $value); - } - - /** - * Accessor for a form element value within the page. - * Finds the first match. - * @param string $label Field label. - * @return string/boolean A value if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getField($label) { - return $this->page->getField(new SimpleByLabelOrName($label)); - } - - /** - * Accessor for a form element value within the page. - * Finds the first match. - * @param string $name Field name. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getFieldByName($name) { - return $this->page->getField(new SimpleByName($name)); - } - - /** - * Accessor for a form element value within the page. - * @param string/integer $id Id of field in forms. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getFieldById($id) { - return $this->page->getField(new SimpleById($id)); - } - - /** - * Clicks the submit button by label. The owning - * form will be submitted by this. - * @param string $label Button label. An unlabeled - * button can be triggered by 'Submit'. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickSubmit($label = 'Submit', $additional = false) { - if (! ($form = $this->page->getFormBySubmit(new SimpleByLabel($label)))) { - return false; - } - $success = $this->load( - $form->getAction(), - $form->submitButton(new SimpleByLabel($label), $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Clicks the submit button by name attribute. The owning - * form will be submitted by this. - * @param string $name Button name. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickSubmitByName($name, $additional = false) { - if (! ($form = $this->page->getFormBySubmit(new SimpleByName($name)))) { - return false; - } - $success = $this->load( - $form->getAction(), - $form->submitButton(new SimpleByName($name), $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Clicks the submit button by ID attribute of the button - * itself. The owning form will be submitted by this. - * @param string $id Button ID. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickSubmitById($id, $additional = false) { - if (! ($form = $this->page->getFormBySubmit(new SimpleById($id)))) { - return false; - } - $success = $this->load( - $form->getAction(), - $form->submitButton(new SimpleById($id), $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Tests to see if a submit button exists with this - * label. - * @param string $label Button label. - * @return boolean True if present. - * @access public - */ - function isSubmit($label) { - return (boolean)$this->page->getFormBySubmit(new SimpleByLabel($label)); - } - - /** - * Clicks the submit image by some kind of label. Usually - * the alt tag or the nearest equivalent. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param string $label ID attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickImage($label, $x = 1, $y = 1, $additional = false) { - if (! ($form = $this->page->getFormByImage(new SimpleByLabel($label)))) { - return false; - } - $success = $this->load( - $form->getAction(), - $form->submitImage(new SimpleByLabel($label), $x, $y, $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Clicks the submit image by the name. Usually - * the alt tag or the nearest equivalent. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param string $name Name attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickImageByName($name, $x = 1, $y = 1, $additional = false) { - if (! ($form = $this->page->getFormByImage(new SimpleByName($name)))) { - return false; - } - $success = $this->load( - $form->getAction(), - $form->submitImage(new SimpleByName($name), $x, $y, $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Clicks the submit image by ID attribute. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param integer/string $id ID attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form data. - * @return string/boolean Page on success. - * @access public - */ - function clickImageById($id, $x = 1, $y = 1, $additional = false) { - if (! ($form = $this->page->getFormByImage(new SimpleById($id)))) { - return false; - } - $success = $this->load( - $form->getAction(), - $form->submitImage(new SimpleById($id), $x, $y, $additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Tests to see if an image exists with this - * title or alt text. - * @param string $label Image text. - * @return boolean True if present. - * @access public - */ - function isImage($label) { - return (boolean)$this->page->getFormByImage(new SimpleByLabel($label)); - } - - /** - * Submits a form by the ID. - * @param string $id The form ID. No submit button value - * will be sent. - * @return string/boolean Page on success. - * @access public - */ - function submitFormById($id, $additional = false) { - if (! ($form = $this->page->getFormById($id))) { - return false; - } - $success = $this->load( - $form->getAction(), - $form->submit($additional)); - return ($success ? $this->getContent() : $success); - } - - /** - * Finds a URL by label. Will find the first link - * found with this link text by default, or a later - * one if an index is given. The match ignores case and - * white space issues. - * @param string $label Text between the anchor tags. - * @param integer $index Link position counting from zero. - * @return string/boolean URL on success. - * @access public - */ - function getLink($label, $index = 0) { - $urls = $this->page->getUrlsByLabel($label); - if (count($urls) == 0) { - return false; - } - if (count($urls) < $index + 1) { - return false; - } - return $urls[$index]; - } - - /** - * Follows a link by label. Will click the first link - * found with this link text by default, or a later - * one if an index is given. The match ignores case and - * white space issues. - * @param string $label Text between the anchor tags. - * @param integer $index Link position counting from zero. - * @return string/boolean Page on success. - * @access public - */ - function clickLink($label, $index = 0) { - $url = $this->getLink($label, $index); - if ($url === false) { - return false; - } - $this->load($url, new SimpleGetEncoding()); - return $this->getContent(); - } - - /** - * Finds a link by id attribute. - * @param string $id ID attribute value. - * @return string/boolean URL on success. - * @access public - */ - function getLinkById($id) { - return $this->page->getUrlById($id); - } - - /** - * Follows a link by id attribute. - * @param string $id ID attribute value. - * @return string/boolean Page on success. - * @access public - */ - function clickLinkById($id) { - if (! ($url = $this->getLinkById($id))) { - return false; - } - $this->load($url, new SimpleGetEncoding()); - return $this->getContent(); - } - - /** - * Clicks a visible text item. Will first try buttons, - * then links and then images. - * @param string $label Visible text or alt text. - * @return string/boolean Raw page or false. - * @access public - */ - function click($label) { - $raw = $this->clickSubmit($label); - if (! $raw) { - $raw = $this->clickLink($label); - } - if (! $raw) { - $raw = $this->clickImage($label); - } - return $raw; - } - - /** - * Tests to see if a click target exists. - * @param string $label Visible text or alt text. - * @return boolean True if target present. - * @access public - */ - function isClickable($label) { - return $this->isSubmit($label) || ($this->getLink($label) !== false) || $this->isImage($label); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/collector.php b/3rdparty/simpletest/collector.php deleted file mode 100644 index ac49937aada01f96b6d53e45c4d1df61b2f94192..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/collector.php +++ /dev/null @@ -1,122 +0,0 @@ -<?php -/** - * This file contains the following classes: {@link SimpleCollector}, - * {@link SimplePatternCollector}. - * - * @author Travis Swicegood <development@domain51.com> - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: collector.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/** - * The basic collector for {@link GroupTest} - * - * @see collect(), GroupTest::collect() - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleCollector { - - /** - * Strips off any kind of slash at the end so as to normalise the path. - * @param string $path Path to normalise. - * @return string Path without trailing slash. - */ - protected function removeTrailingSlash($path) { - if (substr($path, -1) == DIRECTORY_SEPARATOR) { - return substr($path, 0, -1); - } elseif (substr($path, -1) == '/') { - return substr($path, 0, -1); - } else { - return $path; - } - } - - /** - * Scans the directory and adds what it can. - * @param object $test Group test with {@link GroupTest::addTestFile()} method. - * @param string $path Directory to scan. - * @see _attemptToAdd() - */ - function collect(&$test, $path) { - $path = $this->removeTrailingSlash($path); - if ($handle = opendir($path)) { - while (($entry = readdir($handle)) !== false) { - if ($this->isHidden($entry)) { - continue; - } - $this->handle($test, $path . DIRECTORY_SEPARATOR . $entry); - } - closedir($handle); - } - } - - /** - * This method determines what should be done with a given file and adds - * it via {@link GroupTest::addTestFile()} if necessary. - * - * This method should be overriden to provide custom matching criteria, - * such as pattern matching, recursive matching, etc. For an example, see - * {@link SimplePatternCollector::_handle()}. - * - * @param object $test Group test with {@link GroupTest::addTestFile()} method. - * @param string $filename A filename as generated by {@link collect()} - * @see collect() - * @access protected - */ - protected function handle(&$test, $file) { - if (is_dir($file)) { - return; - } - $test->addFile($file); - } - - /** - * Tests for hidden files so as to skip them. Currently - * only tests for Unix hidden files. - * @param string $filename Plain filename. - * @return boolean True if hidden file. - * @access private - */ - protected function isHidden($filename) { - return strncmp($filename, '.', 1) == 0; - } -} - -/** - * An extension to {@link SimpleCollector} that only adds files matching a - * given pattern. - * - * @package SimpleTest - * @subpackage UnitTester - * @see SimpleCollector - */ -class SimplePatternCollector extends SimpleCollector { - private $pattern; - - /** - * - * @param string $pattern Perl compatible regex to test name against - * See {@link http://us4.php.net/manual/en/reference.pcre.pattern.syntax.php PHP's PCRE} - * for full documentation of valid pattern.s - */ - function __construct($pattern = '/php$/i') { - $this->pattern = $pattern; - } - - /** - * Attempts to add files that match a given pattern. - * - * @see SimpleCollector::_handle() - * @param object $test Group test with {@link GroupTest::addTestFile()} method. - * @param string $path Directory to scan. - * @access protected - */ - protected function handle(&$test, $filename) { - if (preg_match($this->pattern, $filename)) { - parent::handle($test, $filename); - } - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/compatibility.php b/3rdparty/simpletest/compatibility.php deleted file mode 100755 index e313db0cb51f177862f48acad85db4cfb9039359..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/compatibility.php +++ /dev/null @@ -1,166 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @version $Id: compatibility.php 1900 2009-07-29 11:44:37Z lastcraft $ - */ - -/** - * Static methods for compatibility between different - * PHP versions. - * @package SimpleTest - */ -class SimpleTestCompatibility { - - /** - * Creates a copy whether in PHP5 or PHP4. - * @param object $object Thing to copy. - * @return object A copy. - * @access public - */ - static function copy($object) { - if (version_compare(phpversion(), '5') >= 0) { - eval('$copy = clone $object;'); - return $copy; - } - return $object; - } - - /** - * Identity test. Drops back to equality + types for PHP5 - * objects as the === operator counts as the - * stronger reference constraint. - * @param mixed $first Test subject. - * @param mixed $second Comparison object. - * @return boolean True if identical. - * @access public - */ - static function isIdentical($first, $second) { - if (version_compare(phpversion(), '5') >= 0) { - return SimpleTestCompatibility::isIdenticalType($first, $second); - } - if ($first != $second) { - return false; - } - return ($first === $second); - } - - /** - * Recursive type test. - * @param mixed $first Test subject. - * @param mixed $second Comparison object. - * @return boolean True if same type. - * @access private - */ - protected static function isIdenticalType($first, $second) { - if (gettype($first) != gettype($second)) { - return false; - } - if (is_object($first) && is_object($second)) { - if (get_class($first) != get_class($second)) { - return false; - } - return SimpleTestCompatibility::isArrayOfIdenticalTypes( - (array) $first, - (array) $second); - } - if (is_array($first) && is_array($second)) { - return SimpleTestCompatibility::isArrayOfIdenticalTypes($first, $second); - } - if ($first !== $second) { - return false; - } - return true; - } - - /** - * Recursive type test for each element of an array. - * @param mixed $first Test subject. - * @param mixed $second Comparison object. - * @return boolean True if identical. - * @access private - */ - protected static function isArrayOfIdenticalTypes($first, $second) { - if (array_keys($first) != array_keys($second)) { - return false; - } - foreach (array_keys($first) as $key) { - $is_identical = SimpleTestCompatibility::isIdenticalType( - $first[$key], - $second[$key]); - if (! $is_identical) { - return false; - } - } - return true; - } - - /** - * Test for two variables being aliases. - * @param mixed $first Test subject. - * @param mixed $second Comparison object. - * @return boolean True if same. - * @access public - */ - static function isReference(&$first, &$second) { - if (version_compare(phpversion(), '5', '>=') && is_object($first)) { - return ($first === $second); - } - if (is_object($first) && is_object($second)) { - $id = uniqid("test"); - $first->$id = true; - $is_ref = isset($second->$id); - unset($first->$id); - return $is_ref; - } - $temp = $first; - $first = uniqid("test"); - $is_ref = ($first === $second); - $first = $temp; - return $is_ref; - } - - /** - * Test to see if an object is a member of a - * class hiearchy. - * @param object $object Object to test. - * @param string $class Root name of hiearchy. - * @return boolean True if class in hiearchy. - * @access public - */ - static function isA($object, $class) { - if (version_compare(phpversion(), '5') >= 0) { - if (! class_exists($class, false)) { - if (function_exists('interface_exists')) { - if (! interface_exists($class, false)) { - return false; - } - } - } - eval("\$is_a = \$object instanceof $class;"); - return $is_a; - } - if (function_exists('is_a')) { - return is_a($object, $class); - } - return ((strtolower($class) == get_class($object)) - or (is_subclass_of($object, $class))); - } - - /** - * Sets a socket timeout for each chunk. - * @param resource $handle Socket handle. - * @param integer $timeout Limit in seconds. - * @access public - */ - static function setTimeout($handle, $timeout) { - if (function_exists('stream_set_timeout')) { - stream_set_timeout($handle, $timeout, 0); - } elseif (function_exists('socket_set_timeout')) { - socket_set_timeout($handle, $timeout, 0); - } elseif (function_exists('set_socket_timeout')) { - set_socket_timeout($handle, $timeout, 0); - } - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/cookies.php b/3rdparty/simpletest/cookies.php deleted file mode 100644 index 7a28f4a5bcc02333798d1cbb5aaf5364b386ed92..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/cookies.php +++ /dev/null @@ -1,380 +0,0 @@ -<?php -/** - * Base include file for SimpleTest - * @package SimpleTest - * @subpackage WebTester - * @version $Id: cookies.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/url.php'); -/**#@-*/ - -/** - * Cookie data holder. Cookie rules are full of pretty - * arbitary stuff. I have used... - * http://wp.netscape.com/newsref/std/cookie_spec.html - * http://www.cookiecentral.com/faq/ - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleCookie { - private $host; - private $name; - private $value; - private $path; - private $expiry; - private $is_secure; - - /** - * Constructor. Sets the stored values. - * @param string $name Cookie key. - * @param string $value Value of cookie. - * @param string $path Cookie path if not host wide. - * @param string $expiry Expiry date as string. - * @param boolean $is_secure Currently ignored. - */ - function __construct($name, $value = false, $path = false, $expiry = false, $is_secure = false) { - $this->host = false; - $this->name = $name; - $this->value = $value; - $this->path = ($path ? $this->fixPath($path) : "/"); - $this->expiry = false; - if (is_string($expiry)) { - $this->expiry = strtotime($expiry); - } elseif (is_integer($expiry)) { - $this->expiry = $expiry; - } - $this->is_secure = $is_secure; - } - - /** - * Sets the host. The cookie rules determine - * that the first two parts are taken for - * certain TLDs and three for others. If the - * new host does not match these rules then the - * call will fail. - * @param string $host New hostname. - * @return boolean True if hostname is valid. - * @access public - */ - function setHost($host) { - if ($host = $this->truncateHost($host)) { - $this->host = $host; - return true; - } - return false; - } - - /** - * Accessor for the truncated host to which this - * cookie applies. - * @return string Truncated hostname. - * @access public - */ - function getHost() { - return $this->host; - } - - /** - * Test for a cookie being valid for a host name. - * @param string $host Host to test against. - * @return boolean True if the cookie would be valid - * here. - */ - function isValidHost($host) { - return ($this->truncateHost($host) === $this->getHost()); - } - - /** - * Extracts just the domain part that determines a - * cookie's host validity. - * @param string $host Host name to truncate. - * @return string Domain or false on a bad host. - * @access private - */ - protected function truncateHost($host) { - $tlds = SimpleUrl::getAllTopLevelDomains(); - if (preg_match('/[a-z\-]+\.(' . $tlds . ')$/i', $host, $matches)) { - return $matches[0]; - } elseif (preg_match('/[a-z\-]+\.[a-z\-]+\.[a-z\-]+$/i', $host, $matches)) { - return $matches[0]; - } - return false; - } - - /** - * Accessor for name. - * @return string Cookie key. - * @access public - */ - function getName() { - return $this->name; - } - - /** - * Accessor for value. A deleted cookie will - * have an empty string for this. - * @return string Cookie value. - * @access public - */ - function getValue() { - return $this->value; - } - - /** - * Accessor for path. - * @return string Valid cookie path. - * @access public - */ - function getPath() { - return $this->path; - } - - /** - * Tests a path to see if the cookie applies - * there. The test path must be longer or - * equal to the cookie path. - * @param string $path Path to test against. - * @return boolean True if cookie valid here. - * @access public - */ - function isValidPath($path) { - return (strncmp( - $this->fixPath($path), - $this->getPath(), - strlen($this->getPath())) == 0); - } - - /** - * Accessor for expiry. - * @return string Expiry string. - * @access public - */ - function getExpiry() { - if (! $this->expiry) { - return false; - } - return gmdate("D, d M Y H:i:s", $this->expiry) . " GMT"; - } - - /** - * Test to see if cookie is expired against - * the cookie format time or timestamp. - * Will give true for a session cookie. - * @param integer/string $now Time to test against. Result - * will be false if this time - * is later than the cookie expiry. - * Can be either a timestamp integer - * or a cookie format date. - * @access public - */ - function isExpired($now) { - if (! $this->expiry) { - return true; - } - if (is_string($now)) { - $now = strtotime($now); - } - return ($this->expiry < $now); - } - - /** - * Ages the cookie by the specified number of - * seconds. - * @param integer $interval In seconds. - * @public - */ - function agePrematurely($interval) { - if ($this->expiry) { - $this->expiry -= $interval; - } - } - - /** - * Accessor for the secure flag. - * @return boolean True if cookie needs SSL. - * @access public - */ - function isSecure() { - return $this->is_secure; - } - - /** - * Adds a trailing and leading slash to the path - * if missing. - * @param string $path Path to fix. - * @access private - */ - protected function fixPath($path) { - if (substr($path, 0, 1) != '/') { - $path = '/' . $path; - } - if (substr($path, -1, 1) != '/') { - $path .= '/'; - } - return $path; - } -} - -/** - * Repository for cookies. This stuff is a - * tiny bit browser dependent. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleCookieJar { - private $cookies; - - /** - * Constructor. Jar starts empty. - * @access public - */ - function __construct() { - $this->cookies = array(); - } - - /** - * Removes expired and temporary cookies as if - * the browser was closed and re-opened. - * @param string/integer $now Time to test expiry against. - * @access public - */ - function restartSession($date = false) { - $surviving_cookies = array(); - for ($i = 0; $i < count($this->cookies); $i++) { - if (! $this->cookies[$i]->getValue()) { - continue; - } - if (! $this->cookies[$i]->getExpiry()) { - continue; - } - if ($date && $this->cookies[$i]->isExpired($date)) { - continue; - } - $surviving_cookies[] = $this->cookies[$i]; - } - $this->cookies = $surviving_cookies; - } - - /** - * Ages all cookies in the cookie jar. - * @param integer $interval The old session is moved - * into the past by this number - * of seconds. Cookies now over - * age will be removed. - * @access public - */ - function agePrematurely($interval) { - for ($i = 0; $i < count($this->cookies); $i++) { - $this->cookies[$i]->agePrematurely($interval); - } - } - - /** - * Sets an additional cookie. If a cookie has - * the same name and path it is replaced. - * @param string $name Cookie key. - * @param string $value Value of cookie. - * @param string $host Host upon which the cookie is valid. - * @param string $path Cookie path if not host wide. - * @param string $expiry Expiry date. - * @access public - */ - function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { - $cookie = new SimpleCookie($name, $value, $path, $expiry); - if ($host) { - $cookie->setHost($host); - } - $this->cookies[$this->findFirstMatch($cookie)] = $cookie; - } - - /** - * Finds a matching cookie to write over or the - * first empty slot if none. - * @param SimpleCookie $cookie Cookie to write into jar. - * @return integer Available slot. - * @access private - */ - protected function findFirstMatch($cookie) { - for ($i = 0; $i < count($this->cookies); $i++) { - $is_match = $this->isMatch( - $cookie, - $this->cookies[$i]->getHost(), - $this->cookies[$i]->getPath(), - $this->cookies[$i]->getName()); - if ($is_match) { - return $i; - } - } - return count($this->cookies); - } - - /** - * Reads the most specific cookie value from the - * browser cookies. Looks for the longest path that - * matches. - * @param string $host Host to search. - * @param string $path Applicable path. - * @param string $name Name of cookie to read. - * @return string False if not present, else the - * value as a string. - * @access public - */ - function getCookieValue($host, $path, $name) { - $longest_path = ''; - foreach ($this->cookies as $cookie) { - if ($this->isMatch($cookie, $host, $path, $name)) { - if (strlen($cookie->getPath()) > strlen($longest_path)) { - $value = $cookie->getValue(); - $longest_path = $cookie->getPath(); - } - } - } - return (isset($value) ? $value : false); - } - - /** - * Tests cookie for matching against search - * criteria. - * @param SimpleTest $cookie Cookie to test. - * @param string $host Host must match. - * @param string $path Cookie path must be shorter than - * this path. - * @param string $name Name must match. - * @return boolean True if matched. - * @access private - */ - protected function isMatch($cookie, $host, $path, $name) { - if ($cookie->getName() != $name) { - return false; - } - if ($host && $cookie->getHost() && ! $cookie->isValidHost($host)) { - return false; - } - if (! $cookie->isValidPath($path)) { - return false; - } - return true; - } - - /** - * Uses a URL to sift relevant cookies by host and - * path. Results are list of strings of form "name=value". - * @param SimpleUrl $url Url to select by. - * @return array Valid name and value pairs. - * @access public - */ - function selectAsPairs($url) { - $pairs = array(); - foreach ($this->cookies as $cookie) { - if ($this->isMatch($cookie, $url->getHost(), $url->getPath(), $cookie->getName())) { - $pairs[] = $cookie->getName() . '=' . $cookie->getValue(); - } - } - return $pairs; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/default_reporter.php b/3rdparty/simpletest/default_reporter.php deleted file mode 100644 index 6feb67a30883f4bc1288b41e1109a6126ee21c9d..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/default_reporter.php +++ /dev/null @@ -1,163 +0,0 @@ -<?php -/** - * Optional include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: default_reporter.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/simpletest.php'); -require_once(dirname(__FILE__) . '/scorer.php'); -require_once(dirname(__FILE__) . '/reporter.php'); -require_once(dirname(__FILE__) . '/xml.php'); -/**#@-*/ - -/** - * Parser for command line arguments. Extracts - * the a specific test to run and engages XML - * reporting when necessary. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleCommandLineParser { - private $to_property = array( - 'case' => 'case', 'c' => 'case', - 'test' => 'test', 't' => 'test', - ); - private $case = ''; - private $test = ''; - private $xml = false; - private $help = false; - private $no_skips = false; - - /** - * Parses raw command line arguments into object properties. - * @param string $arguments Raw commend line arguments. - */ - function __construct($arguments) { - if (! is_array($arguments)) { - return; - } - foreach ($arguments as $i => $argument) { - if (preg_match('/^--?(test|case|t|c)=(.+)$/', $argument, $matches)) { - $property = $this->to_property[$matches[1]]; - $this->$property = $matches[2]; - } elseif (preg_match('/^--?(test|case|t|c)$/', $argument, $matches)) { - $property = $this->to_property[$matches[1]]; - if (isset($arguments[$i + 1])) { - $this->$property = $arguments[$i + 1]; - } - } elseif (preg_match('/^--?(xml|x)$/', $argument)) { - $this->xml = true; - } elseif (preg_match('/^--?(no-skip|no-skips|s)$/', $argument)) { - $this->no_skips = true; - } elseif (preg_match('/^--?(help|h)$/', $argument)) { - $this->help = true; - } - } - } - - /** - * Run only this test. - * @return string Test name to run. - */ - function getTest() { - return $this->test; - } - - /** - * Run only this test suite. - * @return string Test class name to run. - */ - function getTestCase() { - return $this->case; - } - - /** - * Output should be XML or not. - * @return boolean True if XML desired. - */ - function isXml() { - return $this->xml; - } - - /** - * Output should suppress skip messages. - * @return boolean True for no skips. - */ - function noSkips() { - return $this->no_skips; - } - - /** - * Output should be a help message. Disabled during XML mode. - * @return boolean True if help message desired. - */ - function help() { - return $this->help && ! $this->xml; - } - - /** - * Returns plain-text help message for command line runner. - * @return string String help message - */ - function getHelpText() { - return <<<HELP -SimpleTest command line default reporter (autorun) -Usage: php <test_file> [args...] - - -c <class> Run only the test-case <class> - -t <method> Run only the test method <method> - -s Suppress skip messages - -x Return test results in XML - -h Display this help message - -HELP; - } - -} - -/** - * The default reporter used by SimpleTest's autorun - * feature. The actual reporters used are dependency - * injected and can be overridden. - * @package SimpleTest - * @subpackage UnitTester - */ -class DefaultReporter extends SimpleReporterDecorator { - - /** - * Assembles the appropriate reporter for the environment. - */ - function __construct() { - if (SimpleReporter::inCli()) { - $parser = new SimpleCommandLineParser($_SERVER['argv']); - $interfaces = $parser->isXml() ? array('XmlReporter') : array('TextReporter'); - if ($parser->help()) { - // I'm not sure if we should do the echo'ing here -- ezyang - echo $parser->getHelpText(); - exit(1); - } - $reporter = new SelectiveReporter( - SimpleTest::preferred($interfaces), - $parser->getTestCase(), - $parser->getTest()); - if ($parser->noSkips()) { - $reporter = new NoSkipsReporter($reporter); - } - } else { - $reporter = new SelectiveReporter( - SimpleTest::preferred('HtmlReporter'), - @$_GET['c'], - @$_GET['t']); - if (@$_GET['skips'] == 'no' || @$_GET['show-skips'] == 'no') { - $reporter = new NoSkipsReporter($reporter); - } - } - parent::__construct($reporter); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/detached.php b/3rdparty/simpletest/detached.php deleted file mode 100755 index a325e140d0236b85e5cfd82b99a196aff59f793c..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/detached.php +++ /dev/null @@ -1,96 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: detached.php 1784 2008-04-26 13:07:14Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/xml.php'); -require_once(dirname(__FILE__) . '/shell_tester.php'); -/**#@-*/ - -/** - * Runs an XML formated test in a separate process. - * @package SimpleTest - * @subpackage UnitTester - */ -class DetachedTestCase { - private $command; - private $dry_command; - private $size; - - /** - * Sets the location of the remote test. - * @param string $command Test script. - * @param string $dry_command Script for dry run. - * @access public - */ - function __construct($command, $dry_command = false) { - $this->command = $command; - $this->dry_command = $dry_command ? $dry_command : $command; - $this->size = false; - } - - /** - * Accessor for the test name for subclasses. - * @return string Name of the test. - * @access public - */ - function getLabel() { - return $this->command; - } - - /** - * Runs the top level test for this class. Currently - * reads the data as a single chunk. I'll fix this - * once I have added iteration to the browser. - * @param SimpleReporter $reporter Target of test results. - * @returns boolean True if no failures. - * @access public - */ - function run(&$reporter) { - $shell = &new SimpleShell(); - $shell->execute($this->command); - $parser = &$this->createParser($reporter); - if (! $parser->parse($shell->getOutput())) { - trigger_error('Cannot parse incoming XML from [' . $this->command . ']'); - return false; - } - return true; - } - - /** - * Accessor for the number of subtests. - * @return integer Number of test cases. - * @access public - */ - function getSize() { - if ($this->size === false) { - $shell = &new SimpleShell(); - $shell->execute($this->dry_command); - $reporter = &new SimpleReporter(); - $parser = &$this->createParser($reporter); - if (! $parser->parse($shell->getOutput())) { - trigger_error('Cannot parse incoming XML from [' . $this->dry_command . ']'); - return false; - } - $this->size = $reporter->getTestCaseCount(); - } - return $this->size; - } - - /** - * Creates the XML parser. - * @param SimpleReporter $reporter Target of test results. - * @return SimpleTestXmlListener XML reader. - * @access protected - */ - protected function &createParser(&$reporter) { - return new SimpleTestXmlParser($reporter); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/docs/en/authentication_documentation.html b/3rdparty/simpletest/docs/en/authentication_documentation.html deleted file mode 100644 index e058e19a11123ce576fddcd4e90cabb0d868db35..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/authentication_documentation.html +++ /dev/null @@ -1,378 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>SimpleTest documentation for testing log-in and authentication</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <span class="chosen">Authentication</span> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Authentication documentation</h1> - This page... - <ul> -<li> - Getting through <a href="#basic">Basic HTTP authentication</a> - </li> -<li> - Testing <a href="#cookies">cookie based authentication</a> - </li> -<li> - Managing <a href="#session">browser sessions</a> and timeouts - </li> -</ul> -<div class="content"> - - <p> - One of the trickiest, and yet most important, areas - of testing web sites is the security. - Testing these schemes is one of the core goals of - the SimpleTest web tester. - </p> - - <h2> -<a class="target" name="basic"></a>Basic HTTP authentication</h2> - <p> - If you fetch a page protected by basic authentication then - rather than receiving content, you will instead get a 401 - header. - We can illustrate this with this test... -<pre> -class AuthenticationTest extends WebTestCase {<strong> - function test401Header() { - $this->get('http://www.lastcraft.com/protected/'); - $this->showHeaders(); - }</strong> -} -</pre> - This allows us to see the challenge header... - <div class="demo"> - <h1>File test</h1> -<pre> -HTTP/1.1 401 Authorization Required -Date: Sat, 18 Sep 2004 19:25:18 GMT -Server: Apache/1.3.29 (Unix) PHP/4.3.4 -WWW-Authenticate: Basic realm="SimpleTest basic authentication" -Connection: close -Content-Type: text/html; charset=iso-8859-1 -</pre> - <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete. - <strong>0</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div> - </div> - We are trying to get away from visual inspection though, and so SimpleTest - allows to make automated assertions against the challenge. - Here is a thorough test of our header... -<pre> -class AuthenticationTest extends WebTestCase { - function test401Header() { - $this->get('http://www.lastcraft.com/protected/');<strong> - $this->assertAuthentication('Basic'); - $this->assertResponse(401); - $this->assertRealm('SimpleTest basic authentication');</strong> - } -} -</pre> - Any one of these tests would normally do on it's own depending - on the amount of detail you want to see. - </p> - <p> - One theme that runs through SimpleTest is the ability to use - <span class="new_code">SimpleExpectation</span> objects wherever a simple - match is not enough. - If you want only an approximate match to the realm for - example, you can do this... -<pre> -class AuthenticationTest extends WebTestCase { - function test401Header() { - $this->get('http://www.lastcraft.com/protected/'); - $this->assertRealm(<strong>new PatternExpectation('/simpletest/i')</strong>); - } -} -</pre> - This type of test, testing HTTP responses, is not typical. - </p> - <p> - Most of the time we are not interested in testing the - authentication itself, but want to get past it to test - the pages underneath. - As soon as the challenge has been issued we can reply with - an authentication response... -<pre> -class AuthenticationTest extends WebTestCase { - function testCanAuthenticate() { - $this->get('http://www.lastcraft.com/protected/');<strong> - $this->authenticate('Me', 'Secret');</strong> - $this->assertTitle(...); - } -} -</pre> - The username and password will now be sent with every - subsequent request to that directory and subdirectories. - You will have to authenticate again if you step outside - the authenticated directory, but SimpleTest is smart enough - to merge subdirectories into a common realm. - </p> - <p> - If you want, you can shortcut this step further by encoding - the log in details straight into the URL... -<pre> -class AuthenticationTest extends WebTestCase { - function testCanReadAuthenticatedPages() { - $this->get('http://<strong>Me:Secret@</strong>www.lastcraft.com/protected/'); - $this->assertTitle(...); - } -} -</pre> - If your username or password has special characters, then you - will have to URL encode them or the request will not be parsed - correctly. - I'm afraid we leave this up to you. - </p> - <p> - A problem with encoding the login details directly in the URL is - the authentication header will not be sent on subsequent requests. - If you navigate with relative URLs though, the authentication - information will be preserved along with the domain name. - </p> - <p> - Normally though, you use the <span class="new_code">authenticate()</span> call. - SimpleTest will then remember your login information on each request. - </p> - <p> - Only testing with basic authentication is currently supported, and - this is only really secure in tandem with HTTPS connections. - This is usually good enough to protect test server from prying eyes, - however. - Digest authentication and NTLM authentication may be added - in the future if enough people request this feature. - </p> - - <h2> -<a class="target" name="cookies"></a>Cookies</h2> - <p> - Basic authentication doesn't give enough control over the - user interface for web developers. - More likely this functionality will be coded directly into - the web architecture using cookies with complicated timeouts. - We need to be able to test this too. - </p> - <p> - Starting with a simple log-in form... -<pre> -<form> - Username: - <input type="text" name="u" value="" /><br /> - Password: - <input type="password" name="p" value="" /><br /> - <input type="submit" value="Log in" /> -</form> -</pre> - Which looks like... - </p> - <p> - <form class="demo"> - Username: - <input type="text" name="u" value=""><br> - Password: - <input type="password" name="p" value=""><br> - <input type="submit" value="Log in"> - </form> - </p> - <p> - Let's suppose that in fetching this page a cookie has been - set with a session ID. - We are not going to fill the form in yet, just test that - we are tracking the user. - Here is the test... -<pre> -class LogInTest extends WebTestCase { - function testSessionCookieSetBeforeForm() { - $this->get('http://www.my-site.com/login.php');<strong> - $this->assertCookie('SID');</strong> - } -} -</pre> - All we are doing is confirming that the cookie is set. - As the value is likely to be rather cryptic it's not - really worth testing this with... -<pre> -class LogInTest extends WebTestCase { - function testSessionCookieIsCorrectPattern() { - $this->get('http://www.my-site.com/login.php'); - $this->assertCookie('SID', <strong>new PatternExpectation('/[a-f0-9]{32}/i')</strong>); - } -} -</pre> - If you are using PHP to handle sessions for you then - this test is even more useless, as we are just testing PHP itself. - </p> - <p> - The simplest test of logging in is to visually inspect the - next page to see if you are really logged in. - Just test the next page with <span class="new_code">WebTestCase::assertText()</span>. - </p> - <p> - The test is similar to any other form test, - but we might want to confirm that we still have the same - cookie after log-in as before we entered. - We wouldn't want to lose track of this after all. - Here is a possible test for this... -<pre> -class LogInTest extends WebTestCase { - ... - function testSessionCookieSameAfterLogIn() { - $this->get('http://www.my-site.com/login.php');<strong> - $session = $this->getCookie('SID'); - $this->setField('u', 'Me'); - $this->setField('p', 'Secret'); - $this->click('Log in'); - $this->assertText('Welcome Me'); - $this->assertCookie('SID', $session);</strong> - } -} -</pre> - This confirms that the session identifier is maintained - afer log-in and we haven't accidently reset it. - </p> - <p> - We could even attempt to hack our own system by setting - arbitrary cookies to gain access... -<pre> -class LogInTest extends WebTestCase { - ... - function testSessionCookieSameAfterLogIn() { - $this->get('http://www.my-site.com/login.php');<strong> - $this->setCookie('SID', 'Some other session'); - $this->get('http://www.my-site.com/restricted.php');</strong> - $this->assertText('Access denied'); - } -} -</pre> - Is your site protected from this attack? - </p> - - <h2> -<a class="target" name="session"></a>Browser sessions</h2> - <p> - If you are testing an authentication system a critical piece - of behaviour is what happens when a user logs back in. - We would like to simulate closing and reopening a browser... -<pre> -class LogInTest extends WebTestCase { - ... - function testLoseAuthenticationAfterBrowserClose() { - $this->get('http://www.my-site.com/login.php'); - $this->setField('u', 'Me'); - $this->setField('p', 'Secret'); - $this->click('Log in'); - $this->assertText('Welcome Me');<strong> - - $this->restart(); - $this->get('http://www.my-site.com/restricted.php'); - $this->assertText('Access denied');</strong> - } -} -</pre> - The <span class="new_code">WebTestCase::restart()</span> method will - preserve cookies that have unexpired timeouts, but throw away - those that are temporary or expired. - You can optionally specify the time and date that the restart - happened. - </p> - <p> - Expiring cookies can be a problem. - After all, if you have a cookie that expires after an hour, - you don't want to stall the test for an hour while waiting - for the cookie to pass it's timeout. - </p> - <p> - To push the cookies over the hour limit you can age them - before you restart the session... -<pre> -class LogInTest extends WebTestCase { - ... - function testLoseAuthenticationAfterOneHour() { - $this->get('http://www.my-site.com/login.php'); - $this->setField('u', 'Me'); - $this->setField('p', 'Secret'); - $this->click('Log in'); - $this->assertText('Welcome Me'); - <strong> - $this->ageCookies(3600);</strong> - $this->restart(); - $this->get('http://www.my-site.com/restricted.php'); - $this->assertText('Access denied'); - } -} -</pre> - After the restart it will appear that cookies are an - hour older, and any that pass their expiry will have - disappeared. - </p> - - </div> - References and related information... - <ul> -<li> - SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a> - gives full detail on the classes and assertions available. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <span class="chosen">Authentication</span> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/en/browser_documentation.html b/3rdparty/simpletest/docs/en/browser_documentation.html deleted file mode 100644 index 809c143113736fe762a096edbaaacb599098e5bc..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/browser_documentation.html +++ /dev/null @@ -1,501 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>SimpleTest documentation for the scriptable web browser component</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <span class="chosen">Scriptable browser</span> -</div></div> -<h1>PHP Scriptable Web Browser</h1> - This page... - <ul> -<li> - Using the bundled <a href="#scripting">web browser in scripts</a> - </li> -<li> - <a href="#debug">Debugging</a> failed pages - </li> -<li> - Complex <a href="#unit">tests with multiple web browsers</a> - </li> -</ul> -<div class="content"> - - <p> - SimpleTest's web browser component can be used not just - outside of the <span class="new_code">WebTestCase</span> class, but also - independently of the SimpleTest framework itself. - </p> - - <h2> -<a class="target" name="scripting"></a>The Scriptable Browser</h2> - <p> - You can use the web browser in PHP scripts to confirm - services are up and running, or to extract information - from them at a regular basis. - For example, here is a small script to extract the current number of - open PHP 5 bugs from the <a href="http://www.php.net/">PHP web site</a>... -<pre> -<strong><?php -require_once('simpletest/browser.php'); - -$browser = &new SimpleBrowser(); -$browser->get('http://php.net/'); -$browser->click('reporting bugs'); -$browser->click('statistics'); -$page = $browser->click('PHP 5 bugs only'); -preg_match('/status=Open.*?by=Any.*?(\d+)<\/a>/', $page, $matches); -print $matches[1]; -?></strong> -</pre> - There are simpler methods to do this particular example in PHP - of course. - For example you can just use the PHP <span class="new_code">file()</span> - command against what here is a pretty fixed page. - However, using the web browser for scripts allows authentication, - correct handling of cookies, automatic loading of frames, redirects, - form submission and the ability to examine the page headers. - <p> - </p> - Methods such as periodic scraping are fragile against a site that is constantly - evolving and you would want a more direct way of accessing - data in a permanent set up, but for simple tasks this can provide - a very rapid solution. - </p> - <p> - All of the navigation methods used in the - <a href="web_tester_documentation.html">WebTestCase</a> - are present in the <span class="new_code">SimpleBrowser</span> class, but - the assertions are replaced with simpler accessors. - Here is a full list of the page navigation methods... - <table><tbody> - <tr> -<td><span class="new_code">addHeader($header)</span></td> -<td>Adds a header to every fetch</td> -</tr> - <tr> -<td><span class="new_code">useProxy($proxy, $username, $password)</span></td> -<td>Use this proxy from now on</td> -</tr> - <tr> -<td><span class="new_code">head($url, $parameters)</span></td> -<td>Perform a HEAD request</td> -</tr> - <tr> -<td><span class="new_code">get($url, $parameters)</span></td> -<td>Fetch a page with GET</td> -</tr> - <tr> -<td><span class="new_code">post($url, $parameters)</span></td> -<td>Fetch a page with POST</td> -</tr> - <tr> -<td><span class="new_code">click($label)</span></td> -<td>Clicks visible link or button text</td> -</tr> - <tr> -<td><span class="new_code">clickLink($label)</span></td> -<td>Follows a link by label</td> -</tr> - <tr> -<td><span class="new_code">clickLinkById($id)</span></td> -<td>Follows a link by attribute</td> -</tr> - <tr> -<td><span class="new_code">getUrl()</span></td> -<td>Current URL of page or frame</td> -</tr> - <tr> -<td><span class="new_code">getTitle()</span></td> -<td>Page title</td> -</tr> - <tr> -<td><span class="new_code">getContent()</span></td> -<td>Raw page or frame</td> -</tr> - <tr> -<td><span class="new_code">getContentAsText()</span></td> -<td>HTML removed except for alt text</td> -</tr> - <tr> -<td><span class="new_code">retry()</span></td> -<td>Repeat the last request</td> -</tr> - <tr> -<td><span class="new_code">back()</span></td> -<td>Use the browser back button</td> -</tr> - <tr> -<td><span class="new_code">forward()</span></td> -<td>Use the browser forward button</td> -</tr> - <tr> -<td><span class="new_code">authenticate($username, $password)</span></td> -<td>Retry page or frame after a 401 response</td> -</tr> - <tr> -<td><span class="new_code">restart($date)</span></td> -<td>Restarts the browser for a new session</td> -</tr> - <tr> -<td><span class="new_code">ageCookies($interval)</span></td> -<td>Ages the cookies by the specified time</td> -</tr> - <tr> -<td><span class="new_code">setCookie($name, $value)</span></td> -<td>Sets an additional cookie</td> -</tr> - <tr> -<td><span class="new_code">getCookieValue($host, $path, $name)</span></td> -<td>Reads the most specific cookie</td> -</tr> - <tr> -<td><span class="new_code">getCurrentCookieValue($name)</span></td> -<td>Reads cookie for the current context</td> -</tr> - </tbody></table> - The methods <span class="new_code">SimpleBrowser::useProxy()</span> and - <span class="new_code">SimpleBrowser::addHeader()</span> are special. - Once called they continue to apply to all subsequent fetches. - </p> - <p> - Navigating forms is similar to the - <a href="form_testing_documentation.html">WebTestCase form navigation</a>... - <table><tbody> - <tr> -<td><span class="new_code">setField($label, $value)</span></td> -<td>Sets all form fields with that label or name</td> -</tr> - <tr> -<td><span class="new_code">setFieldByName($name, $value)</span></td> -<td>Sets all form fields with that name</td> -</tr> - <tr> -<td><span class="new_code">setFieldById($id, $value)</span></td> -<td>Sets all form fields with that id</td> -</tr> - <tr> -<td><span class="new_code">getField($label)</span></td> -<td>Accessor for a form element value by label tag and then name</td> -</tr> - <tr> -<td><span class="new_code">getFieldByName($name)</span></td> -<td>Accessor for a form element value using name attribute</td> -</tr> - <tr> -<td><span class="new_code">getFieldById($id)</span></td> -<td>Accessor for a form element value</td> -</tr> - <tr> -<td><span class="new_code">clickSubmit($label)</span></td> -<td>Submits form by button label</td> -</tr> - <tr> -<td><span class="new_code">clickSubmitByName($name)</span></td> -<td>Submits form by button attribute</td> -</tr> - <tr> -<td><span class="new_code">clickSubmitById($id)</span></td> -<td>Submits form by button attribute</td> -</tr> - <tr> -<td><span class="new_code">clickImage($label, $x, $y)</span></td> -<td>Clicks an input tag of type image by title or alt text</td> -</tr> - <tr> -<td><span class="new_code">clickImageByName($name, $x, $y)</span></td> -<td>Clicks an input tag of type image by name</td> -</tr> - <tr> -<td><span class="new_code">clickImageById($id, $x, $y)</span></td> -<td>Clicks an input tag of type image by ID attribute</td> -</tr> - <tr> -<td><span class="new_code">submitFormById($id)</span></td> -<td>Submits by the form tag attribute</td> -</tr> - </tbody></table> - At the moment there aren't many methods to list available links and fields. - <table><tbody> - <tr> -<td><span class="new_code">isClickable($label)</span></td> -<td>Test to see if a click target exists by label or name</td> -</tr> - <tr> -<td><span class="new_code">isSubmit($label)</span></td> -<td>Test for the existence of a button with that label or name</td> -</tr> - <tr> -<td><span class="new_code">isImage($label)</span></td> -<td>Test for the existence of an image button with that label or name</td> -</tr> - <tr> -<td><span class="new_code">getLink($label)</span></td> -<td>Finds a URL from its label</td> -</tr> - <tr> -<td><span class="new_code">getLinkById($label)</span></td> -<td>Finds a URL from its ID attribute</td> -</tr> - <tr> -<td><span class="new_code">getUrls()</span></td> -<td>Lists available links in the current page</td> -</tr> - </tbody></table> - This will be expanded in later versions of SimpleTest. - </p> - <p> - Frames are a rather esoteric feature these days, but SimpleTest has - retained support for them. - </p> - <p> - Within a page, individual frames can be selected. - If no selection is made then all the frames are merged together - in one large conceptual page. - The content of the current page will be a concatenation of all of the - frames in the order that they were specified in the "frameset" - tags. - <table><tbody> - <tr> -<td><span class="new_code">getFrames()</span></td> -<td>A dump of the current frame structure</td> -</tr> - <tr> -<td><span class="new_code">getFrameFocus()</span></td> -<td>Current frame label or index</td> -</tr> - <tr> -<td><span class="new_code">setFrameFocusByIndex($choice)</span></td> -<td>Select a frame numbered from 1</td> -</tr> - <tr> -<td><span class="new_code">setFrameFocus($name)</span></td> -<td>Select frame by label</td> -</tr> - <tr> -<td><span class="new_code">clearFrameFocus()</span></td> -<td>Treat all the frames as a single page</td> -</tr> - </tbody></table> - When focused on a single frame, the content will come from - that frame only. - This includes links to click and forms to submit. - </p> - - <h2> -<a class="target" name="debug"></a>What went wrong?</h2> - <p> - All of this functionality is great when we actually manage to fetch pages, - but that doesn't always happen. - To help figure out what went wrong, the browser has some methods to - aid in debugging... - <table><tbody> - <tr> -<td><span class="new_code">setConnectionTimeout($timeout)</span></td> -<td>Close the socket on overrun</td> -</tr> - <tr> -<td><span class="new_code">getUrl()</span></td> -<td>Url of most recent page fetched</td> -</tr> - <tr> -<td><span class="new_code">getRequest()</span></td> -<td>Raw request header of page or frame</td> -</tr> - <tr> -<td><span class="new_code">getHeaders()</span></td> -<td>Raw response header of page or frame</td> -</tr> - <tr> -<td><span class="new_code">getTransportError()</span></td> -<td>Any socket level errors in the last fetch</td> -</tr> - <tr> -<td><span class="new_code">getResponseCode()</span></td> -<td>HTTP response of page or frame</td> -</tr> - <tr> -<td><span class="new_code">getMimeType()</span></td> -<td>Mime type of page or frame</td> -</tr> - <tr> -<td><span class="new_code">getAuthentication()</span></td> -<td>Authentication type in 401 challenge header</td> -</tr> - <tr> -<td><span class="new_code">getRealm()</span></td> -<td>Authentication realm in 401 challenge header</td> -</tr> - <tr> -<td><span class="new_code">getBaseUrl()</span></td> -<td>Base url only of most recent page fetched</td> -</tr> - <tr> -<td><span class="new_code">setMaximumRedirects($max)</span></td> -<td>Number of redirects before page is loaded anyway</td> -</tr> - <tr> -<td><span class="new_code">setMaximumNestedFrames($max)</span></td> -<td>Protection against recursive framesets</td> -</tr> - <tr> -<td><span class="new_code">ignoreFrames()</span></td> -<td>Disables frames support</td> -</tr> - <tr> -<td><span class="new_code">useFrames()</span></td> -<td>Enables frames support</td> -</tr> - <tr> -<td><span class="new_code">ignoreCookies()</span></td> -<td>Disables sending and receiving of cookies</td> -</tr> - <tr> -<td><span class="new_code">useCookies()</span></td> -<td>Enables cookie support</td> -</tr> - </tbody></table> - The methods <span class="new_code">SimpleBrowser::setConnectionTimeout()</span> - <span class="new_code">SimpleBrowser::setMaximumRedirects()</span>, - <span class="new_code">SimpleBrowser::setMaximumNestedFrames()</span>, - <span class="new_code">SimpleBrowser::ignoreFrames()</span>, - <span class="new_code">SimpleBrowser::useFrames()</span>, - <span class="new_code">SimpleBrowser::ignoreCookies()</span> and - <span class="new_code">SimpleBrowser::useCokies()</span> continue to apply - to every subsequent request. - The other methods are frames aware. - This means that if you have an individual frame that is not - loading, navigate to it using <span class="new_code">SimpleBrowser::setFrameFocus()</span> - and you can then use <span class="new_code">SimpleBrowser::getRequest()</span>, etc to - see what happened. - </p> - - <h2> -<a class="target" name="unit"></a>Complex unit tests with multiple browsers</h2> - <p> - Anything that could be done in a - <a href="web_tester_documentation.html">WebTestCase</a> can - now be done in a <a href="unit_tester_documentation.html">UnitTestCase</a>. - This means that we could freely mix domain object testing with the - web interface... -<pre> -<strong>class TestOfRegistration extends UnitTestCase { - function testNewUserAddedToAuthenticator() {</strong> - $browser = new SimpleBrowser(); - $browser->get('http://my-site.com/register.php'); - $browser->setField('email', 'me@here'); - $browser->setField('password', 'Secret'); - $browser->click('Register'); - <strong> - $authenticator = new Authenticator(); - $member = $authenticator->findByEmail('me@here'); - $this->assertEqual($member->getPassword(), 'Secret'); - } -}</strong> -</pre> - While this may be a useful temporary expediency, I am not a fan - of this type of testing. - The testing has cut across application layers, make it twice as - likely it will need refactoring when the code changes. - </p> - <p> - A more useful case of where using the browser directly can be helpful - is where the <span class="new_code">WebTestCase</span> cannot cope. - An example is where two browsers are needed at the same time. - </p> - <p> - For example, say we want to disallow multiple simultaneous - usage of a site with the same username. - This test case will do the job... -<pre> -class TestOfSecurity extends UnitTestCase { - function testNoMultipleLoginsFromSameUser() {<strong> - $first_attempt = new SimpleBrowser(); - $first_attempt->get('http://my-site.com/login.php'); - $first_attempt->setField('name', 'Me'); - $first_attempt->setField('password', 'Secret'); - $first_attempt->click('Enter'); - $this->assertEqual($first_attempt->getTitle(), 'Welcome'); - - $second_attempt = new SimpleBrowser(); - $second_attempt->get('http://my-site.com/login.php'); - $second_attempt->setField('name', 'Me'); - $second_attempt->setField('password', 'Secret'); - $second_attempt->click('Enter'); - $this->assertEqual($second_attempt->getTitle(), 'Access Denied');</strong> - } -} -</pre> - You can also use the <span class="new_code">SimpleBrowser</span> class - directly when you want to write test cases using a different - test tool than SimpleTest, such as PHPUnit. - </p> - - </div> - References and related information... - <ul> -<li> - SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a> - gives full detail on the classes and assertions available. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <span class="chosen">Scriptable browser</span> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/en/docs.css b/3rdparty/simpletest/docs/en/docs.css deleted file mode 100755 index 18368a04f7a6218bb22e359a181755b842aa8814..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/docs.css +++ /dev/null @@ -1,121 +0,0 @@ -body { - padding-left: 3%; - padding-right: 3%; -} -h1, h2, h3 { - font-family: sans-serif; -} -h1 { - text-align: center; -} -pre { - font-family: "courier new", courier, typewriter, monospace; - font-size: 90%; - border: 1px solid; - border-color: #999966; - background-color: #ffffcc; - padding: 5px; - margin-left: 20px; - margin-right: 40px; -} -.code, .new_code, pre.new_code { - font-family: "courier new", courier, typewriter, monospace; - font-weight: bold; -} -div.copyright { - font-size: 80%; - color: gray; -} -div.copyright a { - margin-top: 1em; - color: gray; -} -ul.api { - border: 2px outset; - border-color: gray; - background-color: white; - margin: 5px; - margin-left: 5%; - margin-right: 5%; -} -ul.api li { - margin-top: 0.2em; - margin-bottom: 0.2em; - list-style: none; - text-indent: -3em; - padding-left: 1em; -} -div.demo { - border: 4px ridge; - border-color: gray; - padding: 10px; - margin: 5px; - margin-left: 20px; - margin-right: 40px; - background-color: white; -} -div.demo span.fail { - color: red; -} -div.demo span.pass { - color: green; -} -div.demo h1 { - font-size: 12pt; - text-align: left; - font-weight: bold; -} -div.menu { - text-align: center; -} -table { - border: 2px outset; - border-color: gray; - background-color: white; - margin: 5px; - margin-left: 5%; - margin-right: 5%; -} -td { - font-size: 90%; -} -.shell { - color: white; -} -pre.shell { - border: 4px ridge; - border-color: gray; - padding: 10px; - margin: 5px; - margin-left: 20px; - margin-right: 40px; - background-color: #000100; - color: #99ff99; - font-size: 90%; -} -pre.file { - color: black; - border: 1px solid; - border-color: black; - padding: 10px; - margin: 5px; - margin-left: 20px; - margin-right: 40px; - background-color: white; - font-size: 90%; -} -form.demo { - background-color: lightgray; - border: 4px outset; - border-color: lightgray; - padding: 10px; - margin-right: 40%; -} -dl, dd { - margin: 10px; - margin-left: 30px; -} -em { - font-weight: bold; - font-family: "courier new", courier, typewriter, monospace; -} diff --git a/3rdparty/simpletest/docs/en/expectation_documentation.html b/3rdparty/simpletest/docs/en/expectation_documentation.html deleted file mode 100644 index 26704d5ae83ffefd2592cef94d32456b8cefe55a..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/expectation_documentation.html +++ /dev/null @@ -1,476 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title> - Extending the SimpleTest unit tester with additional expectation classes - </title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <span class="chosen">Expectations</span> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Expectation documentation</h1> - This page... - <ul> -<li> - Using expectations for - <a href="#mock">more precise testing with mock objects</a> - </li> -<li> - <a href="#behaviour">Changing mock object behaviour</a> with expectations - </li> -<li> - <a href="#extending">Extending the expectations</a> - </li> -<li> - Underneath SimpleTest <a href="#unit">uses expectation classes</a> - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="mock"></a>More control over mock objects</h2> - <p> - The default behaviour of the - <a href="mock_objects_documentation.html">mock objects</a> - in - <a href="http://sourceforge.net/projects/simpletest/">SimpleTest</a> - is either an identical match on the argument or to allow any argument at all. - For almost all tests this is sufficient. - Sometimes, though, you want to weaken a test case. - </p> - <p> - One place where a test can be too tightly coupled is with - text matching. - Suppose we have a component that outputs a helpful error - message when something goes wrong. - You want to test that the correct error was sent, but the actual - text may be rather long. - If you test for the text exactly, then every time the exact wording - of the message changes, you will have to go back and edit the test suite. - </p> - <p> - For example, suppose we have a news service that has failed - to connect to its remote source. -<pre> -<strong>class NewsService { - ... - function publish($writer) { - if (! $this->isConnected()) { - $writer->write('Cannot connect to news service "' . - $this->_name . '" at this time. ' . - 'Please try again later.'); - } - ... - } -}</strong> -</pre> - Here it is sending its content to a - <span class="new_code">Writer</span> class. - We could test this behaviour with a - <span class="new_code">MockWriter</span> like so... -<pre> -class TestOfNewsService extends UnitTestCase { - ... - function testConnectionFailure() {<strong> - $writer = new MockWriter(); - $writer->expectOnce('write', array( - 'Cannot connect to news service ' . - '"BBC News" at this time. ' . - 'Please try again later.')); - - $service = new NewsService('BBC News'); - $service->publish($writer);</strong> - } -} -</pre> - This is a good example of a brittle test. - If we decide to add additional instructions, such as - suggesting an alternative news source, we will break - our tests even though no underlying functionality - has been altered. - </p> - <p> - To get around this, we would like to do a regular expression - test rather than an exact match. - We can actually do this with... -<pre> -class TestOfNewsService extends UnitTestCase { - ... - function testConnectionFailure() { - $writer = new MockWriter();<strong> - $writer->expectOnce( - 'write', - array(new PatternExpectation('/cannot connect/i')));</strong> - - $service = new NewsService('BBC News'); - $service->publish($writer); - } -} -</pre> - Instead of passing in the expected parameter to the - <span class="new_code">MockWriter</span> we pass an - expectation class called - <span class="new_code">PatternExpectation</span>. - The mock object is smart enough to recognise this as special - and to treat it differently. - Rather than simply comparing the incoming argument to this - object, it uses the expectation object itself to - perform the test. - </p> - <p> - The <span class="new_code">PatternExpectation</span> takes - the regular expression to match in its constructor. - Whenever a comparison is made by the <span class="new_code">MockWriter</span> - against this expectation class, it will do a - <span class="new_code">preg_match()</span> with this pattern. - With our test case above, as long as "cannot connect" - appears in the text of the string, the mock will issue a pass - to the unit tester. - The rest of the text does not matter. - </p> - <p> - The possible expectation classes are... - <table><tbody> - <tr> -<td><span class="new_code">AnythingExpectation</span></td> -<td>Will always match</td> -</tr> - <tr> -<td><span class="new_code">EqualExpectation</span></td> -<td>An equality, rather than the stronger identity comparison</td> -</tr> - <tr> -<td><span class="new_code">NotEqualExpectation</span></td> -<td>An inequality comparison</td> -</tr> - <tr> -<td><span class="new_code">IndenticalExpectation</span></td> -<td>The default mock object check which must match exactly</td> -</tr> - <tr> -<td><span class="new_code">NotIndenticalExpectation</span></td> -<td>Inverts the mock object logic</td> -</tr> - <tr> -<td><span class="new_code">WithinMarginExpectation</span></td> -<td>Compares a value to within a margin</td> -</tr> - <tr> -<td><span class="new_code">OutsideMarginExpectation</span></td> -<td>Checks that a value is out side the margin</td> -</tr> - <tr> -<td><span class="new_code">PatternExpectation</span></td> -<td>Uses a Perl Regex to match a string</td> -</tr> - <tr> -<td><span class="new_code">NoPatternExpectation</span></td> -<td>Passes only if failing a Perl Regex</td> -</tr> - <tr> -<td><span class="new_code">IsAExpectation</span></td> -<td>Checks the type or class name only</td> -</tr> - <tr> -<td><span class="new_code">NotAExpectation</span></td> -<td>Opposite of the <span class="new_code">IsAExpectation</span> -</td> -</tr> - <tr> -<td><span class="new_code">MethodExistsExpectation</span></td> -<td>Checks a method is available on an object</td> -</tr> - <tr> -<td><span class="new_code">TrueExpectation</span></td> -<td>Accepts any PHP variable that evaluates to true</td> -</tr> - <tr> -<td><span class="new_code">FalseExpectation</span></td> -<td>Accepts any PHP variable that evaluates to false</td> -</tr> - </tbody></table> - Most take the expected value in the constructor. - The exceptions are the pattern matchers, which take a regular expression, - and the <span class="new_code">IsAExpectation</span> and <span class="new_code">NotAExpectation</span> which takes a type - or class name as a string. - </p> - <p> - Some examples... - </p> - <p> -<pre> -$mock->expectOnce('method', array(new IdenticalExpectation(14))); -</pre> - This is the same as <span class="new_code">$mock->expectOnce('method', array(14))</span>. -<pre> -$mock->expectOnce('method', array(new EqualExpectation(14))); -</pre> - This is different from the previous version in that the string - <span class="new_code">"14"</span> as a parameter will also pass. - Sometimes the additional type checks of SimpleTest are too restrictive. -<pre> -$mock->expectOnce('method', array(new AnythingExpectation(14))); -</pre> - This is the same as <span class="new_code">$mock->expectOnce('method', array('*'))</span>. -<pre> -$mock->expectOnce('method', array(new IdenticalExpectation('*'))); -</pre> - This is handy if you want to assert a literal <span class="new_code">"*"</span>. -<pre> -new NotIdenticalExpectation(14) -</pre> - This matches on anything other than integer 14. - Even the string <span class="new_code">"14"</span> would pass. -<pre> -new WithinMarginExpectation(14.0, 0.001) -</pre> - This will accept any value from 13.999 to 14.001 inclusive. - </p> - - <h2> -<a class="target" name="behaviour"></a>Using expectations to control stubs</h2> - <p> - The expectation classes can be used not just for sending assertions - from mock objects, but also for selecting behaviour for the - <a href="mock_objects_documentation.html">mock objects</a>. - Anywhere a list of arguments is given, a list of expectation objects - can be inserted instead. - </p> - <p> - Suppose we want a mock authorisation server to simulate a successful login, - but only if it receives a valid session object. - We can do this as follows... -<pre> -Mock::generate('Authorisation'); -<strong> -$authorisation = new MockAuthorisation(); -$authorisation->returns( - 'isAllowed', - true, - array(new IsAExpectation('Session', 'Must be a session'))); -$authorisation->returns('isAllowed', false);</strong> -</pre> - We have set the default mock behaviour to return false when - <span class="new_code">isAllowed</span> is called. - When we call the method with a single parameter that - is a <span class="new_code">Session</span> object, it will return true. - We have also added a second parameter as a message. - This will be displayed as part of the mock object - failure message if this expectation is the cause of - a failure. - </p> - <p> - This kind of sophistication is rarely useful, but is included for - completeness. - </p> - - <h2> -<a class="target" name="extending"></a>Creating your own expectations</h2> - <p> - The expectation classes have a very simple structure. - So simple that it is easy to create your own versions for - commonly used test logic. - </p> - <p> - As an example here is the creation of a class to test for - valid IP addresses. - In order to work correctly with the stubs and mocks the new - expectation class should extend - <span class="new_code">SimpleExpectation</span> or further extend a subclass... -<pre> -<strong>class ValidIp extends SimpleExpectation { - - function test($ip) { - return (ip2long($ip) != -1); - } - - function testMessage($ip) { - return "Address [$ip] should be a valid IP address"; - } -}</strong> -</pre> - There are only two methods to implement. - The <span class="new_code">test()</span> method should - evaluate to true if the expectation is to pass, and - false otherwise. - The <span class="new_code">testMessage()</span> method - should simply return some helpful text explaining the test - that was carried out. - </p> - <p> - This class can now be used in place of the earlier expectation - classes. - </p> - <p> - Here is a more typical example, matching part of a hash... -<pre> -<strong>class JustField extends EqualExpectation { - private $key; - - function __construct($key, $expected) { - parent::__construct($expected); - $this->key = $key; - } - - function test($compare) { - if (! isset($compare[$this->key])) { - return false; - } - return parent::test($compare[$this->key]); - } - - function testMessage($compare) { - if (! isset($compare[$this->key])) { - return 'Key [' . $this->key . '] does not exist'; - } - return 'Key [' . $this->key . '] -> ' . - parent::testMessage($compare[$this->key]); - } -}</strong> -</pre> - We tend to seperate message clauses with - "&nbsp;->&nbsp;". - This allows derivative tools to reformat the output. - </p> - <p> - Suppose some authenticator is expecting to be given - a database row corresponding to the user, and we - only need to confirm the username is correct. - We can assert just their username with... -<pre> -$mock->expectOnce('authenticate', - array(new JustKey('username', 'marcus'))); -</pre> - </p> - - <h2> -<a class="target" name="unit"></a>Under the bonnet of the unit tester</h2> - <p> - The <a href="http://sourceforge.net/projects/simpletest/">SimpleTest unit testing framework</a> - also uses the expectation classes internally for the - <a href="unit_test_documentation.html">UnitTestCase class</a>. - We can also take advantage of these mechanisms to reuse our - homebrew expectation classes within the test suites directly. - </p> - <p> - The most crude way of doing this is to use the generic - <span class="new_code">SimpleTest::assert()</span> method to - test against it directly... -<pre> -<strong>class TestOfNetworking extends UnitTestCase { - ... - function testGetValidIp() { - $server = &new Server(); - $this->assert( - new ValidIp(), - $server->getIp(), - 'Server IP address->%s'); - } -}</strong> -</pre> - <span class="new_code">assert()</span> will test any expectation class directly. - </p> - <p> - This is a little untidy compared with our usual - <span class="new_code">assert...()</span> syntax. - </p> - <p> - For such a simple case we would normally create a - separate assertion method on our test case rather - than bother using the expectation class. - If we pretend that our expectation is a little more - complicated for a moment, so that we want to reuse it, - we get... -<pre> -class TestOfNetworking extends UnitTestCase { - ...<strong> - function assertValidIp($ip, $message = '%s') { - $this->assert(new ValidIp(), $ip, $message); - }</strong> - - function testGetValidIp() { - $server = &new Server();<strong> - $this->assertValidIp( - $server->getIp(), - 'Server IP address->%s');</strong> - } -} -</pre> - It is rare to need the expectations for more than pattern - matching, but these facilities do allow testers to build - some sort of domain language for testing their application. - Also, complex expectation classes could make the tests - harder to read and debug. - In effect extending the test framework to create their own tool set. - </p> - - </div> - References and related information... - <ul> -<li> - SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - The expectations mimic the constraints in <a href="http://www.jmock.org/">JMock</a>. - </li> -<li> - <a href="http://simpletest.org/api/">Full API for SimpleTest</a> - from the PHPDoc. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <span class="chosen">Expectations</span> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/en/form_testing_documentation.html b/3rdparty/simpletest/docs/en/form_testing_documentation.html deleted file mode 100644 index 328735c9dca59b08d7e73c95479994ea3ec2b11e..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/form_testing_documentation.html +++ /dev/null @@ -1,351 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>SimpleTest documentation for testing HTML forms</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <span class="chosen">Testing forms</span> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Form testing documentation</h1> - This page... - <ul> -<li> - Changing form values and successfully - <a href="#submit">Submitting a simple form</a> - </li> -<li> - Handling <a href="#multiple">widgets with multiple values</a> - by setting lists. - </li> -<li> - Bypassing javascript to <a href="#hidden-field">set a hidden field</a>. - </li> -<li> - <a href="#raw">Raw posting</a> when you don't have a button - to click. - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="submit"></a>Submitting a simple form</h2> - <p> - When a page is fetched by the <span class="new_code">WebTestCase</span> - using <span class="new_code">get()</span> or - <span class="new_code">post()</span> the page content is - automatically parsed. - This results in any form controls that are inside <form> tags - being available from within the test case. - For example, if we have this snippet of HTML... -<pre> -<form> - <input type="text" name="a" value="A default" /> - <input type="submit" value="Go" /> -</form> -</pre> - Which looks like this... - </p> - <p> - <form class="demo"> - <input type="text" name="a" value="A default"> - <input type="submit" value="Go"> - </form> - </p> - <p> - We can navigate to this code, via the - <a href="http://www.lastcraft.com/form_testing_documentation.php">LastCraft</a> - site, with the following test... -<pre> -class SimpleFormTests extends WebTestCase {<strong> - function testDefaultValue() { - $this->get('http://www.lastcraft.com/form_testing_documentation.php'); - $this->assertField('a', 'A default'); - }</strong> -} -</pre> - Immediately after loading the page all of the HTML controls are set at - their default values just as they would appear in the web browser. - The assertion tests that a HTML widget exists in the page with the - name "a" and that it is currently set to the value - "A default". - As usual, we could use a pattern expectation instead of a fixed - string. -<pre> -class SimpleFormTests extends WebTestCase { - function testDefaultValue() { - $this->get('http://www.lastcraft.com/form_testing_documentation.php'); - $this->assertField('a', <strong>new PatternExpectation('/default/')</strong>); - } -} -</pre> - We could submit the form straight away, but first we'll change - the value of the text field and only then submit it... -<pre> -class SimpleFormTests extends WebTestCase { - function testDefaultValue() { - $this->get('http://www.my-site.com/'); - $this->assertField('a', 'A default');<strong> - $this->setField('a', 'New value'); - $this->click('Go');</strong> - } -} -</pre> - Because we didn't specify a method attribute on the form tag, and - didn't specify an action either, the test case will follow - the usual browser behaviour of submitting the form data as a <em>GET</em> - request back to the same location. - In general SimpleTest tries to emulate typical browser behaviour as much as possible, - rather than attempting to catch any form of HTML omission. - This is because the target of the testing framework is the PHP application - logic, not syntax or other errors in the HTML code. - For HTML errors, other tools such as - <a href="http://www.w3.org/People/Raggett/tidy/">HTMLTidy</a> should be used, - or any of the HTML and CSS validators already out there. - </p> - <p> - If a field is not present in any form, or if an option is unavailable, - then <span class="new_code">WebTestCase::setField()</span> will return - <span class="new_code">false</span>. - For example, suppose we wish to verify that a "Superuser" - option is not present in this form... -<pre> -<strong>Select type of user to add:</strong> -<select name="type"> - <option>Subscriber</option> - <option>Author</option> - <option>Administrator</option> -</select> -</pre> - Which looks like... - </p> - <p> - <form class="demo"> - <strong>Select type of user to add:</strong> - <select name="type"> - <option>Subscriber</option> - <option>Author</option> - <option>Administrator</option> - </select> - </form> - </p> - <p> - The following test will confirm it... -<pre> -class SimpleFormTests extends WebTestCase { - ... - function testNoSuperuserChoiceAvailable() {<strong> - $this->get('http://www.lastcraft.com/form_testing_documentation.php'); - $this->assertFalse($this->setField('type', 'Superuser'));</strong> - } -} -</pre> - The current selection will not be changed if the new value is not an option. - </p> - <p> - Here is the full list of widgets currently supported... - <ul> - <li>Text fields, including hidden and password fields.</li> - <li>Submit buttons including the button tag, although not yet reset buttons</li> - <li>Text area. This includes text wrapping behaviour.</li> - <li>Checkboxes, including multiple checkboxes in the same form.</li> - <li>Drop down selections, including multiple selects.</li> - <li>Radio buttons.</li> - <li>Images.</li> - </ul> - </p> - <p> - The browser emulation offered by SimpleTest mimics - the actions which can be perform by a user on a - standard HTML page. Javascript is not supported, and - it's unlikely that support will be added any time - soon. - </p> - <p> - Of particular note is that the Javascript idiom of - passing form results by setting a hidden field cannot - be performed using the normal SimpleTest - commands. See below for a way to test such forms. - </p> - - <h2> -<a class="target" name="multiple"></a>Fields with multiple values</h2> - <p> - SimpleTest can cope with two types of multivalue controls: Multiple - selection drop downs, and multiple checkboxes with the same name - within a form. - The multivalue nature of these means that setting and testing - are slightly different. - Using checkboxes as an example... -<pre> -<form class="demo"> - <strong>Create privileges allowed:</strong> - <input type="checkbox" name="crud" value="c" checked><br> - <strong>Retrieve privileges allowed:</strong> - <input type="checkbox" name="crud" value="r" checked><br> - <strong>Update privileges allowed:</strong> - <input type="checkbox" name="crud" value="u" checked><br> - <strong>Destroy privileges allowed:</strong> - <input type="checkbox" name="crud" value="d" checked><br> - <input type="submit" value="Enable Privileges"> -</form> -</pre> - Which renders as... - </p> - <p> - <form class="demo"> - <strong>Create privileges allowed:</strong> - <input type="checkbox" name="crud" value="c" checked><br> - <strong>Retrieve privileges allowed:</strong> - <input type="checkbox" name="crud" value="r" checked><br> - <strong>Update privileges allowed:</strong> - <input type="checkbox" name="crud" value="u" checked><br> - <strong>Destroy privileges allowed:</strong> - <input type="checkbox" name="crud" value="d" checked><br> - <input type="submit" value="Enable Privileges"> - </form> - </p> - <p> - If we wish to disable all but the retrieval privileges and - submit this information we can do it like this... -<pre> -class SimpleFormTests extends WebTestCase { - ...<strong> - function testDisableNastyPrivileges() { - $this->get('http://www.lastcraft.com/form_testing_documentation.php'); - $this->assertField('crud', array('c', 'r', 'u', 'd')); - $this->setField('crud', array('r')); - $this->click('Enable Privileges'); - }</strong> -} -</pre> - Instead of setting the field to a single value, we give it a list - of values. - We do the same when testing expected values. - We can then write other test code to confirm the effect of this, perhaps - by logging in as that user and attempting an update. - </p> - - <h2> -<a class="target" name="hidden-field"></a>Forms which use javascript to set a hidden field</h2> - <p> - If you want to test a form which relies on javascript to set a hidden - field, you can't just call setField(). - The following code will <em>not</em> work: -<pre> -class SimpleFormTests extends WebTestCase { - function testEmulateMyJavascriptForm() { - <strong>// This does *not* work</strong> - $this->setField('a_hidden_field', '123'); - $this->clickSubmit('OK'); - } -} -</pre> - Instead, you need to pass the additional form parameters to the - clickSubmit() method: -<pre> -class SimpleFormTests extends WebTestCase { - function testMyJavascriptForm() { - <strong>$this->clickSubmit('OK', array('a_hidden_field'=>'123'));</strong> - } - -} -</pre> - Bear in mind that in doing this you're effectively stubbing out a - part of your software (the javascript code in the form), and - perhaps you might be better off using something like - <a href="http://selenium.openqa.org/">Selenium</a> to ensure a complete - test. - </p> - - <h2> -<a class="target" name="raw"></a>Raw posting</h2> - <p> - If you want to test a form handler, but have not yet written - or do not have access to the form itself, you can create a - form submission by hand. -<pre> -class SimpleFormTests extends WebTestCase { - ...<strong> - function testAttemptedHack() { - $this->post( - 'http://www.my-site.com/add_user.php', - array('type' => 'superuser')); - $this->assertNoText('user created'); - }</strong> -} -</pre> - By adding data to the <span class="new_code">WebTestCase::post()</span> - method, we are emulating a form submission. - You would normally only do this as a temporary expedient, or where - you are expecting a 3rd party to submit to a form. - The exception is when you want tests to protect you from - attempts to spoof your pages. - </p> - - </div> - References and related information... - <ul> -<li> - SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a> - gives full detail on the classes and assertions available. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <span class="chosen">Testing forms</span> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/en/group_test_documentation.html b/3rdparty/simpletest/docs/en/group_test_documentation.html deleted file mode 100644 index 10f22a2b1b916dbee5c25c9ac2aefb651ca68ee3..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/group_test_documentation.html +++ /dev/null @@ -1,252 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>SimpleTest for PHP test suites</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <span class="chosen">Group tests</span> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Test suite documentation</h1> - This page... - <ul> -<li> - Different ways to <a href="#group">group tests</a> together. - </li> -<li> - Combining group tests into <a href="#higher">larger groups</a>. - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="group"></a>Grouping tests into suites</h2> - <p> - There are many ways to group tests together into test suites. - One way is to simply place multiple test cases into a single file... -<pre> -<strong><?php -require_once(dirname(__FILE__) . '/simpletest/autorun.php'); -require_once(dirname(__FILE__) . '/../classes/io.php'); - -class FileTester extends UnitTestCase { - ... -} - -class SocketTester extends UnitTestCase { - ... -} -?></strong> -</pre> - As many cases as needed can appear in a single file. - They should include any code they need, such as the library - being tested, but need none of the SimpleTest libraries. - </p> - <p> - Occasionally special subclasses are created that methods useful - for testing part of the application. - These new base classes are then used in place of <span class="new_code">UnitTestCase</span> - or <span class="new_code">WebTestCase</span>. - You don't normally want to run these as test cases. - Simply mark any base test cases that should not be run as abstract... -<pre> -<strong>abstract</strong> class MyFileTestCase extends UnitTestCase { - ... -} - -class FileTester extends MyFileTestCase { ... } - -class SocketTester extends UnitTestCase { ... } -</pre> - Here the <span class="new_code">FileTester</span> class does - not contain any actual tests, but is the base class for other - test cases. - </p> - <p> - We will call this sample <em>file_test.php</em>. - Currently the test cases are grouped simply by being in the same file. - We can build larger constructs just by including other test files in. -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('file_test.php'); -?> -</pre> - This will work, but create a purely flat hierarchy. - INstead we create a test suite file. - Our top level test suite can look like this... -<pre> -<?php -require_once('simpletest/autorun.php'); - -class AllFileTests extends TestSuite { - function __construct() { - parent::__construct(); - <strong>$this->addFile('file_test.php');</strong> - } -} -?> -</pre> - What happens here is that the <span class="new_code">TestSuite</span> - class will do the <span class="new_code">require_once()</span> - for us. - It then checks to see if any new test case classes - have been created by the new file and automatically composes - them to the test suite. - This method gives us the most control as we just manually add - more test files as our test suite grows. - </p> - <p> - If this is too much typing, and you are willing to group - test suites together in their own directories or otherwise - tag the file names, then there is a more automatic way... -<pre> -<?php -require_once('simpletest/autorun.php'); - -class AllFileTests extends TestSuite { - function __construct() { - parent::__construct(); - $this->collect(dirname(__FILE__) . '/unit', - new SimplePatternCollector('/_test.php/')); - } -} -?> -</pre> - This will scan a directory called "unit" for any files - ending with "_test.php" and load them. - You don't have to use <span class="new_code">SimplePatternCollector</span> to - filter by a pattern in the filename, but this is the most common - usage. - </p> - <p> - That snippet above is very common in practice. - Now all you have to do is drop a file of test cases into the - directory and it will run just by running the test suite script. - </p> - <p> - The catch is that you cannot control the order in which the test - cases are run. - If you want to see lower level components fail first in the test suite, - and this will make diagnosis a lot easier, then you should manually - call <span class="new_code">addFile()</span> for these. - Tests cases are only loaded once, so it's fine to have these included - again by a directory scan. - </p> - <p> - Test cases loaded with the <span class="new_code">addFile</span> method have some - useful properties. - You can guarantee that the constructor is run - just before the first test method and the destructor - is run just after the last test method. - This allows you to place test case wide set up and tear down - code in the constructor and destructor, just like a normal - class. - </p> - - <h2> -<a class="target" name="higher"></a>Composite suites</h2> - <p> - The above method places all of the test cases into one large suite. - For larger projects though this may not be flexible enough; you - may want to group the tests together in all sorts of ways. - </p> - <p> - Everything we have described so far with test scripts applies to - <span class="new_code">TestSuite</span>s as well... -<pre> -<?php -require_once('simpletest/autorun.php'); -<strong> -class BigTestSuite extends TestSuite { - function __construct() { - parent::__construct(); - $this->addFile('file_tests.php'); - } -}</strong> -?> -</pre> - This effectively adds our test cases and a single suite below - the first. - When a test fails, we see the breadcrumb trail of the nesting. - We can even mix groups and test cases freely as long as - we are careful about loops in our includes. -<pre> -<?php -require_once('simpletest/autorun.php'); - -class BigTestSuite extends TestSuite { - function __construct() { - parent::__construct(); - $this->addFile('file_tests.php'); - <strong>$this->addFile('some_other_test.php');</strong> - } -} -?> -</pre> - Note that in the event of a double include, ony the first instance - of the test case will be run. - </p> - - </div> - References and related information... - <ul> -<li> - SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <span class="chosen">Group tests</span> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/en/index.html b/3rdparty/simpletest/docs/en/index.html deleted file mode 100644 index 9f022d6b10b304596c86803fd6b89d932e879502..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/index.html +++ /dev/null @@ -1,542 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title> - Download the SimpleTest testing framework - - Unit tests and mock objects for PHP - </title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<span class="chosen">SimpleTest</span> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>SimpleTest for PHP</h1> - This page... - <ul> -<li> - <a href="#unit">Using unit tester</a> - with an example. - </li> -<li> - <a href="#group">Grouping tests</a> - for testing with one click. - </li> -<li> - <a href="#mock">Using mock objects</a> - to ease testing and gain tighter control. - </li> -<li> - <a href="#web">Testing web pages</a> - at the browser level. - </li> -</ul> -<div class="content"> - - - <p> - The following assumes that you are familiar with the concept - of unit testing as well as the PHP web development language. - It is a guide for the impatient new user of - <a href="https://sourceforge.net/project/showfiles.php?group_id=76550">SimpleTest</a>. - For fuller documentation, especially if you are new - to unit testing see the ongoing - <a href="unit_test_documentation.html">documentation</a>, and for - example test cases see the - <a href="http://www.lastcraft.com/first_test_tutorial.php">unit testing tutorial</a>. - </p> - - <h2> -<a class="target" name="unit"></a>Using the tester quickly</h2> - <p> - Amongst software testing tools, a unit tester is the one - closest to the developer. - In the context of agile development the test code sits right - next to the source code as both are written simultaneously. - In this context SimpleTest aims to be a complete PHP developer - test solution and is called "Simple" because it - should be easy to use and extend. - It wasn't a good choice of name really. - It includes all of the typical functions you would expect from - <a href="http://www.junit.org/">JUnit</a> and the - <a href="http://sourceforge.net/projects/phpunit/">PHPUnit</a> - ports, and includes - <a href="http://www.mockobjects.com">mock objects</a>. - </p> - <p> - What makes this tool immediately useful to the PHP developer is the internal - web browser. - This allows tests that navigate web sites, fill in forms and test pages. - Being able to write these test in PHP means that it is easy to write - integrated tests. - An example might be confirming that a user was written to a database - after a signing up through the web site. - </p> - <p> - The quickest way to demonstrate SimpleTest is with an example. - </p> - <p> - Let us suppose we are testing a simple file logging class called - <span class="new_code">Log</span> in <em>classes/log.php</em>. - We start by creating a test script which we will call - <em>tests/log_test.php</em> and populate it as follows... -<pre> -<?php -<strong>require_once('simpletest/autorun.php');</strong> -require_once('../classes/log.php'); - -class TestOfLogging extends <strong>UnitTestCase</strong> { -} -?> -</pre> - Here the <em>simpletest</em> folder is either local or in the path. - You would have to edit these locations depending on where you - unpacked the toolset. - The "autorun.php" file does more than just include the - SimpleTest files, it also runs our test for us. - </p> - <p> - The <span class="new_code">TestOfLogging</span> is our first test case and it's - currently empty. - Each test case is a class that extends one of the SimpleTet base classes - and we can have as many of these in the file as we want. - </p> - <p> - With three lines of scaffolding, and our <span class="new_code">Log</span> class - include, we have a test suite. - No tests though. - </p> - <p> - For our first test, we'll assume that the <span class="new_code">Log</span> class - takes the file name to write to in the constructor, and we have - a temporary folder in which to place this file... -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('../classes/log.php'); - -class TestOfLogging extends UnitTestCase { - function <strong>testLogCreatesNewFileOnFirstMessage()</strong> { - @unlink('/temp/test.log'); - $log = new Log('/temp/test.log'); - <strong>$this->assertFalse(file_exists('/temp/test.log'));</strong> - $log->message('Should write this to a file'); - <strong>$this->assertTrue(file_exists('/temp/test.log'));</strong> - } -} -?> -</pre> - When a test case runs, it will search for any method that - starts with the string "test" - and execute that method. - If the method starts "test", it's a test. - Note the very long name <span class="new_code">testLogCreatesNewFileOnFirstMessage()</span>. - This is considered good style and makes the test output more readable. - </p> - <p> - We would normally have more than one test method in a test case, - but that's for later. - </p> - <p> - Assertions within the test methods trigger messages to the - test framework which displays the result immediately. - This immediate response is important, not just in the event - of the code causing a crash, but also so that - <span class="new_code">print</span> statements can display - their debugging content right next to the assertion concerned. - </p> - <p> - To see these results we have to actually run the tests. - No other code is necessary - we can just open the page - with our browser. - </p> - <p> - On failure the display looks like this... - <div class="demo"> - <h1>TestOfLogging</h1> - <span class="fail">Fail</span>: testLogCreatesNewFileOnFirstMessage->True assertion failed.<br> - <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete. - <strong>1</strong> passes and <strong>1</strong> fails.</div> - </div> - ...and if it passes like this... - <div class="demo"> - <h1>TestOfLogging</h1> - <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete. - <strong>2</strong> passes and <strong>0</strong> fails.</div> - </div> - And if you get this... - <div class="demo"> - <b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b> - </div> - it means you're missing the <em>classes/Log.php</em> file that could look like... -<pre> -<?php<strong> -class Log { - function Log($file_path) { - } - - function message() { - } -}</strong> -?> -</pre> - It's fun to write the code after the test. - More than fun even - - this system is called "Test Driven Development". - </p> - <p> - For more information about <span class="new_code">UnitTestCase</span>, see - the <a href="unit_test_documentation.html">unit test documentation</a>. - </p> - - <h2> -<a class="target" name="group"></a>Building test suites</h2> - <p> - It is unlikely in a real application that we will only ever run - one test case. - This means that we need a way of grouping cases into a test - script that can, if need be, run every test for the application. - </p> - <p> - Our first step is to create a new file called <em>tests/all_tests.php</em> - and insert the following code... -<pre> -<?php -<strong>require_once('simpletest/autorun.php');</strong> - -class AllTests extends <strong>TestSuite</strong> { - function AllTests() { - $this->TestSuite(<strong>'All tests'</strong>); - <strong>$this->addFile('log_test.php');</strong> - } -} -?> -</pre> - The "autorun" include allows our upcoming test suite - to be run just by invoking this script. - </p> - <p> - The <span class="new_code">TestSuite</span> subclass must chain it's constructor. - This limitation will be removed in future versions. - </p> - <p> - The method <span class="new_code">TestSuite::addFile()</span> - will include the test case file and read any new classes - that are descended from <span class="new_code">SimpleTestCase</span>. - <span class="new_code">UnitTestCase</span> is just one example of a class derived from - <span class="new_code">SimpleTestCase</span>, and you can create your own. - <span class="new_code">TestSuite::addFile()</span> can include other test suites. - </p> - <p> - The class will not be instantiated yet. - When the test suite runs it will construct each instance once - it reaches that test, then destroy it straight after. - This means that the constructor is run just before each run - of that test case, and the destructor is run before the next test case starts. - </p> - <p> - It is common to group test case code into superclasses which are not - supposed to run, but become the base classes of other tests. - For "autorun" to work properly the test case file should not blindly run - any other test case extensions that do not actually run tests. - This could result in extra test cases being counted during the test - run. - Hardly a major problem, but to avoid this inconvenience simply mark your - base class as <span class="new_code">abstract</span>. - SimpleTest won't run abstract classes. - If you are still using PHP4, then - a <span class="new_code">SimpleTestOptions::ignore()</span> directive - somewhere in the test case file will have the same effect. - </p> - <p> - Also, the test case file should not have been included - elsewhere or no cases will be added to this group test. - This would be a more serious error as if the test case classes are - already loaded by PHP the <span class="new_code">TestSuite::addFile()</span> - method will not detect them. - </p> - <p> - To display the results it is necessary only to invoke - <em>tests/all_tests.php</em> from the web server or the command line. - </p> - <p> - For more information about building test suites, - see the <a href="group_test_documentation.html">test suite documentation</a>. - </p> - - <h2> -<a class="target" name="mock"></a>Using mock objects</h2> - <p> - Let's move further into the future and do something really complicated. - </p> - <p> - Assume that our logging class is tested and completed. - Assume also that we are testing another class that is - required to write log messages, say a - <span class="new_code">SessionPool</span>. - We want to test a method that will probably end up looking - like this... -<pre><strong> -class SessionPool { - ... - function logIn($username) { - ... - $this->_log->message("User $username logged in."); - ... - } - ... -} -</strong> -</pre> - In the spirit of reuse, we are using our - <span class="new_code">Log</span> class. - A conventional test case might look like this... -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('../classes/log.php'); -<strong>require_once('../classes/session_pool.php');</strong> - -class <strong>TestOfSessionLogging</strong> extends UnitTestCase { - - function setUp() { - <strong>@unlink('/temp/test.log');</strong> - } - - function tearDown() { - <strong>@unlink('/temp/test.log');</strong> - } - - function testLoggingInIsLogged() { - <strong>$log = new Log('/temp/test.log'); - $session_pool = &new SessionPool($log); - $session_pool->logIn('fred');</strong> - $messages = file('/temp/test.log'); - $this->assertEqual($messages[0], "User fred logged in.<strong>\n</strong>"); - } -} -?> -</pre> - We'll explain the <span class="new_code">setUp()</span> and <span class="new_code">tearDown()</span> - methods later. - </p> - <p> - This test case design is not all bad, but it could be improved. - We are spending time fiddling with log files which are - not part of our test. - We have created close ties with the <span class="new_code">Log</span> class and - this test. - What if we don't use files any more, but use ths - <em>syslog</em> library instead? - It means that our <span class="new_code">TestOfSessionLogging</span> test will - fail, even thouh it's not testing Logging. - </p> - <p> - It's fragile in smaller ways too. - Did you notice the extra carriage return in the message? - Was that added by the logger? - What if it also added a time stamp or other data? - </p> - <p> - The only part that we really want to test is that a particular - message was sent to the logger. - We can reduce coupling if we pass in a fake logging class - that simply records the message calls for testing, but - takes no action. - It would have to look exactly like our original though. - </p> - <p> - If the fake object doesn't write to a file then we save on deleting - the file before and after each test. We could save even more - test code if the fake object would kindly run the assertion for us. - <p> - </p> - Too good to be true? - We can create such an object easily... -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('../classes/log.php'); -require_once('../classes/session_pool.php'); - -<strong>Mock::generate('Log');</strong> - -class TestOfSessionLogging extends UnitTestCase { - - function testLoggingInIsLogged() {<strong> - $log = &new MockLog(); - $log->expectOnce('message', array('User fred logged in.'));</strong> - $session_pool = &new SessionPool(<strong>$log</strong>); - $session_pool->logIn('fred'); - } -} -?> -</pre> - The <span class="new_code">Mock::generate()</span> call code generated a new class - called <span class="new_code">MockLog</span>. - This looks like an identical clone, except that we can wire test code - to it. - That's what <span class="new_code">expectOnce()</span> does. - It says that if <span class="new_code">message()</span> is ever called on me, it had - better be with the parameter "User fred logged in.". - </p> - <p> - The test will be triggered when the call to - <span class="new_code">message()</span> is invoked on the - <span class="new_code">MockLog</span> object by <span class="new_code">SessionPool::logIn()</span> code. - The mock call will trigger a parameter comparison and then send the - resulting pass or fail event to the test display. - Wildcards can be included here too, so you don't have to test every parameter of - a call when you only want to test one. - </p> - <p> - If the mock reaches the end of the test case without the - method being called, the <span class="new_code">expectOnce()</span> - expectation will trigger a test failure. - In other words the mocks can detect the absence of - behaviour as well as the presence. - </p> - <p> - The mock objects in the SimpleTest suite can have arbitrary - return values set, sequences of returns, return values - selected according to the incoming arguments, sequences of - parameter expectations and limits on the number of times - a method is to be invoked. - </p> - <p> - For more information about mocking and stubbing, see the - <a href="mock_objects_documentation.html">mock objects documentation</a>. - </p> - - <h2> -<a class="target" name="web"></a>Web page testing</h2> - <p> - One of the requirements of web sites is that they produce web - pages. - If you are building a project top-down and you want to fully - integrate testing along the way then you will want a way of - automatically navigating a site and examining output for - correctness. - This is the job of a web tester. - </p> - <p> - The web testing in SimpleTest is fairly primitive, as there is - no JavaScript. - Most other browser operations are simulated. - </p> - <p> - To give an idea here is a trivial example where a home - page is fetched, from which we navigate to an "about" - page and then test some client determined content. -<pre> -<?php -require_once('simpletest/autorun.php'); -<strong>require_once('simpletest/web_tester.php');</strong> - -class TestOfAbout extends <strong>WebTestCase</strong> { - function testOurAboutPageGivesFreeReignToOurEgo() { - <strong>$this->get('http://test-server/index.php'); - $this->click('About'); - $this->assertTitle('About why we are so great'); - $this->assertText('We are really great');</strong> - } -} -?> -</pre> - With this code as an acceptance test, you can ensure that - the content always meets the specifications of both the - developers, and the other project stakeholders. - </p> - <p> - You can navigate forms too... -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('simpletest/web_tester.php'); - -class TestOfRankings extends WebTestCase { - function testWeAreTopOfGoogle() { - $this->get('http://google.com/'); - $this->setField('q', 'simpletest'); - $this->click("I'm Feeling Lucky"); - $this->assertTitle('SimpleTest - Unit Testing for PHP'); - } -} -?> -</pre> - ...although this could violate Google's(tm) terms and conditions. - </p> - <p> - For more information about web testing, see the - <a href="browser_documentation.html">scriptable - browser documentation</a> and the - <a href="web_tester_documentation.html">WebTestCase</a>. - </p> - <p> - <a href="http://sourceforge.net/projects/simpletest/"><img src="http://sourceforge.net/sflogo.php?group_id=76550&type=5" width="210" height="62" border="0" alt="SourceForge.net Logo"></a> - </p> - - </div> - References and related information... - <ul> -<li> - <a href="https://sourceforge.net/project/showfiles.php?group_id=76550&release_id=153280">Download PHP SimpleTest</a> - from <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a> - gives full detail on the classes and assertions available. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<span class="chosen">SimpleTest</span> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/en/mock_objects_documentation.html b/3rdparty/simpletest/docs/en/mock_objects_documentation.html deleted file mode 100644 index b4697f9ee3b74fb0b258d83ba2ca8a528fbe76ab..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/mock_objects_documentation.html +++ /dev/null @@ -1,870 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>SimpleTest for PHP mock objects documentation</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <span class="chosen">Mock objects</span> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Mock objects documentation</h1> - This page... - <ul> -<li> - <a href="#what">What are mock objects?</a> - </li> -<li> - <a href="#creation">Creating mock objects</a>. - </li> -<li> - <a href="#expectations">Mocks as critics</a> with expectations. - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="what"></a>What are mock objects?</h2> - <p> - Mock objects have two roles during a test case: actor and critic. - </p> - <p> - The actor behaviour is to simulate objects that are difficult to - set up or time consuming to set up for a test. - The classic example is a database connection. - Setting up a test database at the start of each test would slow - testing to a crawl and would require the installation of the - database engine and test data on the test machine. - If we can simulate the connection and return data of our - choosing we not only win on the pragmatics of testing, but can - also feed our code spurious data to see how it responds. - We can simulate databases being down or other extremes - without having to create a broken database for real. - In other words, we get greater control of the test environment. - </p> - <p> - If mock objects only behaved as actors they would simply be - known as "server stubs". - This was originally a pattern named by Robert Binder (<a href="">Testing - object-oriented systems</a>: models, patterns, and tools, - Addison-Wesley) in 1999. - </p> - <p> - A server stub is a simulation of an object or component. - It should exactly replace a component in a system for test - or prototyping purposes, but remain lightweight. - This allows tests to run more quickly, or if the simulated - class has not been written, to run at all. - </p> - <p> - However, the mock objects not only play a part (by supplying chosen - return values on demand) they are also sensitive to the - messages sent to them (via expectations). - By setting expected parameters for a method call they act - as a guard that the calls upon them are made correctly. - If expectations are not met they save us the effort of - writing a failed test assertion by performing that duty on our - behalf. - </p> - <p> - In the case of an imaginary database connection they can - test that the query, say SQL, was correctly formed by - the object that is using the connection. - Set them up with fairly tight expectations and you will - hardly need manual assertions at all. - </p> - - <h2> -<a class="target" name="creation"></a>Creating mock objects</h2> - <p> - All we need is an existing class or interface, say a database connection - that looks like this... -<pre> -<strong>class DatabaseConnection { - function DatabaseConnection() { } - function query($sql) { } - function selectQuery($sql) { } -}</strong> -</pre> - To create a mock version of the class we need to run a - code generator... -<pre> -require_once('simpletest/autorun.php'); -require_once('database_connection.php'); - -<strong>Mock::generate('DatabaseConnection');</strong> -</pre> - This code generates a clone class called - <span class="new_code">MockDatabaseConnection</span>. - This new class appears to be the same, but actually has no behaviour at all. - </p> - <p> - The new class is usually a subclass of <span class="new_code">DatabaseConnection</span>. - Unfortunately, there is no way to create a mock version of a - class with a <span class="new_code">final</span> method without having a living version of - that method. - We consider that unsafe. - If the target is an interface, or if <span class="new_code">final</span> methods are - present in a target class, then a whole new class - is created, but one implemeting the same interfaces. - If you try to pass this separate class through a type hint that specifies - the old concrete class name, it will fail. - Code like that insists on type hinting to a class with <span class="new_code">final</span> - methods probably cannot be safely tested with mocks. - </p> - <p> - If you want to see the generated code, then simply <span class="new_code">print</span> - the output of <span class="new_code">Mock::generate()</span>. - Here is the generated code for the <span class="new_code">DatabaseConnection</span> - class rather than the interface version... -<pre> -class MockDatabaseConnection extends DatabaseConnection { - public $mock; - protected $mocked_methods = array('databaseconnection', 'query', 'selectquery'); - - function MockDatabaseConnection() { - $this->mock = new SimpleMock(); - $this->mock->disableExpectationNameChecks(); - } - ... - function DatabaseConnection() { - $args = func_get_args(); - $result = &$this->mock->invoke("DatabaseConnection", $args); - return $result; - } - function query($sql) { - $args = func_get_args(); - $result = &$this->mock->invoke("query", $args); - return $result; - } - function selectQuery($sql) { - $args = func_get_args(); - $result = &$this->mock->invoke("selectQuery", $args); - return $result; - } -} -</pre> - Your output may vary depending on the exact version - of SimpleTest you are using. - </p> - <p> - Besides the original methods of the class, you will see some extra - methods that help testing. - More on these later. - </p> - <p> - We can now create instances of the new class within - our test case... -<pre> -require_once('simpletest/autorun.php'); -require_once('database_connection.php'); - -Mock::generate('DatabaseConnection'); - -class MyTestCase extends UnitTestCase { - - function testSomething() { - <strong>$connection = new MockDatabaseConnection();</strong> - } -} -</pre> - The mock version now has all the methods of the original. - Also, any type hints will be faithfully preserved. - Say our query methods expect a <span class="new_code">Query</span> object... -<pre> -<strong>class DatabaseConnection { - function DatabaseConnection() { } - function query(Query $query) { } - function selectQuery(Query $query) { } -}</strong> -</pre> - If we now pass the wrong type of object, or worse a non-object... -<pre> -class MyTestCase extends UnitTestCase { - - function testSomething() { - $connection = new MockDatabaseConnection(); - $connection->query('insert into accounts () values ()'); - } -} -</pre> - ...the code will throw a type violation at you just as the - original class would. - </p> - <p> - The mock version now has all the methods of the original. - Unfortunately, they all return <span class="new_code">null</span>. - As methods that always return <span class="new_code">null</span> are not that useful, - we need to be able to set them to something else... - </p> - <p> - <a class="target" name="stub"><h2>Mocks as actors</h2></a> - </p> - <p> - Changing the return value of a method from <span class="new_code">null</span> - to something else is pretty easy... -<pre> -<strong>$connection->returns('query', 37)</strong> -</pre> - Now every time we call - <span class="new_code">$connection->query()</span> we get - the result of 37. - There is nothing special about 37. - The return value can be arbitrarily complicated. - </p> - <p> - Parameters are irrelevant here, we always get the same - values back each time once they have been set up this way. - That may not sound like a convincing replica of a - database connection, but for the half a dozen lines of - a test method it is usually all you need. - </p> - <p> - Things aren't always that simple though. - One common problem is iterators, where constantly returning - the same value could cause an endless loop in the object - being tested. - For these we need to set up sequences of values. - Let's say we have a simple iterator that looks like this... -<pre> -class Iterator { - function Iterator() { } - function next() { } -} -</pre> - This is about the simplest iterator you could have. - Assuming that this iterator only returns text until it - reaches the end, when it returns false, we can simulate it - with... -<pre> -Mock::generate('Iterator'); - -class IteratorTest extends UnitTestCase() { - - function testASequence() {<strong> - $iterator = new MockIterator(); - $iterator->returns('next', false); - $iterator->returnsAt(0, 'next', 'First string'); - $iterator->returnsAt(1, 'next', 'Second string');</strong> - ... - } -} -</pre> - When <span class="new_code">next()</span> is called on the - <span class="new_code">MockIterator</span> it will first return "First string", - on the second call "Second string" will be returned - and on any other call <span class="new_code">false</span> will - be returned. - The sequenced return values take precedence over the constant - return value. - The constant one is a kind of default if you like. - </p> - <p> - Another tricky situation is an overloaded - <span class="new_code">get()</span> operation. - An example of this is an information holder with name/value pairs. - Say we have a configuration class like... -<pre> -class Configuration { - function Configuration() { ... } - function get($key) { ... } -} -</pre> - This is a likely situation for using mock objects, as - actual configuration will vary from machine to machine and - even from test to test. - The problem though is that all the data comes through the - <span class="new_code">get()</span> method and yet - we want different results for different keys. - Luckily the mocks have a filter system... -<pre> -<strong>$config = &new MockConfiguration(); -$config->returns('get', 'primary', array('db_host')); -$config->returns('get', 'admin', array('db_user')); -$config->returns('get', 'secret', array('db_password'));</strong> -</pre> - The extra parameter is a list of arguments to attempt - to match. - In this case we are trying to match only one argument which - is the look up key. - Now when the mock object has the - <span class="new_code">get()</span> method invoked - like this... -<pre> -$config->get('db_user') -</pre> - ...it will return "admin". - It finds this by attempting to match the calling arguments - to its list of returns one after another until - a complete match is found. - </p> - <p> - You can set a default argument argument like so... -<pre><strong> -$config->returns('get', false, array('*'));</strong> -</pre> - This is not the same as setting the return value without - any argument requirements like this... -<pre><strong> -$config->returns('get', false);</strong> -</pre> - In the first case it will accept any single argument, - but exactly one is required. - In the second case any number of arguments will do and - it acts as a catchall after all other matches. - Note that if we add further single parameter options after - the wildcard in the first case, they will be ignored as the wildcard - will match first. - With complex parameter lists the ordering could be important - or else desired matches could be masked by earlier wildcard - ones. - Declare the most specific matches first if you are not sure. - </p> - <p> - There are times when you want a specific reference to be - dished out by the mock rather than a copy or object handle. - This a rarity to say the least, but you might be simulating - a container that can hold primitives such as strings. - For example... -<pre> -class Pad { - function Pad() { } - function &note($index) { } -} -</pre> - In this case you can set a reference into the mock's - return list... -<pre> -function testTaskReads() { - $note = 'Buy books'; - $pad = new MockPad(); - $vector-><strong>returnsByReference(</strong>'note', $note, array(3)<strong>)</strong>; - $task = new Task($pad); - ... -} -</pre> - With this arrangement you know that every time - <span class="new_code">$pad->note(3)</span> is - called it will return the same <span class="new_code">$note</span> each time, - even if it get's modified. - </p> - <p> - These three factors, timing, parameters and whether to copy, - can be combined orthogonally. - For example... -<pre> -$buy_books = 'Buy books'; -$write_code = 'Write code'; -$pad = new MockPad(); -$vector-><strong>returnsByReferenceAt(0, 'note', $buy_books, array('*', 3));</strong> -$vector-><strong>returnsByReferenceAt(1, 'note', $write_code, array('*', 3));</strong> -</pre> - This will return a reference to <span class="new_code">$buy_books</span> and - then to <span class="new_code">$write_code</span>, but only if two parameters - were set the second of which must be the integer 3. - That should cover most situations. - </p> - <p> - A final tricky case is one object creating another, known - as a factory pattern. - Suppose that on a successful query to our imaginary - database, a result set is returned as an iterator, with - each call to the the iterator's <span class="new_code">next()</span> giving - one row until false. - This sounds like a simulation nightmare, but in fact it can all - be mocked using the mechanics above... -<pre> -Mock::generate('DatabaseConnection'); -Mock::generate('ResultIterator'); - -class DatabaseTest extends UnitTestCase { - - function testUserFinderReadsResultsFromDatabase() {<strong> - $result = new MockResultIterator(); - $result->returns('next', false); - $result->returnsAt(0, 'next', array(1, 'tom')); - $result->returnsAt(1, 'next', array(3, 'dick')); - $result->returnsAt(2, 'next', array(6, 'harry')); - - $connection = new MockDatabaseConnection(); - $connection->returns('selectQuery', $result);</strong> - - $finder = new UserFinder(<strong>$connection</strong>); - $this->assertIdentical( - $finder->findNames(), - array('tom', 'dick', 'harry')); - } -} -</pre> - Now only if our - <span class="new_code">$connection</span> is called with the - <span class="new_code">query()</span> method will the - <span class="new_code">$result</span> be returned that is - itself exhausted after the third call to <span class="new_code">next()</span>. - This should be enough - information for our <span class="new_code">UserFinder</span> class, - the class actually - being tested here, to come up with goods. - A very precise test and not a real database in sight. - </p> - <p> - We could refine this test further by insisting that the correct - query is sent... -<pre> -$connection->returns('selectQuery', $result, array(<strong>'select name, id from people'</strong>)); -</pre> - This is actually a bad idea. - </p> - <p> - We have a <span class="new_code">UserFinder</span> in object land, talking to - database tables using a large interface - the whole of SQL. - Imagine that we have written a lot of tests that now depend - on the exact SQL string passed. - These queries could change en masse for all sorts of reasons - not related to the specific test. - For example the quoting rules could change, a table name could - change, a link table added or whatever. - This would require the rewriting of every single test any time - one of these refactoring is made, yet the intended behaviour has - stayed the same. - Tests are supposed to help refactoring, not hinder it. - I'd certainly like to have a test suite that passes while I change - table names. - </p> - <p> - As a rule it is best not to mock a fat interface. - </p> - <p> - By contrast, here is the round trip test... -<pre> -class DatabaseTest extends UnitTestCase {<strong> - function setUp() { ... } - function tearDown() { ... }</strong> - - function testUserFinderReadsResultsFromDatabase() { - $finder = new UserFinder(<strong>new DatabaseConnection()</strong>); - $finder->add('tom'); - $finder->add('dick'); - $finder->add('harry'); - $this->assertIdentical( - $finder->findNames(), - array('tom', 'dick', 'harry')); - } -} -</pre> - This test is immune to schema changes. - It will only fail if you actually break the functionality, which - is what you want a test to do. - </p> - <p> - The catch is those <span class="new_code">setUp()</span> and <span class="new_code">tearDown()</span> - methods that we've rather glossed over. - They have to clear out the database tables and ensure that the - schema is defined correctly. - That can be a chunk of extra work, but you usually have this code - lying around anyway for deployment purposes. - </p> - <p> - One place where you definitely need a mock is simulating failures. - Say the database goes down while <span class="new_code">UserFinder</span> is doing - it's work. - Does <span class="new_code">UserFinder</span> behave well...? -<pre> -class DatabaseTest extends UnitTestCase { - - function testUserFinder() { - $connection = new MockDatabaseConnection();<strong> - $connection->throwOn('selectQuery', new TimedOut('Ouch!'));</strong> - $alert = new MockAlerts();<strong> - $alert->expectOnce('notify', 'Database is busy - please retry');</strong> - $finder = new UserFinder($connection, $alert); - $this->assertIdentical($finder->findNames(), array()); - } -} -</pre> - We've passed the <span class="new_code">UserFinder</span> an <span class="new_code">$alert</span> - object. - This is going to do some kind of pretty notifications in the - user interface in the event of an error. - We'd rather not sprinkle our code with hard wired <span class="new_code">print</span> - statements if we can avoid it. - Wrapping the means of output means we can use this code anywhere. - It also makes testing easier. - </p> - <p> - To pass this test, the finder has to write a nice user friendly - message to <span class="new_code">$alert</span>, rather than propogating the exception. - So far, so good. - </p> - <p> - How do we get the mock <span class="new_code">DatabaseConnection</span> to throw an exception? - We generate the exception using the <span class="new_code">throwOn</span> method - on the mock. - </p> - <p> - Finally, what if the method you want to simulate does not exist yet? - If you set a return value on a method that is not there, SimpleTest - will throw an error. - What if you are using <span class="new_code">__call()</span> to simulate dynamic methods? - </p> - <p> - Objects with dynamic interfaces, using <span class="new_code">__call</span>, can - be problematic with the current mock objects implementation. - You can mock the <span class="new_code">__call()</span> method, but this is ugly. - Why should a test know anything about such low level implementation details? - It just wants to simulate the call. - </p> - <p> - The way round this is to add extra methods to the mock when - generating it. -<pre> -<strong>Mock::generate('DatabaseConnection', 'MockDatabaseConnection', array('setOptions'));</strong> -</pre> - In a large test suite this could cause trouble, as you probably - already have a mock version of the class called - <span class="new_code">MockDatabaseConnection</span> without the extra methods. - The code generator will not generate a mock version of the class if - one of the same name already exists. - You will confusingly fail to see your method if another definition - was run first. - </p> - <p> - To cope with this, SimpleTest allows you to choose any name for the - new class at the same time as you add the extra methods. -<pre> -Mock::generate('DatabaseConnection', <strong>'MockDatabaseConnectionWithOptions'</strong>, array('setOptions')); -</pre> - Here the mock will behave as if the <span class="new_code">setOptions()</span> - existed in the original class. - </p> - <p> - Mock objects can only be used within test cases, as upon expectations - they send messages straight to the currently running test case. - Creating them outside a test case will cause a run time error - when an expectation is triggered and there is no running test case - for the message to end up. - We cover expectations next. - </p> - - <h2> -<a class="target" name="expectations"></a>Mocks as critics</h2> - <p> - Although the server stubs approach insulates your tests from - real world disruption, it is only half the benefit. - You can have the class under test receiving the required - messages, but is your new class sending correct ones? - Testing this can get messy without a mock objects library. - </p> - <p> - By way of example, let's take a simple <span class="new_code">PageController</span> - class to handle a credit card payment form... -<pre> -class PaymentForm extends PageController { - function __construct($alert, $payment_gateway) { ... } - function makePayment($request) { ... } -} -</pre> - This class takes a <span class="new_code">PaymentGateway</span> to actually talk - to the bank. - It also takes an <span class="new_code">Alert</span> object to handle errors. - This class talks to the page or template. - It's responsible for painting the error message and highlighting any - form fields that are incorrect. - </p> - <p> - It might look something like... -<pre> -class Alert { - function warn($warning, $id) { - print '<div class="warning">' . $warning . '</div>'; - print '<style type="text/css">#' . $id . ' { background-color: red }</style>'; - } -} -</pre> - </p> - <p> - Our interest is in the <span class="new_code">makePayment()</span> method. - If we fail to enter a "CVV2" number (the three digit number - on the back of the credit card), we want to show an error rather than - try to process the payment. - In test form... -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('payment_form.php'); -Mock::generate('Alert'); -Mock::generate('PaymentGateway'); - -class PaymentFormFailuresShouldBeGraceful extends UnitTestCase { - - function testMissingCvv2CausesAlert() { - $alert = new MockAlert(); - <strong>$alert->expectOnce( - 'warn', - array('Missing three digit security code', 'cvv2'));</strong> - $controller = new PaymentForm(<strong>$alert</strong>, new MockPaymentGateway()); - $controller->makePayment($this->requestWithMissingCvv2()); - } - - function requestWithMissingCvv2() { ... } -} -?> -</pre> - The first question you may be asking is, where are the assertions? - </p> - <p> - The call to <span class="new_code">expectOnce('warn', array(...))</span> instructs the mock - to expect a call to <span class="new_code">warn()</span> before the test ends. - When it gets a call to <span class="new_code">warn()</span>, it checks the arguments. - If the arguments don't match, then a failure is generated. - It also fails if the method is never called at all. - </p> - <p> - The test above not only asserts that <span class="new_code">warn</span> was called, - but that it received the string "Missing three digit security code" - and also the tag "cvv2". - The equivalent of <span class="new_code">assertIdentical()</span> is applied to both - fields when the parameters are compared. - </p> - <p> - If you are not interested in the actual message, and we are not - for user interface code that changes often, we can skip that - parameter with the "*" operator... -<pre> -class PaymentFormFailuresShouldBeGraceful extends UnitTestCase { - - function testMissingCvv2CausesAlert() { - $alert = new MockAlert(); - $alert->expectOnce('warn', array(<strong>'*'</strong>, 'cvv2')); - $controller = new PaymentForm($alert, new MockPaymentGateway()); - $controller->makePayment($this->requestWithMissingCvv2()); - } - - function requestWithMissingCvv2() { ... } -} -</pre> - We can weaken the test further by missing - out the parameters array... -<pre> -function testMissingCvv2CausesAlert() { - $alert = new MockAlert(); - <strong>$alert->expectOnce('warn');</strong> - $controller = new PaymentForm($alert, new MockPaymentGateway()); - $controller->makePayment($this->requestWithMissingCvv2()); -} -</pre> - This will only test that the method is called, - which is a bit drastic in this case. - Later on, we'll see how we can weaken the expectations more precisely. - </p> - <p> - Tests without assertions can be both compact and very expressive. - Because we intercept the call on the way into an object, here of - the <span class="new_code">Alert</span> class, we avoid having to assert its state - afterwards. - This not only avoids the assertions in the tests, but also having - to add extra test only accessors to the original code. - If you catch yourself adding such accessors, called "state based testing", - it's probably time to consider using mocks in the tests. - This is called "behaviour based testing", and is normally superior. - </p> - <p> - Let's add another test. - Let's make sure that we don't even attempt a payment without a CVV2... -<pre> -class PaymentFormFailuresShouldBeGraceful extends UnitTestCase { - - function testMissingCvv2CausesAlert() { ... } - - function testNoPaymentAttemptedWithMissingCvv2() { - $payment_gateway = new MockPaymentGateway(); - <strong>$payment_gateway->expectNever('pay');</strong> - $controller = new PaymentForm(new MockAlert(), $payment_gateway); - $controller->makePayment($this->requestWithMissingCvv2()); - } - - ... -} -</pre> - Asserting a negative can be very hard in tests, but - <span class="new_code">expectNever()</span> makes it easy. - </p> - <p> - <span class="new_code">expectOnce()</span> and <span class="new_code">expectNever()</span> are - sufficient for most tests, but - occasionally you want to test multiple events. - Normally for usability purposes we want all missing fields - in the form to light up, not just the first one. - This means that we should get multiple calls to - <span class="new_code">Alert::warn()</span>, not just one... -<pre> -function testAllRequiredFieldsHighlightedOnEmptyRequest() { - $alert = new MockAlert();<strong> - $alert->expectAt(0, 'warn', array('*', 'cc_number')); - $alert->expectAt(1, 'warn', array('*', 'expiry')); - $alert->expectAt(2, 'warn', array('*', 'cvv2')); - $alert->expectAt(3, 'warn', array('*', 'card_holder')); - $alert->expectAt(4, 'warn', array('*', 'address')); - $alert->expectAt(5, 'warn', array('*', 'postcode')); - $alert->expectAt(6, 'warn', array('*', 'country')); - $alert->expectCallCount('warn', 7);</strong> - $controller = new PaymentForm($alert, new MockPaymentGateway()); - $controller->makePayment($this->requestWithMissingCvv2()); -} -</pre> - The counter in <span class="new_code">expectAt()</span> is the number of times - the method has been called already. - Here we are asserting that every field will be highlighted. - </p> - <p> - Note that we are forced to assert the order too. - SimpleTest does not yet have a way to avoid this, but - this will be fixed in future versions. - </p> - <p> - Here is the full list of expectations you can set on a mock object - in <a href="http://simpletest.org/">SimpleTest</a>. - As with the assertions, these methods take an optional failure message. - <table> - <thead><tr> -<th>Expectation</th> -<th>Description</th> -</tr></thead> - <tbody> - <tr> - <td><span class="new_code">expect($method, $args)</span></td> - <td>Arguments must match if called</td> - </tr> - <tr> - <td><span class="new_code">expectAt($timing, $method, $args)</span></td> - <td>Arguments must match when called on the <span class="new_code">$timing</span>'th time</td> - </tr> - <tr> - <td><span class="new_code">expectCallCount($method, $count)</span></td> - <td>The method must be called exactly this many times</td> - </tr> - <tr> - <td><span class="new_code">expectMaximumCallCount($method, $count)</span></td> - <td>Call this method no more than <span class="new_code">$count</span> times</td> - </tr> - <tr> - <td><span class="new_code">expectMinimumCallCount($method, $count)</span></td> - <td>Must be called at least <span class="new_code">$count</span> times</td> - </tr> - <tr> - <td><span class="new_code">expectNever($method)</span></td> - <td>Must never be called</td> - </tr> - <tr> - <td><span class="new_code">expectOnce($method, $args)</span></td> - <td>Must be called once and with the expected arguments if supplied</td> - </tr> - <tr> - <td><span class="new_code">expectAtLeastOnce($method, $args)</span></td> - <td>Must be called at least once, and always with any expected arguments</td> - </tr> - </tbody> - </table> - Where the parameters are... - <dl> - <dt class="new_code">$method</dt> - <dd>The method name, as a string, to apply the condition to.</dd> - <dt class="new_code">$args</dt> - <dd> - The arguments as a list. Wildcards can be included in the same - manner as for <span class="new_code">setReturn()</span>. - This argument is optional for <span class="new_code">expectOnce()</span> - and <span class="new_code">expectAtLeastOnce()</span>. - </dd> - <dt class="new_code">$timing</dt> - <dd> - The only point in time to test the condition. - The first call starts at zero and the count is for - each method independently. - </dd> - <dt class="new_code">$count</dt> - <dd>The number of calls expected.</dd> - </dl> - </p> - <p> - If you have just one call in your test, make sure you're using - <span class="new_code">expectOnce</span>.<br> - Using <span class="new_code">$mocked->expectAt(0, 'method', 'args);</span> - on its own will allow the method to never be called. - Checking the arguments and the overall call count - are currently independant. - Add an <span class="new_code">expectCallCount()</span> expectation when you - are using <span class="new_code">expectAt()</span> unless zero calls is allowed. - </p> - <p> - Like the assertions within test cases, all of the expectations - can take a message override as an extra parameter. - Also the original failure message can be embedded in the output - as "%s". - </p> - - </div> - References and related information... - <ul> -<li> - The original - <a href="http://www.mockobjects.com/">Mock objects</a> paper. - </li> -<li> - SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - SimpleTest home page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <span class="chosen">Mock objects</span> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/en/overview.html b/3rdparty/simpletest/docs/en/overview.html deleted file mode 100644 index 85ea9407749f80184f9aeef213383421a3ec3733..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/overview.html +++ /dev/null @@ -1,487 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title> - Overview and feature list for the SimpleTest PHP unit tester and web tester - </title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <span class="chosen">Overview</span> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Overview of SimpleTest</h1> - This page... - <ul> -<li> - <a href="#summary">Quick summary</a> - of the SimpleTest tool for PHP. - </li> -<li> - <a href="#features">List of features</a>, - both current ones and those planned. - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="summary"></a>What is SimpleTest?</h2> - <p> - The heart of SimpleTest is a testing framework built around - test case classes. - These are written as extensions of base test case classes, - each extended with methods that actually contain test code. - Each test method of a test case class is written to invoke - various assertions that the developer expects to be true such as - <span class="new_code">assertEqual()</span>. - If the expectation is correct, then a successful result is - dispatched to the observing test reporter, but any failure - or unexpected exception triggers an alert and a description - of the mismatch. - These test case declarations are transformed into executable - test scripts by including a SimpleTest aurorun.php file. - </p> - <p> - These documents apply to SimpleTest version 1.1, although we - try hard to maintain compatibility between versions. - If you get a test failure after an upgrade, check out the - file "HELP_MY_TESTS_DONT_WORK_ANYMORE" in the - simpletest directory to see if a feature you are using - has since been deprecated and later removed. - </p> - <p> - A <a href="unit_test_documentation.html">test case</a> looks like this... -<pre> -<?php -require_once('simpletest/autorun.php'); - -class <strong>CanAddUp</strong> extends UnitTestCase {<strong> - function testOneAndOneMakesTwo() { - $this->assertEqual(1 + 1, 2); - }</strong> -} -?> -</pre> - Tests are grouped into test cases, which are just - PHP classes that extend <span class="new_code">UnitTestCase</span> - or <span class="new_code">WebTestCase</span>. - The tests themselves are just normal methods that start - their name with the letters "test". - You can have as many test cases as you want in a test - script and each test case can have as many test methods - as it wants too. - </p> - <p> - This test script is immediately runnable. - You just invoke it on the command line like so... -<pre class="shell"> -php adding_test.php -</pre> - </p> - <p> - When run on the command line you should see something like... -<pre class="shell"> -adding_test.php -OK -Test cases run: 1/1, Passes: 1, Failures: 0, Exceptions: 0 -</pre> - </p> - <p> - If you place it on a web server and point your - web browser at it... - <div class="demo"> - <h1>adding_test.php</h1> - <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete. - <strong>6</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div> - </div> - </p> - <p> - Of course this is a silly example. - A more realistic example might be... -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('log.php'); - -class <strong>TestOfLogging</strong> extends UnitTestCase { - function testWillCreateLogFileOnFirstMessage() { - $log = new Log('my.log'); - $this->assertFalse(file_exists('my.log')); - $log->message('Hello'); - $this->assertTrue(file_exists('my.log')); - }</strong> -} -?> -</pre> - </p> - <p> - This tool is designed for the developer. - The target audience of this tool is anyone developing a small - to medium PHP application, including developers new to - unit and web regression testing. - The core principles are ease of use first, with extendibility and - essential features. - </p> - <p> - Tests are written in the PHP language itself more or less - as the application itself is built. - The advantage of using PHP as the testing language is that - there are no new languages to learn, testing can start straight away, - and the developer can test any part of the code. - Basically, all parts that can be accessed by the application code can also be - accessed by the test code when they are in the same programming language. - </p> - <p> - The simplest type of test case is the - <a href="unit_tester_documentation.html">UnitTestCase</a>. - This class of test case includes standard tests for equality, - references and pattern matching. - All these test the typical expectations of what you would - expect the result of a function or method to be. - This is by far the most common type of test in the daily - routine of development, making up about 95% of test cases. - </p> - <p> - The top level task of a web application though is not to - produce correct output from its methods and objects, but - to generate web pages. - The <a href="web_tester_documentation.html">WebTestCase</a> class tests web - pages. - It simulates a web browser requesting a page, complete with - cookies, proxies, secure connections, authentication, forms, frames and most - navigation elements. - With this type of test case, the developer can assert that - information is present in the page and that forms and - sessions are handled correctly. - </p> - <p> - A <a href="web_tester_documentation.html">WebTestCase</a> looks like this... -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('simpletest/web_tester.php'); - -class <strong>MySiteTest</strong> extends WebTestCase { - <strong> - function testHomePageHasContactDetailsLink() { - $this->get('http://www.my-site.com/index.php'); - $this->assertTitle('My Home Page'); - $this->clickLink('Contact'); - $this->assertTitle('Contact me'); - $this->assertText('/Email me at/'); - }</strong> -} -?> -</pre> - </p> - - <h2> -<a class="target" name="features"></a>Feature list</h2> - <p> - The following is a very rough outline of past and future features - and their expected point of release. - I am afraid it is liable to change without warning, as meeting the - milestones rather depends on time available. - </p> - <p> - Green stuff has been coded, but not necessarily released yet. - If you have a pressing need for a green but unreleased feature - then you should check-out the code from Sourceforge SVN directly. - <table> -<thead> - <tr> -<th>Feature</th> -<th>Description</th> -<th>Release</th> -</tr> - </thead> -<tbody> -<tr> - <td>Unit test case</td> - <td>Core test case class and assertions</td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Html display</td> - <td>Simplest possible display</td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Autoloading of test cases</td> - <td> - Reading a file with test cases and loading them into a - group test automatically - </td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Mock objects</td> - <td> - Objects capable of simulating other objects removing - test dependencies - </td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Web test case</td> - <td>Allows link following and title tag matching</td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Partial mocks</td> - <td> - Mocking parts of a class for testing less than a class - or for complex simulations - </td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Web cookie handling</td> - <td>Correct handling of cookies when fetching pages</td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Following redirects</td> - <td>Page fetching automatically follows 300 redirects</td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Form parsing</td> - <td>Ability to submit simple forms and read default form values</td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Command line interface</td> - <td>Test display without the need of a web browser</td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Exposure of expectation classes</td> - <td>Can create precise tests with mocks as well as test cases</td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>XML output and parsing</td> - <td> - Allows multi host testing and the integration of acceptance - testing extensions - </td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Browser component</td> - <td> - Exposure of lower level web browser interface for more - detailed test cases - </td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>HTTP authentication</td> - <td> - Fetching protected web pages with basic authentication - only - </td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>SSL support</td> - <td>Can connect to https: pages</td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Proxy support</td> - <td>Can connect via. common proxies</td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>Frames support</td> - <td>Handling of frames in web test cases</td> - <td style="color: green;">1.0</td> - </tr> - <tr> - <td>File upload testing</td> - <td>Can simulate the input type file tag</td> - <td style="color: green;">1.0.1</td> - </tr> - <tr> - <td>Mocking interfaces</td> - <td> - Can generate mock objects to interfaces as well as classes - and class interfaces are carried for type hints - </td> - <td style="color: green;">1.0.1</td> - </tr> - <tr> - <td>Testing exceptions</td> - <td>Similar to testing PHP errors</td> - <td style="color: green;">1.0.1</td> - </tr> - <tr> - <td>HTML label support</td> - <td>Can access all controls using the visual label</td> - <td style="color: green;">1.0.1</td> - </tr> - <tr> - <td>Base tag support</td> - <td>Respects page base tag when clicking</td> - <td style="color: green;">1.0.1</td> - </tr> - <tr> - <td>PHP 5 E_STRICT compliant</td> - <td>PHP 5 only version that works with the E_STRICT error level</td> - <td style="color: green;">1.1</td> - </tr> - <tr> - <td>Alternate HTML parsers</td> - <td>Can detect compiled parsers for performance improvements</td> - <td style="color: green;">1.1</td> - </tr> - <tr> - <td>REST support</td> - <td>Support for REST verbs as put(), delete(), etc.</td> - <td style="color: green;">1.1</td> - </tr> - <tr> - <td>BDD style fixtures</td> - <td>Can import fixtures using a mixin like given() method</td> - <td style="color: red;">1.5</td> - </tr> - <tr> - <td>Plug-in architecture</td> - <td>Automatic import of extensions including command line options</td> - <td style="color: red;">1.5</td> - </tr> - <tr> - <td>Reporting machinery enhancements</td> - <td>Improved message passing for better cooperation with IDEs</td> - <td style="color: red;">1.5</td> - </tr> - <tr> - <td>Fluent mock interface</td> - <td>More flexible and concise mock objects</td> - <td style="color: red;">1.6</td> - </tr> - <tr> - <td>Localisation</td> - <td>Messages abstracted and code generated as well as UTF support</td> - <td style="color: red;">1.6</td> - </tr> - <tr> - <td>CSS selectors</td> - <td>HTML content can be examined using CSS selectors</td> - <td style="color: red;">1.7</td> - </tr> - <tr> - <td>HTML table assertions</td> - <td>Can match HTML or other table elements to expectations</td> - <td style="color: red;">1.7</td> - </tr> - <tr> - <td>Unified acceptance testing model</td> - <td>Content searchable through selectors combined with expectations</td> - <td style="color: red;">1.7</td> - </tr> - <tr> - <td>DatabaseTestCase</td> - <td>SQL selectors and DB drivers</td> - <td style="color: red;">1.7</td> - </tr> - <tr> - <td>IFrame support</td> - <td>Reads IFrame content that can be refreshed</td> - <td style="color: red;">1.8</td> - </tr> - <tr> - <td>Integrated Selenium support</td> - <td>Easy to use built in Selenium driver and tutorial or similar browser automation</td> - <td style="color: red;">1.9</td> - </tr> - <tr> - <td>Code coverage</td> - <td>Reports using the bundled tool when using XDebug</td> - <td style="color: red;">1.9</td> - </tr> - <tr> - <td>Deprecation of old methods</td> - <td>Simpler interface for SimpleTest2</td> - <td style="color: red;">2.0</td> - </tr> - <tr> - <td>Javascript suport</td> - <td>Use of PECL module to add Javascript to the native browser</td> - <td style="color: red;">3.0</td> - </tr> - </tbody> -</table> - PHP 5 migration is complete, which means that only PHP 5.0.3+ - will be supported in SimpleTest version 1.1+. - Earlier versions of SimpleTest are compatible with PHP 4.2 up to - PHP 5 (non E_STRICT). - </p> - - </div> - References and related information... - <ul> -<li> - <a href="unit_test_documentation.html">Documentation for SimpleTest</a>. - </li> -<li> - <a href="http://www.lastcraft.com/first_test_tutorial.php">How to write PHP test cases</a> - is a fairly advanced tutorial. - </li> -<li> - <a href="http://simpletest.org/api/">SimpleTest API</a> from phpdoc. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <span class="chosen">Overview</span> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/en/partial_mocks_documentation.html b/3rdparty/simpletest/docs/en/partial_mocks_documentation.html deleted file mode 100644 index cb70b1f86df11e2c95312c26be36ea5e428bed32..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/partial_mocks_documentation.html +++ /dev/null @@ -1,457 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>SimpleTest for PHP partial mocks documentation</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <span class="chosen">Partial mocks</span> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Partial mock objects documentation</h1> - This page... - <ul> -<li> - <a href="#inject">The mock injection problem</a>. - </li> -<li> - Moving creation to a <a href="#creation">protected factory</a> method. - </li> -<li> - <a href="#partial">Partial mocks</a> generate subclasses. - </li> -<li> - Partial mocks <a href="#less">test less than a class</a>. - </li> -</ul> -<div class="content"> - - <p> - A partial mock is simply a pattern to alleviate a specific problem - in testing with mock objects, - that of getting mock objects into tight corners. - It's quite a limited tool and possibly not even a good idea. - It is included with SimpleTest because I have found it useful - on more than one occasion and has saved a lot of work at that point. - </p> - - <h2> -<a class="target" name="inject"></a>The mock injection problem</h2> - <p> - When one object uses another it is very simple to just pass a mock - version in already set up with its expectations. - Things are rather tricker if one object creates another and the - creator is the one you want to test. - This means that the created object should be mocked, but we can - hardly tell our class under test to create a mock instead. - The tested class doesn't even know it is running inside a test - after all. - </p> - <p> - For example, suppose we are building a telnet client and it - needs to create a network socket to pass its messages. - The connection method might look something like... -<pre> -<strong><?php -require_once('socket.php'); - -class Telnet { - ... - function connect($ip, $port, $username, $password) { - $socket = new Socket($ip, $port); - $socket->read( ... ); - ... - } -} -?></strong> -</pre> - We would really like to have a mock object version of the socket - here, what can we do? - </p> - <p> - The first solution is to pass the socket in as a parameter, - forcing the creation up a level. - Having the client handle this is actually a very good approach - if you can manage it and should lead to factoring the creation from - the doing. - In fact, this is one way in which testing with mock objects actually - forces you to code more tightly focused solutions. - They improve your programming. - </p> - <p> - Here this would be... -<pre> -<?php -require_once('socket.php'); - -class Telnet { - ... - <strong>function connect($socket, $username, $password) { - $socket->read( ... ); - ... - }</strong> -} -?> -</pre> - This means that the test code is typical for a test involving - mock objects. -<pre> -class TelnetTest extends UnitTestCase { - ... - function testConnection() {<strong> - $socket = new MockSocket(); - ... - $telnet = new Telnet(); - $telnet->connect($socket, 'Me', 'Secret'); - ...</strong> - } -} -</pre> - It is pretty obvious though that one level is all you can go. - You would hardly want your top level application creating - every low level file, socket and database connection ever - needed. - It wouldn't know the constructor parameters anyway. - </p> - <p> - The next simplest compromise is to have the created object passed - in as an optional parameter... -<pre> -<?php -require_once('socket.php'); - -class Telnet { - ...<strong> - function connect($ip, $port, $username, $password, $socket = false) { - if (! $socket) { - $socket = new Socket($ip, $port); - } - $socket->read( ... );</strong> - ... - return $socket; - } -} -?> -</pre> - For a quick solution this is usually good enough. - The test now looks almost the same as if the parameter - was formally passed... -<pre> -class TelnetTest extends UnitTestCase { - ... - function testConnection() {<strong> - $socket = new MockSocket(); - ... - $telnet = new Telnet(); - $telnet->connect('127.0.0.1', 21, 'Me', 'Secret', $socket); - ...</strong> - } -} -</pre> - The problem with this approach is its untidiness. - There is test code in the main class and parameters passed - in the test case that are never used. - This is a quick and dirty approach, but nevertheless effective - in most situations. - </p> - <p> - The next method is to pass in a factory object to do the creation... -<pre> -<?php -require_once('socket.php'); - -class Telnet {<strong> - function Telnet($network) { - $this->_network = $network; - }</strong> - ... - function connect($ip, $port, $username, $password) {<strong> - $socket = $this->_network->createSocket($ip, $port); - $socket->read( ... );</strong> - ... - return $socket; - } -} -?> -</pre> - This is probably the most highly factored answer as creation - is now moved into a small specialist class. - The networking factory can now be tested separately, but mocked - easily when we are testing the telnet class... -<pre> -class TelnetTest extends UnitTestCase { - ... - function testConnection() {<strong> - $socket = new MockSocket(); - ... - $network = new MockNetwork(); - $network->returnsByReference('createSocket', $socket); - $telnet = new Telnet($network); - $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');</strong> - } -} -</pre> - The downside is that we are adding a lot more classes to the - library. - Also we are passing a lot of factories around which will - make the code a little less intuitive. - The most flexible solution, but the most complex. - </p> - <p> - Well techniques like "Dependency Injection" tackle the problem of - instantiating a lot of constructor parameters. - Unfortunately knowledge of this pattern is not widespread, and if you - are trying to get older code to work, rearchitecting the whole - application is not really an option. - </p> - <p> - Is there a middle ground? - </p> - - <h2> -<a class="target" name="creation"></a>Protected factory method</h2> - <p> - There is a way we can circumvent the problem without creating - any new application classes, but it involves creating a subclass - when we do the actual testing. - Firstly we move the socket creation into its own method... -<pre> -<?php -require_once('socket.php'); - -class Telnet { - ... - function connect($ip, $port, $username, $password) { - <strong>$socket = $this->createSocket($ip, $port);</strong> - $socket->read( ... ); - ... - }<strong> - - protected function createSocket($ip, $port) { - return new Socket($ip, $port); - }</strong> -} -?> -</pre> - This is a pretty safe step even for very tangled legacy code. - This is the only change we make to the application. - </p> - <p> - For the test case we have to create a subclass so that - we can intercept the socket creation... -<pre> -<strong>class TelnetTestVersion extends Telnet { - var $mock; - - function TelnetTestVersion($mock) { - $this->mock = $mock; - $this->Telnet(); - } - - protected function createSocket() { - return $this->mock; - } -}</strong> -</pre> - Here I have passed the mock in the constructor, but a - setter would have done just as well. - Note that the mock was set into the object variable - before the constructor was chained. - This is necessary in case the constructor calls - <span class="new_code">connect()</span>. - Otherwise it could get a null value from - <span class="new_code">createSocket()</span>. - </p> - <p> - After the completion of all of this extra work the - actual test case is fairly easy. - We just test our new class instead... -<pre> -class TelnetTest extends UnitTestCase { - ... - function testConnection() {<strong> - $socket = new MockSocket(); - ... - $telnet = new TelnetTestVersion($socket); - $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');</strong> - } -} -</pre> - The new class is very simple of course. - It just sets up a return value, rather like a mock. - It would be nice if it also checked the incoming parameters - as well. - Just like a mock. - It seems we are likely to do this often, can - we automate the subclass creation? - </p> - - <h2> -<a class="target" name="partial"></a>A partial mock</h2> - <p> - Of course the answer is "yes" or I would have stopped writing - this by now! - The previous test case was a lot of work, but we can - generate the subclass using a similar approach to the mock objects. - </p> - <p> - Here is the partial mock version of the test... -<pre> -<strong>Mock::generatePartial( - 'Telnet', - 'TelnetTestVersion', - array('createSocket'));</strong> - -class TelnetTest extends UnitTestCase { - ... - function testConnection() {<strong> - $socket = new MockSocket(); - ... - $telnet = new TelnetTestVersion(); - $telnet->setReturnReference('createSocket', $socket); - $telnet->Telnet(); - $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');</strong> - } -} -</pre> - The partial mock is a subclass of the original with - selected methods "knocked out" with test - versions. - The <span class="new_code">generatePartial()</span> call - takes three parameters: the class to be subclassed, - the new test class name and a list of methods to mock. - </p> - <p> - Instantiating the resulting objects is slightly tricky. - The only constructor parameter of a partial mock is - the unit tester reference. - As with the normal mock objects this is needed for sending - test results in response to checked expectations. - </p> - <p> - The original constructor is not run yet. - This is necessary in case the constructor is going to - make use of the as yet unset mocked methods. - We set any return values at this point and then run the - constructor with its normal parameters. - This three step construction of "new", followed - by setting up the methods, followed by running the constructor - proper is what distinguishes the partial mock code. - </p> - <p> - Apart from construction, all of the mocked methods have - the same features as mock objects and all of the unmocked - methods behave as before. - We can set expectations very easily... -<pre> -class TelnetTest extends UnitTestCase { - ... - function testConnection() { - $socket = new MockSocket(); - ... - $telnet = new TelnetTestVersion(); - $telnet->setReturnReference('createSocket', $socket); - <strong>$telnet->expectOnce('createSocket', array('127.0.0.1', 21));</strong> - $telnet->Telnet(); - $telnet->connect('127.0.0.1', 21, 'Me', 'Secret'); - } -} -</pre> - Partial mocks are not used often. - I consider them transitory. - Useful while refactoring, but once the application has - all of it's dependencies nicely separated then the - partial mocks can wither away. - </p> - - <h2> -<a class="target" name="less"></a>Testing less than a class</h2> - <p> - The mocked out methods don't have to be factory methods, - they could be any sort of method. - In this way partial mocks allow us to take control of any part of - a class except the constructor. - We could even go as far as to mock every method - except one we actually want to test. - </p> - <p> - This last situation is all rather hypothetical, as I've hardly - tried it. - I am a little worried that - forcing object granularity may be better for the code quality. - I personally use partial mocks as a way of overriding creation - or for occasional testing of the TemplateMethod pattern. - </p> - <p> - It's all going to come down to the coding standards of your - project to decide if you allow test mechanisms like this. - </p> - - </div> - References and related information... - <ul> -<li> - SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - <a href="http://simpletest.org/api/">Full API for SimpleTest</a> - from the PHPDoc. - </li> -<li> - The protected factory is described in - <a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">this paper from IBM</a>. - This is the only formal comment I have seen on this problem. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <span class="chosen">Partial mocks</span> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/en/reporter_documentation.html b/3rdparty/simpletest/docs/en/reporter_documentation.html deleted file mode 100644 index 8924b7bb67a32fa6809fe0758ce30b5ec41adf5c..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/reporter_documentation.html +++ /dev/null @@ -1,616 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>SimpleTest for PHP test runner and display documentation</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <span class="chosen">Reporting</span> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Test reporter documentation</h1> - This page... - <ul> -<li> - Displaying <a href="#html">results in HTML</a> - </li> -<li> - Displaying and <a href="#other">reporting results</a> - in other formats - </li> -<li> - Using <a href="#cli">SimpleTest from the command line</a> - </li> -<li> - <a href="#xml">Using XML</a> for remote testing - </li> -</ul> -<div class="content"> - - <p> - SimpleTest pretty much follows the MVC-ish pattern - (Model-View-Controller). - The reporter classes are the view and the model is your - test cases and their hiearchy. - The controller is mostly hidden from the user of - SimpleTest unless you want to change how the test cases - are actually run, in which case it is possible to - override the runner objects from within the test case. - As usual with MVC, the controller is mostly undefined - and there are other places to control the test run. - </p> - - <h2> -<a class="target" name="html"></a>Reporting results in HTML</h2> - <p> - The default HTML display is minimal in the extreme. - It reports success and failure with the conventional red and - green bars and shows a breadcrumb trail of test groups - for every failed assertion. - Here's a fail... - <div class="demo"> - <h1>File test</h1> - <span class="fail">Fail</span>: createnewfile->True assertion failed.<br> - <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete. - <strong>0</strong> passes, <strong>1</strong> fails and <strong>0</strong> exceptions.</div> - </div> - And here all tests passed... - <div class="demo"> - <h1>File test</h1> - <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete. - <strong>1</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div> - </div> - The good news is that there are several points in the display - hiearchy for subclassing. - </p> - <p> - For web page based displays there is the - <span class="new_code">HtmlReporter</span> class with the following - signature... -<pre> -class HtmlReporter extends SimpleReporter { - public __construct($encoding) { ... } - public makeDry(boolean $is_dry) { ... } - public void paintHeader(string $test_name) { ... } - public void sendNoCacheHeaders() { ... } - public void paintFooter(string $test_name) { ... } - public void paintGroupStart(string $test_name, integer $size) { ... } - public void paintGroupEnd(string $test_name) { ... } - public void paintCaseStart(string $test_name) { ... } - public void paintCaseEnd(string $test_name) { ... } - public void paintMethodStart(string $test_name) { ... } - public void paintMethodEnd(string $test_name) { ... } - public void paintFail(string $message) { ... } - public void paintPass(string $message) { ... } - public void paintError(string $message) { ... } - public void paintException(string $message) { ... } - public void paintMessage(string $message) { ... } - public void paintFormattedMessage(string $message) { ... } - protected string getCss() { ... } - public array getTestList() { ... } - public integer getPassCount() { ... } - public integer getFailCount() { ... } - public integer getExceptionCount() { ... } - public integer getTestCaseCount() { ... } - public integer getTestCaseProgress() { ... } -} -</pre> - Here is what some of these methods mean. First the display methods - that you will probably want to override... - <ul class="api"> - <li> - <span class="new_code">HtmlReporter(string $encoding)</span><br> - is the constructor. - Note that the unit test sets up the link to the display - rather than the other way around. - The display is a mostly passive receiver of test events. - This allows easy adaption of the display for other test - systems beside unit tests, such as monitoring servers. - The encoding is the character encoding you wish to - display the test output in. - In order to correctly render debug output when - using the web tester, this should match the encoding - of the site you are trying to test. - The available character set strings are described in - the PHP <a href="http://www.php.net/manual/en/function.htmlentities.php">html_entities()</a> - function. - </li> - <li> - <span class="new_code">void paintHeader(string $test_name)</span><br> - is called once at the very start of the test when the first - start event arrives. - The first start event is usually delivered by the top level group - test and so this is where <span class="new_code">$test_name</span> - comes from. - It paints the page title, CSS, body tag, etc. - It returns nothing (<span class="new_code">void</span>). - </li> - <li> - <span class="new_code">void paintFooter(string $test_name)</span><br> - Called at the very end of the test to close any tags opened - by the page header. - By default it also displays the red/green bar and the final - count of results. - Actually the end of the test happens when a test end event - comes in with the same name as the one that started it all - at the same level. - The tests nest you see. - Closing the last test finishes the display. - </li> - <li> - <span class="new_code">void paintMethodStart(string $test_name)</span><br> - is called at the start of each test method. - The name normally comes from method name. - The other test start events behave the same way except - that the group test one tells the reporter how large - it is in number of held test cases. - This is so that the reporter can display a progress bar - as the runner churns through the test cases. - </li> - <li> - <span class="new_code">void paintMethodEnd(string $test_name)</span><br> - backs out of the test started with the same name. - </li> - <li> - <span class="new_code">void paintFail(string $message)</span><br> - paints a failure. - By default it just displays the word fail, a breadcrumbs trail - showing the current test nesting and the message issued by - the assertion. - </li> - <li> - <span class="new_code">void paintPass(string $message)</span><br> - by default does nothing. - </li> - <li> - <span class="new_code">string getCss()</span><br> - Returns the CSS styles as a string for the page header - method. - Additional styles have to be appended here if you are - not overriding the page header. - You will want to use this method in an overriden page header - if you want to include the original CSS. - </li> - </ul> - There are also some accessors to get information on the current - state of the test suite. - Use these to enrich the display... - <ul class="api"> - <li> - <span class="new_code">array getTestList()</span><br> - is the first convenience method for subclasses. - Lists the current nesting of the tests as a list - of test names. - The first, top level test case, is first in the - list and the current test method will be last. - </li> - <li> - <span class="new_code">integer getPassCount()</span><br> - returns the number of passes chalked up so far. - Needed for the display at the end. - </li> - <li> - <span class="new_code">integer getFailCount()</span><br> - is likewise the number of fails so far. - </li> - <li> - <span class="new_code">integer getExceptionCount()</span><br> - is likewise the number of errors so far. - </li> - <li> - <span class="new_code">integer getTestCaseCount()</span><br> - is the total number of test cases in the test run. - This includes the grouping tests themselves. - </li> - <li> - <span class="new_code">integer getTestCaseProgress()</span><br> - is the number of test cases completed so far. - </li> - </ul> - One simple modification is to get the HtmlReporter to display - the passes as well as the failures and errors... -<pre> -<strong>class ReporterShowingPasses extends HtmlReporter { - - function paintPass($message) { - parent::paintPass($message); - print "<span class=\"pass\">Pass</span>: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode("-&gt;", $breadcrumb); - print "-&gt;$message<br />\n"; - } - - protected function getCss() { - return parent::getCss() . ' .pass { color: green; }'; - } -}</strong> -</pre> - </p> - <p> - One method that was glossed over was the <span class="new_code">makeDry()</span> - method. - If you run this method, with no parameters, on the reporter - before the test suite is run no actual test methods - will be called. - You will still get the events of entering and leaving the - test methods and test cases, but no passes or failures etc, - because the test code will not actually be executed. - </p> - <p> - The reason for this is to allow for more sophistcated - GUI displays that allow the selection of individual test - cases. - In order to build a list of possible tests they need a - report on the test structure for drawing, say a tree view - of the test suite. - With a reporter set to dry run that just sends drawing events - this is easily accomplished. - </p> - - <h2> -<a class="target" name="other"></a>Extending the reporter</h2> - <p> - Rather than simply modifying the existing display, you might want to - produce a whole new HTML look, or even generate text or XML. - Rather than override every method in - <span class="new_code">HtmlReporter</span> we can take one - step up the class hiearchy to <span class="new_code">SimpleReporter</span> - in the <em>simple_test.php</em> source file. - </p> - <p> - A do nothing display, a blank canvas for your own creation, would - be... -<pre> -<strong>require_once('simpletest/simpletest.php');</strong> - -class MyDisplay extends SimpleReporter {<strong> - </strong> - function paintHeader($test_name) { } - - function paintFooter($test_name) { } - - function paintStart($test_name, $size) {<strong> - parent::paintStart($test_name, $size);</strong> - } - - function paintEnd($test_name, $size) {<strong> - parent::paintEnd($test_name, $size);</strong> - } - - function paintPass($message) {<strong> - parent::paintPass($message);</strong> - } - - function paintFail($message) {<strong> - parent::paintFail($message);</strong> - } - - function paintError($message) {<strong> - parent::paintError($message);</strong> - } - - function paintException($exception) {<strong> - parent::paintException($exception);</strong> - } -} -</pre> - No output would come from this class until you add it. - </p> - <p> - The catch with using this low level class is that you must - explicitely invoke it in the test script. - The "autorun" facility will not be able to use - its runtime context (whether it's running in a web browser - or the command line) to select the reporter. - </p> - <p> - You explicitely invoke the test runner like so... -<pre> -<?php -require_once('simpletest/autorun.php'); - -$test = new TestSuite('File test'); -$test->addFile('tests/file_test.php'); -$test->run(<strong>new MyReporter()</strong>); -?> -</pre> - ...perhaps like this... -<pre> -<?php -require_once('simpletest/simpletest.php'); -require_once('my_reporter.php'); - -class MyTest extends TestSuite { - function __construct() { - parent::__construct(); - $this->addFile('tests/file_test.php'); - } -} - -$test = new MyTest(); -$test->run(<strong>new MyReporter()</strong>); -?> -</pre> - We'll show how to fit in with "autorun" later. - </p> - - <h2> -<a class="target" name="cli"></a>The command line reporter</h2> - <p> - SimpleTest also ships with a minimal command line reporter. - The interface mimics JUnit to some extent, but paints the - failure messages as they arrive. - To use the command line reporter explicitely, substitute it - for the HTML version... -<pre> -<?php -require_once('simpletest/autorun.php'); - -$test = new TestSuite('File test'); -$test->addFile('tests/file_test.php'); -$test->run(<strong>new TextReporter()</strong>); -?> -</pre> - Then invoke the test suite from the command line... -<pre class="shell"> -php file_test.php -</pre> - You will need the command line version of PHP installed - of course. - A passing test suite looks like this... -<pre class="shell"> -File test -OK -Test cases run: 1/1, Passes: 1, Failures: 0, Exceptions: 0 -</pre> - A failure triggers a display like this... -<pre class="shell"> -File test -1) True assertion failed. - in createNewFile -FAILURES!!! -Test cases run: 1/1, Passes: 0, Failures: 1, Exceptions: 0 -</pre> - </p> - <p> - One of the main reasons for using a command line driven - test suite is of using the tester as part of some automated - process. - To function properly in shell scripts the test script should - return a non-zero exit code on failure. - If a test suite fails the value <span class="new_code">false</span> - is returned from the <span class="new_code">SimpleTest::run()</span> - method. - We can use that result to exit the script with the desired return - code... -<pre> -<?php -require_once('simpletest/autorun.php'); - -$test = new TestSuite('File test'); -$test->addFile('tests/file_test.php'); -<strong>exit ($test->run(new TextReporter()) ? 0 : 1);</strong> -?> -</pre> - Of course we wouldn't really want to create two test scripts, - a command line one and a web browser one, for each test suite. - The command line reporter includes a method to sniff out the - run time environment... -<pre> -<?php -require_once('simpletest/autorun.php'); - -$test = new TestSuite('File test'); -$test->addFile('tests/file_test.php'); -<strong>if (TextReporter::inCli()) {</strong> - exit ($test->run(new TextReporter()) ? 0 : 1); -<strong>}</strong> -$test->run(new HtmlReporter()); -?> -</pre> - This is the form used within SimpleTest itself. - When you use the "autorun.php", and no - test has been run by the end, this is pretty much - the code that SimpleTest will run for you implicitely. - </p> - <p> - In other words, this is gives the same result... -<pre> -<?php -require_once('simpletest/autorun.php'); - -class MyTest extends TestSuite { - function __construct() { - parent::__construct(); - $this->addFile('tests/file_test.php'); - } -} -?> -</pre> - </p> - - <h2> -<a class="target" name="xml"></a>Remote testing</h2> - <p> - SimpleTest ships with an <span class="new_code">XmlReporter</span> class - used for internal communication. - When run the output looks like... -<pre class="shell"> -<?xml version="1.0"?> -<run> - <group size="4"> - <name>Remote tests</name> - <group size="4"> - <name>Visual test with 48 passes, 48 fails and 4 exceptions</name> - <case> - <name>testofunittestcaseoutput</name> - <test> - <name>testofresults</name> - <pass>This assertion passed</pass> - <fail>This assertion failed</fail> - </test> - <test> - ... - </test> - </case> - </group> - </group> -</run> -</pre> - To get your normal test cases to produce this format, on the - command line add the <span class="new_code">--xml</span> flag. -<pre class="shell"> -php my_test.php --xml -</pre> - You can do teh same thing in the web browser by adding the - URL parameter <span class="new_code">xml=1</span>. - Any true value will do. - </p> - <p> - You can consume this format with the parser - supplied as part of SimpleTest itself. - This is called <span class="new_code">SimpleTestXmlParser</span> and - resides in <em>xml.php</em> within the SimpleTest package... -<pre> -<?php -require_once('simpletest/xml.php'); - -... -$parser = new SimpleTestXmlParser(new HtmlReporter()); -$parser->parse($test_output); -?> -</pre> - The <span class="new_code">$test_output</span> should be the XML format - from the XML reporter, and could come from say a command - line run of a test case. - The parser sends events to the reporter just like any - other test run. - There are some odd occasions where this is actually useful. - </p> - <p> - Most likely it's when you want to isolate a problematic crash - prone test. - You can collect the XML output using the backtick operator - from another test. - In that way it runs in its own process... -<pre> -<?php -require_once('simpletest/xml.php'); - -if (TextReporter::inCli()) { - $parser = new SimpleTestXmlParser(new TextReporter()); -} else { - $parser = new SimpleTestXmlParser(new HtmlReporter()); -} -$parser->parse(`php flakey_test.php --xml`); -?> -</pre> - </p> - <p> - Another use is breaking up large test suites. - </p> - <p> - A problem with large test suites is thet they can exhaust - the default 16Mb memory limit on a PHP process. - By having the test groups output in XML and run in - separate processes, the output can be reparsed to - aggregate the results into a much smaller footprint top level - test. - </p> - <p> - Because the XML output can come from anywhere, this opens - up the possibility of aggregating test runs from remote - servers. - A test case already exists to do this within the SimpleTest - framework, but it is currently experimental... -<pre> -<?php -<strong>require_once('../remote.php');</strong> -require_once('simpletest/autorun.php'); - -$test_url = ...; -$dry_url = ...; - -class MyTestOnAnotherServer extends RemoteTestCase { - function __construct() { - $test_url = ... - parent::__construct($test_url, $test_url . ' --dry'); - } -} -?> -</pre> - The <span class="new_code">RemoteTestCase</span> takes the actual location - of the test runner, basically a web page in XML format. - It also takes the URL of a reporter set to do a dry run. - This is so that progress can be reported upward correctly. - The <span class="new_code">RemoteTestCase</span> can be added to test suites - just like any other test suite. - </p> - - </div> - References and related information... - <ul> -<li> - SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a> - gives full detail on the classes and assertions available. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <span class="chosen">Reporting</span> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/en/unit_test_documentation.html b/3rdparty/simpletest/docs/en/unit_test_documentation.html deleted file mode 100644 index a399bf34cb1172facc164b64c0c9fd904be0f214..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/unit_test_documentation.html +++ /dev/null @@ -1,442 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>SimpleTest for PHP regression test documentation</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <span class="chosen">Unit tester</span> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>PHP Unit Test documentation</h1> - This page... - <ul> -<li> - <a href="#unit">Unit test cases</a> and basic assertions. - </li> -<li> - <a href="#extending_unit">Extending test cases</a> to - customise them for your own project. - </li> -<li> - <a href="#running_unit">Running a single case</a> as - a single script. - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="unit"></a>Unit test cases</h2> - <p> - The core system is a regression testing framework built around - test cases. - A sample test case looks like this... -<pre> -<strong>class FileTestCase extends UnitTestCase { -}</strong> -</pre> - Actual tests are added as methods in the test case whose names - by default start with the string "test" and - when the test case is invoked all such methods are run in - the order that PHP introspection finds them. - As many test methods can be added as needed. - </p> - <p> - For example... -<pre> -require_once('simpletest/autorun.php'); -require_once('../classes/writer.php'); - -class FileTestCase extends UnitTestCase { - function FileTestCase() { - $this->UnitTestCase('File test'); - }<strong> - - function setUp() { - @unlink('../temp/test.txt'); - } - - function tearDown() { - @unlink('../temp/test.txt'); - } - - function testCreation() { - $writer = &new FileWriter('../temp/test.txt'); - $writer->write('Hello'); - $this->assertTrue(file_exists('../temp/test.txt'), 'File created'); - }</strong> -} -</pre> - The constructor is optional and usually omitted. - Without a name, the class name is taken as the name of the test case. - </p> - <p> - Our only test method at the moment is <span class="new_code">testCreation()</span> - where we check that a file has been created by our - <span class="new_code">Writer</span> object. - We could have put the <span class="new_code">unlink()</span> - code into this method as well, but by placing it in - <span class="new_code">setUp()</span> and - <span class="new_code">tearDown()</span> we can use it with - other test methods that we add. - </p> - <p> - The <span class="new_code">setUp()</span> method is run - just before each and every test method. - <span class="new_code">tearDown()</span> is run just after - each and every test method. - </p> - <p> - You can place some test case set up into the constructor to - be run once for all the methods in the test case, but - you risk test interference that way. - This way is slightly slower, but it is safer. - Note that if you come from a JUnit background this will not - be the behaviour you are used to. - JUnit surprisingly reinstantiates the test case for each test - method to prevent such interference. - SimpleTest requires the end user to use <span class="new_code">setUp()</span>, but - supplies additional hooks for library writers. - </p> - <p> - The means of reporting test results (see below) are by a - visiting display class - that is notified by various <span class="new_code">assert...()</span> - methods. - Here is the full list for the <span class="new_code">UnitTestCase</span> - class, the default for SimpleTest... - <table><tbody> - <tr> -<td><span class="new_code">assertTrue($x)</span></td> -<td>Fail if $x is false</td> -</tr> - <tr> -<td><span class="new_code">assertFalse($x)</span></td> -<td>Fail if $x is true</td> -</tr> - <tr> -<td><span class="new_code">assertNull($x)</span></td> -<td>Fail if $x is set</td> -</tr> - <tr> -<td><span class="new_code">assertNotNull($x)</span></td> -<td>Fail if $x not set</td> -</tr> - <tr> -<td><span class="new_code">assertIsA($x, $t)</span></td> -<td>Fail if $x is not the class or type $t</td> -</tr> - <tr> -<td><span class="new_code">assertNotA($x, $t)</span></td> -<td>Fail if $x is of the class or type $t</td> -</tr> - <tr> -<td><span class="new_code">assertEqual($x, $y)</span></td> -<td>Fail if $x == $y is false</td> -</tr> - <tr> -<td><span class="new_code">assertNotEqual($x, $y)</span></td> -<td>Fail if $x == $y is true</td> -</tr> - <tr> -<td><span class="new_code">assertWithinMargin($x, $y, $m)</span></td> -<td>Fail if abs($x - $y) < $m is false</td> -</tr> - <tr> -<td><span class="new_code">assertOutsideMargin($x, $y, $m)</span></td> -<td>Fail if abs($x - $y) < $m is true</td> -</tr> - <tr> -<td><span class="new_code">assertIdentical($x, $y)</span></td> -<td>Fail if $x == $y is false or a type mismatch</td> -</tr> - <tr> -<td><span class="new_code">assertNotIdentical($x, $y)</span></td> -<td>Fail if $x == $y is true and types match</td> -</tr> - <tr> -<td><span class="new_code">assertReference($x, $y)</span></td> -<td>Fail unless $x and $y are the same variable</td> -</tr> - <tr> -<td><span class="new_code">assertClone($x, $y)</span></td> -<td>Fail unless $x and $y are identical copies</td> -</tr> - <tr> -<td><span class="new_code">assertPattern($p, $x)</span></td> -<td>Fail unless the regex $p matches $x</td> -</tr> - <tr> -<td><span class="new_code">assertNoPattern($p, $x)</span></td> -<td>Fail if the regex $p matches $x</td> -</tr> - <tr> -<td><span class="new_code">expectError($x)</span></td> -<td>Fail if matching error does not occour</td> -</tr> - <tr> -<td><span class="new_code">expectException($x)</span></td> -<td>Fail if matching exception is not thrown</td> -</tr> - <tr> -<td><span class="new_code">ignoreException($x)</span></td> -<td>Swallows any upcoming matching exception</td> -</tr> - <tr> -<td><span class="new_code">assert($e)</span></td> -<td>Fail on failed <a href="expectation_documentation.html">expectation</a> object $e</td> -</tr> - </tbody></table> - All assertion methods can take an optional description as a - last parameter. - This is to label the displayed result with. - If omitted a default message is sent instead, which is usually - sufficient. - This default message can still be embedded in your own message - if you include "%s" within the string. - All the assertions return true on a pass or false on failure. - </p> - <p> - Some examples... -<pre> -$variable = null; -<strong>$this->assertNull($variable, 'Should be cleared');</strong> -</pre> - ...will pass and normally show no message. - If you have - <a href="http://www.lastcraft.com/display_subclass_tutorial.php">set up the tester to display passes</a> - as well then the message will be displayed as is. -<pre> -<strong>$this->assertIdentical(0, false, 'Zero is not false [%s]');</strong> -</pre> - This will fail as it performs a type - check, as well as a comparison, between the two values. - The "%s" part is replaced by the default - error message that would have been shown if we had not - supplied our own. -<pre> -$a = 1; -$b = $a; -<strong>$this->assertReference($a, $b);</strong> -</pre> - Will fail as the variable <span class="new_code">$a</span> is a copy of <span class="new_code">$b</span>. -<pre> -<strong>$this->assertPattern('/hello/i', 'Hello world');</strong> -</pre> - This will pass as using a case insensitive match the string - <span class="new_code">hello</span> is contained in <span class="new_code">Hello world</span>. -<pre> -<strong>$this->expectError();</strong> -trigger_error('Catastrophe'); -</pre> - Here the check catches the "Catastrophe" - message without checking the text and passes. - This removes the error from the queue. -<pre> -<strong>$this->expectError('Catastrophe');</strong> -trigger_error('Catastrophe'); -</pre> - The next error check tests not only the existence of the error, - but also the text which, here matches so another pass. - If any unchecked errors are left at the end of a test method then - an exception will be reported in the test. - </p> - <p> - Note that SimpleTest cannot catch compile time PHP errors. - </p> - <p> - The test cases also have some convenience methods for debugging - code or extending the suite... - <table><tbody> - <tr> -<td><span class="new_code">setUp()</span></td> -<td>Runs this before each test method</td> -</tr> - <tr> -<td><span class="new_code">tearDown()</span></td> -<td>Runs this after each test method</td> -</tr> - <tr> -<td><span class="new_code">pass()</span></td> -<td>Sends a test pass</td> -</tr> - <tr> -<td><span class="new_code">fail()</span></td> -<td>Sends a test failure</td> -</tr> - <tr> -<td><span class="new_code">error()</span></td> -<td>Sends an exception event</td> -</tr> - <tr> -<td><span class="new_code">signal($type, $payload)</span></td> -<td>Sends a user defined message to the test reporter</td> -</tr> - <tr> -<td><span class="new_code">dump($var)</span></td> -<td>Does a formatted <span class="new_code">print_r()</span> for quick and dirty debugging</td> -</tr> - </tbody></table> - </p> - - <h2> -<a class="target" name="extending_unit"></a>Extending test cases</h2> - <p> - Of course additional test methods can be added to create - specific types of test case, so as to extend framework... -<pre> -require_once('simpletest/autorun.php'); -<strong> -class FileTester extends UnitTestCase { - function FileTester($name = false) { - $this->UnitTestCase($name); - } - - function assertFileExists($filename, $message = '%s') { - $this->assertTrue( - file_exists($filename), - sprintf($message, 'File [$filename] existence check')); - }</strong> -} -</pre> - Here the SimpleTest library is held in a folder called - <em>simpletest</em> that is local. - Substitute your own path for this. - </p> - <p> - To prevent this test case being run accidently, it is - advisable to mark it as <span class="new_code">abstract</span>. - </p> - <p> - Alternatively you could add a - <span class="new_code">SimpleTestOptions::ignore('FileTester');</span> - directive in your code. - </p> - <p> - This new case can be now be inherited just like - a normal test case... -<pre> -class FileTestCase extends <strong>FileTester</strong> { - - function setUp() { - @unlink('../temp/test.txt'); - } - - function tearDown() { - @unlink('../temp/test.txt'); - } - - function testCreation() { - $writer = &new FileWriter('../temp/test.txt'); - $writer->write('Hello');<strong> - $this->assertFileExists('../temp/test.txt');</strong> - } -} -</pre> - </p> - <p> - If you want a test case that does not have all of the - <span class="new_code">UnitTestCase</span> assertions, - only your own and a few basics, - you need to extend the <span class="new_code">SimpleTestCase</span> - class instead. - It is found in <em>simple_test.php</em> rather than - <em>unit_tester.php</em>. - See <a href="group_test_documentation.html">later</a> if you - want to incorporate other unit tester's - test cases in your test suites. - </p> - - <h2> -<a class="target" name="running_unit"></a>Running a single test case</h2> - <p> - You won't often run single test cases except when bashing - away at a module that is having difficulty, and you don't - want to upset the main test suite. - With <em>autorun</em> no particular scaffolding is needed, - just launch your particular test file and you're ready to go. - </p> - <p> - You can even decide which reporter (for example, - <span class="new_code">TextReporter</span> or <span class="new_code">HtmlReporter</span>) - you prefer for a specific file when launched on its own... -<pre> -<?php -require_once('simpletest/autorun.php');<strong> -SimpleTest :: prefer(new TextReporter());</strong> -require_once('../classes/writer.php'); - -class FileTestCase extends UnitTestCase { - ... -} -?> -</pre> - This script will run as is, but of course will output zero passes - and zero failures until test methods are added. - </p> - - </div> - References and related information... - <ul> -<li> - SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - <a href="http://simpletest.org/api/">Full API for SimpleTest</a> - from the PHPDoc. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <span class="chosen">Unit tester</span> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/en/web_tester_documentation.html b/3rdparty/simpletest/docs/en/web_tester_documentation.html deleted file mode 100644 index aa9df50a6798ce4bc8a1c0d321ba8191a1080d5e..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/en/web_tester_documentation.html +++ /dev/null @@ -1,588 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>SimpleTest for PHP web script testing documentation</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <span class="chosen">Web tester</span> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Web tester documentation</h1> - This page... - <ul> -<li> - Successfully <a href="#fetch">fetching a web page</a> - </li> -<li> - Testing the <a href="#content">page content</a> - </li> -<li> - <a href="#navigation">Navigating a web site</a> - while testing - </li> -<li> - <a href="#request">Raw request modifications</a> and debugging methods - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="fetch"></a>Fetching a page</h2> - <p> - Testing classes is all very well, but PHP is predominately - a language for creating functionality within web pages. - How do we test the front end presentation role of our PHP - applications? - Well the web pages are just text, so we should be able to - examine them just like any other test data. - </p> - <p> - This leads to a tricky issue. - If we test at too low a level, testing for matching tags - in the page with pattern matching for example, our tests will - be brittle. - The slightest change in layout could break a large number of - tests. - If we test at too high a level, say using mock versions of a - template engine, then we lose the ability to automate some classes - of test. - For example, the interaction of forms and navigation will - have to be tested manually. - These types of test are extremely repetitive and error prone. - </p> - <p> - SimpleTest includes a special form of test case for the testing - of web page actions. - The <span class="new_code">WebTestCase</span> includes facilities - for navigation, content and cookie checks and form handling. - Usage of these test cases is similar to the - <a href="unit_tester_documentation.html">UnitTestCase</a>... -<pre> -<strong>class TestOfLastcraft extends WebTestCase { -}</strong> -</pre> - Here we are about to test the - <a href="http://www.lastcraft.com/">Last Craft</a> site itself. - If this test case is in a file called <em>lastcraft_test.php</em> - then it can be loaded in a runner script just like unit tests... -<pre> -<?php -require_once('simpletest/autorun.php');<strong> -require_once('simpletest/web_tester.php');</strong> -SimpleTest::prefer(new TextReporter()); - -class WebTests extends TestSuite { - function WebTests() { - $this->TestSuite('Web site tests');<strong> - $this->addFile('lastcraft_test.php');</strong> - } -} -?> -</pre> - I am using the text reporter here to more clearly - distinguish the web content from the test output. - </p> - <p> - Nothing is being tested yet. - We can fetch the home page by using the - <span class="new_code">get()</span> method... -<pre> -class TestOfLastcraft extends WebTestCase { - <strong> - function testHomepage() { - $this->assertTrue($this->get('http://www.lastcraft.com/')); - }</strong> -} -</pre> - The <span class="new_code">get()</span> method will - return true only if page content was successfully - loaded. - It is a simple, but crude way to check that a web page - was actually delivered by the web server. - However that content may be a 404 response and yet - our <span class="new_code">get()</span> method will still return true. - </p> - <p> - Assuming that the web server for the Last Craft site is up - (sadly not always the case), we should see... -<pre class="shell"> -Web site tests -OK -Test cases run: 1/1, Failures: 0, Exceptions: 0 -</pre> - All we have really checked is that any kind of page was - returned. - We don't yet know if it was the right one. - </p> - - <h2> -<a class="target" name="content"></a>Testing page content</h2> - <p> - To confirm that the page we think we are on is actually the - page we are on, we need to verify the page content. -<pre> -class TestOfLastcraft extends WebTestCase { - - function testHomepage() {<strong> - $this->get('http://www.lastcraft.com/'); - $this->assertText('Why the last craft');</strong> - } -} -</pre> - The page from the last fetch is held in a buffer in - the test case, so there is no need to refer to it directly. - The pattern match is always made against the buffer. - </p> - <p> - Here is the list of possible content assertions... - <table><tbody> - <tr> -<td><span class="new_code">assertTitle($title)</span></td> -<td>Pass if title is an exact match</td> -</tr> - <tr> -<td><span class="new_code">assertText($text)</span></td> -<td>Pass if matches visible and "alt" text</td> -</tr> - <tr> -<td><span class="new_code">assertNoText($text)</span></td> -<td>Pass if doesn't match visible and "alt" text</td> -</tr> - <tr> -<td><span class="new_code">assertPattern($pattern)</span></td> -<td>A Perl pattern match against the page content</td> -</tr> - <tr> -<td><span class="new_code">assertNoPattern($pattern)</span></td> -<td>A Perl pattern match to not find content</td> -</tr> - <tr> -<td><span class="new_code">assertLink($label)</span></td> -<td>Pass if a link with this text is present</td> -</tr> - <tr> -<td><span class="new_code">assertNoLink($label)</span></td> -<td>Pass if no link with this text is present</td> -</tr> - <tr> -<td><span class="new_code">assertLinkById($id)</span></td> -<td>Pass if a link with this id attribute is present</td> -</tr> - <tr> -<td><span class="new_code">assertNoLinkById($id)</span></td> -<td>Pass if no link with this id attribute is present</td> -</tr> - <tr> -<td><span class="new_code">assertField($name, $value)</span></td> -<td>Pass if an input tag with this name has this value</td> -</tr> - <tr> -<td><span class="new_code">assertFieldById($id, $value)</span></td> -<td>Pass if an input tag with this id has this value</td> -</tr> - <tr> -<td><span class="new_code">assertResponse($codes)</span></td> -<td>Pass if HTTP response matches this list</td> -</tr> - <tr> -<td><span class="new_code">assertMime($types)</span></td> -<td>Pass if MIME type is in this list</td> -</tr> - <tr> -<td><span class="new_code">assertAuthentication($protocol)</span></td> -<td>Pass if the current challenge is this protocol</td> -</tr> - <tr> -<td><span class="new_code">assertNoAuthentication()</span></td> -<td>Pass if there is no current challenge</td> -</tr> - <tr> -<td><span class="new_code">assertRealm($name)</span></td> -<td>Pass if the current challenge realm matches</td> -</tr> - <tr> -<td><span class="new_code">assertHeader($header, $content)</span></td> -<td>Pass if a header was fetched matching this value</td> -</tr> - <tr> -<td><span class="new_code">assertNoHeader($header)</span></td> -<td>Pass if a header was not fetched</td> -</tr> - <tr> -<td><span class="new_code">assertCookie($name, $value)</span></td> -<td>Pass if there is currently a matching cookie</td> -</tr> - <tr> -<td><span class="new_code">assertNoCookie($name)</span></td> -<td>Pass if there is currently no cookie of this name</td> -</tr> - </tbody></table> - As usual with the SimpleTest assertions, they all return - false on failure and true on pass. - They also allow an optional test message and you can embed - the original test message inside using "%s" inside - your custom message. - </p> - <p> - So now we could instead test against the title tag with... -<pre> -<strong>$this->assertTitle('The Last Craft? Web developer tutorials on PHP, Extreme programming and Object Oriented development');</strong> -</pre> - ...or, if that is too long and fragile... -<pre> -<strong>$this->assertTitle(new PatternExpectation('/The Last Craft/'));</strong> -</pre> - As well as the simple HTML content checks we can check - that the MIME type is in a list of allowed types with... -<pre> -<strong>$this->assertMime(array('text/plain', 'text/html'));</strong> -</pre> - More interesting is checking the HTTP response code. - Like the MIME type, we can assert that the response code - is in a list of allowed values... -<pre> -class TestOfLastcraft extends WebTestCase { - - function testRedirects() { - $this->get('http://www.lastcraft.com/test/redirect.php'); - $this->assertResponse(200);</strong> - } -} -</pre> - Here we are checking that the fetch is successful by - allowing only a 200 HTTP response. - This test will pass, but it is not actually correct to do so. - There is no page, instead the server issues a redirect. - The <span class="new_code">WebTestCase</span> will - automatically follow up to three such redirects. - The tests are more robust this way and we are usually - interested in the interaction with the pages rather - than their delivery. - If the redirects are of interest then this ability must - be disabled... -<pre> -class TestOfLastcraft extends WebTestCase { - - function testHomepage() {<strong> - $this->setMaximumRedirects(0);</strong> - $this->get('http://www.lastcraft.com/test/redirect.php'); - $this->assertResponse(200); - } -} -</pre> - The assertion now fails as expected... -<pre class="shell"> -Web site tests -1) Expecting response in [200] got [302] - in testhomepage - in testoflastcraft - in lastcraft_test.php -FAILURES!!! -Test cases run: 1/1, Failures: 1, Exceptions: 0 -</pre> - We can modify the test to correctly assert redirects with... -<pre> -class TestOfLastcraft extends WebTestCase { - - function testHomepage() { - $this->setMaximumRedirects(0); - $this->get('http://www.lastcraft.com/test/redirect.php'); - $this->assertResponse(<strong>array(301, 302, 303, 307)</strong>); - } -} -</pre> - This now passes. - </p> - - <h2> -<a class="target" name="navigation"></a>Navigating a web site</h2> - <p> - Users don't often navigate sites by typing in URLs, but by - clicking links and buttons. - Here we confirm that the contact details can be reached - from the home page... -<pre> -class TestOfLastcraft extends WebTestCase { - ... - function testContact() { - $this->get('http://www.lastcraft.com/');<strong> - $this->clickLink('About'); - $this->assertTitle(new PatternExpectation('/About Last Craft/'));</strong> - } -} -</pre> - The parameter is the text of the link. - </p> - <p> - If the target is a button rather than an anchor tag, then - <span class="new_code">clickSubmit()</span> can be used - with the button title... -<pre> -<strong>$this->clickSubmit('Go!');</strong> -</pre> - If you are not sure or don't care, the usual case, then just - use the <span class="new_code">click()</span> method... -<pre> -<strong>$this->click('Go!');</strong> -</pre> - </p> - <p> - The list of navigation methods is... - <table><tbody> - <tr> -<td><span class="new_code">getUrl()</span></td> -<td>The current location</td> -</tr> - <tr> -<td><span class="new_code">get($url, $parameters)</span></td> -<td>Send a GET request with these parameters</td> -</tr> - <tr> -<td><span class="new_code">post($url, $parameters)</span></td> -<td>Send a POST request with these parameters</td> -</tr> - <tr> -<td><span class="new_code">head($url, $parameters)</span></td> -<td>Send a HEAD request without replacing the page content</td> -</tr> - <tr> -<td><span class="new_code">retry()</span></td> -<td>Reload the last request</td> -</tr> - <tr> -<td><span class="new_code">back()</span></td> -<td>Like the browser back button</td> -</tr> - <tr> -<td><span class="new_code">forward()</span></td> -<td>Like the browser forward button</td> -</tr> - <tr> -<td><span class="new_code">authenticate($name, $password)</span></td> -<td>Retry after a challenge</td> -</tr> - <tr> -<td><span class="new_code">restart()</span></td> -<td>Restarts the browser as if a new session</td> -</tr> - <tr> -<td><span class="new_code">getCookie($name)</span></td> -<td>Gets the cookie value for the current context</td> -</tr> - <tr> -<td><span class="new_code">ageCookies($interval)</span></td> -<td>Ages current cookies prior to a restart</td> -</tr> - <tr> -<td><span class="new_code">clearFrameFocus()</span></td> -<td>Go back to treating all frames as one page</td> -</tr> - <tr> -<td><span class="new_code">clickSubmit($label)</span></td> -<td>Click the first button with this label</td> -</tr> - <tr> -<td><span class="new_code">clickSubmitByName($name)</span></td> -<td>Click the button with this name attribute</td> -</tr> - <tr> -<td><span class="new_code">clickSubmitById($id)</span></td> -<td>Click the button with this ID attribute</td> -</tr> - <tr> -<td><span class="new_code">clickImage($label, $x, $y)</span></td> -<td>Click an input tag of type image by title or alt text</td> -</tr> - <tr> -<td><span class="new_code">clickImageByName($name, $x, $y)</span></td> -<td>Click an input tag of type image by name</td> -</tr> - <tr> -<td><span class="new_code">clickImageById($id, $x, $y)</span></td> -<td>Click an input tag of type image by ID attribute</td> -</tr> - <tr> -<td><span class="new_code">submitFormById($id)</span></td> -<td>Submit a form without the submit value</td> -</tr> - <tr> -<td><span class="new_code">clickLink($label, $index)</span></td> -<td>Click an anchor by the visible label text</td> -</tr> - <tr> -<td><span class="new_code">clickLinkById($id)</span></td> -<td>Click an anchor by the ID attribute</td> -</tr> - <tr> -<td><span class="new_code">getFrameFocus()</span></td> -<td>The name of the currently selected frame</td> -</tr> - <tr> -<td><span class="new_code">setFrameFocusByIndex($choice)</span></td> -<td>Focus on a frame counting from 1</td> -</tr> - <tr> -<td><span class="new_code">setFrameFocus($name)</span></td> -<td>Focus on a frame by name</td> -</tr> - </tbody></table> - </p> - <p> - The parameters in the <span class="new_code">get()</span>, <span class="new_code">post()</span> or - <span class="new_code">head()</span> methods are optional. - The HTTP HEAD fetch does not change the browser context, only loads - cookies. - This can be useful for when an image or stylesheet sets a cookie - for crafty robot blocking. - </p> - <p> - The <span class="new_code">retry()</span>, <span class="new_code">back()</span> and - <span class="new_code">forward()</span> commands work as they would on - your web browser. - They use the history to retry pages. - This can be handy for checking the effect of hitting the - back button on your forms. - </p> - <p> - The frame methods need a little explanation. - By default a framed page is treated just like any other. - Content will be searced for throughout the entire frameset, - so clicking a link will work no matter which frame - the anchor tag is in. - You can override this behaviour by focusing on a single - frame. - If you do that, all searches and actions will apply to that - frame alone, such as authentication and retries. - If a link or button is not in a focused frame then it cannot - be clicked. - </p> - <p> - Testing navigation on fixed pages only tells you when you - have broken an entire script. - For highly dynamic pages, such as for bulletin boards, this can - be crucial for verifying the correctness of the application. - For most applications though, the really tricky logic is usually in - the handling of forms and sessions. - Fortunately SimpleTest includes - <a href="form_testing_documentation.html">tools for testing web forms</a> - as well. - </p> - - <h2> -<a class="target" name="request"></a>Modifying the request</h2> - <p> - Although SimpleTest does not have the goal of testing networking - problems, it does include some methods to modify and debug - the requests it makes. - Here is another method list... - <table><tbody> - <tr> -<td><span class="new_code">getTransportError()</span></td> -<td>The last socket error</td> -</tr> - <tr> -<td><span class="new_code">showRequest()</span></td> -<td>Dump the outgoing request</td> -</tr> - <tr> -<td><span class="new_code">showHeaders()</span></td> -<td>Dump the incoming headers</td> -</tr> - <tr> -<td><span class="new_code">showSource()</span></td> -<td>Dump the raw HTML page content</td> -</tr> - <tr> -<td><span class="new_code">ignoreFrames()</span></td> -<td>Do not load framesets</td> -</tr> - <tr> -<td><span class="new_code">setCookie($name, $value)</span></td> -<td>Set a cookie from now on</td> -</tr> - <tr> -<td><span class="new_code">addHeader($header)</span></td> -<td>Always add this header to the request</td> -</tr> - <tr> -<td><span class="new_code">setMaximumRedirects($max)</span></td> -<td>Stop after this many redirects</td> -</tr> - <tr> -<td><span class="new_code">setConnectionTimeout($timeout)</span></td> -<td>Kill the connection after this time between bytes</td> -</tr> - <tr> -<td><span class="new_code">useProxy($proxy, $name, $password)</span></td> -<td>Make requests via this proxy URL</td> -</tr> - </tbody></table> - These methods are principally for debugging. - </p> - - </div> - References and related information... - <ul> -<li> - SimpleTest project page on <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - SimpleTest download page on <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - The <a href="http://simpletest.org/api/">developer's API for SimpleTest</a> - gives full detail on the classes and assertions available. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <span class="chosen">Web tester</span> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/authentication_documentation.html b/3rdparty/simpletest/docs/fr/authentication_documentation.html deleted file mode 100644 index fe70e035593eca76706975cf8513406b9d7a68ab..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/authentication_documentation.html +++ /dev/null @@ -1,372 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>Documentation Simple Test : tester l'authentification</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Documentation sur l'authentification</h1> - This page... - <ul> -<li> - Passer au travers d'une <a href="#basique">authentification HTTP basique</a> - </li> -<li> - Tester l'<a href="#cookies">authentification basée sur des cookies</a> - </li> -<li> - Gérer les <a href="#session">sessions du navigateur</a> et les timeouts - </li> -</ul> -<div class="content"> - - <p> - Un des secteurs à la fois délicat et important lors d'un test - de site web reste la sécurité. Tester ces schémas est au coeur - des objectifs du testeur web de SimpleTest. - </p> - - <h2> -<a class="target" name="basique"></a>Authentification HTTP basique</h2> - <p> - Si vous allez chercher une page web protégée - par une authentification basique, vous hériterez d'une entête 401. - Nous pouvons représenter ceci par ce test... -<pre> -class AuthenticationTest extends WebTestCase {<strong> - function test401Header() { - $this->get('http://www.lastcraft.com/protected/'); - $this->showHeaders(); - }</strong> -} -</pre> - Ce qui nous permet de voir les entêtes reçues... - <div class="demo"> - <h1>File test</h1> -<pre style="background-color: lightgray; color: black"> -HTTP/1.1 401 Authorization Required -Date: Sat, 18 Sep 2004 19:25:18 GMT -Server: Apache/1.3.29 (Unix) PHP/4.3.4 -WWW-Authenticate: Basic realm="SimpleTest basic authentication" -Connection: close -Content-Type: text/html; charset=iso-8859-1 -</pre> - <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete. - <strong>0</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div> - </div> - Sauf que nous voulons éviter l'inspection visuelle, - on souhaite que SimpleTest puisse nous dire si oui ou non - la page est protégée. Voici un test en profondeur sur nos entêtes... -<pre> -class AuthenticationTest extends WebTestCase { - function test401Header() { - $this->get('http://www.lastcraft.com/protected/');<strong> - $this->assertAuthentication('Basic'); - $this->assertResponse(401); - $this->assertRealm('SimpleTest basic authentication');</strong> - } -} -</pre> - N'importe laquelle de ces assertions suffirait, - tout dépend de la masse de détails que vous souhaitez voir. - </p> - <p> - Un des axes qui traverse SimpleTest est la possibilité d'utiliser - des objets <span class="new_code">SimpleExpectation</span> à chaque fois qu'une - vérification simple suffit. - Si vous souhaitez vérifiez simplement le contenu du realm - l'identification - du domaine - dans notre exemple, il suffit de faire... -<pre> -class AuthenticationTest extends WebTestCase { - function test401Header() { - $this->get('http://www.lastcraft.com/protected/'); - $this->assertRealm(<strong>new PatternExpectation('/simpletest/i')</strong>); - } -} -</pre> - Ce type de test, vérifier les réponses HTTP, n'est cependant pas commun. - </p> - <p> - La plupart du temps, nous ne souhaitons pas tester - l'authentification en elle-même, mais plutôt - les pages protégées par cette authentification. - Dès que la tentative d'authentification est reçue, - nous pouvons y répondre à l'aide d'une réponse d'authentification : -<pre> -class AuthenticationTest extends WebTestCase { - function testAuthentication() { - $this->get('http://www.lastcraft.com/protected/');<strong> - $this->authenticate('Me', 'Secret');</strong> - $this->assertTitle(...); - } -} -</pre> - Le nom d'utilisateur et le mot de passe seront désormais - envoyés à chaque requête vers ce répertoire - et ses sous-répertoires. - En revanche vous devrez vous authentifier à nouveau - si vous sortez de ce répertoire mais SimpleTest est assez - intelligent pour fusionner les sous-répertoires dans un même domaine. - </p> - <p> - Vous pouvez gagner une ligne en définissant - l'authentification au niveau de l'URL... -<pre> -class AuthenticationTest extends WebTestCase { - function testCanReadAuthenticatedPages() { - $this->get('http://<strong>Me:Secret@</strong>www.lastcraft.com/protected/'); - $this->assertTitle(...); - } -} -</pre> - Si votre nom d'utilisateur ou mot de passe comporte - des caractères spéciaux, alors n'oubliez pas de les encoder, - sinon la requête ne sera pas analysée correctement. - De plus cette entête ne sera pas envoyée aux - sous requêtes si vous la définissez avec une URL absolue. - Par contre si vous naviguez avec des URL relatives, - l'information d'authentification sera préservée. - </p> - <p> - Normalement, vous utilisez l'appel <span class="new_code">authenticate()</span>. SimpleTest - utilisera alors vos informations de connexion à chaque requête. - </p> - <p> - Pour l'instant, seule l'authentification de base est implémentée - et elle n'est réellement fiable qu'en tandem avec une connexion HTTPS. - C'est généralement suffisant pour protéger - le serveur testé des regards malveillants. - Les authentifications Digest et NTLM pourraient être ajoutées prochainement. - </p> - - <h2> -<a class="target" name="cookies"></a>Cookies</h2> - <p> - L'authentification de base ne donne pas assez de contrôle - au développeur Web sur l'interface utilisateur. - Il y a de forte chance pour que cette fonctionnalité - soit codée directement dans l'architecture web - à grand renfort de cookies et de timeouts compliqués. - </p> - <p> - Commençons par un simple formulaire de connexion... -<pre> -<form> - Username: - <input type="text" name="u" value="" /><br /> - Password: - <input type="password" name="p" value="" /><br /> - <input type="submit" value="Log in" /> -</form> -</pre> - Lequel doit ressembler à... - </p> - <p> - <form class="demo"> - Username: - <input type="text" name="u" value=""><br> - Password: - <input type="password" name="p" value=""><br> - <input type="submit" value="Log in"> - </form> - </p> - <p> - Supposons que, durant le chargement de la page, - un cookie ait été inscrit avec un numéro d'identifiant de session. - Nous n'allons pas encore remplir le formulaire, - juste tester que nous pistons bien l'utilisateur. - Voici le test... -<pre> -class LogInTest extends WebTestCase { - function testSessionCookieSetBeforeForm() { - $this->get('http://www.my-site.com/login.php');<strong> - $this->assertCookie('SID');</strong> - } -} -</pre> - Nous nous contentons ici de vérifier que le cookie a bien été défini. - Etant donné que sa valeur est plutôt énigmatique, - elle ne vaudrait pas la peine d'être testée avec... -<pre> -class LogInTest extends WebTestCase { - function testSessionCookieIsCorrectPattern() { - $this->get('http://www.my-site.com/login.php'); - $this->assertCookie('SID', <strong>new PatternExpectation('/[a-f0-9]{32}/i')</strong>); - } -} -</pre> - Si vous utilisez PHP pour gérer vos sessions alors - ce test est encore plus inutile, étant donné qu'il ne fait - que tester PHP lui-même. - </p> - <p> - Le test le plus simple pour vérifier que la connexion a bien eu lieu - reste d'inspecter visuellement la page suivante : - un simple appel à <span class="new_code">WebTestCase::assertText()</span> et le tour est joué. - </p> - <p> - Le reste du test est le même que dans n'importe quel autre formulaire, - mais nous pourrions souhaiter nous assurer - que le cookie n'a pas été modifié depuis la phase de connexion. - Voici comment cela pourrait être testé : -<pre> -class LogInTest extends WebTestCase { - ... - function testSessionCookieSameAfterLogIn() { - $this->get('http://www.my-site.com/login.php');<strong> - $session = $this->getCookie('SID'); - $this->setField('u', 'Me'); - $this->setField('p', 'Secret'); - $this->clickSubmit('Log in'); - $this->assertWantedPattern('/Welcome Me/'); - $this->assertCookie('SID', $session);</strong> - } -} -</pre> - Ceci confirme que l'identifiant de session - est identique avant et après la connexion. - </p> - <p> - Nous pouvons même essayer de duper notre propre système - en créant un cookie arbitraire pour se connecter... -<pre> -class LogInTest extends WebTestCase { - ... - function testSessionCookieSameAfterLogIn() { - $this->get('http://www.my-site.com/login.php');<strong> - $this->setCookie('SID', 'Some other session'); - $this->get('http://www.my-site.com/restricted.php');</strong> - $this->assertWantedPattern('/Access denied/'); - } -} -</pre> - Votre site est-il protégé contre ce type d'attaque ? - </p> - - <h2> -<a class="target" name="session"></a>Sessions de navigateur</h2> - <p> - Si vous testez un système d'authentification, - la reconnexion par un utilisateur est un point sensible. - Essayons de simuler ce qui se passe dans ce cas : -<pre> -class LogInTest extends WebTestCase { - ... - function testLoseAuthenticationAfterBrowserClose() { - $this->get('http://www.my-site.com/login.php'); - $this->setField('u', 'Me'); - $this->setField('p', 'Secret'); - $this->clickSubmit('Log in'); - $this->assertWantedPattern('/Welcome Me/');<strong> - - $this->restart(); - $this->get('http://www.my-site.com/restricted.php'); - $this->assertWantedPattern('/Access denied/');</strong> - } -} -</pre> - La méthode <span class="new_code">WebTestCase::restart()</span> préserve - les cookies dont le timeout n'a pas expiré, - mais jette les cookies temporaires ou expirés. - Vous pouvez spécifier l'heure et la date de leur réactivation. - </p> - <p> - L'expiration des cookies peut être un problème. - Si vous avez un cookie qui doit expirer au bout d'une heure, - nous n'allons pas mettre le test en veille en attendant - que le cookie expire... - </p> - <p> - Afin de provoquer leur expiration, - vous pouvez dater manuellement les cookies, - avant le début de la session. -<pre> -class LogInTest extends WebTestCase { - ... - function testLoseAuthenticationAfterOneHour() { - $this->get('http://www.my-site.com/login.php'); - $this->setField('u', 'Me'); - $this->setField('p', 'Secret'); - $this->clickSubmit('Log in'); - $this->assertWantedPattern('/Welcome Me/'); - <strong> - $this->ageCookies(3600);</strong> - $this->restart(); - $this->get('http://www.my-site.com/restricted.php'); - $this->assertWantedPattern('/Access denied/'); - } -} -</pre> - Après le redémarrage, les cookies seront plus vieux - d'une heure et que tous ceux dont la date d'expiration - sera passée auront disparus. - </p> - - </div> - References and related information... - <ul> -<li> - La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - La page de téléchargement de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - <a href="http://simpletest.org/api/">L'API du développeur pour SimpleTest</a> donne tous les détails sur les classes et les assertions disponibles. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/browser_documentation.html b/3rdparty/simpletest/docs/fr/browser_documentation.html deleted file mode 100644 index 6be1267773badcce33078570ca0b93023ebb16d6..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/browser_documentation.html +++ /dev/null @@ -1,500 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>Documentation SimpleTest : le composant de navigation web scriptable</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Documentation sur le navigateur scriptable</h1> - This page... - <ul> -<li> - Utiliser le <a href="#scripting">navigateur web dans des scripts</a> - </li> -<li> - <a href="#deboguer">Déboguer</a> les erreurs sur les pages - </li> -<li> - <a href="#unit">Tests complexes avec des navigateurs web multiples</a> - </li> -</ul> -<div class="content"> - - <p> - Le composant de navigation web de SimpleTest peut être utilisé - non seulement à l'extérieur de la classe <span class="new_code">WebTestCase</span>, - mais aussi indépendamment du framework SimpleTest lui-même. - </p> - - <h2> -<a class="target" name="script"></a>Le navigateur scriptable</h2> - <p> - Vous pouvez utiliser le navigateur web dans des scripts PHP - pour confirmer que des services marchent bien comme il faut - ou pour extraire des informations à partir de ceux-ci de façon régulière. - Par exemple, voici un petit script pour extraire - le nombre de bogues ouverts dans PHP 5 à partir - du <a href="http://www.php.net/">site web PHP</a>... -<pre> -<?php - require_once('simpletest/browser.php'); - - $browser = &new SimpleBrowser(); - $browser->get('http://php.net/'); - $browser->clickLink('reporting bugs'); - $browser->clickLink('statistics'); - $browser->clickLink('PHP 5 bugs only'); - $page = $browser->getContent(); - preg_match('/status=Open.*?by=Any.*?(\d+)<\/a>/', $page, $matches); - print $matches[1]; -?> -</pre> - Bien sûr Il y a des méthodes plus simple pour réaliser - cet exemple en PHP. Par exemple, vous pourriez juste - utiliser la commande PHP <span class="new_code">file()</span> sur ce qui est - ici une page fixe. Cependant, en utilisant des scripts - avec le navigateur web vous vous autorisez l'authentification, - la gestion des cookies, le chargement automatique des fenêtres, - les redirections, la transmission de formulaires et la capacité - d'examiner les entêtes. - </p> - <p> - Ces méthodes qui se basent sur le contenu textuel des pages - sont fragiles dans un site en constante évolution - et vous voudrez employer une méthode plus directe - pour accéder aux données de façon permanente, - mais pour des tâches simples cette technique peut s'avérer - une solution très rapide. - </p> - <p> - Toutes les méthode de navigation utilisées dans <a href="web_tester_documentation.html">WebTestCase</a> sont présente dans la classe <span class="new_code">SimpleBrowser</span>, mais les assertions sont remplacées par de simples accesseurs. Voici une liste complète des méthodes de navigation de page à page... - <table><tbody> - <tr> -<td><span class="new_code">addHeader($header)</span></td> -<td>Ajouter une entête à chaque téléchargement</td> -</tr> - <tr> -<td><span class="new_code">useProxy($proxy, $username, $password)</span></td> -<td>Utilise ce proxy à partir de maintenant</td> -</tr> - <tr> -<td><span class="new_code">head($url, $parameters)</span></td> -<td>Effectue une requête HEAD</td> -</tr> - <tr> -<td><span class="new_code">get($url, $parameters)</span></td> -<td>Télécharge une page avec un GET</td> -</tr> - <tr> -<td><span class="new_code">post($url, $parameters)</span></td> -<td>Télécharge une page avec un POST</td> -</tr> - <tr> -<td><span class="new_code">click($label)</span></td> -<td>Suit un lien visible ou un bouton texte par son étiquette</td> -</tr> - <tr> -<td><span class="new_code">clickLink($label)</span></td> -<td>Suit un lien par son étiquette</td> -</tr> - <tr> -<td><span class="new_code">isLink($label)</span></td> -<td>Vérifie l'existance d'un lien par son étiquette</td> -</tr> - <tr> -<td><span class="new_code">clickLinkById($id)</span></td> -<td>Suit un lien par son attribut d'identification</td> -</tr> - <tr> -<td><span class="new_code">isLinkById($id)</span></td> -<td>Vérifie l'existance d'un lien par son attribut d'identification</td> -</tr> - <tr> -<td><span class="new_code">getUrl()</span></td> -<td>La page ou la fenêtre URL en cours</td> -</tr> - <tr> -<td><span class="new_code">getTitle()</span></td> -<td>Le titre de la page</td> -</tr> - <tr> -<td><span class="new_code">getContent()</span></td> -<td>Le page ou la fenêtre brute</td> -</tr> - <tr> -<td><span class="new_code">getContentAsText()</span></td> -<td>Sans code HTML à l'exception du text "alt"</td> -</tr> - <tr> -<td><span class="new_code">retry()</span></td> -<td>Répète la dernière requête</td> -</tr> - <tr> -<td><span class="new_code">back()</span></td> -<td>Utilise le bouton "précédent" du navigateur</td> -</tr> - <tr> -<td><span class="new_code">forward()</span></td> -<td>Utilise le bouton "suivant" du navigateur</td> -</tr> - <tr> -<td><span class="new_code">authenticate($username, $password)</span></td> -<td>Retente la page ou la fenêtre après une réponse 401</td> -</tr> - <tr> -<td><span class="new_code">restart($date)</span></td> -<td>Relance le navigateur pour une nouvelle session</td> -</tr> - <tr> -<td><span class="new_code">ageCookies($interval)</span></td> -<td>Change la date des cookies</td> -</tr> - <tr> -<td><span class="new_code">setCookie($name, $value)</span></td> -<td>Lance un nouveau cookie</td> -</tr> - <tr> -<td><span class="new_code">getCookieValue($host, $path, $name)</span></td> -<td>Lit le cookie le plus spécifique</td> -</tr> - <tr> -<td><span class="new_code">getCurrentCookieValue($name)</span></td> -<td>Lit le contenue du cookie en cours</td> -</tr> - </tbody></table> - Les méthode <span class="new_code">SimpleBrowser::useProxy()</span> et - <span class="new_code">SimpleBrowser::addHeader()</span> sont spéciales. - Une fois appelées, elles continuent à s'appliquer sur les téléchargements suivants. - </p> - <p> - Naviguer dans les formulaires est similaire à la <a href="form_testing_documentation.html">navigation des formulaires via WebTestCase</a>... - <table><tbody> - <tr> -<td><span class="new_code">setField($label, $value)</span></td> -<td>Modifie tous les champs avec cette étiquette ou ce nom</td> -</tr> - <tr> -<td><span class="new_code">setFieldByName($name, $value)</span></td> -<td>Modifie tous les champs avec ce nom</td> -</tr> - <tr> -<td><span class="new_code">setFieldById($id, $value)</span></td> -<td>Modifie tous les champs avec cet identifiant</td> -</tr> - <tr> -<td><span class="new_code">getField($label)</span></td> -<td>Accesseur de la valeur d'un élément de formulaire avec cette étiquette ou ce nom</td> -</tr> - <tr> -<td><span class="new_code">getFieldByName($name)</span></td> -<td>Accesseur de la valeur d'un élément de formulaire avec ce nom</td> -</tr> - <tr> -<td><span class="new_code">getFieldById($id)</span></td> -<td>Accesseur de la valeur de l'élément de formulaire avec cet identifiant</td> -</tr> - <tr> -<td><span class="new_code">clickSubmit($label)</span></td> -<td>Transmet le formulaire avec l'étiquette de son bouton</td> -</tr> - <tr> -<td><span class="new_code">clickSubmitByName($name)</span></td> -<td>Transmet le formulaire avec l'attribut de son bouton</td> -</tr> - <tr> -<td><span class="new_code">clickSubmitById($id)</span></td> -<td>Transmet le formulaire avec l'identifiant de son bouton</td> -</tr> - <tr> -<td><span class="new_code">clickImage($label, $x, $y)</span></td> -<td>Clique sur une balise input de type image par son titre (title="*") our son texte alternatif (alt="*")</td> -</tr> - <tr> -<td><span class="new_code">clickImageByName($name, $x, $y)</span></td> -<td>Clique sur une balise input de type image par son attribut (name="*")</td> -</tr> - <tr> -<td><span class="new_code">clickImageById($id, $x, $y)</span></td> -<td>Clique sur une balise input de type image par son identifiant (id="*")</td> -</tr> - <tr> -<td><span class="new_code">submitFormById($id)</span></td> -<td>Transmet le formulaire par son identifiant propre</td> -</tr> - </tbody></table> - Au jourd d'aujourd'hui il n'existe pas beaucoup de méthodes pour lister - les formulaires et les champs disponibles. - <table><tbody> - <tr> -<td><span class="new_code">isClickable($label)</span></td> -<td>Vérifie si un lien existe avec cette étiquette ou ce nom</td> -</tr> - <tr> -<td><span class="new_code">isSubmit($label)</span></td> -<td>Vérifie si un bouton existe avec cette étiquette ou ce nom</td> -</tr> - <tr> -<td><span class="new_code">isImage($label)</span></td> -<td>Vérifie si un bouton image existe avec cette étiquette ou ce nom</td> -</tr> - <tr> -<td><span class="new_code">getLink($label)</span></td> -<td>Trouve une URL à partir de son label</td> -</tr> - <tr> -<td><span class="new_code">getLinkById($label)</span></td> -<td>Trouve une URL à partir de son identifiant</td> -</tr> - <tr> -<td><span class="new_code">getUrls()</span></td> -<td>Liste l'ensemble des liens de la page courante</td> -</tr> - </tbody></table> - Ce sera probablement - ajouté dans des versions successives de SimpleTest. - </p> - <p> - A l'intérieur d'une page, les fenêtres individuelles peuvent être - sélectionnées. Si aucune sélection n'est réalisée alors - toutes les fenêtres sont fusionnées ensemble dans - une unique et grande page. - Le contenu de la page en cours sera une concaténation des - toutes les fenêtres dans l'ordre spécifié par les balises "frameset". - <table><tbody> - <tr> -<td><span class="new_code">getFrames()</span></td> -<td>Un déchargement de la structure de la fenêtre courante</td> -</tr> - <tr> -<td><span class="new_code">getFrameFocus()</span></td> -<td>L'index ou l'étiquette de la fenêtre en courante</td> -</tr> - <tr> -<td><span class="new_code">setFrameFocusByIndex($choice)</span></td> -<td>Sélectionne la fenêtre numérotée à partir de 1</td> -</tr> - <tr> -<td><span class="new_code">setFrameFocus($name)</span></td> -<td>Sélectionne une fenêtre par son étiquette</td> -</tr> - <tr> -<td><span class="new_code">clearFrameFocus()</span></td> -<td>Traite toutes les fenêtres comme une seule page</td> -</tr> - </tbody></table> - Lorsqu'on est focalisé sur une fenêtre unique, - le contenu viendra de celle-ci uniquement. - Cela comprend les liens à cliquer et les formulaires à transmettre. - </p> - - <h2> -<a class="target" name="deboguer"></a>Où sont les erreurs ?</h2> - <p> - Toute cette masse de fonctionnalités est géniale - lorsqu'on arrive à bien télécharger les pages, - mais ce n'est pas toujours évident. - Pour aider à découvrir les erreurs, le navigateur a aussi - des méthodes pour aider au débogage. - <table><tbody> - <tr> -<td><span class="new_code">setConnectionTimeout($timeout)</span></td> -<td>Ferme la socket avec un délai trop long</td> -</tr> - <tr> -<td><span class="new_code">getUrl()</span></td> -<td>L'URL de la page chargée le plus récemment</td> -</tr> - <tr> -<td><span class="new_code">getRequest()</span></td> -<td>L'entête de la requête brute de la page ou de la fenêtre</td> -</tr> - <tr> -<td><span class="new_code">getHeaders()</span></td> -<td>L'entête de réponse de la page ou de la fenêtre</td> -</tr> - <tr> -<td><span class="new_code">getTransportError()</span></td> -<td>N'importe quel erreur au niveau de la socket dans le dernier téléchargement</td> -</tr> - <tr> -<td><span class="new_code">getResponseCode()</span></td> -<td>La réponse HTTP de la page ou de la fenêtre</td> -</tr> - <tr> -<td><span class="new_code">getMimeType()</span></td> -<td>Le type Mime de la page our de la fenêtre</td> -</tr> - <tr> -<td><span class="new_code">getAuthentication()</span></td> -<td>Le type d'authentification dans l'entête d'une provocation 401</td> -</tr> - <tr> -<td><span class="new_code">getRealm()</span></td> -<td>Le realm d'authentification dans l'entête d'une provocation 401</td> -</tr> - <tr> -<td><span class="new_code">getBaseUrl()</span></td> -<td>Uniquement la base de l'URL de la page chargée le plus récemment</td> -</tr> - <tr> -<td><span class="new_code">setMaximumRedirects($max)</span></td> -<td>Nombre de redirections avant que la page ne soit chargée automatiquement</td> -</tr> - <tr> -<td><span class="new_code">setMaximumNestedFrames($max)</span></td> -<td>Protection contre des framesets récursifs</td> -</tr> - <tr> -<td><span class="new_code">ignoreFrames()</span></td> -<td>Neutralise le support des fenêtres</td> -</tr> - <tr> -<td><span class="new_code">useFrames()</span></td> -<td>Autorise le support des fenêtres</td> -</tr> - </tbody></table> - Les méthodes <span class="new_code">SimpleBrowser::setConnectionTimeout()</span>, - <span class="new_code">SimpleBrowser::setMaximumRedirects()</span>, - <span class="new_code">SimpleBrowser::setMaximumNestedFrames()</span>, - <span class="new_code">SimpleBrowser::ignoreFrames()</span> - et <span class="new_code">SimpleBrowser::useFrames()</span> continuent à s'appliquer - sur toutes les requêtes suivantes. - Les autres méthodes tiennent compte des fenêtres. - Cela veut dire que si une fenêtre individuelle ne se charge pas, - il suffit de se diriger vers elle avec - <span class="new_code">SimpleBrowser::setFrameFocus()</span> : ensuite on utilisera - <span class="new_code">SimpleBrowser::getRequest()</span>, etc. pour voir ce qui se passe. - </p> - - <h2> -<a class="target" name="unit"></a>Tests unitaires complexes avec des navigateurs multiples</h2> - <p> - Tout ce qui peut être fait dans - <a href="web_tester_documentation.html">WebTestCase</a> peut maintenant - être fait dans un <a href="unit_tester_documentation.html">UnitTestCase</a>. - Ce qui revient à dire que nous pouvons librement mélanger - des tests sur des objets de domaine avec l'interface web... -<pre><strong> -class TestOfRegistration extends UnitTestCase { - function testNewUserAddedToAuthenticator() {</strong> - $browser = new SimpleBrowser(); - $browser->get('http://my-site.com/register.php'); - $browser->setField('email', 'me@here'); - $browser->setField('password', 'Secret'); - $browser->clickSubmit('Register'); - <strong> - $authenticator = new Authenticator(); - $member = $authenticator->findByEmail('me@here'); - $this->assertEqual($member->getPassword(), 'Secret');</strong> - } -} -</pre> - Bien que ça puisse être utile par convenance temporaire, - je ne suis pas fan de ce genre de test. Ce test s'applique - à plusieurs couches de l'application, ça implique qu'il est - plus que probable qu'il faudra le remanier lorsque le code changera. - </p> - <p> - Un cas plus utile d'utilisation directe du navigateur est - le moment où le <span class="new_code">WebTestCase</span> ne peut plus suivre. - Un exemple ? Quand deux navigateurs doivent être utilisés en même temps. - </p> - <p> - Par exemple, supposons que nous voulions interdire - des usages simultanés d'un site avec le même login d'identification. - Ce scénario de test le vérifie... -<pre> -class TestOfSecurity extends UnitTestCase { - function testNoMultipleLoginsFromSameUser() { - $first = &new SimpleBrowser(); - $first->get('http://my-site.com/login.php'); - $first->setField('name', 'Me'); - $first->setField('password', 'Secret'); - $first->clickSubmit('Enter'); - $this->assertEqual($first->getTitle(), 'Welcome'); - - $second = &new SimpleBrowser(); - $second->get('http://my-site.com/login.php'); - $second->setField('name', 'Me'); - $second->setField('password', 'Secret'); - $second->clickSubmit('Enter'); - $this->assertEqual($second->getTitle(), 'Access Denied'); - } -} -</pre> - Vous pouvez aussi utiliser la classe <span class="new_code">SimpleBrowser</span> - quand vous souhaitez écrire des scénarios de test en utilisant - un autre outil que SimpleTest, comme PHPUnit par exemple. - </p> - - </div> - References and related information... - <ul> -<li> - La page du projet SimpleTest sur - <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - La page de téléchargement de SimpleTest sur - <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - <a href="http://simpletest.org/api/">L'API de développeur pour SimpleTest</a> - donne tous les détails sur les classes et les assertions disponibles. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/docs.css b/3rdparty/simpletest/docs/fr/docs.css deleted file mode 100755 index 49170486ab373695859cedde4296e415915393ab..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/docs.css +++ /dev/null @@ -1,84 +0,0 @@ -body { - padding-left: 3%; - padding-right: 3%; -} -pre { - font-family: "courier new", courier; - font-size: 80%; - border: 1px solid; - background-color: #cccccc; - padding: 5px; - margin-left: 5%; - margin-right: 8%; -} -.code, .new_code, pre.new_code { - font-weight: bold; -} -div.copyright { - font-size: 80%; - color: gray; -} -div.copyright a { - color: gray; -} -ul.api { - padding-left: 0em; - padding-right: 25%; -} -ul.api li { - margin-top: 0.2em; - margin-bottom: 0.2em; - list-style: none; - text-indent: -3em; - padding-left: 3em; -} -div.demo { - border: 4px ridge; - border-color: gray; - padding: 10px; - margin: 5px; - margin-left: 20px; - margin-right: 40px; - background-color: white; -} -div.demo span.fail { - color: red; -} -div.demo span.pass { - color: green; -} -div.demo h1 { - font-size: 12pt; - text-align: left; - font-weight: bold; -} -table { - border: 2px outset; - border-color: gray; - background-color: white; - margin: 5px; - margin-left: 5%; - margin-right: 5%; -} -td { - font-size: 80%; -} -.shell { - color: white; -} -pre.shell { - border: 4px ridge; - border-color: gray; - padding: 10px; - margin: 5px; - margin-left: 20px; - margin-right: 40px; - background-color: black; -} -form.demo { - background-color: lightgray; - border: 4px outset; - border-color: lightgray; - padding: 10px; - margin-right: 40%; -} diff --git a/3rdparty/simpletest/docs/fr/expectation_documentation.html b/3rdparty/simpletest/docs/fr/expectation_documentation.html deleted file mode 100644 index ee579110a6ded937fbad65b7d392223ab7f84d36..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/expectation_documentation.html +++ /dev/null @@ -1,451 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>Documentation SimpleTest : étendre le testeur unitaire avec des classes d'attentes supplémentaires</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Documentation sur les attentes</h1> - This page... - <ul> -<li> - Utiliser les attentes <a href="#fantaisie">pour des tests - plus précis avec des objets fantaisie</a> - </li> -<li> - <a href="#comportement">Changer le comportement d'un objet fantaisie</a> - avec des attentes - </li> -<li> - <a href="#etendre">Créer des attentes</a> - </li> -<li> - Par dessous SimpleTest <a href="#unitaire">utilise des classes d'attente</a> - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="fantaisie"></a>Plus de contrôle sur les objets fantaisie</h2> - <p> - Le comportement par défaut des - <a href="mock_objects_documentation.html">objets fantaisie</a> dans - <a href="http://sourceforge.net/projects/simpletest/">SimpleTest</a> - est soit une correspondance identique sur l'argument, - soit l'acceptation de n'importe quel argument. - Pour la plupart des tests, c'est suffisant. - Cependant il est parfois nécessaire de ramollir un scénario de test. - </p> - <p> - Un des endroits où un test peut être trop serré - est la reconnaissance textuelle. Prenons l'exemple - d'un composant qui produirait un message d'erreur - utile lorsque quelque chose plante. Il serait utile de tester - que l'erreur correcte est renvoyée, - mais le texte proprement dit risque d'être plutôt long. - Si vous testez le texte dans son ensemble alors - à chaque modification de ce même message - -- même un point ou une virgule -- vous aurez - à revenir sur la suite de test pour la modifier. - </p> - <p> - Voici un cas concret, nous avons un service d'actualités - qui a échoué dans sa tentative de connexion à sa source distante. -<pre> -<strong>class NewsService { - ... - function publish($writer) { - if (! $this->isConnected()) { - $writer->write('Cannot connect to news service "' . - $this->_name . '" at this time. ' . - 'Please try again later.'); - } - ... - } -}</strong> -</pre> - Là il envoie son contenu vers un classe <span class="new_code">Writer</span>. - Nous pourrions tester ce comportement avec un <span class="new_code">MockWriter</span>... -<pre> -class TestOfNewsService extends UnitTestCase { - ... - function testConnectionFailure() {<strong> - $writer = new MockWriter($this); - $writer->expectOnce('write', array( - 'Cannot connect to news service ' . - '"BBC News" at this time. ' . - 'Please try again later.')); - - $service = new NewsService('BBC News'); - $service->publish($writer); - - $writer->tally();</strong> - } -} -</pre> - C'est un bon exemple d'un test fragile. - Si nous décidons d'ajouter des instructions complémentaires, - par exemple proposer une source d'actualités alternative, - nous casserons nos tests par la même occasion sans pourtant - avoir modifié une seule fonctionnalité. - </p> - <p> - Pour contourner ce problème, nous voudrions utiliser - un test avec une expression rationnelle plutôt - qu'une correspondance exacte. Nous pouvons y parvenir avec... -<pre> -class TestOfNewsService extends UnitTestCase { - ... - function testConnectionFailure() { - $writer = new MockWriter($this);<strong> - $writer->expectOnce( - 'write', - array(new PatternExpectation('/cannot connect/i')));</strong> - - $service = new NewsService('BBC News'); - $service->publish($writer); - - $writer->tally(); - } -} -</pre> - Plutôt que de transmettre le paramètre attendu au <span class="new_code">MockWriter</span>, - nous envoyons une classe d'attente appelée <span class="new_code">PatternExpectation</span>. - L'objet fantaisie est suffisamment élégant pour reconnaître - qu'il s'agit d'un truc spécial et pour le traiter différemment. - Plutôt que de comparer l'argument entrant à cet objet, - il utilise l'objet attente lui-même pour exécuter le test. - </p> - <p> - <span class="new_code">PatternExpectation</span> utilise - l'expression rationnelle pour la comparaison avec son constructeur. - A chaque fois qu'une comparaison est fait à travers - <span class="new_code">MockWriter</span> par rapport à cette classe attente, - elle fera un <span class="new_code">preg_match()</span> avec ce motif. - Dans notre scénario de test ci-dessus, aussi longtemps - que la chaîne "cannot connect" apparaît dans le texte, - la fantaisie transmettra un succès au testeur unitaire. - Peu importe le reste du texte. - </p> - <p> - Les classes attente possibles sont... - <table><tbody> - <tr> -<td><span class="new_code">AnythingExpectation</span></td> -<td>Sera toujours validé</td> -</tr> - <tr> -<td><span class="new_code">EqualExpectation</span></td> -<td>Une égalité, plutôt que la plus forte comparaison à l'identique</td> -</tr> - <tr> -<td><span class="new_code">NotEqualExpectation</span></td> -<td>Une comparaison sur la non-égalité</td> -</tr> - <tr> -<td><span class="new_code">IndenticalExpectation</span></td> -<td>La vérification par défaut de l'objet fantaisie qui doit correspondre exactement</td> -</tr> - <tr> -<td><span class="new_code">NotIndenticalExpectation</span></td> -<td>Inverse la logique de l'objet fantaisie</td> -</tr> - <tr> -<td><span class="new_code">PatternExpectation</span></td> -<td>Utilise une expression rationnelle Perl pour comparer une chaîne</td> -</tr> - <tr> -<td><span class="new_code">NoPatternExpectation</span></td> -<td>Passe seulement si l'expression rationnelle Perl échoue</td> -</tr> - <tr> -<td><span class="new_code">IsAExpectation</span></td> -<td>Vérifie le type ou le nom de la classe uniquement</td> -</tr> - <tr> -<td><span class="new_code">NotAExpectation</span></td> -<td>L'opposé de <span class="new_code">IsAExpectation</span> -</td> -</tr> - <tr> -<td><span class="new_code">MethodExistsExpectation</span></td> -<td>Vérifie si la méthode est disponible sur un objet</td> -</tr> - <tr> -<td><span class="new_code">TrueExpectation</span></td> -<td>Accepte n'importe quelle variable PHP qui vaut vrai</td> -</tr> - <tr> -<td><span class="new_code">FalseExpectation</span></td> -<td>Accepte n'importe quelle variable PHP qui vaut faux</td> -</tr> - </tbody></table> - La plupart utilisent la valeur attendue dans le constructeur. - Les exceptions sont les vérifications sur motif, - qui utilisent une expression rationnelle, ainsi que - <span class="new_code">IsAExpectation</span> et <span class="new_code">NotAExpectation</span>, - qui prennent un type ou un nom de classe comme chaîne. - </p> - - <h2> -<a class="target" name="comportement"></a>Utiliser les attentes pour contrôler les bouchons serveur</h2> - <p> - Les classes attente peuvent servir à autre chose - que l'envoi d'assertions depuis les objets fantaisie, - afin de choisir le comportement d'un - <a href="mock_objects_documentation.html">objet fantaisie</a> - ou celui d'un <a href="server_stubs_documentation.html">bouchon serveur</a>. - A chaque fois qu'une liste d'arguments est donnée, - une liste d'objets d'attente peut être insérée à la place. - </p> - <p> - Mettons que nous voulons qu'un bouchon serveur - d'autorisation simule une connexion réussie seulement - si il reçoit un objet de session valide. - Nous pouvons y arriver avec ce qui suit... -<pre> -Stub::generate('Authorisation'); -<strong> -$authorisation = new StubAuthorisation(); -$authorisation->returns( - 'isAllowed', - true, - array(new IsAExpectation('Session', 'Must be a session'))); -$authorisation->returns('isAllowed', false);</strong> -</pre> - Le comportement par défaut du bouchon serveur - est défini pour renvoyer <span class="new_code">false</span> - quand <span class="new_code">isAllowed</span> est appelé. - Lorsque nous appelons cette méthode avec un unique paramètre - qui est un objet <span class="new_code">Session</span>, il renverra <span class="new_code">true</span>. - Nous avons aussi ajouté un deuxième paramètre comme message. - Il sera affiché dans le message d'erreur de l'objet fantaisie - si l'attente est la cause de l'échec. - </p> - <p> - Ce niveau de sophistication est rarement utile : - il n'est inclut que pour être complet. - </p> - - <h2> -<a class="target" name="etendre"></a>Créer vos propres attentes</h2> - <p> - Les classes d'attentes ont une structure très simple. - Tellement simple qu'il devient très simple de créer - vos propres version de logique pour des tests utilisés couramment. - </p> - <p> - Par exemple voici la création d'une classe pour tester - la validité d'adresses IP. Pour fonctionner correctement - avec les bouchons serveurs et les objets fantaisie, - cette nouvelle classe d'attente devrait étendre - <span class="new_code">SimpleExpectation</span> ou une autre de ses sous-classes... -<pre> -<strong>class ValidIp extends SimpleExpectation { - - function test($ip) { - return (ip2long($ip) != -1); - } - - function testMessage($ip) { - return "Address [$ip] should be a valid IP address"; - } -}</strong> -</pre> - Il n'y a véritablement que deux méthodes à mettre en place. - La méthode <span class="new_code">test()</span> devrait renvoyer un <span class="new_code">true</span> - si l'attente doit passer, et une erreur <span class="new_code">false</span> - dans le cas contraire. La méthode <span class="new_code">testMessage()</span> - ne devrait renvoyer que du texte utile à la compréhension du test en lui-même. - </p> - <p> - Cette classe peut désormais être employée à la place - des classes d'attente précédentes. - </p> - <p> - Voici un exemple plus typique, vérifier un hash... -<pre> -<strong>class JustField extends EqualExpectation { - private $key; - - function __construct($key, $expected) { - parent::__construct($expected); - $this->key = $key; - } - - function test($compare) { - if (! isset($compare[$this->key])) { - return false; - } - return parent::test($compare[$this->key]); - } - - function testMessage($compare) { - if (! isset($compare[$this->key])) { - return 'Key [' . $this->key . '] does not exist'; - } - return 'Key [' . $this->key . '] -> ' . - parent::testMessage($compare[$this->key]); - } -}</strong> -</pre> - L'habitude a été prise pour séparer les clauses du message avec - "&nbsp;->&nbsp;". - Cela permet aux outils dérivés de reformater la sortie. - </p> - <p> - Supposons qu'un authentificateur s'attend à recevoir - une ligne de base de données correspondant à l'utilisateur, - et que nous avons juste besoin de valider le nom d'utilisateur. - Nous pouvons le faire très simplement avec... -<pre> -$mock->expectOnce('authenticate', - array(new JustKey('username', 'marcus'))); -</pre> - </p> - - <h2> -<a class="target" name="unitaire"></a>Sous le capot du testeur unitaire</h2> - <p> - Le <a href="http://sourceforge.net/projects/simpletest/">framework - de test unitaire SimpleTest</a> utilise aussi dans son coeur - des classes d'attente pour - la <a href="unit_test_documentation.html">classe UnitTestCase</a>. - Nous pouvons aussi tirer parti de ces mécanismes pour réutiliser - nos propres classes attente à l'intérieur même des suites de test. - </p> - <p> - La méthode la plus directe est d'utiliser la méthode - <span class="new_code">SimpleTest::assert()</span> pour effectuer le test... -<pre> -<strong>class TestOfNetworking extends UnitTestCase { - ... - function testGetValidIp() { - $server = &new Server(); - $this->assert( - new ValidIp(), - $server->getIp(), - 'Server IP address->%s'); - } -}</strong> -</pre> - <span class="new_code">assert()</span> testera toute attente directement. - </p> - <p> - C'est plutôt sale par rapport à notre syntaxe habituelle - du type <span class="new_code">assert...()</span>. - </p> - <p> - Pour un cas aussi simple, nous créons d'ordinaire une méthode - d'assertion distincte en utilisant la classe d'attente. - Supposons un instant que notre attente soit un peu plus - compliquée et que par conséquent nous souhaitions la réutiliser, - nous obtenons... -<pre> -class TestOfNetworking extends UnitTestCase { - ...<strong> - function assertValidIp($ip, $message = '%s') { - $this->assertExpectation(new ValidIp(), $ip, $message); - }</strong> - - function testGetValidIp() { - $server = &new Server();<strong> - $this->assertValidIp( - $server->getIp(), - 'Server IP address->%s');</strong> - } -} -</pre> - It is rare to need the expectations for more than pattern - matching, but these facilities do allow testers to build - some sort of domain language for testing their application. - Also, complex expectation classes could make the tests - harder to read and debug. - In effect extending the test framework to create their own tool set. - - - Il est assez rare que le besoin d'une attente dépasse - le stade de la reconnaissance d'un motif, mais ils permettent - aux testeurs de construire leur propre langage dédié ou DSL - (Domain Specific Language) pour tester leurs applications. - Attention, les classes d'attente complexes peuvent rendre - les tests difficiles à lire et à déboguer. - Ces mécanismes sont véritablement là pour les auteurs - de système qui étendront le framework de test - pour leurs propres outils de test. - </p> - - </div> - References and related information... - <ul> -<li> - La page du projet SimpleTest sur - <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - La page de téléchargement de SimpleTest sur - <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - Les attentes imitent les contraintes dans - <a href="http://www.jmock.org/">JMock</a>. - </li> -<li> - <a href="http://simpletest.org/api/">L'API complète pour SimpleTest</a> - réalisé avec PHPDoc. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/form_testing_documentation.html b/3rdparty/simpletest/docs/fr/form_testing_documentation.html deleted file mode 100644 index e3cb6a10a19031802dd4b47b45905483cc973ddd..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/form_testing_documentation.html +++ /dev/null @@ -1,363 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>Documentation SimpleTest : tester des formulaires HTML</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Documentation sur les tests de formulaire</h1> - This page... - <ul> -<li> - Modifier les valeurs d'un formulaire et - <a href="#submit">réussir à transmettre un simple formulaire</a> - </li> -<li> - Gérer des <a href="#multiple">objets à valeurs multiples</a> - en initialisant des listes. - </li> -<li> - Le cas des formulaires utilisant Javascript pour - modifier <a href="#hidden-field">un champ caché</a> - </li> -<li> - <a href="#brut">Envoi brut</a> quand il n'existe pas de bouton à cliquer. - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="submit"></a>Valider un formulaire simple</h2> - <p> - Lorsqu'une page est téléchargée par <span class="new_code">WebTestCase</span> - en utilisant <span class="new_code">get()</span> ou <span class="new_code">post()</span> - le contenu de la page est automatiquement analysé. - De cette analyse découle le fait que toutes les commandes - à l'intérieur de la balise <form> sont disponibles - depuis l'intérieur du scénario de test. - Prenons par exemple cet extrait de code HTML... -<pre> -<form> - <input type="text" name="a" value="A default" /> - <input type="submit" value="Go" /> -</form> -</pre> - Il ressemble à... - </p> - <p> - <form class="demo"> - <input type="text" name="a" value="A default"> - <input type="submit" value="Go"> - </form> - </p> - <p> - Nous pouvons naviguer vers ce code, via le site - <a href="http://www.lastcraft.com/form_testing_documentation.php">LastCraft</a>, - avec le test suivant... -<pre> -class SimpleFormTests extends WebTestCase {<strong> - function testDefaultValue() { - $this->get('http://www.lastcraft.com/form_testing_documentation.php'); - $this->assertField('a', 'A default'); - }</strong> -} -</pre> - Directement après le chargement de la page toutes les commandes HTML - sont initiées avec leur valeur par défaut, comme elles apparaîtraient - dans un navigateur web. L'assertion teste qu'un objet HTML - avec le nom "a" existe dans la page - et qu'il contient la valeur "A default". - </p> - <p> - Nous pourrions retourner le formulaire tout de suite... -<pre> -class SimpleFormTests extends WebTestCase { - function testDefaultValue() { - $this->get('http://www.lastcraft.com/form_testing_documentation.php'); - $this->assertField('a', <strong>new PatternExpectation('/default/')</strong>); - } -} -</pre> - Mais d'abord nous allons changer la valeur du champ texte. - Ce n'est qu'après que nous le transmettrons... -<pre> -class SimpleFormTests extends WebTestCase { - - function testDefaultValue() { - $this->get('http://www.my-site.com/'); - $this->assertField('a', 'A default');<strong> - $this->setField('a', 'New value'); - $this->clickSubmit('Go');</strong> - } -} -</pre> - Parce que nous n'avons spécifié ni attribut "method" - sur la balise form, ni attribut "action", - le scénario de test suivra le comportement classique d'un navigateur : - transmission des données avec une requête <em>GET</em> - vers la même page. En règle générale SimpleTest essaie d'émuler - le comportement typique d'un navigateur autant que possible, - plutôt que d'essayer d'attraper des attributs manquants sur les balises. - La raison est simple : la cible d'un framework de test est - la logique d'une application PHP, pas les erreurs - -- de syntaxe ou autres -- du code HTML. - Pour les erreurs HTML, d'autres outils tel - <a href="http://www.w3.org/People/Raggett/tidy/">HTMLTidy</a> - devraient être employés, ou même n'importe lequel des validateurs HTML et CSS - déjà sur le marché. - </p> - <p> - Si un champ manque dans n'importe quel formulaire ou si - une option est indisponible alors <span class="new_code">WebTestCase::setField()</span> - renverra <span class="new_code">false</span>. Par exemple, supposons que - nous souhaitons vérifier qu'une option "Superuser" - n'est pas présente dans ce formulaire... -<pre> -<strong>Select type of user to add:</strong> -<select name="type"> - <option>Subscriber</option> - <option>Author</option> - <option>Administrator</option> -</select> -</pre> - Qui ressemble à... - </p> - <p> - <form class="demo"> - <strong>Select type of user to add:</strong> - <select name="type"> - <option>Subscriber</option> - <option>Author</option> - <option>Administrator</option> - </select> - </form> - </p> - <p> - Le test suivant le confirmera... -<pre> -class SimpleFormTests extends WebTestCase { - ... - function testNoSuperuserChoiceAvailable() {<strong> - $this->get('http://www.lastcraft.com/form_testing_documentation.php'); - $this->assertFalse($this->setField('type', 'Superuser'));</strong> - } -} -</pre> - La sélection ne sera pas changée si la nouvelle valeur n'est pas une des options. - </p> - <p> - Voici la liste complète des objets supportés à aujourd'hui... - <ul> - <li>Champs texte, y compris les champs masqués (hidden) ou cryptés (password).</li> - <li>Boutons submit, en incluant aussi la balise button, mais pas encore les boutons reset</li> - <li>Aires texte (textarea) avec leur gestion des retours à la ligne (wrap).</li> - <li>Cases à cocher, y compris les cases à cocher multiples dans un même formulaire.</li> - <li>Listes à menu déroulant, y compris celles à sélections multiples.</li> - <li>Boutons radio.</li> - <li>Images.</li> - </ul> - </p> - <p> - Le navigateur proposé par SimpleTest émule les actions - qui peuvent être réalisées par un utilisateur sur - une page HTML standard. Javascript n'est pas supporté et - il y a peu de chance pour qu'il le soit prochainement. - </p> - <p> - Une attention particulière doit être porté aux techniques Javascript - qui changent la valeur d'un champ caché : elles ne peuvent pas être - réalisées avec les commandes classiques de SimpleTest. - Une méthode alternative est proposée plus loin. - </p> - - <h2> -<a class="target" name="multiple"></a>Champs à valeurs multiples</h2> - <p> - SimpleTest peut gérer deux types de commandes à valeur multiple : - les menus déroulants à sélection multiple et les cases à cocher - avec le même nom à l'intérieur même d'un formulaire. - La nature de ceux-ci implique que leur initialisation - et leur test sont légèrement différents. - Voici un exemple avec des cases à cocher... -<pre> -<form class="demo"> - <strong>Create privileges allowed:</strong> - <input type="checkbox" name="crud" value="c" checked><br> - <strong>Retrieve privileges allowed:</strong> - <input type="checkbox" name="crud" value="r" checked><br> - <strong>Update privileges allowed:</strong> - <input type="checkbox" name="crud" value="u" checked><br> - <strong>Destroy privileges allowed:</strong> - <input type="checkbox" name="crud" value="d" checked><br> - <input type="submit" value="Enable Privileges"> -</form> -</pre> - Qui se traduit par... - </p> - <p> - <form class="demo"> - <strong>Create privileges allowed:</strong> - <input type="checkbox" name="crud" value="c" checked><br> - <strong>Retrieve privileges allowed:</strong> - <input type="checkbox" name="crud" value="r" checked><br> - <strong>Update privileges allowed:</strong> - <input type="checkbox" name="crud" value="u" checked><br> - <strong>Destroy privileges allowed:</strong> - <input type="checkbox" name="crud" value="d" checked><br> - <input type="submit" value="Enable Privileges"> - </form> - </p> - <p> - Si nous souhaitons désactiver tous les privilèges sauf - ceux de téléchargement (Retrieve) et transmettre cette information, - nous pouvons y arriver par... -<pre> -class SimpleFormTests extends WebTestCase { - ...<strong> - function testDisableNastyPrivileges() { - $this->get('http://www.lastcraft.com/form_testing_documentation.php'); - $this->assertField('crud', array('c', 'r', 'u', 'd')); - $this->setField('crud', array('r')); - $this->clickSubmit('Enable Privileges'); - }</strong> -} -</pre> - Plutôt que d'initier le champ à une valeur unique, - nous lui donnons une liste de valeurs. - Nous faisons la même chose pour tester les valeurs attendues. - Nous pouvons écrire d'autres bouts de code de test - pour confirmer cet effet, peut-être en nous connectant - comme utilisateur et en essayant d'effectuer une mise à jour. - </p> - - <h2> -<a class="target" name="hidden-field"></a>Formulaires utilisant Javascript pour changer un champ caché</h2> - <p> - Si vous souhaitez tester un formulaire dépendant de Javascript - pour la modification d'un champ caché, vous ne pouvez pas - simplement utiliser setField(). - Le code suivant <em>ne fonctionnera pas</em> : -<pre> -class SimpleFormTests extends WebTestCase { - function testEmulateMyJavascriptForm() { - <strong>// This does *not* work</strong> - $this->setField('a_hidden_field', '123'); - $this->clickSubmit('OK'); - } -} -</pre> - A la place, vous aurez besoin d'ajouter le paramètre supplémentaire - du formulaire à la méthode clickSubmit() : -<pre> -class SimpleFormTests extends WebTestCase { - function testMyJavascriptForm() { - <strong>$this->clickSubmit('OK', array('a_hidden_field'=>'123'));</strong> - } - -} -</pre> - </p> - <p> - N'oubliez pas que de la sorte, vous êtes effectivement en train - de court-circuitez une partie de votre application (le code Javascript - dans le formulaire) et que peut-être serait-il plus prudent - d'utiliser un outil comme - <a href="http://selenium.openqa.org/">Selenium</a> pour mettre sur pied - un test complet. - </p> - - <h2> -<a class="target" name="brut"></a>Envoi brut</h2> - <p> - Si vous souhaitez tester un gestionnaire de formulaire - mais que vous ne l'avez pas écrit ou que vous n'y avez - pas encore accès, vous pouvez créer un envoi de formulaire à la main. -<pre> -class SimpleFormTests extends WebTestCase { - ...<strong> - function testAttemptedHack() { - $this->post( - 'http://www.my-site.com/add_user.php', - array('type' => 'superuser')); - $this->assertNoUnwantedPattern('/user created/i'); - }</strong> -} -</pre> - En ajoutant des données à la méthode <span class="new_code">WebTestCase::post()</span>, - nous émulons la transmission d'un formulaire. - D'ordinaire, vous ne ferez cela que pour parer au plus pressé, - ou alors si vous espérez un tiers (javascript ?) transmette le formulaire. - Il reste quand même exception : si vous souhaitez vous protégez - d'attaques de type "spoofing". - </p> - - </div> - References and related information... - <ul> -<li> - La page du projet SimpleTest sur - <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - La page de téléchargement de SimpleTest sur - <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - <a href="http://simpletest.org/api/">L'API du développeur pour SimpleTest</a> - donne tous les détails sur les classes et les assertions disponibles. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/group_test_documentation.html b/3rdparty/simpletest/docs/fr/group_test_documentation.html deleted file mode 100644 index fb546af4603b69ca1e79dae02f4f40aae0f92e5a..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/group_test_documentation.html +++ /dev/null @@ -1,265 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>Documentation SimpleTest : Grouper des tests</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Documentation sur le groupement des tests</h1> - This page... - <ul> -<li> - Plusieurs approches pour <a href="#group">grouper des tests</a> ensemble. - </li> -<li> - Combiner des groupes des tests dans des - <a href="#plus-haut">groupes plus grands</a>. - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="grouper"></a>Grouper des tests</h2> - <p> - Il existe beaucoup de moyens pour grouper des tests dans des suites de tests. - Le premier d'entre eux est tout simplement ajouter tous les scénarios de test - au fur et à mesure d'un unique fichier... -<pre> -<strong><?php -require_once(dirname(__FILE__) . '/simpletest/autorun.php'); -require_once(dirname(__FILE__) . '/../classes/io.php'); - -class FileTester extends UnitTestCase { - ... -} - -class SocketTester extends UnitTestCase { - ... -} -?></strong> -</pre> - Autant de scénarios que nécessaires peuvent être - mis dans cet unique fichier. Ils doivent contenir - tout le code nécessaire, entre autres la bibliothèque testée, - mais aucune des bibliothèques de SimpleTest. - </p> - <p> - Occasionnellement des sous-classes spéciales sont créés pour - ajouter des méthodes nécessaires à certains tests spécifiques - au sein de l'application. - Ces nouvelles classes de base sont ensuite utilisées - à la place de <span class="new_code">UnitTestCase</span> - ou de <span class="new_code">WebTestCase</span>. - Bien sûr vous ne souhaitez pas les lancer en tant que - scénario de tests : il suffit alors de les identifier - comme "abstraites"... -<pre> -<strong>abstract</strong> class MyFileTestCase extends UnitTestCase { - ... -} - -class FileTester extends MyFileTestCase { ... } - -class SocketTester extends UnitTestCase { ... } -</pre> - La classe <span class="new_code">FileTester</span> ne contient aucun test véritable, - il s'agit d'une classe de base pour d'autres scénarios de test. - </p> - <p> - Nous appelons ce fichier <em>file_test.php</em>. - Pour l'instant les scénarios de tests sont simplement groupés dans le même fichier. - Nous pouvons mettre en place des structures plus importantes - en incluant d'autres fichiers de tests. -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('file_test.php'); -?> -</pre> - Ceci fontionnera, tout en créant une hiérarchie tout à fait plate. - A la place, nous créons un fichier de suite de tests. - Notre suite des tests de premier niveau devient... -<pre> -<?php -require_once('simpletest/autorun.php'); - -class AllFileTests extends TestSuite { - function __construct() { - parent::__construct(); - <strong>$this->addFile('file_test.php');</strong> - } -} -?> -</pre> - Voici ce qui arrive : la class <span class="new_code">TestSuite</span> - effecturera le <span class="new_code">require_once()</span> pour nous. - Ensuite elle vérifie si de nouvelles classes de test - ont été créées par ce nouveau fichier et les inclut - automatiquement dans la suite de tests. - Cette méthode nous donne un maximum de contrôle - tout comme le ferait des ajouts manuels de fichiers de tests - au fur et à mesure où notre suite grandit. - </p> - <p> - Si c'est trop de boulot pour vos petits doigts et qu'en plus - vous avez envie de grouper vos suites de tests par répertoire - ou par un tag dans le nom des fichiers, alors il y a un moyen - encore plus automatique... -<pre> -<?php -require_once('simpletest/autorun.php'); - -class AllFileTests extends TestSuite { - function __construct() { - parent::__construct(); - $this->collect(dirname(__FILE__) . '/unit', - new SimplePatternCollector('/_test.php/')); - } -} -?> -</pre> - Cette fonctionnalités va scanner un répertoire appelé "unit", - y détecter tous les fichiers finissant par "_test.php" - et les charger. - Vous n'avez pas besoin d'utiliser <span class="new_code">SimplePatternCollector</span> pour - filtrer en fonction d'un motif dans le nom de fichier, - mais c'est son usage le plus courant. - </p> - <p> - Ce morceau de code est très courant. - Désormais la seule chose qu'il vous reste à faire, c'est de - déposer un fichier avec des scénarios de tests dans ce répertoire - et il sera lancé directement par le script de la suite de tests. - </p> - <p> - Juste un bémol : vous ne pouvez pas contrôler l'ordre de lancement - des tests. - Si vous souhaitez voir des composants de bas niveau renvoyer leurs erreurs - dès le début de la suite de tests - en particulier pour se facilier le travail - de diagnostic - alors vous devriez plutôt passer par <span class="new_code">addFile()</span> - pour ces cas spécifiques. - Les scénarios de tests ne sont chargés qu'une fois, pas d'inquiétude donc - lors du scan de votre répertoire avec tous les tests. - </p> - <p> - Les tests chargés avec la méthode <span class="new_code">addFile</span> ont certaines propriétés - qui peuvent s'avérer intéressantes. - Elle vous assure que le constructeur est lancé avant la première méthode - de test et que le destructeur est lancé après la dernière méthode de test. - Cela vous permet de placer une initialisation (setUp et tearDown) globale - au sein de ce destructeur et desctructeur, comme dans n'importe - quelle classe. - </p> - - <h2> -<a class="target" name="plus-haut"></a>Groupements de plus haut niveau</h2> - <p> - La technique ci-dessus place tous les scénarios de test - dans un unique et grand groupe. - Sauf que pour des projets plus conséquents, - ce n'est probablement pas assez souple; - vous voudriez peut-être grouper les tests tout à fait différemment. - </p> -<p> - Tout ce que nous avons décrit avec des scripts de tests - s'applique pareillement avec des <span class="new_code">TestSuite</span>s... -<pre> -<?php -require_once('simpletest/autorun.php'); -<strong> -class BigTestSuite extends TestSuite { - function __construct() { - parent::__construct(); - $this->addFile('file_tests.php'); - } -}</strong> -?> -</pre> - Cette opération additionne nos scénarios de tests et une unique suite - sous la première. - Quand un test échoue, nous voyons le fil d'ariane avec l'enchainement. - Nous pouvons même mélanger groupes et tests librement en prenant - quand même soin d'éviter les inclusions en boucle. -<pre> -<?php -require_once('simpletest/autorun.php'); - -class BigTestSuite extends TestSuite { - function __construct() { - parent::__construct(); - $this->addFile('file_tests.php'); - <strong>$this->addFile('some_other_test.php');</strong> - } -} -?> -</pre> - Petite précision, en cas de double inclusion, seule la première instance - sera lancée. - </p> - - </div> - References and related information... - <ul> -<li> - La page du projet SimpleTest sur - <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - La page de téléchargement de SimpleTest sur - <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/index.html b/3rdparty/simpletest/docs/fr/index.html deleted file mode 100644 index f7e022c36ecae8679f28fe93d3f2f065b708aed3..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/index.html +++ /dev/null @@ -1,576 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title> - Prise en main rapide de SimpleTest pour PHP - - Tests unitaire et objets fantaisie pour PHP - </title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Prise en main rapide de SimpleTest</h1> - This page... - <ul> -<li> - <a href="#unit">Utiliser le testeur rapidement</a> - avec un exemple. - </li> -<li> - <a href="#group">Groupes de tests</a> - pour tester en un seul clic. - </li> -<li> - <a href="#mock">Utiliser les objets fantaisie</a> - pour faciliter les tests et gagner en contrôle. - </li> -<li> - <a href="#web">Tester des pages web</a> - au niveau de l'HTML. - </li> -</ul> -<div class="content"> - - <p> - Le présent article présuppose que vous soyez familier avec - le concept de tests unitaires ainsi que celui de développement - web avec le langage PHP. Il s'agit d'un guide pour le nouvel - et impatient utilisateur de - <a href="https://sourceforge.net/project/showfiles.php?group_id=76550">SimpleTest</a>. - Pour une documentation plus complète, particulièrement si - vous découvrez les tests unitaires, consultez la - <a href="http://www.lastcraft.com/unit_test_documentation.php">documentation - en cours</a>, et pour des exemples de scénarios de test, - consultez le - <a href="http://www.lastcraft.com/first_test_tutorial.php">tutorial - sur les tests unitaires</a>. - </p> - - <h2> -<a class="target" name="unit"></a>Utiliser le testeur rapidement</h2> - <p> - Parmi les outils de test pour logiciel, le testeur unitaire - est le plus proche du développeur. Dans un contexte de - développement agile, le code de test se place juste à côté - du code source étant donné que tous les deux sont écrits - simultanément. Dans ce contexte, SimpleTest aspire à être - une solution complète de test pour un développeur PHP et - s'appelle "Simple" parce qu'elle devrait être simple à - utiliser et à étendre. Ce nom n'était pas vraiment un bon - choix. Non seulement cette solution inclut toutes les - fonctions classiques qu'on est en droit d'attendre de la - part des portages de <a href="http://www.junit.org/">JUnit</a> et des <a href="http://sourceforge.net/projects/phpunit/">PHPUnit</a>, - mais elle inclut aussi les <a href="http://www.mockobjects.com/">objets fantaisie ou - "mock objects"</a>. - </p> - <p> - Ce qui rend cet outil immédiatement utile pour un développeur PHP, - c'est son navigateur web interne. - Il permet des tests qui parcourent des sites web, remplissent - des formulaires et testent le contenu des pages. - Etre capable d'écrire ces tests en PHP veut dire qu'il devient - facile d'écrire des tests de recette (ou d'intégration). - Un exemple serait de confirmer qu'un utilisateur a bien été ajouté - dans une base de données après s'être enregistré sur une site web. - </p> - <p> - La démonstration la plus rapide : l'exemple - </p> - <p> - Supposons que nous sommes en train de tester une simple - classe de log dans un fichier : elle s'appelle - <span class="new_code">Log</span> dans <em>classes/Log.php</em>. Commençons - par créer un script de test, appelé - <em>tests/log_test.php</em>. Son contenu est le suivant... -<pre> -<?php -<strong>require_once('simpletest/autorun.php');</strong> -require_once('../classes/log.php'); - -class TestOfLogging extends <strong>UnitTestCase</strong> { -} -?> -</pre> - Ici le répertoire <em>simpletest</em> est soit dans le - dossier courant, soit dans les dossiers pour fichiers - inclus. Vous auriez à éditer ces arborescences suivant - l'endroit où vous avez installé SimpleTest. - Le fichier "autorun.php" fait plus que juste inclure - les éléments de SimpleTest : il lance aussi les tests pour nous. - </p> - <p> - <span class="new_code">TestOfLogging</span> est notre premier scénario de test - et il est pour l'instant vide. - Chaque scénario de test est une classe qui étend une des classes - de base de SimpleTest. Nous pouvons avoir autant de classes de ce type - que nous voulons. - </p> - <p> - Avec ces trois lignes d'échafaudage - l'inclusion de notre classe <span class="new_code">Log</span>, nous avons une suite - de tests. Mais pas encore de test ! - </p> - <p> - Pour notre premier test, supposons que la classe <span class="new_code">Log</span> - prenne le nom du fichier à écrire au sein du constructeur, - et que nous avons un répertoire temporaire dans lequel placer - ce fichier. -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('../classes/log.php'); - -class TestOfLogging extends UnitTestCase { - function <strong>testLogCreatesNewFileOnFirstMessage()</strong> { - @unlink('/temp/test.log'); - $log = new Log('/temp/test.log'); - <strong>$this->assertFalse(file_exists('/temp/test.log'));</strong> - $log->message('Should write this to a file'); - <strong>$this->assertTrue(file_exists('/temp/test.log'));</strong> - } -} -?> -</pre> - Au lancement du scénario de test, toutes les méthodes qui - commencent avec la chaîne <span class="new_code">test</span> sont - identifiées puis exécutées. - Si la méthode commence par <span class="new_code">test</span>, c'est un test. - Remarquez bien le nom très long de notre exemple : - <span class="new_code">testLogCreatesNewFileOnFirstMessage()</span>. - C'est bel et bien délibéré : ce style est considéré désirable - et il rend la sortie du test plus lisible. - </p> - <p> - D'ordinaire nous avons bien plusieurs méthodes de tests. - Mais ce sera pour plus tard. - </p> - <p> - Les assertions dans les - méthodes de test envoient des messages vers le framework de - test qui affiche immédiatement le résultat. Cette réponse - immédiate est importante, non seulement lors d'un crash - causé par le code, mais aussi de manière à rapprocher - l'affichage de l'erreur au plus près du scénario de test - concerné via un appel à <span class="new_code">print</span>code>. - </p> - <p> - Pour voir ces résultats lançons effectivement les tests. - Aucun autre code n'est nécessaire, il suffit d'ouvrir - la page dans un navigateur. - </p> - <p> - En cas échec, l'affichage ressemble à... - <div class="demo"> - <h1>TestOfLogging</h1> - <span class="fail">Fail</span>: testcreatingnewfile->True assertion failed.<br> - <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete. - <strong>1</strong> passes and <strong>1</strong> fails.</div> - </div> - ...et si ça passe, on obtient... - <div class="demo"> - <h1>TestOfLogging</h1> - <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete. - <strong>2</strong> passes and <strong>0</strong> fails.</div> - </div> - Et si vous obtenez ça... - <div class="demo"> - <b>Fatal error</b>: Failed opening required '../classes/log.php' (include_path='') in <b>/home/marcus/projects/lastcraft/tutorial_tests/Log/tests/log_test.php</b> on line <b>7</b> - </div> - c'est qu'il vous manque le fichier <em>classes/Log.php</em> - qui pourrait ressembler à : -<pre> -<?php<strong> -class Log { - function Log($file_path) { - } - - function message() { - } -}</strong> -?> -</pre> - C'est largement plus sympathique d'écrire le code après le test. - Plus que sympatique même - cette technique s'appelle - "Développement Piloté par les Tests" ou - "Test Driven Development" en anglais. - </p> - <p> - Pour plus de renseignements sur le testeur, voyez la - <a href="unit_test_documentation.html">documentation pour les tests de régression</a>. - </p> - - <h2> -<a class="target" name="group"></a>Construire des groupes de tests</h2> - <p> - Il est peu probable que dans une véritable application on - ait uniquement besoin de passer un seul scénario de test. - Cela veut dire que nous avons besoin de grouper les - scénarios dans un script de test qui peut, si nécessaire, - lancer tous les tests de l'application. - </p> - <p> - Notre première étape est de créer un nouveau fichier appelé - <em>tests/all_tests.php</em> et d'y inclure le code suivant... -<pre> -<?php -<strong>require_once('simpletest/autorun.php');</strong> - -class AllTests extends <strong>TestSuite</strong> { - function AllTests() { - $this->TestSuite(<strong>'All tests'</strong>); - <strong>$this->addFile('log_test.php');</strong> - } -} -?> -</pre> - L'inclusion de "autorun" permettra à notre future suite - de tests d'être lancée juste en invoquant ce script. - </p> - <p> - La sous-classe <span class="new_code">TestSuite</span> doit chaîner - son constructeur. Cette limitation sera supprimée dans - les versions à venir. - </p> - <p> - The method <span class="new_code">TestSuite::addFile()</span> - will include the test case file and read any new classes - that are descended from <span class="new_code">SimpleTestCase</span>. - - Cette méthode <span class="new_code">TestSuite::addTestFile()</span> va - inclure le fichier de scénarios de test et lire parmi - toutes les nouvelles classes créées celles qui sont issues - de <span class="new_code">SimpleTestCase</span>. - <span class="new_code">UnitTestCase</span> est juste un exemple de classe dérivée - depuis <span class="new_code">SimpleTestCase</span> et vous pouvez créer les vôtres. - <span class="new_code">TestSuite::addFile()</span> peut aussi inclure d'autres suites. - </p> - <p> - La classe ne sera pas encore instanciée. - Quand la suite de tests est lancée, elle construira chaque instance - une fois le test atteint, et le détuira juste ensuite. - Cela veut dire que le constructeur n'est lancé qu'une fois avant - chaque initialisation de ce scénario de test et que le destructeur - est lui aussi lancé avant que le test suivant ne commence. - </p> - <p> - Il est commun de grouper des scénarios de test dans des super-classes - qui ne sont pas sensées être lancées, mais qui deviennent une classe de base - pour d'autres tests. - Pour que "autorun" fonctionne proprement les fichiers - des scénarios de test ne devraient pas lancer aveuglement - d'autres extensions de scénarios de test qui ne lanceraient pas - effectivement des tests. - Cela pourrait aboutir à un mauvais comptages des scénarios de test - pendant la procédure. - Pas vraiement un problème majeure, mais pour éviter cet inconvénient - il suffit de marquer vos classes de base comme <span class="new_code">abstract</span>. - SimpleTest ne lance pas les classes abstraites. Et si vous utilisez encore - PHP4 alors une directive <span class="new_code">SimpleTestOptions::ignore()</span> - dans votre fichier de scénario de test aura le même effet. - </p> - <p> - Par ailleurs, le fichier avec le scénario de test ne devrait pas - avoir été inclus ailleurs. Sinon aucun scénario de test - ne sera inclus à ce groupe. - Ceci pourrait se transformer en un problème plus grave : - si des fichiers ont déjà été inclus par PHP alors la méthode - <span class="new_code">TestSuite::addFile()</span> ne les détectera pas. - </p> - <p> - Pour afficher les résultats, il est seulement nécessaire - d'invoquer <em>tests/all_tests.php</em> à partir du serveur - web. - </p> - <p> - Pour plus de renseignements des groupes de tests, voyez le - <a href="group_test_documentation.html">documentation sur le groupement des tests</a>. - </p> - - <h2> -<a class="target" name="mock"></a>Utiliser les objets fantaisie</h2> - <p> - Avançons un peu plus dans le futur. - </p> - <p> - Supposons que notre class logging soit testée et terminée. - Supposons aussi que nous testons une autre classe qui ait - besoin d'écrire des messages de log, disons - <span class="new_code">SessionPool</span>. Nous voulons tester une méthode - qui ressemblera probablement à quelque chose comme... -<pre><strong> -class SessionPool { - ... - function logIn($username) { - ... - $this->_log->message('User $username logged in.'); - ... - } - ... -} -</strong> -</pre> - Avec le concept de "réutilisation de code" comme fil - conducteur, nous utilisons notre class <span class="new_code">Log</span>. Un - scénario de test classique ressemblera peut-être à... -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('../classes/log.php'); -<strong>require_once('../classes/session_pool.php');</strong> - -class <strong>TestOfSessionLogging</strong> extends UnitTestCase { - - function setUp() { - <strong>@unlink('/temp/test.log');</strong> - } - - function tearDown() { - <strong>@unlink('/temp/test.log');</strong> - } - - function testLoggingInIsLogged() { - <strong>$log = new Log('/temp/test.log'); - $session_pool = &new SessionPool($log); - $session_pool->logIn('fred');</strong> - $messages = file('/temp/test.log'); - $this->assertEqual($messages[0], "User fred logged in.<strong>\n</strong>"); - } -} -?> -</pre> - Nous expliquerons les méthodes <span class="new_code">setUp()</span> - et <span class="new_code">tearDown()</span> plus tard. - </p> - <p> - Le design de ce scénario de test n'est pas complètement - mauvais, mais on peut l'améliorer. Nous passons du temps à - tripoter les fichiers de log qui ne font pas partie de - notre test. - Pire, nous avons créé des liens de proximité - entre la classe <span class="new_code">Log</span> et ce test. Que se - passerait-il si nous n'utilisions plus de fichiers, mais la - bibliothèque <em>syslog</em> à la place ? - - Cela veut dire que notre test <span class="new_code">TestOfSessionLogging</span> - enverra un échec alors même qu'il ne teste pas Logging. - </p> - <p> - Il est aussi fragile sur des petites retouches. Avez-vous - remarqué le retour chariot supplémentaire à la fin du - message ? A-t-il été ajouté par le loggueur ? Et si il - ajoutait aussi un timestamp ou d'autres données ? - </p> - <p> - L'unique partie à tester réellement est l'envoi d'un - message précis au loggueur. - Nous pouvons réduire le couplage en - créant une fausse classe de logging : elle ne fait - qu'enregistrer le message pour le test, mais ne produit - aucun résultat. Sauf qu'elle doit ressembler exactement à - l'original. - </p> - <p> - Si l'objet fantaisie n'écrit pas dans un fichier alors nous - nous épargnons la suppression du fichier avant et après le - test. Nous pourrions même nous épargner quelques lignes de - code supplémentaires si l'objet fantaisie pouvait exécuter - l'assertion. - <p> - </p> - Trop beau pour être vrai ? Pas vraiement on peut créer un tel - objet très facilement... -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('../classes/log.php'); -require_once('../classes/session_pool.php'); - -<strong>Mock::generate('Log');</strong> - -class TestOfSessionLogging extends UnitTestCase { - - function testLoggingInIsLogged() {<strong> - $log = &new MockLog(); - $log->expectOnce('message', array('User fred logged in.'));</strong> - $session_pool = &new SessionPool(<strong>$log</strong>); - $session_pool->logIn('fred'); - } -} -?> -</pre> - L'appel <span class="new_code">Mock::generate()</span> a généré - une nouvelle classe appelé <span class="new_code">MockLog</span>. - Cela ressemble à un clone identique, sauf que nous pouvons - y adjoindre du code de test. - C'est ce que fait <span class="new_code">expectOnce()</span>. - Cela dit que si <span class="new_code">message()</span> m'est appelé, - il a intérêt à l'être avec le paramètre - "User fred logged in.". - </p> - <p> - L'appel <span class="new_code">tally()</span> est nécessaire pour annoncer à - l'objet fantaisie qu'il n'y aura plus d'appels ultérieurs. - Sans ça l'objet fantaisie pourrait attendre pendant une - éternité l'appel de la méthode sans jamais prévenir le - scénario de test. Les autres tests sont déclenchés - automatiquement quand l'appel à <span class="new_code">message()</span> est - invoqué sur l'objet <span class="new_code">MockLog</span> par le code - <span class="new_code">SessionPool::logIn()</span>. - L'appel <span class="new_code">mock</span> va déclencher une comparaison des - paramètres et ensuite envoyer le message "pass" ou "fail" - au test pour l'affichage. Des jokers peuvent être inclus - pour ne pas avoir à tester tous les paramètres d'un appel - alors que vous ne souhaitez qu'en tester un. - </p> - <p> - Les objets fantaisie dans la suite SimpleTest peuvent avoir - un ensemble de valeurs de sortie arbitraires, des séquences - de sorties, des valeurs de sortie sélectionnées à partir - des arguments d'entrée, des séquences de paramètres - attendus et des limites sur le nombre de fois qu'une - méthode peut être invoquée. - </p> - <p> - Pour que ce test fonctionne la librairie avec les objets - fantaisie doit être incluse dans la suite de tests, par - exemple dans <em>all_tests.php</em>. - </p> - <p> - Pour plus de renseignements sur les objets fantaisie, voyez le - <a href="mock_objects_documentation.html">documentation sur les objets fantaisie</a>. - </p> - - <h2> -<a class="target" name="web"></a>Tester une page web</h2> - <p> - Une des exigences des sites web, c'est qu'ils produisent - des pages web. Si vous construisez un projet de A à Z et - que vous voulez intégrer des tests au fur et à mesure alors - vous voulez un outil qui puisse effectuer une navigation - automatique et en examiner le résultat. C'est le boulot - d'un testeur web. - </p> - <p> - Effectuer un test web via SimpleTest reste assez primitif : - il n'y a pas de javascript par exemple. - La plupart des autres opérations d'un navigateur sont simulées. - </p> - <p> - Pour vous donner une idée, voici un exemple assez trivial : - aller chercher une page web, - à partir de là naviguer vers la page "about" - et finalement tester un contenu déterminé par le client. -<pre> -<?php -require_once('simpletest/autorun.php'); -<strong>require_once('simpletest/web_tester.php');</strong> - -class TestOfAbout extends <strong>WebTestCase</strong> { - function testOurAboutPageGivesFreeReignToOurEgo() { - <strong>$this->get('http://test-server/index.php'); - $this->click('About'); - $this->assertTitle('About why we are so great'); - $this->assertText('We are really great');</strong> - } -} -?> -</pre> - Avec ce code comme test de recette, vous pouvez vous - assurer que le contenu corresponde toujours aux - spécifications à la fois des développeurs et des autres - parties prenantes au projet. - </p> - <p> - Vous pouvez aussi naviguer à travers des formulaires... -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('simpletest/web_tester.php'); - -class TestOfRankings extends WebTestCase { - function testWeAreTopOfGoogle() { - $this->get('http://google.com/'); - $this->setField('q', 'simpletest'); - $this->click("I'm Feeling Lucky"); - $this->assertTitle('SimpleTest - Unit Testing for PHP'); - } -} -?> -</pre> - ...même si cela pourrait constituer une violation - des documents juridiques de Google(tm). - </p> - <p> - Pour plus de renseignements sur comment tester une page web, voyez la - <a href="web_tester_documentation.html">documentation sur tester des scripts web</a>. - </p> - <p> - <a href="http://sourceforge.net/projects/simpletest/"><img src="http://sourceforge.net/sflogo.php?group_id=76550&type=5" width="210" height="62" border="0" alt="SourceForge.net Logo"></a> - </p> - - </div> - References and related information... - <ul> -<li> - <a href="https://sourceforge.net/project/showfiles.php?group_id=76550&release_id=153280">Télécharger PHP SimpleTest</a> - depuis <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - L'<a href="http://simpletest.org/api/">API de SimpleTest pour développeur</a> - donne tous les détails sur les classes et assertions existantes. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/mock_objects_documentation.html b/3rdparty/simpletest/docs/fr/mock_objects_documentation.html deleted file mode 100644 index 97e2c86ee7329bf31682691ab4ef76c47ee6cb10..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/mock_objects_documentation.html +++ /dev/null @@ -1,933 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>Documentation SimpleTest : les objets fantaise</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Documentation sur les objets fantaisie</h1> - This page... - <ul> -<li> - <a href="#what">Que sont les objets fantaisie ?</a> - </li> -<li> - <a href="#creation">Créer des objets fantaisie</a>. - </li> -<li> - <a href="#expectations">Les objets fantaisie en tant que critiques</a> avec les attentes. - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="what"></a>Que sont les objets fantaisie ?</h2> - <p> - Les objets fantaisie - ou "mock objects" en anglais - - ont deux rôles pendant un scénario de test : acteur et critique. - </p> - <p> - Le comportement d'acteur est celui de simuler - des objets difficiles à initialiser ou trop consommateurs - en temps pendant un test. - Le cas classique est celui de la connexion à une base de données. - Mettre sur pied une base de données de test au lancement - de chaque test ralentirait considérablement les tests - et en plus exigerait l'installation d'un moteur - de base de données ainsi que des données sur la machine de test. - Si nous pouvons simuler la connexion - et renvoyer des données à notre guise - alors non seulement nous gagnons en pragmatisme - sur les tests mais en sus nous pouvons nourrir - notre base avec des données falsifiées - et voir comment il répond. Nous pouvons - simuler une base de données en suspens ou - d'autres cas extrêmes sans avoir à créer - une véritable panne de base de données. - En d'autres termes nous pouvons gagner - en contrôle sur l'environnement de test. - </p> - <p> - Si les objets fantaisie ne se comportaient que comme - des acteurs alors on les connaîtrait sous le nom de - <a href="server_stubs_documentation.html">bouchons serveur</a>. - Il s'agissait originairement d'un patron de conception - identifié par Robert Binder (<a href="">Testing - object-oriented systems</a>: models, patterns, and tools, - Addison-Wesley) en 1999. - </p> - <p> - Un bouchon serveur est une simulation d'un objet ou d'un composant. - Il doit remplacer exactement un composant dans un système - en vue d'effectuer des tests ou un prototypage, - tout en restant ultra-léger. - Il permet aux tests de s'exécuter plus rapidement, ou - si la classe simulée n'a pas encore été écrite, - de se lancer tout court. - </p> - <p> - Cependant non seulement les objets fantaisie jouent - un rôle (en fournissant à la demande les valeurs requises) - mais en plus ils sont aussi sensibles aux messages qui - leur sont envoyés (par le biais d'attentes). - En posant les paramètres attendus d'une méthode - ils agissent comme des gardiens : - un appel sur eux doit être réalisé correctement. - Si les attentes ne sont pas atteintes ils nous épargnent - l'effort de l'écriture d'une assertion de test avec - échec en réalisant cette tâche à notre place. - </p> - <p> - Dans le cas d'une connexion à une base de données - imaginaire ils peuvent tester si la requête, disons SQL, - a bien été formé par l'objet qui utilise cette connexion. - Mettez-les sur pied avec des attentes assez précises - et vous verrez que vous n'aurez presque plus d'assertion à écrire manuellement. - </p> - - <h2> -<a class="target" name="creation"></a>Créer des objets fantaisie</h2> - <p> - Tout ce dont nous avons besoin est une classe existante ou une interface, - par exemple une connexion à la base de données qui ressemblerait à... -<pre> -<strong>class DatabaseConnection { - function DatabaseConnection() { } - function query($sql) { } - function selectQuery($sql) { } -}</strong> -</pre> - Pour en créer sa version fantaisie nous devons juste - lancer le générateur... -<pre> -require_once('simpletest/autorun.php'); -require_once('database_connection.php'); - -<strong>Mock::generate('DatabaseConnection');</strong> -</pre> - Ce code génère une classe clone appelée <span class="new_code">MockDatabaseConnection</span>. - Cette nouvelle classe lui ressemble en tout point, - sauf qu'elle ne fait rien du tout. - </p> - <p> - Cette nouvelle classe est génératlement - une sous-classe de <span class="new_code">DatabaseConnection</span>. - Malheureusement, il n'y as aucun moyen de créer une version fantaisie - d'une classe avec une méthode <span class="new_code">final</span> sans avoir - une version fonctionnelle de cette méthode. - Ce n'est pas pas très satisfaisant. - Si la cible est une interface ou si les méthodes <span class="new_code">final</span> - existent dans la classe cible, alors une toute nouvelle classe - est créée, elle implémente juste les même interfaces. - Si vous essayer de faire passer cette classe à travers un indice de type - qui spécifie le véritable nom de l'ancienne classe, alors il échouera. - Du code qui forcerait un indice de type tout en utilisant - des méthodes <span class="new_code">final</span> ne pourrait probablement pas être - testé efficacement avec des objets fantaisie. - </p> - <p> - Si vous voulez voir le code généré, il suffit de faire un <span class="new_code">print</span> - de la sortie de <span class="new_code">Mock::generate()</span>. - VOici le code généré pour la classe <span class="new_code">DatabaseConnection</span> - à la place de son interface... -<pre> -class MockDatabaseConnection extends DatabaseConnection { - public $mock; - protected $mocked_methods = array('databaseconnection', 'query', 'selectquery'); - - function MockDatabaseConnection() { - $this->mock = new SimpleMock(); - $this->mock->disableExpectationNameChecks(); - } - ... - function DatabaseConnection() { - $args = func_get_args(); - $result = &$this->mock->invoke("DatabaseConnection", $args); - return $result; - } - function query($sql) { - $args = func_get_args(); - $result = &$this->mock->invoke("query", $args); - return $result; - } - function selectQuery($sql) { - $args = func_get_args(); - $result = &$this->mock->invoke("selectQuery", $args); - return $result; - } -} -</pre> - Votre sortie dépendra quelque peu de votre version précise de SimpleTest. - </p> - <p> - En plus des méthodes d'origine de la classe, vous en verrez d'autres - pour faciliter les tests. - Nous y reviendrons. - </p> - <p> - Nous pouvons désormais créer des instances de - cette nouvelle classe à l'intérieur même de notre scénario de test... -<pre> -require_once('simpletest/autorun.php'); -require_once('database_connection.php'); - -Mock::generate('DatabaseConnection'); - -class MyTestCase extends UnitTestCase { - - function testSomething() { - <strong>$connection = new MockDatabaseConnection();</strong> - } -} -</pre> - La version fantaisie contient toutles méthodes de l'originale. - En outre, tous les indices de type seront préservés. - Dison que nos méthodes de requête attend un objet <span class="new_code">Query</span>... -<pre> -<strong>class DatabaseConnection { - function DatabaseConnection() { } - function query(Query $query) { } - function selectQuery(Query $query) { } -}</strong> -</pre> - Si nous lui passons le mauvais type d'objet - ou même pire un non-objet... -<pre> -class MyTestCase extends UnitTestCase { - - function testSomething() { - $connection = new MockDatabaseConnection(); - $connection->query('insert into accounts () values ()'); - } -} -</pre> - ...alors le code renverra une violation de typage, - exactement comme on aurait pû s'y attendre - avec la classe d'origine. - </p> - <p> - Si la version fantaisie implémente bien toutes les méthodes - de l'originale, elle renvoit aussi systématiquement <span class="new_code">null</span>. - Et comme toutes les méthodes qui renvoient toujours <span class="new_code">null</span> - ne sont pas très utiles, nous avons besoin de leur faire dire - autre chose... - </p> - - <h2> -<a class="target" name="bouchon"></a>Objets fantaisie en action</h2> - <p> - Changer le <span class="new_code">null</span> renvoyé par la méthode fantaisie - en autre chose est assez facile... -<pre> -<strong>$connection->returns('query', 37)</strong> -</pre> - Désormais à chaque appel de <span class="new_code">$connection->query()</span> - nous obtenons un résultat de 37. - Il n'y a rien de particulier à cette valeur de 37. - Cette valeur de retour peut être aussi compliqué que nécessaire. - </p> - <p> - Ici les paramètres ne sont pas significatifs, - nous aurons systématiquement la même valeur en retour - une fois initialisés de la sorte. - Cela pourrait ne pas ressembler à une copie convaincante - de notre connexion à la base de données, mais pour - la demi-douzaine de lignes de code de notre méthode de test - c'est généralement largement assez. - </p> - <p> - Sauf que les choses ne sont pas toujours si simples. - Les itérateurs sont un problème récurrent, si par exemple - renvoyer systématiquement la même valeur entraine - une boucle infinie dans l'objet testé. - Pour ces cas-là, nous avons besoin d'une séquence de valeurs. - Supposons que nous avons un itérateur simple qui ressemble à... -<pre> -class Iterator { - function Iterator() { } - function next() { } -} -</pre> - Il s'agit là de l'itérateur le plus basique que nous puissions imaginer. - Supponsons que cet itérateur ne renvoit que du texte - jusqu'à ce qu'il atteigne la fin et qu'il renvoie alors un false, - nous pouvons le simuler avec... -<pre> -Mock::generate('Iterator'); - -class IteratorTest extends UnitTestCase() { - - function testASequence() {<strong> - $iterator = new MockIterator(); - $iterator->returns('next', false); - $iterator->returnsAt(0, 'next', 'First string'); - $iterator->returnsAt(1, 'next', 'Second string');</strong> - ... - } -} -</pre> - Quand <span class="new_code">next()</span> est appelé par le <span class="new_code">MockIterator</span> - il commencera par renvoyer "First string", - au deuxième passage "Second string" sera renvoyé - et sur n'importe quel autre appel <span class="new_code">false</span> sera renvoyé - à son tour. - Les valeurs renvoyées les unes après les autres auront la priorité - sur la valeur constante. - Cette dernière est la valeur par défaut en quelque sorte. - </p> - <p> - Une autre situation délicate serait une opération - <span class="new_code">get()</span> surchargée. - Un exemple serait un conteneur d'information avec des pairs clef/valeur. - Nous partons cette fois d'une classe de configuration telle... -<pre> -class Configuration { - function Configuration() { ... } - function get($key) { ... } -} -</pre> - C'est une situation courante pour utiliser des objets fantaisie, - étant donné que la véritable configuration sera différente - d'une machine à l'autre et parfois même d'un test à l'autre. - Cependant un problème apparaît quand toutes les données passent - par la méthode <span class="new_code">get()</span> et que nous souhaitons - quand même des résultats différents pour des clefs différentes. - Par chance les objets fantaisie ont un système de filtre... -<pre> -<strong>$config = &new MockConfiguration(); -$config->returns('get', 'primary', array('db_host')); -$config->returns('get', 'admin', array('db_user')); -$config->returns('get', 'secret', array('db_password'));</strong> -</pre> - Le dernier paramètre est une liste d'arguements - pour vérifier une correspondance. - Dans ce cas, nous essayons de faire correspondre un argument - qui se trouve être la clef de recherche. - Désormais quand l'objet fantaisie voit - sa méthode <span class="new_code">get()</span> invoquée... -<pre> -$config->get('db_user') -</pre> - ...il renverra "admin". - Il trouve cette valeur en essayant de faire correspondre - l'argument reçu à ceux de ses propres listes : dès qu'une - correspondance complète est trouvé, il s'arrête. - </p> - <p> - Vous pouvez préciser un argument par défaut via... -<pre><strong> -$config->returns('get', false, array('*'));</strong> -</pre> - Ce n'est pas la même chose que de définir la valeur renvoyée - sans aucun arguement... -<pre><strong> -$config->returns('get', false);</strong> -</pre> - Dans le premier cas, il acceptera n'importe quel argument, - mais il en faut au moins un. - Dans le deuxième cas, n'importe quel nombre d'arguments - fera l'affaire and il agit comme un attrape-tout après - toutes les autres vérifications. - Notez que si - dans le premier cas - nous ajoutons - d'autres options avec paramètre unique après le joker, - alors elle seront ignorés puisque le joker fera - la première correspondance. - Avec des listes complexes de paramètres, l'ordre devient - important au risque de voir la correspondance souhaitée - masqué par un joker apparu plus tôt. - Déclarez les plus spécifiques d'abord si vous n'êtes pas sûr. - </p> - <p> - Il y a des moments où vous souhaitez qu'une référence - bien spécifique soit servie par l'objet fantaisie plutôt - qu'une copie. - C'est plutôt rare pour dire le moins, mais vous pourriez - être en train de simuler un conteneur qui détiendrait - des primitives, tels des chaînes de caractères. - Par exemple. -<pre> -class Pad { - function Pad() { } - function &note($index) { } -} -</pre> - Dans ce cas, vous pouvez définir une référence dans la liste - des valeurs retournées par l'objet fantaisie... -<pre> -function testTaskReads() { - $note = 'Buy books'; - $pad = new MockPad(); - $vector-><strong>returnsByReference(</strong>'note', $note, array(3)<strong>)</strong>; - $task = new Task($pad); - ... -} -</pre> - Avec cet assemblage vous savez qu'à chaque fois - que <span class="new_code">$pad->note(3)</span> est appelé - il renverra toujours la même <span class="new_code">$note</span>, - même si celle-ci est modifiée. - </p> - <p> - Ces trois facteurs, timing, paramètres et références, - peuvent être combinés orthogonalement. - Par exemple... -<pre> -$buy_books = 'Buy books'; -$write_code = 'Write code'; -$pad = new MockPad(); -$vector-><strong>returnsByReferenceAt(0, 'note', $buy_books, array('*', 3));</strong> -$vector-><strong>returnsByReferenceAt(1, 'note', $write_code, array('*', 3));</strong> -</pre> - Cela renverra une référence à <span class="new_code">$buy_books</span> et - ensuite à <span class="new_code">$write_code</span>, mais seuleent si deux paramètres - sont utilisés, le deuxième devant être l'entier 3. - Cela devrait couvrir la plupart des situations. - </p> - <p> - Un dernier cas délicat reste : celui d'un objet créant - un autre objet, plus connu sous le patron de conception "fabrique" - (ou "factory"). - Supponsons qu'à la réussite d'une requête à - notre base de données imaginaire, un jeu d'enregistrements - est renvoyé sous la forme d'un itérateur, où chaque appel - au <span class="new_code">next()</span> sur notre itérateur donne une ligne - avant de s'arrêtre avec un false. - Cela semble à un cauchemar à simuler, alors qu'en fait un objet - fantaisie peut être créé avec les mécansimes ci-dessus... -<pre> -Mock::generate('DatabaseConnection'); -Mock::generate('ResultIterator'); - -class DatabaseTest extends UnitTestCase { - - function testUserFinderReadsResultsFromDatabase() {<strong> - $result = new MockResultIterator(); - $result->returns('next', false); - $result->returnsAt(0, 'next', array(1, 'tom')); - $result->returnsAt(1, 'next', array(3, 'dick')); - $result->returnsAt(2, 'next', array(6, 'harry')); - - $connection = new MockDatabaseConnection(); - $connection->returns('selectQuery', $result);</strong> - - $finder = new UserFinder(<strong>$connection</strong>); - $this->assertIdentical( - $finder->findNames(), - array('tom', 'dick', 'harry')); - } -} -</pre> - Désormais ce n'est que si notre <span class="new_code">$connection</span> - est appelée par la méthode <span class="new_code">query()</span> - que sera retourné le <span class="new_code">$result</span>, - lui-même s'arrêtant au troisième appel - à <span class="new_code">next()</span>. - Ce devrait être suffisant comme information - pour que notre classe <span class="new_code">UserFinder</span>, - la classe effectivement testée ici, - fasse son boulot. - Un test très précis et toujours pas - de base de données en vue. - </p> - <p> - Nous pourrsion affiner ce test encore plus - en insistant pour que la bonne requête - soit envoyée... -<pre> -$connection->returns('selectQuery', $result, array(<strong>'select name, id from people'</strong>)); -</pre> - Là, c'est une mauvaise idée. - </p> - <p> - Niveau objet, nous avons un <span class="new_code">UserFinder</span> - qui parle à une base de données à travers une interface géante - - l'ensemble du SQL. - Imaginez si nous avions écrit un grand nombre de tests - qui dépendrait désormais de cette requête SQL précise. - Ces requêtes pourraient changer en masse pour tout un tas - de raisons non liés à ce test spécifique. - Par exemple, la règle pour les quotes pourrait changer, - un nom de table pourrait évoluer, une table de liaison pourrait - être ajouté, etc. - Cela entrainerait une ré-écriture de tous les tests à chaque fois - qu'un remaniement est fait, alors même que le comportement lui - n'a pas bougé. - Les tests sont censés aider au remaniement, pas le bloquer. - Pour ma part, je préfère avoir une suite de tests qui passent - quand je fais évoluer le nom des tables. - </p> - <p> - Et si vous voulez une règle, c'est toujours mieux de ne pas - créer un objet fantaisie sur une grosse interface. - </p> - <p> - Par contrast, voici le test complet... -<pre> -class DatabaseTest extends UnitTestCase {<strong> - function setUp() { ... } - function tearDown() { ... }</strong> - - function testUserFinderReadsResultsFromDatabase() { - $finder = new UserFinder(<strong>new DatabaseConnection()</strong>); - $finder->add('tom'); - $finder->add('dick'); - $finder->add('harry'); - $this->assertIdentical( - $finder->findNames(), - array('tom', 'dick', 'harry')); - } -} -</pre> - Ce test est immunisé contre le changement de schéma. - Il échouera uniquement si vous changez la fonctionnalité, - ce qui correspond bien à ce qu'un test doit faire. - </p> - <p> - Il faut juste faire attention à ces méthodes <span class="new_code">setUp()</span> - et <span class="new_code">tearDown()</span> que nous avons survolé pour l'instant. - Elles doivent vider les tables de la base de données - et s'assurer que le schéma est bien défini. - Cela peut se engendrer un peu de travail supplémentaire, - mais d'ordinaire ce type de code existe déjà - à commencer pour - le déploiement. - </p> - <p> - Il y a au moins un endroit où vous aurez besoin d'objets fantaisie : - c'est la simulation des erreurs. - Exemple, la base de données tombe pendant que <span class="new_code">UserFinder</span> - fait son travail. Le <span class="new_code">UserFinder</span> se comporte-t-il bien ? -<pre> -class DatabaseTest extends UnitTestCase { - - function testUserFinder() { - $connection = new MockDatabaseConnection();<strong> - $connection->throwOn('selectQuery', new TimedOut('Ouch!'));</strong> - $alert = new MockAlerts();<strong> - $alert->expectOnce('notify', 'Database is busy - please retry');</strong> - $finder = new UserFinder($connection, $alert); - $this->assertIdentical($finder->findNames(), array()); - } -} -</pre> - Nous avons transmis au <span class="new_code">UserFinder</span> - un objet <span class="new_code">$alert</span>. - Il va transmettre un certain nombre de belles notifications - à l'interface utilisatuer en cas d'erreur. - Nous préfèrerions éviter de saupoudrer notre code avec - des commandes <span class="new_code">print</span> codées en dur si nous pouvons - l'éviter. - Emballer les moyens de sortie veut dire que nous pouvons utiliser - ce code partout. Et cela rend notre code plus facile. - </p> - <p> - Pour faire passer ce test, le finder doit écrire un message sympathique - et compréhensible à l'<span class="new_code">$alert</span>, plutôt que de propager - l'exception. Jusque là, tout va bien. - </p> - <p> - Comment faire en sorte que la <span class="new_code">DatabaseConnection</span> fantaisie - soulève une exception ? - Nous la générons avec la méthode <span class="new_code">throwOn</span> sur l'objet fantaisie. - </p> - <p> - Enfin, que se passe-t-il si la méthode voulue pour la simulation - n'existe pas encore ? - Si vous définissez une valeur de retour sur une méthode absente, - alors SimpleTest vous répondra avec une erreur. - Et si vous utilisez <span class="new_code">__call()</span> pour simuler - des méthodes dynamiques ? - </p> - <p> - Les objets avec des interfaces dynamiques, avec <span class="new_code">__call</span>, - peuvent être problématiques dans l'implémentation courante - des objets fantaisie. - Vous pouvez en créer un autour de la méthode <span class="new_code">__call()</span> - mais c'est très laid. - Et pourquoi un test devrait connaître quelque chose avec un niveau - si bas dans l'implémentation. Il n'a besoin que de simuler l'appel. - </p> - <p> - Il y a bien moyen de contournement : ajouter des méthodes complémentaires - à l'objet fantaisie à la génération. -<pre> -<strong>Mock::generate('DatabaseConnection', 'MockDatabaseConnection', array('setOptions'));</strong> -</pre> - Dans une longue suite de tests cela pourrait entraîner des problèmes, - puisque vous avez probablement déjà une version fantaisie - de la classe appellée <span class="new_code">MockDatabaseConnection</span> - sans les méthodes complémentaires. - Le générateur de code ne générera pas la version fantaisie de la classe - s'il en existe déjà une version avec le même nom. - Il vous deviendra impossible de déterminer où est passée votre méthode - si une autre définition a été lancé au préalable. - </p> - <p> - Pour pallier à ce problème, SimpleTest vous permet de choisir - n'importe autre nom pour la nouvelle classe au moment même où - vous ajouter les méthodes complémentaires. -<pre> -Mock::generate('DatabaseConnection', <strong>'MockDatabaseConnectionWithOptions'</strong>, array('setOptions')); -</pre> - Ici l'objet fantaisie se comportera comme si - <span class="new_code">setOptions()</span> existait bel et bien - dans la classe originale. - </p> - <p> - Les objets fantaisie ne peuvent être utilisés qu'à l'intérieur - des scénarios de test, étant donné qu'à l'apparition d'une attente - ils envoient des messages directement au scénario de test courant. - Les créer en dehors d'un scénario de test entraînera une erreur - de run time quand une attente est déclenchée et qu'il n'y a pas - de scénario de test en cours pour recevoir le message. - Nous pouvons désormais couvrir ces attentes. - </p> - - <h2> -<a class="target" name="expectations"></a>Objets fantaisie en tant que critiques</h2> - <p> - Même si les bouchons serveur isolent vos tests des perturbations - du monde réel, ils n'apportent que le moitié des bénéfices possibles. - Vous pouvez obtenir une classe de test qui reçoive les bons messages, - mais cette nouvelle classe envoie-t-elle les bons ? - Le tester peut devenir très bordélique sans - une librairie d'objets fantaise. - </p> - <p> - Voici un exemple, prenons une classe <span class="new_code">PageController</span> - toute simple qui traitera un formulaire de paiement - par carte bleue... -<pre> -class PaymentForm extends PageController { - function __construct($alert, $payment_gateway) { ... } - function makePayment($request) { ... } -} -</pre> - Cette classe a besoin d'un <span class="new_code">PaymentGateway</span> - pour parler concrètement à la banque. - Il utilise aussi un objet <span class="new_code">Alert</span> - pour gérer les erreurs. - Cette dernière classe parle à la page ou au template. - Elle est responsable de l'affichage du message d'erreur - et de la mise en valeur de tout champ du formulaire - qui serait incorrecte. - </p> - <p> - Elle pourrait ressembler à... -<pre> -class Alert { - function warn($warning, $id) { - print '<div class="warning">' . $warning . '</div>'; - print '<style type="text/css">#' . $id . ' { background-color: red }</style>'; - } -} -</pre> - </p> - <p> - Portons notre attention à la méthode <span class="new_code">makePayment()</span>. - Si nous n'inscrivons pas un numéro "CVV2" (celui à trois - chiffre au dos de la carte bleue), nous souhaitons afficher - une erreur plutôt que d'essayer de traiter le paiement. - En mode test... -<pre> -<?php -require_once('simpletest/autorun.php'); -require_once('payment_form.php'); -Mock::generate('Alert'); -Mock::generate('PaymentGateway'); - -class PaymentFormFailuresShouldBeGraceful extends UnitTestCase { - - function testMissingCvv2CausesAlert() { - $alert = new MockAlert(); - <strong>$alert->expectOnce( - 'warn', - array('Missing three digit security code', 'cvv2'));</strong> - $controller = new PaymentForm(<strong>$alert</strong>, new MockPaymentGateway()); - $controller->makePayment($this->requestWithMissingCvv2()); - } - - function requestWithMissingCvv2() { ... } -} -?> -</pre> - Première question : où sont passés les assertions ? - </p> - <p> - L'appel à <span class="new_code">expectOnce('warn', array(...))</span> annonce - à l'objet fantaisie qu'il faut s'attendre à un appel à <span class="new_code">warn()</span> - avant la fin du test. - Quand il débouche sur l'appel à <span class="new_code">warn()</span>, il vérifie - les arguments. Si ceux-ci ne correspondent pas, alors un échec - est généré. Il échouera aussi si la méthode n'est jamais appelée. - </p> - <p> - Non seulement le test ci-dessus s'assure que <span class="new_code">warn</span> - a bien été appelé, mais en plus qu'il a bien reçu la chaîne - de caractère "Missing three digit security code" - et même le tag "cvv2". - L'équivalent de <span class="new_code">assertIdentical()</span> est appliqué - aux deux champs quand les paramètres sont comparés. - </p> - <p> - Si le contenu du message vous importe peu, surtout dans le cas - d'une interface utilisateur qui change régulièrement, - nous pouvons passer ce paramètre avec l'opérateur "*"... -<pre> -class PaymentFormFailuresShouldBeGraceful extends UnitTestCase { - - function testMissingCvv2CausesAlert() { - $alert = new MockAlert(); - $alert->expectOnce('warn', array(<strong>'*'</strong>, 'cvv2')); - $controller = new PaymentForm($alert, new MockPaymentGateway()); - $controller->makePayment($this->requestWithMissingCvv2()); - } - - function requestWithMissingCvv2() { ... } -} -</pre> - Nous pouvons même rendre le test encore moins spécifique - en supprimant complètement la liste des paramètres... -<pre> -function testMissingCvv2CausesAlert() { - $alert = new MockAlert(); - <strong>$alert->expectOnce('warn');</strong> - $controller = new PaymentForm($alert, new MockPaymentGateway()); - $controller->makePayment($this->requestWithMissingCvv2()); -} -</pre> - Ceci vérifiera uniquement si la méthode a été appelé, - ce qui est peut-être un peu drastique dans ce cas. - Plus tard, nous verrons comment alléger les attentes - plus précisement. - </p> - <p> - Des tests sans assertions peuvent être à la fois compacts - et très expressifs. Parce que nous interceptons l'appel - sur le chemin de l'objet, ici de classe <span class="new_code">Alert</span>, - nous évitons de tester l'état par la suite. - Cela évite les assertions dans les tests, mais aussi - l'obligation d'ajouter des accesseurs uniquement - pour les tests dans le code original. - Si vous en arrivez à ajouter des accesseurs de ce type, - on parle alors de "state based testing" dans le jargon - ("test piloté par l'état"), - il est probablement plus que temps d'utiliser - des objets fantaisie dans vos tests. - On peut alors parler de "behaviour based testing" - (ou "test piloté par le comportement") : - c'est largement mieux ! - </p> - <p> - Ajoutons un autre test. - Assurons nous que nous essayons même pas un paiement sans CVV2... -<pre> -class PaymentFormFailuresShouldBeGraceful extends UnitTestCase { - - function testMissingCvv2CausesAlert() { ... } - - function testNoPaymentAttemptedWithMissingCvv2() { - $payment_gateway = new MockPaymentGateway(); - <strong>$payment_gateway->expectNever('pay');</strong> - $controller = new PaymentForm(new MockAlert(), $payment_gateway); - $controller->makePayment($this->requestWithMissingCvv2()); - } - - ... -} -</pre> - Vérifier une négation peut être très difficile - dans les tests, mais <span class="new_code">expectNever()</span> - rend l'opération très facile heureusement. - </p> - <p> - <span class="new_code">expectOnce()</span> et <span class="new_code">expectNever()</span> sont - suffisants pour la plupart des tests, mais - occasionnellement vous voulez tester plusieurs évènements. - D'ordinaire pour des raisons d'usabilité, nous souhaitons - que tous les champs manquants du formulaire soient - mis en relief, et pas uniquement le premier. - Cela veut dire que nous devrions voir de multiples appels - à <span class="new_code">Alert::warn()</span>, pas juste un... -<pre> -function testAllRequiredFieldsHighlightedOnEmptyRequest() { - $alert = new MockAlert();<strong> - $alert->expectAt(0, 'warn', array('*', 'cc_number')); - $alert->expectAt(1, 'warn', array('*', 'expiry')); - $alert->expectAt(2, 'warn', array('*', 'cvv2')); - $alert->expectAt(3, 'warn', array('*', 'card_holder')); - $alert->expectAt(4, 'warn', array('*', 'address')); - $alert->expectAt(5, 'warn', array('*', 'postcode')); - $alert->expectAt(6, 'warn', array('*', 'country')); - $alert->expectCallCount('warn', 7);</strong> - $controller = new PaymentForm($alert, new MockPaymentGateway()); - $controller->makePayment($this->requestWithMissingCvv2()); -} -</pre> - Le compteur dans <span class="new_code">expectAt()</span> précise - le nombre de fois que la méthode a déjà été appelée. - Ici nous vérifions que chaque champ sera bien mis en relief. - </p> - <p> - Notez que nous sommes forcé de tester l'ordre en même temps. - SimpleTest n'a pas encore de moyen pour éviter cela, - mais dans une version future ce sera corrigé. - </p> - <p> - Voici la liste complètes des attentes - que vous pouvez préciser sur une objet fantaisie - dans <a href="http://simpletest.org/">SimpleTest</a>. - Comme pour les assertions, ces méthodes prennent en option - un message d'erreur. - <table> - <thead><tr> -<th>Attente</th> -<th>Description</th> -</tr></thead> - <tbody> - <tr> - <td><span class="new_code">expect($method, $args)</span></td> - <td>Les arguements doivent correspondre si appelés</td> - </tr> - <tr> - <td><span class="new_code">expectAt($timing, $method, $args)</span></td> - <td>Les arguements doiven correspondre si appelés lors du passage numéro <span class="new_code">$timing</span> -</td> - </tr> - <tr> - <td><span class="new_code">expectCallCount($method, $count)</span></td> - <td>La méthode doit être appelée exactement <span class="new_code">$count</span> fois</td> - </tr> - <tr> - <td><span class="new_code">expectMaximumCallCount($method, $count)</span></td> - <td>La méthode ne doit pas être appelée plus de <span class="new_code">$count</span> fois</td> - </tr> - <tr> - <td><span class="new_code">expectMinimumCallCount($method, $count)</span></td> - <td>La méthode ne doit pas être appelée moins de <span class="new_code">$count</span> fois</td> - </tr> - <tr> - <td><span class="new_code">expectNever($method)</span></td> - <td>La méthode ne doit jamais être appelée</td> - </tr> - <tr> - <td><span class="new_code">expectOnce($method, $args)</span></td> - <td>La méthode ne doit être appelée qu'une seule fois et avec les arguments (en option)</td> - </tr> - <tr> - <td><span class="new_code">expectAtLeastOnce($method, $args)</span></td> - <td>La méthode doit être appelée au moins une seule fois et toujours avec au moins un des arguments attendus</td> - </tr> - </tbody> - </table> - Où les paramètres sont... - <dl> - <dt class="new_code">$method</dt> - <dd> - Le nom de la méthode, sous la forme d'une chaîne de caractères, - à laquelle il faut appliquer la condition. - </dd> - <dt class="new_code">$args</dt> - <dd> - Les argumetns sous la forme d'une liste. - Les jokers peuvent être inclus de la même manière - que pour <span class="new_code">setReturn()</span>. - Cet argument est optionnel pour <span class="new_code">expectOnce()</span> - et <span class="new_code">expectAtLeastOnce()</span>. - </dd> - <dt class="new_code">$timing</dt> - <dd> - La seule marque dans le temps pour tester la condition. - Le premier appel commence à zéro et le comptage se fait - séparement sur chaque méthode. - </dd> - <dt class="new_code">$count</dt> - <dd>Le nombre d'appels attendu.</dd> - </dl> - </p> - <p> - Si vous n'avez qu'un seul appel dans votre test, assurez vous - d'utiliser <span class="new_code">expectOnce</span>.<br> - Utiliser <span class="new_code">$mocked->expectAt(0, 'method', 'args);</span> - tout seul ne permettra qu'à la méthode de ne jamais être appelée. - Vérifier les arguements et le comptage total sont pour le moment - indépendants. - Ajouter une attente <span class="new_code">expectCallCount()</span> quand - vous utilisez <span class="new_code">expectAt()</span> (dans le cas sans appel) - est permis. - </p> - <p> - Comme les assertions à l'intérieur des scénarios de test, - toutes ces attentes peuvent incorporer une surchage - sur le message sous la forme d'un paramètre supplémentaire. - Par ailleurs le message original peut être inclus dans la sortie - avec "%s". - </p> - - </div> - References and related information... - <ul> -<li> - Le papier original sur les Objets fantaisie ou - <a href="http://www.mockobjects.com/">Mock objects</a>. - </li> -<li> - La page du projet SimpleTest sur <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - La page d'accueil de SimpleTest sur <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/overview.html b/3rdparty/simpletest/docs/fr/overview.html deleted file mode 100644 index 968bbc48e50a44b4d7f2e579436caa79697dbbd7..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/overview.html +++ /dev/null @@ -1,321 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title> - Aperçu et liste des fonctionnalités des testeurs unitaires PHP et web de SimpleTest PHP - </title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Apercu de SimpleTest</h1> - This page... - <ul> -<li> - <a href="#resume">Résumé rapide</a> de l'outil SimpleTest pour PHP. - </li> -<li> - <a href="#fonctionnalites">La liste des fonctionnalites</a>, à la fois présentes et à venir. - </li> -<li> - Il y a beaucoup de <a href="#ressources">ressources sur les tests unitaires</a> sur le web. - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="resume"></a>Qu'est-ce que SimpleTest ?</h2> - <p> - Le coeur de SimpleTest est un framework de test construit autour de classes de scénarios de test. Celles-ci sont écrites comme des extensions des classes premières de scénarios de test, chacune élargie avec des méthodes qui contiennent le code de test effectif. Les scripts de test de haut niveau invoque la méthode <span class="new_code">run()</span> à chaque scénario de test successivement. Chaque méthode de test est écrite pour appeler des assertions diverses que le développeur suppose être vraies, <span class="new_code">assertEqual()</span> par exemple. Si l'assertion est correcte, alors un succès est expédié au rapporteur observant le test, mais toute erreur déclenche une alerte et une description de la dissension. - </p> - <p> - Un <a href="unit_test_documentation.html">scénario de test</a> ressemble à... -<pre> -class <strong>MyTestCase</strong> extends UnitTestCase { - <strong> - function testLog() { - $log = &new Log('my.log'); - $log->message('Hello'); - $this->assertTrue(file_exists('my.log')); - }</strong> -} -</pre> - </p> - <p> - Ces outils sont conçus pour le développeur. Les tests sont écrits en PHP directement, plus ou moins simultanément avec la construction de l'application elle-même. L'avantage d'utiliser PHP lui-même comme langage de test est qu'il n'y a pas de nouveau langage à apprendre, les tests peuvent commencer directement et le développeur peut tester n'importe quelle partie du code. Plus simplement, toutes les parties qui peuvent être accédées par le code de l'application peuvent aussi être accédées par le code de test si ils sont tous les deux dans le même langage. - </p> - <p> - Le type de scénario de test le plus simple est le <span class="new_code">UnitTestCase</span>. Cette classe de scénario de test inclut les tests standards pour l'égalité, les références et l'appariement de motifs (via les expressions rationnelles). Ceux-ci testent ce que vous seriez en droit d'attendre du résultat d'une fonction ou d'une méthode. Il s'agit du type de test le plus commun pendant le quotidien du développeur, peut-être 95% des scénarios de test. - </p> - <p> - La tâche ultime d'une application web n'est cependant pas de produire une sortie correcte à partir de méthodes ou d'objets, mais plutôt de produire des pages web. La classe <span class="new_code">WebTestCase</span> teste des pages web. Elle simule un navigateur web demandant une page, de façon exhaustive : cookies, proxies, connexions sécurisées, authentification, formulaires, cadres et la plupart des éléments de navigation. Avec ce type de scénario de test, le développeur peut garantir que telle ou telle information est présente dans la page et que les formulaires ainsi que les sessions sont gérés comme il faut. - </p> - <p> - Un <a href="web_tester_documentation.html">scénario de test web</a> ressemble à... -<pre> -class <strong>MySiteTest</strong> extends WebTestCase { - <strong> - function testHomePage() { - $this->get('http://www.my-site.com/index.php'); - $this->assertTitle('My Home Page'); - $this->clickLink('Contact'); - $this->assertTitle('Contact me'); - $this->assertWantedPattern('/Email me at/'); - }</strong> -} -</pre> - </p> - - <h2> -<a class="target" name="fonctionnalites"></a>Liste des fonctionnalites</h2> - <p> - Ci-dessous vous trouverez un canevas assez brut des fonctionnalités à aujourd'hui et pour demain, sans oublier leur date approximative de publication. J'ai bien peur qu'il soit modifiable sans pré-avis étant donné que les jalons dépendent beaucoup sur le temps disponible. Les trucs en vert ont été codés, mais pas forcément déjà rendus public. Si vous avez une besoin pressant pour une fonctionnalité verte mais pas encore publique alors vous devriez retirer le code directement sur le CVS chez SourceFourge. Une fonctionnalitée publiée est indiqué par "Fini". - <table> -<thead> - <tr> -<th>Fonctionnalité</th> -<th>Description</th> -<th>Publication</th> -</tr> - </thead> -<tbody> -<tr> - <td>Scénariot de test unitaire</td> - <td>Les classes de test et assertions de base</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Affichage HTML</td> - <td>L'affichage le plus simple possible</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Autochargement des scénarios de test</td> - <td>Lire un fichier avec des scénarios de test et les charger dans un groupe de tests automatiquement</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Générateur de code d'objets fantaisie</td> - <td>Des objets capable de simuler d'autres objets, supprimant les dépendances dans les tests</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Bouchons serveur</td> - <td>Des objets fantaisie sans résultat attendu à utiliser à l'extérieur des scénarios de test, pour le prototypage par exemple.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Intégration d'autres testeurs unitaires</td> - <td> - La capacité de lire et simuler d'autres scénarios de test en provenance de PHPUnit et de PEAR::Phpunit.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Scénario de test web</td> - <td>Appariement basique de motifs dans une page téléchargée.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Analyse de page HTML</td> - <td>Permet de suivre les liens et de trouver la balise de titre</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Simulacre partiel</td> - <td>Simuler des parties d'une classe pour tester moins qu'une classe ou dans des cas complexes.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Gestion des cookies Web</td> - <td>Gestion correcte des cookies au téléchargement d'une page.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Suivi des redirections</td> - <td>Le téléchargement d'une page suit automatiquement une redirection 300.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Analyse d'un formulaire</td> - <td>La capacité de valider un formulaire simple et d'en lire les valeurs par défaut.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Interface en ligne de commande</td> - <td>Affiche le résultat des tests sans navigateur web.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Mise à nu des attentes d'une classe</td> - <td>Peut créer des tests précis avec des simulacres ainsi que des scénarios de test.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Sortie et analyse XML</td> - <td>Permet de tester sur plusieurs hôtes et d'intégrer des extensions d'acceptation de test.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Scénario de test en ligne de commande</td> - <td>Permet de tester des outils ou scripts en ligne de commande et de manier des fichiers.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Compatibilité avec PHP Documentor</td> - <td>Génération automatique et complète de la documentation au niveau des classes.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Interface navigateur</td> - <td>Mise à nu des niveaux bas de l'interface du navigateur web pour des scénarios de test plus précis.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Authentification HTTP</td> - <td>Téléchargement des pages web protégées avec une authentification basique seulement.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Boutons de navigation d'un navigateur</td> - <td>Arrière, avant et recommencer</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Support de SSL</td> - <td>Peut se connecter à des pages de type https.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Support de proxy</td> - <td>Peut se connecter via des proxys communs</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Support des cadres</td> - <td>Gère les cadres dans les scénarios de test web.</td> - <td style="color: green;">Fini</td> - </tr> - <tr> - <td>Test de l'upload de fichier</td> - <td>Peut simuler la balise input de type file</td> - <td style="color: red;">1.0.1</td> - </tr> - <tr> - <td>Amélioration sur la machinerie des rapports</td> - <td>Retouche sur la transmission des messages pour une meilleur coopération avec les IDEs</td> - <td style="color: red;">1.1</td> - </tr> - <tr> - <td>Amélioration de l'affichage des tests</td> - <td>Une meilleure interface graphique web, avec un arbre des scénarios de test.</td> - <td style="color: red;">1.1</td> - </tr> - <tr> - <td>Localisation</td> - <td>Abstraction des messages et génration du code à partir de fichiers XML.</td> - <td style="color: red;">1.1</td> - </tr> - <tr> - <td>Simulation d'interface</td> - <td>Peut générer des objets fantaisie tant vers des interfaces que vers des classes.</td> - <td style="color: red;">2.0</td> - </tr> - <tr> - <td>Test sur es exceptions</td> - <td>Dans le même esprit que sur les tests des erreurs PHP.</td> - <td style="color: red;">2.0</td> - </tr> - <tr> - <td>Rercherche d'éléments avec XPath</td> - <td>Peut utiliser Tidy HTML pour un appariement plus rapide et plus souple.</td> - <td style="color: red;">2.0</td> - </tr> - </tbody> -</table> - La migration vers PHP5 commencera juste après la série des 1.0, à partir de là PHP4 ne sera plus supporté. SimpleTest est actuellement compatible avec PHP5 mais n'utilisera aucune des nouvelles fonctionnalités avant la version 2. - </p> - - <h2> -<a class="target" name="ressources"></a>Ressources sur le web pour les tests</h2> - <p> - Le processus est au moins aussi important que les outils. Le type de procédure que fait un usage le plus intensif des outils de test pour développeur est bien sûr l'<a href="http://www.extremeprogramming.org/">Extreme Programming</a>. Il s'agit là d'une des <a href="http://www.agilealliance.com/articles/index">méthodes agiles</a> qui combinent plusieurs pratiques pour "lisser la courbe de coût" du développement logiciel. La plus extrème reste le <a href="http://www.testdriven.com/modules/news/">développement piloté par les tests</a>, où vous devez adhérer à la règle du <cite>pas de code avant d'avoir un test</cite>. Si vous êtes plutôt du genre planninficateur ou que vous estimez que l'expérience compte plus que l'évolution, vous préférerez peut-être l'approche <a href="http://www.therationaledge.com/content/dec_01/f_spiritOfTheRUP_pk.html">RUP</a>. Je ne l'ai pas testé mais je peux voir où vous aurez besoin d'outils de test (cf. illustration 9). - </p> - <p> - La plupart des testeurs unitaires sont dans une certaine mesure un clone de <a href="http://www.junit.org/">JUnit</a>, au moins dans l'interface. Il y a énormément d'information sur le site de JUnit, à commencer par la <a href="http://junit.sourceforge.net/doc/faq/faq.htm">FAQ</a> quie contient pas mal de conseils généraux sur les tests. Une fois mordu par le bogue vous apprécierez sûrement la phrase <a href="http://junit.sourceforge.net/doc/testinfected/testing.htm">infecté par les tests</a> trouvée par Eric Gamma. Si vous êtes encore en train de tergiverser sur un testeur unitaire, sachez que les choix principaux sont <a href="http://phpunit.sourceforge.net/">PHPUnit</a> et <a href="http://pear.php.net/manual/en/package.php.phpunit.php">Pear PHP::PHPUnit</a>. De nombreuses fonctionnalités de SimpleTest leurs font défaut, mais la version PEAR a d'ores et déjà été mise à jour pour PHP5. Elle est aussi recommandée si vous portez des scénarios de test existant depuis <a href="http://www.junit.org/">JUnit</a>. - </p> - <p> - Les développeurs de bibliothèque n'ont pas l'air de livrer très souvent des tests avec leur code : c'est bien dommage. Le code d'une bibliothèque qui inclut des tests peut être remanié avec plus de sécurité et le code de test sert de documentation additionnelle dans un format assez standard. Ceci peut épargner la pêche aux indices dans le code source lorsque qu'un problème survient, en particulier lors de la mise à jour d'une telle bibliothèque. Parmi les bibliothèques utilisant SimpleTest comme testeur unitaire on retrouve <a href="http://wact.sourceforge.net/">WACT</a> et <a href="http://sourceforge.net/projects/htmlsax">PEAR::XML_HTMLSax</a>. - </p> - <p> - Au jour d'aujourd'hui il manque tristement beaucoup de matière sur les objets fantaisie : dommage, surtout que tester unitairement sans eux représente pas mal de travail en plus. L'<a href="http://www.sidewize.com/company/mockobjects.pdf">article original sur les objets fantaisie</a> est très orienté Java, mais reste intéressant à lire. Etant donné qu'il s'agit d'une nouvelle technologie il y a beaucoup de discussions et de débats sur comment les utiliser, souvent sur des wikis comme <a href="http://xpdeveloper.com/cgi-bin/oldwiki.cgi?MockObjects">Extreme Tuesday</a> ou <a href="http://www.mockobjects.com/MocksObjectsPaper.html">www.mockobjects.com</a>ou <a href="http://c2.com/cgi/wiki?MockObject">the original C2 Wiki</a>. Injecter des objets fantaisie dans une classe est un des champs principaux du débat : cet <a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html">article chez IBM</a> en est un bon point de départ. - </p> - <p> - Il y a énormement d'outils de test web mais la plupart sont écrits en Java. De plus les tutoriels et autres conseils sont plutôt rares. Votre seul espoir est de regarder directement la documentation pour <a href="http://httpunit.sourceforge.net/">HTTPUnit</a>, <a href="http://htmlunit.sourceforge.net/">HTMLUnit</a> ou <a href="http://jwebunit.sourceforge.net/">JWebUnit</a> et d'espérer y trouver pour des indices. Il y a aussi des frameworks basés sur XML, mais de nouveau la plupart ont besoin de Java pour tourner. - </p> - - </div> - References and related information... - <ul> -<li> - <a href="unit_test_documentation.html">Documentation pour SimpleTest</a>. - </li> -<li> - <a href="http://www.lastcraft.com/first_test_tutorial.php">Comment écrire des scénarios de test en PHP</a> est un tutoriel plutôt avancé. - </li> -<li> - <a href="http://simpletest.org/api/">L'API de SimpleTest</a> par phpdoc. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/partial_mocks_documentation.html b/3rdparty/simpletest/docs/fr/partial_mocks_documentation.html deleted file mode 100644 index 740ae7b402607be4f03219b9bd626da0ec57b4aa..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/partial_mocks_documentation.html +++ /dev/null @@ -1,475 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>Documentation SimpleTest : les objets fantaisie partiels</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Documentation sur les objets fantaisie partiels</h1> - This page... - <ul> -<li> - <a href="#injection">Le problème de l'injection d'un objet fantaisie</a>. - </li> -<li> - Déplacer la création vers une méthode <a href="#creation">fabrique protégée</a>. - </li> -<li> - <a href="#partiel">L'objet fantaisie partiel</a> génère une sous-classe. - </li> -<li> - Les objets fantaisie partiels <a href="#moins">testent moins qu'une classe</a>. - </li> -</ul> -<div class="content"> - - <p> - Un objet fantaisie partiel n'est ni plus ni moins - qu'un modèle de conception pour soulager un problème spécifique - du test avec des objets fantaisie, celui de placer - des objets fantaisie dans des coins serrés. - Il s'agit d'un outil assez limité et peut-être même - une idée pas si bonne que ça. Elle est incluse dans SimpleTest - pour la simple raison que je l'ai trouvée utile - à plus d'une occasion et qu'elle m'a épargnée - pas mal de travail dans ces moments-là. - </p> - - <h2> -<a class="target" name="injection"></a>Le problème de l'injection dans un objet fantaisie</h2> - <p> - Quand un objet en utilise un autre il est très simple - d'y faire circuler une version fantaisie déjà prête - avec ses attentes. Les choses deviennent un peu plus délicates - si un objet en crée un autre et que le créateur est celui - que l'on souhaite tester. Cela revient à dire que l'objet - créé devrait être une fantaisie, mais nous pouvons - difficilement dire à notre classe sous test de créer - un objet fantaisie plutôt qu'un "vrai" objet. - La classe testée ne sait même pas qu'elle travaille dans un environnement de test. - </p> - <p> - Par exemple, supposons que nous sommes en train - de construire un client telnet et qu'il a besoin - de créer une socket réseau pour envoyer ses messages. - La méthode de connexion pourrait ressemble à quelque chose comme... -<pre> -<strong><?php -require_once('socket.php'); - -class Telnet { - ... - function connect($ip, $port, $username, $password) { - $socket = new Socket($ip, $port); - $socket->read( ... ); - ... - } -} -?></strong> -</pre> - Nous voudrions vraiment avoir une version fantaisie - de l'objet socket, que pouvons nous faire ? - </p> - <p> - La première solution est de passer la socket en - tant que paramètre, ce qui force la création - au niveau inférieur. Charger le client de cette tâche - est effectivement une bonne approche si c'est possible - et devrait conduire à un remaniement -- de la création - à partir de l'action. En fait, c'est là une des manières - avec lesquels tester en s'appuyant sur des objets fantaisie - vous force à coder des solutions plus resserrées sur leur objectif. - Ils améliorent votre programmation. - </p> - <p> - Voici ce que ça devrait être... -<pre> -<?php -require_once('socket.php'); - -class Telnet { - ... - <strong>function connect($socket, $username, $password) { - $socket->read( ... ); - ... - }</strong> -} -?> -</pre> - Sous-entendu, votre code de test est typique d'un cas - de test avec un objet fantaisie. -<pre> -class TelnetTest extends UnitTestCase { - ... - function testConnection() {<strong> - $socket = new MockSocket(); - ... - $telnet = new Telnet(); - $telnet->connect($socket, 'Me', 'Secret'); - ...</strong> - } -} -</pre> - C'est assez évident que vous ne pouvez descendre que d'un niveau. - Vous ne voudriez pas que votre application de haut niveau - crée tous les fichiers de bas niveau, sockets et autres connexions - à la base de données dont elle aurait besoin. - Elle ne connaîtrait pas les paramètres du constructeur de toute façon. - </p> - <p> - La solution suivante est de passer l'objet créé sous la forme - d'un paramètre optionnel... -<pre> -<?php -require_once('socket.php'); - -class Telnet { - ...<strong> - function connect($ip, $port, $username, $password, $socket = false) { - if (! $socket) { - $socket = new Socket($ip, $port); - } - $socket->read( ... );</strong> - ... - return $socket; - } -} -?> -</pre> - Pour une solution rapide, c'est généralement suffisant. - Ensuite le test est très similaire : comme si le paramètre - était transmis formellement... -<pre> -class TelnetTest extends UnitTestCase { - ... - function testConnection() {<strong> - $socket = new MockSocket(); - ... - $telnet = new Telnet(); - $telnet->connect('127.0.0.1', 21, 'Me', 'Secret', $socket); - ...</strong> - } -} -</pre> - Le problème de cette approche tient dans son manque de netteté. - Il y a du code de test dans la classe principale et aussi - des paramètres transmis dans le scénario de test - qui ne sont jamais utilisés. Il s'agit là d'une approche - rapide et sale, mais qui ne reste pas moins efficace - dans la plupart des situations. - </p> - <p> - Une autre solution encore est de laisser un objet fabrique - s'occuper de la création... -<pre> -<?php -require_once('socket.php'); - -class Telnet {<strong> - function Telnet($network) { - $this->_network = $network; - }</strong> - ... - function connect($ip, $port, $username, $password) {<strong> - $socket = $this->_network->createSocket($ip, $port); - $socket->read( ... );</strong> - ... - return $socket; - } -} -?> -</pre> - Il s'agit là probablement de la réponse la plus travaillée - étant donné que la création est maintenant située - dans une petite classe spécialisée. La fabrique réseau - peut être testée séparément et utilisée en tant que fantaisie - quand nous testons la classe telnet... -<pre> -class TelnetTest extends UnitTestCase { - ... - function testConnection() {<strong> - $socket = new MockSocket(); - ... - $network = new MockNetwork(); - $network->returnsByReference('createSocket', $socket); - $telnet = new Telnet($network); - $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');</strong> - } -} -</pre> - Le problème reste que nous ajoutons beaucoup de classes - à la bibliothèque. Et aussi que nous utilisons beaucoup - de fabriques ce qui rend notre code un peu moins intuitif. - La solution la plus flexible, mais aussi la plus complexe. - </p> - <p> - Des techniques comme "l'Injection de Dépendance" - (ou "Dependency Injection") s'attelle au problème - de l'instanciation d'une classe avec beaucoup de paramètres. - Malheureusement la connaissance de ce patron de conception - n'est pas très répandue et si vous êtes en train d'essayer - de faire fonctionner du vieux code, ré-achitecturer toute - l'application n'est pas vraiment une option. - </p> - <p> - Peut-on trouver un juste milieu ? - </p> - - <h2> -<a class="target" name="creation"></a>Méthode fabrique protégée</h2> - <p> - Il existe une technique pour palier à ce problème - sans créer de nouvelle classe dans l'application; - par contre elle induit la création d'une sous-classe au moment du test. - Premièrement nous déplaçons la création de la socket dans sa propre méthode... -<pre> -<?php -require_once('socket.php'); - -class Telnet { - ... - function connect($ip, $port, $username, $password) { - <strong>$socket = $this->createSocket($ip, $port);</strong> - $socket->read( ... ); - ... - }<strong> - - protected function createSocket($ip, $port) { - return new Socket($ip, $port); - }</strong> -} -?> -</pre> - Une première étape plutôt précautionneuse même pour - du code legacy et intermélé. - Il s'agit là de la seule modification dans le code de l'application. - </p> - <p> - Pour le scénario de test, nous devons créer - une sous-classe de manière à intercepter la création de la socket... -<pre> -<strong>class TelnetTestVersion extends Telnet { - var $mock; - - function TelnetTestVersion($mock) { - $this->mock = $mock; - $this->Telnet(); - } - - protected function createSocket() { - return $this->mock; - } -}</strong> -</pre> - Ici j'ai déplacé la fantaisie dans le constructeur, - mais un setter aurait fonctionné tout aussi bien. - Notez bien que la fantaisie est placée dans une variable - d'objet avant que le constructeur ne soit attaché. - C'est nécessaire dans le cas où le constructeur appelle - <span class="new_code">connect()</span>. - Autrement il pourrait donner un valeur nulle à partir de - <span class="new_code">createSocket()</span>. - </p> - <p> - Après la réalisation de tout ce travail supplémentaire - le scénario de test est assez simple. - Nous avons juste besoin de tester notre nouvelle classe à la place... -<pre> -class TelnetTest extends UnitTestCase { - ... - function testConnection() {<strong> - $socket = new MockSocket(); - ... - $telnet = new TelnetTestVersion($socket); - $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');</strong> - } -} -</pre> - Cette nouvelle classe est très simple bien sûr. - Elle ne fait qu'initier une valeur renvoyée, à la manière - d'une fantaisie. Ce serait pas mal non plus si elle pouvait - vérifier les paramètres entrants. - Exactement comme un objet fantaisie. - Il se pourrait bien que nous ayons à réaliser cette astuce régulièrement : - serait-il possible d'automatiser la création de cette sous-classe ? - </p> - - <h2> -<a class="target" name="partiel"></a>Un objet fantaisie partiel</h2> - <p> - Bien sûr la réponse est "oui" - ou alors j'aurais arrêté d'écrire depuis quelques temps déjà ! - Le test précédent a représenté beaucoup de travail, - mais nous pouvons générer la sous-classe en utilisant - une approche à celle des objets fantaisie. - </p> - <p> - Voici donc une version avec objet fantaisie partiel du test... -<pre> -<strong>Mock::generatePartial( - 'Telnet', - 'TelnetTestVersion', - array('createSocket'));</strong> - -class TelnetTest extends UnitTestCase { - ... - function testConnection() {<strong> - $socket = new MockSocket(); - ... - $telnet = new TelnetTestVersion(); - $telnet->setReturnReference('createSocket', $socket); - $telnet->Telnet(); - $telnet->connect('127.0.0.1', 21, 'Me', 'Secret');</strong> - } -} -</pre> - La fantaisie partielle est une sous-classe de l'original - dont on aurait "remplacé" les méthodes sélectionnées - avec des versions de test. L'appel à <span class="new_code">generatePartial()</span> - nécessite trois paramètres : la classe à sous classer, - le nom de la nouvelle classe et une liste des méthodes à simuler. - </p> - <p> - Instancier les objets qui en résultent est plutôt délicat. - L'unique paramètre du constructeur d'un objet fantaisie partiel - est la référence du testeur unitaire. - Comme avec les objets fantaisie classiques c'est nécessaire - pour l'envoi des résultats de test en réponse à la vérification des attentes. - </p> - <p> - Une nouvelle fois le constructeur original n'est pas lancé. - Indispensable dans le cas où le constructeur aurait besoin - des méthodes fantaisie : elles n'ont pas encore été initiées ! - Nous initions les valeurs retournées à cet instant et - ensuite lançons le constructeur avec ses paramètres normaux. - Cette construction en trois étapes de "new", - suivie par la mise en place des méthodes et ensuite - par la lancement du constructeur proprement dit est - ce qui distingue le code d'un objet fantaisie partiel. - </p> - <p> - A part pour leur construction, toutes ces méthodes - fantaisie ont les mêmes fonctionnalités que dans - le cas des objets fantaisie et toutes les méthodes - non fantaisie se comportent comme avant. - Nous pouvons mettre en place des attentes très facilement... -<pre> -class TelnetTest extends UnitTestCase { - ... - function testConnection() { - $socket = new MockSocket(); - ... - $telnet = new TelnetTestVersion(); - $telnet->setReturnReference('createSocket', $socket); - <strong>$telnet->expectOnce('createSocket', array('127.0.0.1', 21));</strong> - $telnet->Telnet(); - $telnet->connect('127.0.0.1', 21, 'Me', 'Secret'); - } -} -</pre> - Les objets fantaisie partiels ne sont pas très utilisés. - Je les considère comme transitoire. - Utile lors d'un remaniement, mais une fois que l'application - a eu toutes ses dépendances bien séparées alors - ils peuvent disparaître. - </p> - - <h2> -<a class="target" name="moins"></a>Tester moins qu'une classe</h2> - <p> - Les méthodes issues d'un objet fantaisie n'ont pas - besoin d'être des méthodes fabrique, Il peut s'agir - de n'importe quelle sorte de méthode. - Ainsi les objets fantaisie partiels nous permettent - de prendre le contrôle de n'importe quelle partie d'une classe, - le constructeur excepté. Nous pourrions même aller jusqu'à - créer des fantaisies sur toutes les méthodes à part celle - que nous voulons effectivement tester. - </p> - <p> - Cette situation est assez hypothétique, étant donné - que je ne l'ai pas souvent essayée. - Je crains qu'en forçant la granularité d'un objet - on n'obtienne pas forcément un code de meilleur qualité. - Personnellement j'utilise les objets fantaisie partiels - comme moyen de passer outre la création ou alors - de temps en temps pour tester le modèle de conception TemplateMethod. - </p> - <p> - On en revient toujours aux standards de code de votre projet : - c'est à vous de trancher si vous autorisez ce mécanisme ou non. - </p> - - </div> - References and related information... - <ul> -<li> - La page du projet SimpleTest sur - <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - <a href="http://simpletest.org/api/">L'API complète pour SimpleTest</a> - à partir de PHPDoc. - </li> -<li> - La méthode fabrique protégée est décrite dans - <a href="http://www-106.ibm.com/developerworks/java/library/j-mocktest.html"> - cet article d'IBM</a>. Il s'agit de l'unique papier - formel que j'ai vu sur ce problème. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/reporter_documentation.html b/3rdparty/simpletest/docs/fr/reporter_documentation.html deleted file mode 100644 index 485fc74c7a49d30d0bb9278cfe469e4768c72b89..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/reporter_documentation.html +++ /dev/null @@ -1,630 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>Documentation SimpleTest : le rapporteur de test</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Documentation sur le rapporteur de test</h1> - This page... - <ul> -<li> - Afficher <a href="#html">les résultats en HTML</a> - </li> -<li> - Afficher et <a href="#autres">rapporter les résultats</a> - dans d'autres formats - </li> -<li> - Utilisé <a href="#cli">SimpleTest depuis la ligne de commande</a> - </li> -<li> - <a href="#xml">Utiliser XML</a> pour des tests distants - </li> -</ul> -<div class="content"> - - <p> - SimpleTest suit plutôt plus que moins le modèle MVC (Modèle-Vue-Contrôleur). - Les classes "reporter" sont les vues et les modèles - sont vos scénarios de test et leur hiérarchie. - Le contrôleur est le plus souvent masqué à l'utilisateur - de SimpleTest à moins de vouloir changer la façon - dont les tests sont effectivement exécutés, - auquel cas il est possible de surcharger les objets - "runner" (ceux de l'exécuteur) depuis l'intérieur - d'un scénario de test. Comme d'habitude avec MVC, - le contrôleur est plutôt indéfini et il existe d'autres endroits - pour contrôler l'exécution des tests. - </p> - - <h2> -<a class="target" name="html"></a>Les résultats rapportés au format HTML</h2> - <p> - L'affichage par défaut est minimal à l'extrême. - Il renvoie le succès ou l'échec avec les barres conventionnelles - - rouge et verte - et affichent une trace d'arborescence - des groupes de test pour chaque assertion erronée. Voici un tel échec... - <div class="demo"> - <h1>File test</h1> - <span class="fail">Fail</span>: createnewfile->True assertion failed.<br> - <div style="padding: 8px; margin-top: 1em; background-color: red; color: white;">1/1 test cases complete. - <strong>0</strong> passes, <strong>1</strong> fails and <strong>0</strong> exceptions.</div> - </div> - Alors qu'ici tous les tests passent... - <div class="demo"> - <h1>File test</h1> - <div style="padding: 8px; margin-top: 1em; background-color: green; color: white;">1/1 test cases complete. - <strong>1</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</div> - </div> - La bonne nouvelle, c'est qu'il existe pas mal de points - dans la hiérarchie de l'affichage pour créer des sous-classes. - </p> - <p> - Pour l'affichage basé sur des pages web, - il y a la classe <span class="new_code">HtmlReporter</span> avec la signature suivante... -<pre> -class HtmlReporter extends SimpleReporter { - public __construct($encoding) { ... } - public makeDry(boolean $is_dry) { ... } - public void paintHeader(string $test_name) { ... } - public void sendNoCacheHeaders() { ... } - public void paintFooter(string $test_name) { ... } - public void paintGroupStart(string $test_name, integer $size) { ... } - public void paintGroupEnd(string $test_name) { ... } - public void paintCaseStart(string $test_name) { ... } - public void paintCaseEnd(string $test_name) { ... } - public void paintMethodStart(string $test_name) { ... } - public void paintMethodEnd(string $test_name) { ... } - public void paintFail(string $message) { ... } - public void paintPass(string $message) { ... } - public void paintError(string $message) { ... } - public void paintException(string $message) { ... } - public void paintMessage(string $message) { ... } - public void paintFormattedMessage(string $message) { ... } - protected string getCss() { ... } - public array getTestList() { ... } - public integer getPassCount() { ... } - public integer getFailCount() { ... } - public integer getExceptionCount() { ... } - public integer getTestCaseCount() { ... } - public integer getTestCaseProgress() { ... } -} -</pre> - Voici ce que certaines de ces méthodes veulent dire. - Premièrement les méthodes d'affichage que vous voudrez probablement surcharger... - <ul class="api"> - <li> - <span class="new_code">HtmlReporter(string $encoding)</span><br> - est le constructeur. Notez que le test unitaire initie - le lien à l'affichage plutôt que l'opposé. - L'affichage est principalement un receveur passif - des évènements de tests. Cela permet d'adapter - facilement l'affichage pour d'autres systèmes - en dehors des tests unitaires, tel le suivi - de la charge de serveurs. - L'"encoding" est le type d'encodage - que vous souhaitez utiliser pour l'affichage du test. - Pour pouvoir effectuer un rendu correct de la sortie - de débogage quand on utilise le testeur web, - il doit correspondre à l'encodage du site testé. - Les chaînes de caractères disponibles - sont indiquées dans la fonction PHP - <a href="http://www.php.net/manual/fr/function.htmlentities.php">html_entities()</a>. - </li> - <li> - <span class="new_code">void paintHeader(string $test_name)</span><br> - est appelé une fois, au début du test quand l'évènement - de démarrage survient. Le premier évènement de démarrage - est souvent délivré par le groupe de tests du niveau - le plus haut et donc c'est de là que le - <span class="new_code">$test_name</span> arrive. - Il peint le titre de la page, CSS, la balise "body", etc. - Il ne renvoie rien du tout (<span class="new_code">void</span>). - </li> - <li> - <span class="new_code">void paintFooter(string $test_name)</span><br> - est appelé à la toute fin du test pour fermer - les balises ouvertes par l'entête de la page. - Par défaut il affiche aussi la barre rouge ou verte - et le décompte final des résultats. - En fait la fin des tests arrive quand l'évènement - de fin de test arrive avec le même nom - que celui qui l'a initié au même niveau. - Le nid des tests en quelque sorte. - Fermer le dernier test finit l'affichage. - </li> - <li> - <span class="new_code">void paintMethodStart(string $test_name)</span><br> - est appelé au début de chaque méthode de test. - Normalement le nom vient de celui de la méthode. - Les autres évènements de départ de test - se comportent de la même manière sauf que - celui du groupe de tests indique au rapporteur - le nombre de scénarios de test qu'il contient. - De la sorte le rapporteur peut afficher une barre - de progrès au fur et à mesure que l'exécuteur - passe en revue les scénarios de test. - </li> - <li> - <span class="new_code">void paintMethodEnd(string $test_name)</span><br> - clôt le test lancé avec le même nom. - </li> - <li> - <span class="new_code">void paintFail(string $message)</span><br> - peint un échec. Par défaut il ne fait qu'afficher - le mot "fail", une trace d'arborescence - affichant la position du test en cours - et le message transmis par l'assertion. - </li> - <li> - <span class="new_code">void paintPass(string $message)</span><br> - ne fait rien, par défaut. - </li> - <li> - <span class="new_code">string getCss()</span><br> - renvoie les styles CSS sous la forme d'une chaîne - à l'attention de la méthode d'entêtes d'une page. - Des styles additionnels peuvent être ajoutés ici - si vous ne surchargez pas les entêtes de la page. - Vous ne voudrez pas utiliser cette méthode dans - des entêtes d'une page surchargée si vous souhaitez - inclure le feuille de style CSS d'origine. - </li> - </ul> - Il y a aussi des accesseurs pour aller chercher l'information - sur l'état courant de la suite de test. Vous les utiliserez - pour enrichir l'affichage... - <ul class="api"> - <li> - <span class="new_code">array getTestList()</span><br> - est la première méthode très commode pour les sous-classes. - Elle liste l'arborescence courante des tests - sous la forme d'une liste de noms de tests. - Le premier test -- celui de premier niveau -- - sera le premier dans la liste et la méthode de test - en cours sera la dernière. - </li> - <li> - <span class="new_code">integer getPassCount()</span><br> - renvoie le nombre de succès atteint. Il est nécessaire - pour l'affichage à la fin. - </li> - <li> - <span class="new_code">integer getFailCount()</span><br> - renvoie de la même manière le nombre d'échecs. - </li> - <li> - <span class="new_code">integer getExceptionCount()</span><br> - renvoie quant à lui le nombre d'erreurs. - </li> - <li> - <span class="new_code">integer getTestCaseCount()</span><br> - est le nombre total de scénarios lors de l'exécution des tests. - Il comprend aussi les tests groupés. - </li> - <li> - <span class="new_code">integer getTestCaseProgress()</span><br> - est le nombre de scénarios réalisés jusqu'à présent. - </li> - </ul> - Une modification simple : demander à l'HtmlReporter d'afficher - aussi bien les succès que les échecs et les erreurs... -<pre> -<strong>class ReporterShowingPasses extends HtmlReporter { - - function paintPass($message) { - parent::paintPass($message); - print "<span class=\"pass\">Pass</span>: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode("-&gt;", $breadcrumb); - print "-&gt;$message<br />\n"; - } - - protected function getCss() { - return parent::getCss() . ' .pass { color: green; }'; - } -}</strong> -</pre> - </p> - <p> - Une méthode qui a beaucoup fait jaser reste la méthode <span class="new_code">makeDry()</span>. - Si vous lancez cette méthode, sans paramètre, - sur le rapporteur avant que la suite de test - ne soit exécutée alors aucune méthode de test - ne sera appelée. Vous continuerez à avoir - les évènements entrants et sortants des méthodes - et scénarios de test, mais aucun succès ni échec ou erreur, - parce que le code de test ne sera pas exécuté. - </p> - <p> - La raison ? Pour permettre un affichage complexe - d'une IHM (ou GUI) qui permettrait la sélection - de scénarios de test individuels. - Afin de construire une liste de tests possibles, - ils ont besoin d'un rapport sur la structure du test - pour l'affichage, par exemple, d'une vue en arbre - de la suite de test. Avec un rapporteur lancé - sur une exécution sèche qui ne renverrait - que les évènements d'affichage, cela devient - facilement réalisable. - </p> - - <h2> -<a class="target" name="autre"></a>Etendre le rapporteur</h2> - <p> - Plutôt que de modifier l'affichage existant, - vous voudrez peut-être produire une présentation HTML - complètement différente, ou même générer une version texte ou XML. - Plutôt que de surcharger chaque méthode dans - <span class="new_code">HtmlReporter</span> nous pouvons nous rendre - une étape plus haut dans la hiérarchie de classe vers - <span class="new_code">SimpleReporter</span> dans le fichier source <em>simple_test.php</em>. - </p> - <p> - Un affichage sans rien, un canevas vierge - pour votre propre création, serait... -<pre> -<strong>require_once('simpletest/simpletest.php');</strong> - -class MyDisplay extends SimpleReporter {<strong> - </strong> - function paintHeader($test_name) { } - - function paintFooter($test_name) { } - - function paintStart($test_name, $size) {<strong> - parent::paintStart($test_name, $size);</strong> - } - - function paintEnd($test_name, $size) {<strong> - parent::paintEnd($test_name, $size);</strong> - } - - function paintPass($message) {<strong> - parent::paintPass($message);</strong> - } - - function paintFail($message) {<strong> - parent::paintFail($message);</strong> - } - - function paintError($message) {<strong> - parent::paintError($message);</strong> - } - - function paintException($exception) {<strong> - parent::paintException($exception);</strong> - } -} -</pre> - Aucune sortie ne viendrait de cette classe jusqu'à un ajout de votre part. - </p> - <p> - Sauf qu'il y a un problème : en utilisant cette cette classe - de bas niveau, vous devez explicitement l'invoquer - dans les scripts de test. - La commande "autorun" ne sera pas capable - d'utiliser son contexte courant (qu'elle soit lancée - dans un navigateur web ou via une ligne de commande) - pour sélectionner le rapporteur. - </p> - <p> - Vous invoquez explicitement la lanceur de tests comme suit... -<pre> -<?php -require_once('simpletest/autorun.php'); - -$test = new TestSuite('File test'); -$test->addFile('tests/file_test.php'); -$test->run(<strong>new MyReporter()</strong>); -?> -</pre> - ...ou peut-être comme cela... -<pre> -<?php -require_once('simpletest/simpletest.php'); -require_once('my_reporter.php'); - -class MyTest extends TestSuite { - function __construct() { - parent::__construct(); - $this->addFile('tests/file_test.php'); - } -} - -$test = new MyTest(); -$test->run(<strong>new MyReporter()</strong>); -?> -</pre> - Nous verrons plus comment l'intégrer avec l'"autorun". - </p> - - <h2> -<a class="target" name="cli"></a>Le rapporteur en ligne de commande</h2> - <p> - SimpleTest est aussi livré avec un rapporteur - en ligne de commande, minime lui aussi. - Pour utiliser le rapporteur en ligne de commande explicitement, - il suffit de l'intervertir avec celui de la version HTML... -<pre> -<?php -require_once('simpletest/autorun.php'); - -$test = new TestSuite('File test'); -$test->addFile('tests/file_test.php'); -$test->run(<strong>new TextReporter()</strong>); -?> -</pre> - Et ensuite d'invoquer la suite de test à partir d'une ligne de commande... -<pre class="shell"> -php file_test.php -</pre> - Bien sûr vous aurez besoin d'installer PHP - en ligne de commande. Une suite de test qui - passerait toutes ses assertions ressemble à... -<pre class="shell"> -File test -OK -Test cases run: 1/1, Passes: 1, Failures: 0, Exceptions: 0 -</pre> - Un échec déclenche un affichage comme... -<pre class="shell"> -File test -1) True assertion failed. - in createNewFile -FAILURES!!! -Test cases run: 1/1, Passes: 0, Failures: 1, Exceptions: 0 -</pre> - </p> - <p> - Une des principales raisons pour utiliser - une suite de test en ligne de commande tient - dans l'utilisation possible du testeur avec - un processus automatisé. Pour fonctionner comme - il faut dans des scripts shell le script de test - devrait renvoyer un code de sortie non-nul suite à un échec. - Si une suite de test échoue la valeur <span class="new_code">false</span> - est renvoyée par la méthode <span class="new_code">SimpleTest::run()</span>. - Nous pouvons utiliser ce résultat pour terminer le script - avec la bonne valeur renvoyée... -<pre> -<?php -require_once('simpletest/autorun.php'); - -$test = new TestSuite('File test'); -$test->addFile('tests/file_test.php'); -<strong>exit ($test->run(new TextReporter()) ? 0 : 1);</strong> -?> -</pre> - Bien sûr l'objectif ne serait pas de créer deux scripts de test, - l'un en ligne de commande et l'autre pour un navigateur web, - pour chaque suite de test. - Le rapporteur en ligne de commande inclut - une méthode pour déterminer l'environnement d'exécution... -<pre> -<?php -require_once('simpletest/autorun.php'); - -$test = new TestSuite('File test'); -$test->addFile('tests/file_test.php'); -<strong>if (TextReporter::inCli()) {</strong> - exit ($test->run(new TextReporter()) ? 0 : 1); -<strong>}</strong> -$test->run(new HtmlReporter()); -?> -</pre> - Il s'agit là de la forme utilisée par SimpleTest lui-même. - Quand vous utilisez l'"autorun.php" - et qu'aucun test n'a été lancé avant la fin, - c'est quasiment le code que SimpleTest lancera - pour vous implicitement. - </p> - <p> - En d'autres termes, ceci donne le même résultat... -<pre> -<?php -require_once('simpletest/autorun.php'); - -class MyTest extends TestSuite { - function __construct() { - parent::__construct(); - $this->addFile('tests/file_test.php'); - } -} -?> -</pre> </p> - - <h2> -<a class="target" name="xml"></a>Test distant</h2> - <p> - SimpleTest est livré avec une classe <span class="new_code">XmlReporter</span> - utilisée pour de la communication interne. - Lors de son exécution, le résultat ressemble à... -<pre class="shell"> -<?xml version="1.0"?> -<run> - <group size="4"> - <name>Remote tests</name> - <group size="4"> - <name>Visual test with 48 passes, 48 fails and 4 exceptions</name> - <case> - <name>testofunittestcaseoutput</name> - <test> - <name>testofresults</name> - <pass>This assertion passed</pass> - <fail>This assertion failed</fail> - </test> - <test> - ... - </test> - </case> - </group> - </group> -</run> -</pre> - Pour faire en sorte ue vos scénarios de test produisent ce format, - dans la ligne de commande, ajoutez le flag <span class="new_code">--xml</span>. -<pre class="shell"> -php my_test.php --xml -</pre> - Vous pouvez faire la même chose dans le navigation web - en ajoutant le paramètre <span class="new_code">xml=1</span> dans l'URL. - N'importe quelle valeur "true" fera l'affaire. - </p> - <p> - Vous pouvez utiliser ce format avec le parseur - fourni dans SimpleTest lui-même. - Il s'agit de <span class="new_code">SimpleTestXmlParser</span> - et se trouve <em>xml.php</em> à l'intérieur du paquet SimpleTest... -<pre> -<?php -require_once('simpletest/xml.php'); - -... -$parser = new SimpleTestXmlParser(new HtmlReporter()); -$parser->parse($test_output); -?> -</pre> - <span class="new_code">$test_output</span> devrait être au format XML, - à partir du rapporteur XML, et pourrait venir - d'une exécution en ligne de commande d'un scénario de test. - Le parseur envoie des évènements au rapporteur exactement - comme tout autre exécution de test. - Il y a des occasions bizarres dans lesquelles c'est en fait très utile. - </p> - <p> - Le plus courant, c'est quand vous voulez isoler - un test sensible au crash. - Vous pouvez collecter la sortie XML en utilisant - l'opérateur antiquote (Ndt : backtick) à partir - d'un autre test. - De la sorte, il tourne dans son propre processus... -<pre> -<?php -require_once('simpletest/xml.php'); - -if (TextReporter::inCli()) { - $parser = new SimpleTestXmlParser(new TextReporter()); -} else { - $parser = new SimpleTestXmlParser(new HtmlReporter()); -} -$parser->parse(`php flakey_test.php --xml`); -?> -</pre> - </p> - <p> - Un autre cas est celui des très longues suites de tests. - </p> - <p> - Elles peuvent venir à bout de la limite de mémoire - par défaut d'un process PHP - 16Mb. - En plaçant la sortie des groupes de test dans du XML - et leur exécution dans des process différents, - le résultat peut être parsé à nouveau pour agréger - les résultats avec moins d'impact sur le test au premier niveau. - </p> - <p> - Parce que la sortie XML peut venir de n'importe où, - ça ouvre des possibilités d'agrégation d'exécutions de test - depuis des serveur distants. - Un scénario de test pour le réaliser existe déjà - à l'intérieur du framework SimpleTest, mais il est encore expérimental... -<pre> -<?php -<strong>require_once('../remote.php');</strong> -require_once('simpletest/autorun.php'); - -$test_url = ...; -$dry_url = ...; - -class MyTestOnAnotherServer extends RemoteTestCase { - function __construct() { - $test_url = ... - parent::__construct($test_url, $test_url . ' --dry'); - } -} -?> -</pre> - <span class="new_code">RemoteTestCase</span> prend la localisation réelle - du lanceur de test, tout simplement un page web au format XML. - Il prend aussi l'URL d'un rapporteur initié - pour effectuer une exécution sèche. - Cette technique est employée pour que les progrès - soient correctement rapportés vers le haut. - <span class="new_code">RemoteTestCase</span> peut être ajouté à - une suite de test comme n'importe quelle autre suite de tests. - </p> - - </div> - References and related information... - <ul> -<li> - La page du projet SimpleTest sur - <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - La page de téléchargement de SimpleTest sur - <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - L'<a href="http://simpletest.org/api/">API pour développeur de SimpleTest</a> - donne tous les détails sur les classes et les assertions disponibles. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/unit_test_documentation.html b/3rdparty/simpletest/docs/fr/unit_test_documentation.html deleted file mode 100644 index a7c31f95dbb6b90e9f03daefabb812e078b309bc..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/unit_test_documentation.html +++ /dev/null @@ -1,447 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>Documentation SimpleTest pour les tests de régression en PHP</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Documentation sur les tests unitaires en PHP</h1> - This page... - <ul> -<li> - <a href="#unitaire">Scénarios de test unitaire</a> - et opérations basiques. - </li> -<li> - <a href="#extension_unitaire">Étendre des scénarios de test</a> - pour les personnaliser à votre propre projet. - </li> -<li> - <a href="#lancement_unitaire">Lancer un scénario seul</a> - comme un script unique. - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="unitaire"></a>Scénarios de tests unitaires</h2> - <p> - Le coeur du système est un framework de tests de régression - construit autour des scénarios de test. - Un exemple de scénario de test ressemble à... -<pre> -<strong>class FileTestCase extends UnitTestCase { -}</strong> -</pre> - Si aucun nom de test n'est fourni au moment - de la liaison avec le constructeur alors - le nom de la classe sera utilisé. - Il s'agit du nom qui sera affiché dans les résultats du test. - </p> - <p> - Les véritables tests sont ajoutés en tant que méthode - dans le scénario de test dont le nom par défaut - commence par la chaîne "test" - et quand le scénario de test est appelé toutes les méthodes - de ce type sont exécutées dans l'ordre utilisé - par l'introspection de PHP pour les trouver. - Peuvent être ajoutées autant de méthodes de test que nécessaires. - Par exemple... -<pre> -require_once('simpletest/autorun.php'); -require_once('../classes/writer.php'); - -class FileTestCase extends UnitTestCase { - function FileTestCase() { - $this->UnitTestCase('File test'); - }<strong> - - function setUp() { - @unlink('../temp/test.txt'); - } - - function tearDown() { - @unlink('../temp/test.txt'); - } - - function testCreation() { - $writer = &new FileWriter('../temp/test.txt'); - $writer->write('Hello'); - $this->assertTrue(file_exists('../temp/test.txt'), 'File created'); - }</strong> -} -</pre> - Le constructeur est optionnel et souvent omis. Sans nom, - le nom de la classe est utilisé comme nom pour le scénario de test. - </p> - <p> - Notre unique méthode de test pour le moment est - <span class="new_code">testCreation()</span> où nous vérifions - qu'un fichier a bien été créé par notre objet - <span class="new_code">Writer</span>. Nous pourrions avoir mis - le code <span class="new_code">unlink()</span> dans cette méthode, - mais en la plaçant dans <span class="new_code">setUp()</span> - et <span class="new_code">tearDown()</span> nous pouvons l'utiliser - pour nos autres méthodes de test que nous ajouterons. - </p> - <p> - La méthode <span class="new_code">setUp()</span> est lancé - juste avant chaque méthode de test. - <span class="new_code">tearDown()</span> est lancé après chaque méthode de test. - </p> - <p> - Vous pouvez placer une initialisation de - scénario de test dans le constructeur afin qu'elle soit lancée - pour toutes les méthodes dans le scénario de test - mais dans un tel cas vous vous exposeriez à des interférences. - Cette façon de faire est légèrement moins rapide, - mais elle est plus sûre. - Notez que si vous arrivez avec des notions de JUnit, - il ne s'agit pas du comportement auquel vous êtes habitués. - Bizarrement JUnit re-instancie le scénario de test - pour chaque méthode de test pour se prévenir - d'une telle interférence. - SimpleTest demande à l'utilisateur final d'utiliser - <span class="new_code">setUp()</span>, mais fournit aux codeurs de bibliothèque d'autres crochets. - </p> - <p> - Pour rapporter les résultats de test, - le passage par une classe d'affichage - notifiée par - les différentes méthodes de type <span class="new_code">assert...()</span> - - est utilisée. En voici la liste complète pour - la classe <span class="new_code">UnitTestCase</span>, - celle par défaut dans SimpleTest... - <table><tbody> - <tr> -<td><span class="new_code">assertTrue($x)</span></td> -<td>Echoue si $x est faux</td> -</tr> - <tr> -<td><span class="new_code">assertFalse($x)</span></td> -<td>Echoue si $x est vrai</td> -</tr> - <tr> -<td><span class="new_code">assertNull($x)</span></td> -<td>Echoue si $x est initialisé</td> -</tr> - <tr> -<td><span class="new_code">assertNotNull($x)</span></td> -<td>Echoue si $x n'est pas initialisé</td> -</tr> - <tr> -<td><span class="new_code">assertIsA($x, $t)</span></td> -<td>Echoue si $x n'est pas de la classe ou du type $t</td> -</tr> - <tr> -<td><span class="new_code">assertEqual($x, $y)</span></td> -<td>Echoue si $x == $y est faux</td> -</tr> - <tr> -<td><span class="new_code">assertNotEqual($x, $y)</span></td> -<td>Echoue si $x == $y est vrai</td> -</tr> - <tr> -<td><span class="new_code">assertIdentical($x, $y)</span></td> -<td>Echoue si $x === $y est faux</td> -</tr> - <tr> -<td><span class="new_code">assertNotIdentical($x, $y)</span></td> -<td>Echoue si $x === $y est vrai</td> -</tr> - <tr> -<td><span class="new_code">assertReference($x, $y)</span></td> -<td>Echoue sauf si $x et $y sont la même variable</td> -</tr> - <tr> -<td><span class="new_code">assertCopy($x, $y)</span></td> -<td>Echoue si $x et $y sont la même variable</td> -</tr> - <tr> -<td><span class="new_code">assertPattern($p, $x)</span></td> -<td>Echoue sauf si l'expression rationnelle $p capture $x</td> -</tr> - <tr> -<td><span class="new_code">assertNoPattern($p, $x)</span></td> -<td>Echoue si l'expression rationnelle $p capture $x</td> -</tr> - <tr> -<td><span class="new_code">expectError($x)</span></td> -<td>Echoue si l'erreur correspondante n'arrive pas</td> -</tr> - <tr> -<td><span class="new_code">expectException($x)</span></td> -<td>Echoue si l'exception correspondante n'est pas levée</td> -</tr> - <tr> -<td><span class="new_code">ignoreException($x)</span></td> -<td>Avale toutes les exceptions correspondantes qui surviendraient</td> -</tr> - <tr> -<td><span class="new_code">assert($e)</span></td> -<td>Echoue sur un objet <a href="expectation_documentation.html">attente</a> $e qui échouerait</td> -</tr> - </tbody></table> - Toutes les méthodes d'assertion peuvent recevoir - une description optionnelle : - cette description sert pour étiqueter le résultat. - Sans elle, une message par défaut est envoyée à la place : - il est généralement suffisant. - Ce message par défaut peut encore être encadré - dans votre propre message si vous incluez "%s" - dans la chaîne. - Toutes les assertions renvoient vrai / true en cas de succès - et faux / false en cas d'échec. - </p> - <p> - D'autres exemples... -<pre> -<strong>$variable = null; -$this->assertNull($variable, 'Should be cleared');</strong> -</pre> - ...passera et normalement n'affichera aucun message. - Si vous avez <a href="http://www.lastcraft.com/display_subclass_tutorial.php"> - configuré le testeur pour afficher aussi les succès</a> - alors le message sera affiché comme tel. -<pre> -<strong>$this->assertIdentical(0, false, 'Zero is not false [%s]');</strong> -</pre> - Ceci échouera étant donné qu'il effectue une vérification - sur le type en plus d'une comparaison sur les deux valeurs. - La partie "%s" est remplacée par le message d'erreur - par défaut qui aurait été affiché si nous n'avions pas fourni le nôtre. - Cela nous permet d'emboîter les messages de test. -<pre> -<strong>$a = 1; -$b = $a; -$this->assertReference($a, $b);</strong> -</pre> - Échouera étant donné que la variable <span class="new_code">$b</span> - est une copie de <span class="new_code">$a</span>. -<pre> -<strong>$this->assertPattern('/hello/i', 'Hello world');</strong> -</pre> - Là, ça passe puisque la recherche est insensible - à la casse et que donc <span class="new_code">hello</span> - est bien repérable dans <span class="new_code">Hello world</span>. -<pre> -<strong>$this->expectError();</strong> -trigger_error('Catastrophe'); -</pre> - Ici la vérification attrape le message "Catastrophe" - sans vérifier le texte et passe. - Elle enlève l'erreur de la queue au passage. -<pre> -<strong>$this->expectError('Catastrophe');</strong> -trigger_error('Catastrophe'); -</pre> - La vérification d'erreur suivante teste non seulement - l'existance de l'erreur mais aussi le texte qui, - dans le cas présent, correspond et donc un nouveau succès. - Si des erreurs non vérifiées sont laissées pour compte - à la fin d'une méthode de test alors un exception sera levé - dans le test. - </p> - <p> - Notez que SimpleTest ne peut pas attraper des erreurs PHP - au moment de la compilation. - </p> - <p> - Les scénarios de tests peuvent utiliser des méthodes - bien pratiques pour déboguer le code ou pour étendre la suite... - <table><tbody> - <tr> -<td><span class="new_code">setUp()</span></td> -<td>Est lancée avant chaque méthode de test</td> -</tr> - <tr> -<td><span class="new_code">tearDown()</span></td> -<td>Est lancée après chaque méthode de test</td> -</tr> - <tr> -<td><span class="new_code">pass()</span></td> -<td>Envoie un succès</td> -</tr> - <tr> -<td><span class="new_code">fail()</span></td> -<td>Envoie un échec</td> -</tr> - <tr> -<td><span class="new_code">error()</span></td> -<td>Envoi un évènement exception</td> -</tr> - <tr> -<td><span class="new_code">signal($type, $payload)</span></td> -<td>Envoie un message défini par l'utilisateur au rapporteur du test</td> -</tr> - <tr> -<td><span class="new_code">dump($var)</span></td> -<td>Effectue un <span class="new_code">print_r()</span> formaté pour du déboguage rapide et grossier</td> -</tr> - </tbody></table> - </p> - - <h2> -<a class="target" name="extension_unitaire"></a>Etendre les scénarios de test</h2> - <p> - Bien sûr des méthodes supplémentaires de test - peuvent être ajoutées pour créer d'autres types - de scénario de test afin d'étendre le framework... -<pre> -require_once('simpletest/autorun.php'); -<strong> -class FileTester extends UnitTestCase { - function FileTester($name = false) { - $this->UnitTestCase($name); - } - - function assertFileExists($filename, $message = '%s') { - $this->assertTrue( - file_exists($filename), - sprintf($message, 'File [$filename] existence check')); - }</strong> -} -</pre> - Ici la bibliothèque SimpleTest est localisée - dans un répertoire local appelé <em>simpletest</em>. - Pensez à le modifier pour votre propre environnement. - </p> - <p> - Alternativement vous pourriez utiliser dans votre code - un directive <span class="new_code">SimpleTestOptions::ignore('FileTester');</span>. - </p> - <p> - Ce nouveau scénario peut être hérité exactement - comme un scénario de test classique... -<pre> -class FileTestCase extends <strong>FileTester</strong> { - - function setUp() { - @unlink('../temp/test.txt'); - } - - function tearDown() { - @unlink('../temp/test.txt'); - } - - function testCreation() { - $writer = &new FileWriter('../temp/test.txt'); - $writer->write('Hello');<strong> - $this->assertFileExists('../temp/test.txt');</strong> - } -} -</pre> - </p> - <p> - Si vous souhaitez un scénario de test sans - toutes les assertions de <span class="new_code">UnitTestCase</span> - mais uniquement avec les vôtres propres, - vous aurez besoin d'étendre la classe - <span class="new_code">SimpleTestCase</span> à la place. - Elle se trouve dans <em>simple_test.php</em> - en lieu et place de <em>unit_tester.php</em>. - A consulter <a href="group_test_documentation.html">plus tard</a> - si vous souhaitez incorporer les scénarios - d'autres testeurs unitaires dans votre suite de test. - </p> - - <h2> -<a class="target" name="lancement_unitaire"></a>Lancer un unique scénario de test</h2> - <p> - Ce n'est pas souvent qu'il faille lancer des scénarios - avec un unique test. Sauf lorsqu'il s'agit de s'arracher - les cheveux sur un module à problème sans pour - autant désorganiser la suite de test principale. - Avec <em>autorun</em> aucun échafaudage particulier - n'est nécessaire, il suffit de lancer votre test et - vous y êtes. - </p> - <p> - Vous pouvez même décider quel rapporteur - (par exemple, <span class="new_code">TextReporter</span> ou <span class="new_code">HtmlReporter</span>) - vous préférez pour un fichier spécifique quand il est lancé - tout seul... -<pre> -<?php -require_once('simpletest/autorun.php');<strong> -SimpleTest :: prefer(new TextReporter());</strong> -require_once('../classes/writer.php'); - -class FileTestCase extends UnitTestCase { - ... -} -?> -</pre> - Ce script sera lancé tel que mais il n'y aura - aucun succès ou échec avant que des méthodes de test soient ajoutées. - </p> - - </div> - References and related information... - <ul> -<li> - La page de SimpleTest sur - <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - La page de téléchargement de SimpleTest sur - <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - <a href="http://simpletest.org/api/">L'API complète de SimpleTest</a> - à partir de PHPDoc. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/docs/fr/web_tester_documentation.html b/3rdparty/simpletest/docs/fr/web_tester_documentation.html deleted file mode 100644 index 308fbc9ccbbd9e2912f784db5b8566d48b91b435..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/docs/fr/web_tester_documentation.html +++ /dev/null @@ -1,570 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<title>Documentation SimpleTest : tester des scripts web</title> -<link rel="stylesheet" type="text/css" href="docs.css" title="Styles"> -</head> -<body> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<h1>Documentation sur le testeur web</h1> - This page... - <ul> -<li> - Réussir à <a href="#telecharger">télécharger une page web</a> - </li> -<li> - Tester le <a href="#contenu">contenu de la page</a> - </li> -<li> - <a href="#navigation">Naviguer sur un site web</a> pendant le test - </li> -<li> - Méthodes pour <a href="#requete">modifier une requête</a> et pour déboguer - </li> -</ul> -<div class="content"> - <h2> -<a class="target" name="telecharger"></a>Télécharger une page</h2> - <p> - Tester des classes c'est très bien. - Reste que PHP est avant tout un langage - pour créer des fonctionnalités à l'intérieur de pages web. - Comment pouvons tester la partie de devant - -- celle de l'interface -- dans nos applications en PHP ? - Etant donné qu'une page web n'est constituée que de texte, - nous devrions pouvoir les examiner exactement - comme n'importe quelle autre donnée de test. - </p> - <p> - Cela nous amène à une situation délicate. - Si nous testons dans un niveau trop bas, - vérifier des balises avec un motif ad hoc par exemple, - nos tests seront trop fragiles. Le moindre changement - dans la présentation pourrait casser un grand nombre de test. - Si nos tests sont situés trop haut, en utilisant - une version fantaisie du moteur de template pour - donner un cas précis, alors nous perdons complètement - la capacité à automatiser certaines classes de test. - Par exemple, l'interaction entre des formulaires - et la navigation devra être testé manuellement. - Ces types de test sont extrêmement fastidieux - et plutôt sensibles aux erreurs. - </p> - <p> - SimpleTest comprend une forme spéciale de scénario - de test pour tester les actions d'une page web. - <span class="new_code">WebTestCase</span> inclut des facilités pour la navigation, - des vérifications sur le contenu - et les cookies ainsi que la gestion des formulaires. - Utiliser ces scénarios de test ressemble - fortement à <span class="new_code">UnitTestCase</span>... -<pre> -<strong>class TestOfLastcraft extends WebTestCase { -}</strong> -</pre> - Ici nous sommes sur le point de tester - le site de <a href="http://www.lastcraft.com/">Last Craft</a>. - Si ce scénario de test est situé dans un fichier appelé - <em>lastcraft_test.php</em> alors il peut être chargé - dans un script de lancement tout comme des tests unitaires... -<pre> -<?php -require_once('simpletest/autorun.php');<strong> -require_once('simpletest/web_tester.php');</strong> -SimpleTest::prefer(new TextReporter()); - -class WebTests extends TestSuite { - function WebTests() { - $this->TestSuite('Web site tests');<strong> - $this->addFile('lastcraft_test.php');</strong> - } -} -?> -</pre> - J'utilise ici le rapporteur en mode texte - pour mieux distinguer le contenu au format HTML - du résultat du test proprement dit. - </p> - <p> - Rien n'est encore testé. Nous pouvons télécharger - la page d'accueil en utilisant la méthode <span class="new_code">get()</span>... -<pre> -class TestOfLastcraft extends WebTestCase { - <strong> - function testHomepage() { - $this->assertTrue($this->get('http://www.lastcraft.com/')); - }</strong> -} -</pre> - La méthode <span class="new_code">get()</span> renverra "true" - uniquement si le contenu de la page a bien été téléchargé. - C'est un moyen simple, mais efficace pour vérifier - qu'une page web a bien été délivré par le serveur web. - Cependant le contenu peut révéler être une erreur 404 - et dans ce cas notre méthode <span class="new_code">get()</span> renverrait encore un succès. - </p> - <p> - En supposant que le serveur web pour le site Last Craft - soit opérationnel (malheureusement ce n'est pas toujours le cas), - nous devrions voir... -<pre class="shell"> -Web site tests -OK -Test cases run: 1/1, Failures: 0, Exceptions: 0 -</pre> - Nous avons vérifié qu'une page, de n'importe quel type, - a bien été renvoyée. Nous ne savons pas encore - s'il s'agit de celle que nous souhaitions. - </p> - - <h2> -<a class="target" name="contenu"></a>Tester le contenu d'une page</h2> - <p> - Pour obtenir la confirmation que la page téléchargée - est bien celle que nous attendions, - nous devons vérifier son contenu. -<pre> -class TestOfLastcraft extends WebTestCase { - - function testHomepage() {<strong> - $this->get('http://www.lastcraft.com/'); - $this->assertWantedPattern('/why the last craft/i');</strong> - } -} -</pre> - La page obtenue par le dernier téléchargement est - placée dans un buffer au sein même du scénario de test. - Il n'est donc pas nécessaire de s'y référer directement. - La correspondance du motif est toujours effectuée - par rapport à ce buffer. - </p> - <p> - Voici une liste possible d'assertions sur le contenu... - <table><tbody> - <tr> -<td><span class="new_code">assertWantedPattern($pattern)</span></td> -<td>Vérifier une correspondance sur le contenu via une expression rationnelle Perl</td> -</tr> - <tr> -<td><span class="new_code">assertNoUnwantedPattern($pattern)</span></td> -<td>Une expression rationnelle Perl pour vérifier une absence</td> -</tr> - <tr> -<td><span class="new_code">assertTitle($title)</span></td> -<td>Passe si le titre de la page correspond exactement</td> -</tr> - <tr> -<td><span class="new_code">assertLink($label)</span></td> -<td>Passe si un lien avec ce texte est présent</td> -</tr> - <tr> -<td><span class="new_code">assertNoLink($label)</span></td> -<td>Passe si aucun lien avec ce texte est présent</td> -</tr> - <tr> -<td><span class="new_code">assertLinkById($id)</span></td> -<td>Passe si un lien avec cet attribut d'identification est présent</td> -</tr> - <tr> -<td><span class="new_code">assertField($name, $value)</span></td> -<td>Passe si une balise input avec ce nom contient cette valeur</td> -</tr> - <tr> -<td><span class="new_code">assertFieldById($id, $value)</span></td> -<td>Passe si une balise input avec cet identifiant contient cette valeur</td> -</tr> - <tr> -<td><span class="new_code">assertResponse($codes)</span></td> -<td>Passe si la réponse HTTP trouve une correspondance dans la liste</td> -</tr> - <tr> -<td><span class="new_code">assertMime($types)</span></td> -<td>Passe si le type MIME se retrouve dans cette liste</td> -</tr> - <tr> -<td><span class="new_code">assertAuthentication($protocol)</span></td> -<td>Passe si l'authentification provoquée est de ce type de protocole</td> -</tr> - <tr> -<td><span class="new_code">assertNoAuthentication()</span></td> -<td>Passe s'il n'y pas d'authentification provoquée en cours</td> -</tr> - <tr> -<td><span class="new_code">assertRealm($name)</span></td> -<td>Passe si le domaine provoqué correspond</td> -</tr> - <tr> -<td><span class="new_code">assertHeader($header, $content)</span></td> -<td>Passe si une entête téléchargée correspond à cette valeur</td> -</tr> - <tr> -<td><span class="new_code">assertNoUnwantedHeader($header)</span></td> -<td>Passe si une entête n'a pas été téléchargé</td> -</tr> - <tr> -<td><span class="new_code">assertHeaderPattern($header, $pattern)</span></td> -<td>Passe si une entête téléchargée correspond à cette expression rationnelle Perl</td> -</tr> - <tr> -<td><span class="new_code">assertCookie($name, $value)</span></td> -<td>Passe s'il existe un cookie correspondant</td> -</tr> - <tr> -<td><span class="new_code">assertNoCookie($name)</span></td> -<td>Passe s'il n'y a pas de cookie avec un tel nom</td> -</tr> - </tbody></table> - Comme d'habitude avec les assertions de SimpleTest, - elles renvoient toutes "false" en cas d'échec - et "true" si c'est un succès. - Elles renvoient aussi un message de test optionnel : - vous pouvez l'ajouter dans votre propre message en utilisant "%s". - </p> - <p> - A présent nous pourrions effectué le test sur le titre uniquement... -<pre> -<strong>$this->assertTitle('The Last Craft?');</strong> -</pre> - En plus d'une simple vérification sur le contenu HTML, - nous pouvons aussi vérifier que le type MIME est bien d'un type acceptable... -<pre> -<strong>$this->assertMime(array('text/plain', 'text/html'));</strong> -</pre> - Plus intéressant encore est la vérification sur - le code de la réponse HTTP. Pareillement au type MIME, - nous pouvons nous assurer que le code renvoyé se trouve - bien dans un liste de valeurs possibles... -<pre> -class TestOfLastcraft extends WebTestCase { - - function testHomepage() { - $this->get('http://simpletest.sourceforge.net/');<strong> - $this->assertResponse(200);</strong> - } -} -</pre> - Ici nous vérifions que le téléchargement s'est - bien terminé en ne permettant qu'une réponse HTTP 200. - Ce test passera, mais ce n'est pas la meilleure façon de procéder. - Il n'existe aucune page sur <em>http://simpletest.sourceforge.net/</em>, - à la place le serveur renverra une redirection vers - <em>http://www.lastcraft.com/simple_test.php</em>. - <span class="new_code">WebTestCase</span> suit automatiquement trois - de ces redirections. Les tests sont quelque peu plus - robustes de la sorte. Surtout qu'on est souvent plus intéressé - par l'interaction entre les pages que de leur simple livraison. - Si les redirections se révèlent être digne d'intérêt, - il reste possible de les supprimer... -<pre> -class TestOfLastcraft extends WebTestCase { - - function testHomepage() {<strong> - $this->setMaximumRedirects(0);</strong> - $this->get('http://simpletest.sourceforge.net/'); - $this->assertResponse(200); - } -} -</pre> - Alors l'assertion échoue comme prévue... -<pre class="shell"> -Web site tests -1) Expecting response in [200] got [302] - in testhomepage - in testoflastcraft - in lastcraft_test.php -FAILURES!!! -Test cases run: 1/1, Failures: 1, Exceptions: 0 -</pre> - Nous pouvons modifier le test pour accepter les redirections... -<pre> -class TestOfLastcraft extends WebTestCase { - - function testHomepage() { - $this->setMaximumRedirects(0); - $this->get('http://simpletest.sourceforge.net/'); - $this->assertResponse(<strong>array(301, 302, 303, 307)</strong>); - } -} -</pre> - Maitenant ça passe. - </p> - - <h2> -<a class="target" name="navigation"></a>Navigeur dans un site web</h2> - <p> - Les utilisateurs ne naviguent pas souvent en tapant les URLs, - mais surtout en cliquant sur des liens et des boutons. - Ici nous confirmons que les informations sur le contact - peuvent être atteintes depuis la page d'accueil... -<pre> -class TestOfLastcraft extends WebTestCase { - ... - function testContact() { - $this->get('http://www.lastcraft.com/');<strong> - $this->clickLink('About'); - $this->assertTitle('About Last Craft');</strong> - } -} -</pre> - Le paramètre est le texte du lien. - </p> - <p> - Il l'objectif est un bouton plutôt qu'une balise ancre, - alors <span class="new_code">clickSubmit()</span> doit être utilisé avec - le titre du bouton... -<pre> -<strong>$this->clickSubmit('Go!');</strong> -</pre> - </p> - <p> - La liste des méthodes de navigation est... - <table><tbody> - <tr> -<td><span class="new_code">get($url, $parameters)</span></td> -<td>Envoie une requête GET avec ces paramètres</td> -</tr> - <tr> -<td><span class="new_code">post($url, $parameters)</span></td> -<td>Envoie une requête POST avec ces paramètres</td> -</tr> - <tr> -<td><span class="new_code">head($url, $parameters)</span></td> -<td>Envoie une requête HEAD sans remplacer le contenu de la page</td> -</tr> - <tr> -<td><span class="new_code">retry()</span></td> -<td>Relance la dernière requête</td> -</tr> - <tr> -<td><span class="new_code">back()</span></td> -<td>Identique au bouton "Précédent" du navigateur</td> -</tr> - <tr> -<td><span class="new_code">forward()</span></td> -<td>Identique au bouton "Suivant" du navigateur</td> -</tr> - <tr> -<td><span class="new_code">authenticate($name, $password)</span></td> -<td>Re-essaye avec une tentative d'authentification</td> -</tr> - <tr> -<td><span class="new_code">getFrameFocus()</span></td> -<td>Le nom de la fenêtre en cours d'utilisation</td> -</tr> - <tr> -<td><span class="new_code">setFrameFocusByIndex($choice)</span></td> -<td>Change le focus d'une fenêtre en commençant par 1</td> -</tr> - <tr> -<td><span class="new_code">setFrameFocus($name)</span></td> -<td>Change le focus d'une fenêtre en utilisant son nom</td> -</tr> - <tr> -<td><span class="new_code">clearFrameFocus()</span></td> -<td>Revient à un traitement de toutes les fenêtres comme une seule</td> -</tr> - <tr> -<td><span class="new_code">clickSubmit($label)</span></td> -<td>Clique sur le premier bouton avec cette étiquette</td> -</tr> - <tr> -<td><span class="new_code">clickSubmitByName($name)</span></td> -<td>Clique sur le bouton avec cet attribut de nom</td> -</tr> - <tr> -<td><span class="new_code">clickSubmitById($id)</span></td> -<td>Clique sur le bouton avec cet attribut d'identification</td> -</tr> - <tr> -<td><span class="new_code">clickImage($label, $x, $y)</span></td> -<td>Clique sur une balise input de type image par son titre (title="*") our son texte alternatif (alt="*")</td> -</tr> - <tr> -<td><span class="new_code">clickImageByName($name, $x, $y)</span></td> -<td>Clique sur une balise input de type image par son attribut (name="*")</td> -</tr> - <tr> -<td><span class="new_code">clickImageById($id, $x, $y)</span></td> -<td>Clique sur une balise input de type image par son identifiant (id="*")</td> -</tr> - <tr> -<td><span class="new_code">submitFormById($id)</span></td> -<td>Soumet un formulaire sans valeur de soumission</td> -</tr> - <tr> -<td><span class="new_code">clickLink($label, $index)</span></td> -<td>Clique sur une ancre avec ce texte d'étiquette visible</td> -</tr> - <tr> -<td><span class="new_code">clickLinkById($id)</span></td> -<td>Clique sur une ancre avec cet attribut d'identification</td> -</tr> - </tbody></table> - </p> - <p> - Les paramètres dans les méthodes <span class="new_code">get()</span>, - <span class="new_code">post()</span> et <span class="new_code">head()</span> sont optionnels. - Le téléchargement via HTTP HEAD ne modifie pas - le contexte du navigateur, il se limite au chargement des cookies. - Cela peut être utilise lorsqu'une image ou une feuille de style - initie un cookie pour bloquer un robot trop entreprenant. - </p> - <p> - Les commandes <span class="new_code">retry()</span>, <span class="new_code">back()</span> - et <span class="new_code">forward()</span> fonctionnent exactement comme - dans un navigateur. Elles utilisent l'historique pour - relancer les pages. Une technique bien pratique pour - vérifier les effets d'un bouton retour sur vos formulaires. - </p> - <p> - Les méthodes sur les fenêtres méritent une petite explication. - Par défaut, une page avec des fenêtres est traitée comme toutes - les autres. Le contenu sera vérifié à travers l'ensemble de - la "frameset", par conséquent un lien fonctionnera, - peu importe la fenêtre qui contient la balise ancre. - Vous pouvez outrepassé ce comportement en exigeant - le focus sur une unique fenêtre. Si vous réalisez cela, - toutes les recherches et toutes les actions se limiteront - à cette unique fenêtre, y compris les demandes d'authentification. - Si un lien ou un bouton n'est pas dans la fenêtre en focus alors - il ne peut pas être cliqué. - </p> - <p> - Tester la navigation sur des pages fixes ne vous alerte que - quand vous avez cassé un script entier. - Pour des pages fortement dynamiques, - un forum de discussion par exemple, - ça peut être crucial pour vérifier l'état de l'application. - Pour la plupart des applications cependant, - la logique vraiment délicate se situe dans la gestion - des formulaires et des sessions. - Heureusement SimpleTest aussi inclut - <a href="form_testing_documentation.html"> - des outils pour tester des formulaires web</a>. - </p> - - <h2> -<a class="target" name="requete"></a>Modifier la requête</h2> - <p> - Bien que SimpleTest n'ait pas comme objectif - de contrôler des erreurs réseau, il contient quand même - des méthodes pour modifier et déboguer les requêtes qu'il lance. - Voici une autre liste de méthode... - <table><tbody> - <tr> -<td><span class="new_code">getTransportError()</span></td> -<td>La dernière erreur de socket</td> -</tr> - <tr> -<td><span class="new_code">getUrl()</span></td> -<td>La localisation courante</td> -</tr> - <tr> -<td><span class="new_code">showRequest()</span></td> -<td>Déverse la requête sortante</td> -</tr> - <tr> -<td><span class="new_code">showHeaders()</span></td> -<td>Déverse les entêtes d'entrée</td> -</tr> - <tr> -<td><span class="new_code">showSource()</span></td> -<td>Déverse le contenu brut de la page HTML</td> -</tr> - <tr> -<td><span class="new_code">ignoreFrames()</span></td> -<td>Ne recharge pas les framesets</td> -</tr> - <tr> -<td><span class="new_code">setCookie($name, $value)</span></td> -<td>Initie un cookie à partir de maintenant</td> -</tr> - <tr> -<td><span class="new_code">addHeader($header)</span></td> -<td>Ajoute toujours cette entête à la requête</td> -</tr> - <tr> -<td><span class="new_code">setMaximumRedirects($max)</span></td> -<td>S'arrête après autant de redirections</td> -</tr> - <tr> -<td><span class="new_code">setConnectionTimeout($timeout)</span></td> -<td>Termine la connexion après autant de temps entre les bytes</td> -</tr> - <tr> -<td><span class="new_code">useProxy($proxy, $name, $password)</span></td> -<td>Effectue les requêtes à travers ce proxy d'URL</td> -</tr> - </tbody></table> - </p> - - </div> - References and related information... - <ul> -<li> - La page du projet SimpleTest sur - <a href="http://sourceforge.net/projects/simpletest/">SourceForge</a>. - </li> -<li> - La page de téléchargement de SimpleTest sur - <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>. - </li> -<li> - <a href="http://simpletest.org/api/">L'API du développeur pour SimpleTest</a> - donne tous les détails sur les classes et les assertions disponibles. - </li> -</ul> -<div class="menu_back"><div class="menu"> -<a href="index.html">SimpleTest</a> - | - <a href="overview.html">Overview</a> - | - <a href="unit_test_documentation.html">Unit tester</a> - | - <a href="group_test_documentation.html">Group tests</a> - | - <a href="mock_objects_documentation.html">Mock objects</a> - | - <a href="partial_mocks_documentation.html">Partial mocks</a> - | - <a href="reporter_documentation.html">Reporting</a> - | - <a href="expectation_documentation.html">Expectations</a> - | - <a href="web_tester_documentation.html">Web tester</a> - | - <a href="form_testing_documentation.html">Testing forms</a> - | - <a href="authentication_documentation.html">Authentication</a> - | - <a href="browser_documentation.html">Scriptable browser</a> -</div></div> -<div class="copyright"> - Copyright<br>Marcus Baker 2006 - </div> -</body> -</html> diff --git a/3rdparty/simpletest/dumper.php b/3rdparty/simpletest/dumper.php deleted file mode 100755 index 339923c224f3c475dfc4b3e4cd5fac262d4fae93..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/dumper.php +++ /dev/null @@ -1,407 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: dumper.php 1909 2009-07-29 15:58:11Z dgheath $ - */ -/** - * does type matter - */ -if (! defined('TYPE_MATTERS')) { - define('TYPE_MATTERS', true); -} - -/** - * Displays variables as text and does diffs. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleDumper { - - /** - * Renders a variable in a shorter form than print_r(). - * @param mixed $value Variable to render as a string. - * @return string Human readable string form. - * @access public - */ - function describeValue($value) { - $type = $this->getType($value); - switch($type) { - case "Null": - return "NULL"; - case "Boolean": - return "Boolean: " . ($value ? "true" : "false"); - case "Array": - return "Array: " . count($value) . " items"; - case "Object": - return "Object: of " . get_class($value); - case "String": - return "String: " . $this->clipString($value, 200); - default: - return "$type: $value"; - } - return "Unknown"; - } - - /** - * Gets the string representation of a type. - * @param mixed $value Variable to check against. - * @return string Type. - * @access public - */ - function getType($value) { - if (! isset($value)) { - return "Null"; - } elseif (is_bool($value)) { - return "Boolean"; - } elseif (is_string($value)) { - return "String"; - } elseif (is_integer($value)) { - return "Integer"; - } elseif (is_float($value)) { - return "Float"; - } elseif (is_array($value)) { - return "Array"; - } elseif (is_resource($value)) { - return "Resource"; - } elseif (is_object($value)) { - return "Object"; - } - return "Unknown"; - } - - /** - * Creates a human readable description of the - * difference between two variables. Uses a - * dynamic call. - * @param mixed $first First variable. - * @param mixed $second Value to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Description of difference. - * @access public - */ - function describeDifference($first, $second, $identical = false) { - if ($identical) { - if (! $this->isTypeMatch($first, $second)) { - return "with type mismatch as [" . $this->describeValue($first) . - "] does not match [" . $this->describeValue($second) . "]"; - } - } - $type = $this->getType($first); - if ($type == "Unknown") { - return "with unknown type"; - } - $method = 'describe' . $type . 'Difference'; - return $this->$method($first, $second, $identical); - } - - /** - * Tests to see if types match. - * @param mixed $first First variable. - * @param mixed $second Value to compare with. - * @return boolean True if matches. - * @access private - */ - protected function isTypeMatch($first, $second) { - return ($this->getType($first) == $this->getType($second)); - } - - /** - * Clips a string to a maximum length. - * @param string $value String to truncate. - * @param integer $size Minimum string size to show. - * @param integer $position Centre of string section. - * @return string Shortened version. - * @access public - */ - function clipString($value, $size, $position = 0) { - $length = strlen($value); - if ($length <= $size) { - return $value; - } - $position = min($position, $length); - $start = ($size/2 > $position ? 0 : $position - $size/2); - if ($start + $size > $length) { - $start = $length - $size; - } - $value = substr($value, $start, $size); - return ($start > 0 ? "..." : "") . $value . ($start + $size < $length ? "..." : ""); - } - - /** - * Creates a human readable description of the - * difference between two variables. The minimal - * version. - * @param null $first First value. - * @param mixed $second Value to compare with. - * @return string Human readable description. - * @access private - */ - protected function describeGenericDifference($first, $second) { - return "as [" . $this->describeValue($first) . - "] does not match [" . - $this->describeValue($second) . "]"; - } - - /** - * Creates a human readable description of the - * difference between a null and another variable. - * @param null $first First null. - * @param mixed $second Null to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - protected function describeNullDifference($first, $second, $identical) { - return $this->describeGenericDifference($first, $second); - } - - /** - * Creates a human readable description of the - * difference between a boolean and another variable. - * @param boolean $first First boolean. - * @param mixed $second Boolean to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - protected function describeBooleanDifference($first, $second, $identical) { - return $this->describeGenericDifference($first, $second); - } - - /** - * Creates a human readable description of the - * difference between a string and another variable. - * @param string $first First string. - * @param mixed $second String to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - protected function describeStringDifference($first, $second, $identical) { - if (is_object($second) || is_array($second)) { - return $this->describeGenericDifference($first, $second); - } - $position = $this->stringDiffersAt($first, $second); - $message = "at character $position"; - $message .= " with [" . - $this->clipString($first, 200, $position) . "] and [" . - $this->clipString($second, 200, $position) . "]"; - return $message; - } - - /** - * Creates a human readable description of the - * difference between an integer and another variable. - * @param integer $first First number. - * @param mixed $second Number to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - protected function describeIntegerDifference($first, $second, $identical) { - if (is_object($second) || is_array($second)) { - return $this->describeGenericDifference($first, $second); - } - return "because [" . $this->describeValue($first) . - "] differs from [" . - $this->describeValue($second) . "] by " . - abs($first - $second); - } - - /** - * Creates a human readable description of the - * difference between two floating point numbers. - * @param float $first First float. - * @param mixed $second Float to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - protected function describeFloatDifference($first, $second, $identical) { - if (is_object($second) || is_array($second)) { - return $this->describeGenericDifference($first, $second); - } - return "because [" . $this->describeValue($first) . - "] differs from [" . - $this->describeValue($second) . "] by " . - abs($first - $second); - } - - /** - * Creates a human readable description of the - * difference between two arrays. - * @param array $first First array. - * @param mixed $second Array to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - protected function describeArrayDifference($first, $second, $identical) { - if (! is_array($second)) { - return $this->describeGenericDifference($first, $second); - } - if (! $this->isMatchingKeys($first, $second, $identical)) { - return "as key list [" . - implode(", ", array_keys($first)) . "] does not match key list [" . - implode(", ", array_keys($second)) . "]"; - } - foreach (array_keys($first) as $key) { - if ($identical && ($first[$key] === $second[$key])) { - continue; - } - if (! $identical && ($first[$key] == $second[$key])) { - continue; - } - return "with member [$key] " . $this->describeDifference( - $first[$key], - $second[$key], - $identical); - } - return ""; - } - - /** - * Compares two arrays to see if their key lists match. - * For an identical match, the ordering and types of the keys - * is significant. - * @param array $first First array. - * @param array $second Array to compare with. - * @param boolean $identical If true then type anomolies count. - * @return boolean True if matching. - * @access private - */ - protected function isMatchingKeys($first, $second, $identical) { - $first_keys = array_keys($first); - $second_keys = array_keys($second); - if ($identical) { - return ($first_keys === $second_keys); - } - sort($first_keys); - sort($second_keys); - return ($first_keys == $second_keys); - } - - /** - * Creates a human readable description of the - * difference between a resource and another variable. - * @param resource $first First resource. - * @param mixed $second Resource to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - * @access private - */ - protected function describeResourceDifference($first, $second, $identical) { - return $this->describeGenericDifference($first, $second); - } - - /** - * Creates a human readable description of the - * difference between two objects. - * @param object $first First object. - * @param mixed $second Object to compare with. - * @param boolean $identical If true then type anomolies count. - * @return string Human readable description. - */ - protected function describeObjectDifference($first, $second, $identical) { - if (! is_object($second)) { - return $this->describeGenericDifference($first, $second); - } - return $this->describeArrayDifference( - $this->getMembers($first), - $this->getMembers($second), - $identical); - } - - /** - * Get all members of an object including private and protected ones. - * A safer form of casting to an array. - * @param object $object Object to list members of, - * including private ones. - * @return array Names and values in the object. - */ - protected function getMembers($object) { - $reflection = new ReflectionObject($object); - $members = array(); - foreach ($reflection->getProperties() as $property) { - if (method_exists($property, 'setAccessible')) { - $property->setAccessible(true); - } - try { - $members[$property->getName()] = $property->getValue($object); - } catch (ReflectionException $e) { - $members[$property->getName()] = - $this->getPrivatePropertyNoMatterWhat($property->getName(), $object); - } - } - return $members; - } - - /** - * Extracts a private member's value when reflection won't play ball. - * @param string $name Property name. - * @param object $object Object to read. - * @return mixed Value of property. - */ - private function getPrivatePropertyNoMatterWhat($name, $object) { - foreach ((array)$object as $mangled_name => $value) { - if ($this->unmangle($mangled_name) == $name) { - return $value; - } - } - } - - /** - * Removes crud from property name after it's been converted - * to an array. - * @param string $mangled Name from array cast. - * @return string Cleaned up name. - */ - function unmangle($mangled) { - $parts = preg_split('/[^a-zA-Z0-9_\x7f-\xff]+/', $mangled); - return array_pop($parts); - } - - /** - * Find the first character position that differs - * in two strings by binary chop. - * @param string $first First string. - * @param string $second String to compare with. - * @return integer Position of first differing - * character. - * @access private - */ - protected function stringDiffersAt($first, $second) { - if (! $first || ! $second) { - return 0; - } - if (strlen($first) < strlen($second)) { - list($first, $second) = array($second, $first); - } - $position = 0; - $step = strlen($first); - while ($step > 1) { - $step = (integer)(($step + 1) / 2); - if (strncmp($first, $second, $position + $step) == 0) { - $position += $step; - } - } - return $position; - } - - /** - * Sends a formatted dump of a variable to a string. - * @param mixed $variable Variable to display. - * @return string Output from print_r(). - * @access public - */ - function dump($variable) { - ob_start(); - print_r($variable); - $formatted = ob_get_contents(); - ob_end_clean(); - return $formatted; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/eclipse.php b/3rdparty/simpletest/eclipse.php deleted file mode 100644 index 20bd4530bb68f990242f1a23c24f01adc987e765..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/eclipse.php +++ /dev/null @@ -1,307 +0,0 @@ -<?php -/** - * base include file for eclipse plugin - * @package SimpleTest - * @subpackage Eclipse - * @version $Id: eclipse.php 2011 2011-04-29 08:22:48Z pp11 $ - */ -/**#@+ - * simpletest include files - */ -include_once 'unit_tester.php'; -include_once 'test_case.php'; -include_once 'invoker.php'; -include_once 'socket.php'; -include_once 'mock_objects.php'; -/**#@-*/ - -/** - * base reported class for eclipse plugin - * @package SimpleTest - * @subpackage Eclipse - */ -class EclipseReporter extends SimpleScorer { - - /** - * Reporter to be run inside of Eclipse interface. - * @param object $listener Eclipse listener (?). - * @param boolean $cc Whether to include test coverage. - */ - function __construct(&$listener, $cc=false){ - $this->listener = &$listener; - $this->SimpleScorer(); - $this->case = ""; - $this->group = ""; - $this->method = ""; - $this->cc = $cc; - $this->error = false; - $this->fail = false; - } - - /** - * Means to display human readable object comparisons. - * @return SimpleDumper Visual comparer. - */ - function getDumper() { - return new SimpleDumper(); - } - - /** - * Localhost connection from Eclipse. - * @param integer $port Port to connect to Eclipse. - * @param string $host Normally localhost. - * @return SimpleSocket Connection to Eclipse. - */ - function &createListener($port, $host="127.0.0.1"){ - $tmplistener = &new SimpleSocket($host, $port, 5); - return $tmplistener; - } - - /** - * Wraps the test in an output buffer. - * @param SimpleInvoker $invoker Current test runner. - * @return EclipseInvoker Decorator with output buffering. - * @access public - */ - function &createInvoker(&$invoker){ - $eclinvoker = &new EclipseInvoker($invoker, $this->listener); - return $eclinvoker; - } - - /** - * C style escaping. - * @param string $raw String with backslashes, quotes and whitespace. - * @return string Replaced with C backslashed tokens. - */ - function escapeVal($raw){ - $needle = array("\\","\"","/","\b","\f","\n","\r","\t"); - $replace = array('\\\\','\"','\/','\b','\f','\n','\r','\t'); - return str_replace($needle, $replace, $raw); - } - - /** - * Stash the first passing item. Clicking the test - * item goes to first pass. - * @param string $message Test message, but we only wnat the first. - * @access public - */ - function paintPass($message){ - if (! $this->pass){ - $this->message = $this->escapeVal($message); - } - $this->pass = true; - } - - /** - * Stash the first failing item. Clicking the test - * item goes to first fail. - * @param string $message Test message, but we only wnat the first. - * @access public - */ - function paintFail($message){ - //only get the first failure or error - if (! $this->fail && ! $this->error){ - $this->fail = true; - $this->message = $this->escapeVal($message); - $this->listener->write('{status:"fail",message:"'.$this->message.'",group:"'.$this->group.'",case:"'.$this->case.'",method:"'.$this->method.'"}'); - } - } - - /** - * Stash the first error. Clicking the test - * item goes to first error. - * @param string $message Test message, but we only wnat the first. - * @access public - */ - function paintError($message){ - if (! $this->fail && ! $this->error){ - $this->error = true; - $this->message = $this->escapeVal($message); - $this->listener->write('{status:"error",message:"'.$this->message.'",group:"'.$this->group.'",case:"'.$this->case.'",method:"'.$this->method.'"}'); - } - } - - - /** - * Stash the first exception. Clicking the test - * item goes to first message. - * @param string $message Test message, but we only wnat the first. - * @access public - */ - function paintException($exception){ - if (! $this->fail && ! $this->error){ - $this->error = true; - $message = 'Unexpected exception of type[' . get_class($exception) . - '] with message [' . $exception->getMessage() . '] in [' . - $exception->getFile() .' line '. $exception->getLine() . ']'; - $this->message = $this->escapeVal($message); - $this->listener->write( - '{status:"error",message:"' . $this->message . '",group:"' . - $this->group . '",case:"' . $this->case . '",method:"' . $this->method - . '"}'); - } - } - - - /** - * We don't display any special header. - * @param string $test_name First test top level - * to start. - * @access public - */ - function paintHeader($test_name) { - } - - /** - * We don't display any special footer. - * @param string $test_name The top level test. - * @access public - */ - function paintFooter($test_name) { - } - - /** - * Paints nothing at the start of a test method, but stash - * the method name for later. - * @param string $test_name Name of test that is starting. - * @access public - */ - function paintMethodStart($method) { - $this->pass = false; - $this->fail = false; - $this->error = false; - $this->method = $this->escapeVal($method); - } - - /** - * Only send one message if the test passes, after that - * suppress the message. - * @param string $test_name Name of test that is ending. - * @access public - */ - function paintMethodEnd($method){ - if ($this->fail || $this->error || ! $this->pass){ - } else { - $this->listener->write( - '{status:"pass",message:"' . $this->message . '",group:"' . - $this->group . '",case:"' . $this->case . '",method:"' . - $this->method . '"}'); - } - } - - /** - * Stashes the test case name for the later failure message. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseStart($case){ - $this->case = $this->escapeVal($case); - } - - /** - * Drops the name. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseEnd($case){ - $this->case = ""; - } - - /** - * Stashes the name of the test suite. Starts test coverage - * if enabled. - * @param string $group Name of test or other label. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($group, $size){ - $this->group = $this->escapeVal($group); - if ($this->cc){ - if (extension_loaded('xdebug')){ - xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE); - } - } - } - - /** - * Paints coverage report if enabled. - * @param string $group Name of test or other label. - * @access public - */ - function paintGroupEnd($group){ - $this->group = ""; - $cc = ""; - if ($this->cc){ - if (extension_loaded('xdebug')){ - $arrfiles = xdebug_get_code_coverage(); - xdebug_stop_code_coverage(); - $thisdir = dirname(__FILE__); - $thisdirlen = strlen($thisdir); - foreach ($arrfiles as $index=>$file){ - if (substr($index, 0, $thisdirlen)===$thisdir){ - continue; - } - $lcnt = 0; - $ccnt = 0; - foreach ($file as $line){ - if ($line == -2){ - continue; - } - $lcnt++; - if ($line==1){ - $ccnt++; - } - } - if ($lcnt > 0){ - $cc .= round(($ccnt/$lcnt) * 100, 2) . '%'; - }else{ - $cc .= "0.00%"; - } - $cc.= "\t". $index . "\n"; - } - } - } - $this->listener->write('{status:"coverage",message:"' . - EclipseReporter::escapeVal($cc) . '"}'); - } -} - -/** - * Invoker decorator for Eclipse. Captures output until - * the end of the test. - * @package SimpleTest - * @subpackage Eclipse - */ -class EclipseInvoker extends SimpleInvokerDecorator{ - function __construct(&$invoker, &$listener) { - $this->listener = &$listener; - $this->SimpleInvokerDecorator($invoker); - } - - /** - * Starts output buffering. - * @param string $method Test method to call. - * @access public - */ - function before($method){ - ob_start(); - $this->invoker->before($method); - } - - /** - * Stops output buffering and send the captured output - * to the listener. - * @param string $method Test method to call. - * @access public - */ - function after($method) { - $this->invoker->after($method); - $output = ob_get_contents(); - ob_end_clean(); - if ($output !== ""){ - $result = $this->listener->write('{status:"info",message:"' . - EclipseReporter::escapeVal($output) . '"}'); - } - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/encoding.php b/3rdparty/simpletest/encoding.php deleted file mode 100644 index cadc84e7a3bbae39cca96a5cdf892f36eeac583c..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/encoding.php +++ /dev/null @@ -1,649 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage WebTester - * @version $Id: encoding.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/socket.php'); -/**#@-*/ - -/** - * Single post parameter. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleEncodedPair { - private $key; - private $value; - - /** - * Stashes the data for rendering later. - * @param string $key Form element name. - * @param string $value Data to send. - */ - function __construct($key, $value) { - $this->key = $key; - $this->value = $value; - } - - /** - * The pair as a single string. - * @return string Encoded pair. - * @access public - */ - function asRequest() { - return urlencode($this->key) . '=' . urlencode($this->value); - } - - /** - * The MIME part as a string. - * @return string MIME part encoding. - * @access public - */ - function asMime() { - $part = 'Content-Disposition: form-data; '; - $part .= "name=\"" . $this->key . "\"\r\n"; - $part .= "\r\n" . $this->value; - return $part; - } - - /** - * Is this the value we are looking for? - * @param string $key Identifier. - * @return boolean True if matched. - * @access public - */ - function isKey($key) { - return $key == $this->key; - } - - /** - * Is this the value we are looking for? - * @return string Identifier. - * @access public - */ - function getKey() { - return $this->key; - } - - /** - * Is this the value we are looking for? - * @return string Content. - * @access public - */ - function getValue() { - return $this->value; - } -} - -/** - * Single post parameter. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleAttachment { - private $key; - private $content; - private $filename; - - /** - * Stashes the data for rendering later. - * @param string $key Key to add value to. - * @param string $content Raw data. - * @param hash $filename Original filename. - */ - function __construct($key, $content, $filename) { - $this->key = $key; - $this->content = $content; - $this->filename = $filename; - } - - /** - * The pair as a single string. - * @return string Encoded pair. - * @access public - */ - function asRequest() { - return ''; - } - - /** - * The MIME part as a string. - * @return string MIME part encoding. - * @access public - */ - function asMime() { - $part = 'Content-Disposition: form-data; '; - $part .= 'name="' . $this->key . '"; '; - $part .= 'filename="' . $this->filename . '"'; - $part .= "\r\nContent-Type: " . $this->deduceMimeType(); - $part .= "\r\n\r\n" . $this->content; - return $part; - } - - /** - * Attempts to figure out the MIME type from the - * file extension and the content. - * @return string MIME type. - * @access private - */ - protected function deduceMimeType() { - if ($this->isOnlyAscii($this->content)) { - return 'text/plain'; - } - return 'application/octet-stream'; - } - - /** - * Tests each character is in the range 0-127. - * @param string $ascii String to test. - * @access private - */ - protected function isOnlyAscii($ascii) { - for ($i = 0, $length = strlen($ascii); $i < $length; $i++) { - if (ord($ascii[$i]) > 127) { - return false; - } - } - return true; - } - - /** - * Is this the value we are looking for? - * @param string $key Identifier. - * @return boolean True if matched. - * @access public - */ - function isKey($key) { - return $key == $this->key; - } - - /** - * Is this the value we are looking for? - * @return string Identifier. - * @access public - */ - function getKey() { - return $this->key; - } - - /** - * Is this the value we are looking for? - * @return string Content. - * @access public - */ - function getValue() { - return $this->filename; - } -} - -/** - * Bundle of GET/POST parameters. Can include - * repeated parameters. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleEncoding { - private $request; - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function __construct($query = false) { - if (! $query) { - $query = array(); - } - $this->clear(); - $this->merge($query); - } - - /** - * Empties the request of parameters. - * @access public - */ - function clear() { - $this->request = array(); - } - - /** - * Adds a parameter to the query. - * @param string $key Key to add value to. - * @param string/array $value New data. - * @access public - */ - function add($key, $value) { - if ($value === false) { - return; - } - if (is_array($value)) { - foreach ($value as $item) { - $this->addPair($key, $item); - } - } else { - $this->addPair($key, $value); - } - } - - /** - * Adds a new value into the request. - * @param string $key Key to add value to. - * @param string/array $value New data. - * @access private - */ - protected function addPair($key, $value) { - $this->request[] = new SimpleEncodedPair($key, $value); - } - - /** - * Adds a MIME part to the query. Does nothing for a - * form encoded packet. - * @param string $key Key to add value to. - * @param string $content Raw data. - * @param hash $filename Original filename. - * @access public - */ - function attach($key, $content, $filename) { - $this->request[] = new SimpleAttachment($key, $content, $filename); - } - - /** - * Adds a set of parameters to this query. - * @param array/SimpleQueryString $query Multiple values are - * as lists on a single key. - * @access public - */ - function merge($query) { - if (is_object($query)) { - $this->request = array_merge($this->request, $query->getAll()); - } elseif (is_array($query)) { - foreach ($query as $key => $value) { - $this->add($key, $value); - } - } - } - - /** - * Accessor for single value. - * @return string/array False if missing, string - * if present and array if - * multiple entries. - * @access public - */ - function getValue($key) { - $values = array(); - foreach ($this->request as $pair) { - if ($pair->isKey($key)) { - $values[] = $pair->getValue(); - } - } - if (count($values) == 0) { - return false; - } elseif (count($values) == 1) { - return $values[0]; - } else { - return $values; - } - } - - /** - * Accessor for listing of pairs. - * @return array All pair objects. - * @access public - */ - function getAll() { - return $this->request; - } - - /** - * Renders the query string as a URL encoded - * request part. - * @return string Part of URL. - * @access protected - */ - protected function encode() { - $statements = array(); - foreach ($this->request as $pair) { - if ($statement = $pair->asRequest()) { - $statements[] = $statement; - } - } - return implode('&', $statements); - } -} - -/** - * Bundle of GET parameters. Can include - * repeated parameters. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleGetEncoding extends SimpleEncoding { - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function __construct($query = false) { - parent::__construct($query); - } - - /** - * HTTP request method. - * @return string Always GET. - * @access public - */ - function getMethod() { - return 'GET'; - } - - /** - * Writes no extra headers. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeHeadersTo(&$socket) { - } - - /** - * No data is sent to the socket as the data is encoded into - * the URL. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeTo(&$socket) { - } - - /** - * Renders the query string as a URL encoded - * request part for attaching to a URL. - * @return string Part of URL. - * @access public - */ - function asUrlRequest() { - return $this->encode(); - } -} - -/** - * Bundle of URL parameters for a HEAD request. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHeadEncoding extends SimpleGetEncoding { - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function __construct($query = false) { - parent::__construct($query); - } - - /** - * HTTP request method. - * @return string Always HEAD. - * @access public - */ - function getMethod() { - return 'HEAD'; - } -} - -/** - * Bundle of URL parameters for a DELETE request. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleDeleteEncoding extends SimpleGetEncoding { - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function __construct($query = false) { - parent::__construct($query); - } - - /** - * HTTP request method. - * @return string Always DELETE. - * @access public - */ - function getMethod() { - return 'DELETE'; - } -} - -/** - * Bundles an entity-body for transporting - * a raw content payload with the request. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleEntityEncoding extends SimpleEncoding { - private $content_type; - private $body; - - function __construct($query = false, $content_type = false) { - $this->content_type = $content_type; - if (is_string($query)) { - $this->body = $query; - parent::__construct(); - } else { - parent::__construct($query); - } - } - - /** - * Returns the media type of the entity body - * @return string - * @access public - */ - function getContentType() { - if (!$this->content_type) { - return ($this->body) ? 'text/plain' : 'application/x-www-form-urlencoded'; - } - return $this->content_type; - } - - /** - * Dispatches the form headers down the socket. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeHeadersTo(&$socket) { - $socket->write("Content-Length: " . (integer)strlen($this->encode()) . "\r\n"); - $socket->write("Content-Type: " . $this->getContentType() . "\r\n"); - } - - /** - * Dispatches the form data down the socket. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeTo(&$socket) { - $socket->write($this->encode()); - } - - /** - * Renders the request body - * @return Encoded entity body - * @access protected - */ - protected function encode() { - return ($this->body) ? $this->body : parent::encode(); - } -} - -/** - * Bundle of POST parameters. Can include - * repeated parameters. - * @package SimpleTest - * @subpackage WebTester - */ -class SimplePostEncoding extends SimpleEntityEncoding { - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function __construct($query = false, $content_type = false) { - if (is_array($query) and $this->hasMoreThanOneLevel($query)) { - $query = $this->rewriteArrayWithMultipleLevels($query); - } - parent::__construct($query, $content_type); - } - - function hasMoreThanOneLevel($query) { - foreach ($query as $key => $value) { - if (is_array($value)) { - return true; - } - } - return false; - } - - function rewriteArrayWithMultipleLevels($query) { - $query_ = array(); - foreach ($query as $key => $value) { - if (is_array($value)) { - foreach ($value as $sub_key => $sub_value) { - $query_[$key."[".$sub_key."]"] = $sub_value; - } - } else { - $query_[$key] = $value; - } - } - if ($this->hasMoreThanOneLevel($query_)) { - $query_ = $this->rewriteArrayWithMultipleLevels($query_); - } - - return $query_; - } - - /** - * HTTP request method. - * @return string Always POST. - * @access public - */ - function getMethod() { - return 'POST'; - } - - /** - * Renders the query string as a URL encoded - * request part for attaching to a URL. - * @return string Part of URL. - * @access public - */ - function asUrlRequest() { - return ''; - } -} - -/** - * Encoded entity body for a PUT request. - * @package SimpleTest - * @subpackage WebTester - */ -class SimplePutEncoding extends SimpleEntityEncoding { - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function __construct($query = false, $content_type = false) { - parent::__construct($query, $content_type); - } - - /** - * HTTP request method. - * @return string Always PUT. - * @access public - */ - function getMethod() { - return 'PUT'; - } -} - -/** - * Bundle of POST parameters in the multipart - * format. Can include file uploads. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleMultipartEncoding extends SimplePostEncoding { - private $boundary; - - /** - * Starts empty. - * @param array $query Hash of parameters. - * Multiple values are - * as lists on a single key. - * @access public - */ - function __construct($query = false, $boundary = false) { - parent::__construct($query); - $this->boundary = ($boundary === false ? uniqid('st') : $boundary); - } - - /** - * Dispatches the form headers down the socket. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeHeadersTo(&$socket) { - $socket->write("Content-Length: " . (integer)strlen($this->encode()) . "\r\n"); - $socket->write("Content-Type: multipart/form-data; boundary=" . $this->boundary . "\r\n"); - } - - /** - * Dispatches the form data down the socket. - * @param SimpleSocket $socket Socket to write to. - * @access public - */ - function writeTo(&$socket) { - $socket->write($this->encode()); - } - - /** - * Renders the query string as a URL encoded - * request part. - * @return string Part of URL. - * @access public - */ - function encode() { - $stream = ''; - foreach ($this->getAll() as $pair) { - $stream .= "--" . $this->boundary . "\r\n"; - $stream .= $pair->asMime() . "\r\n"; - } - $stream .= "--" . $this->boundary . "--\r\n"; - return $stream; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/errors.php b/3rdparty/simpletest/errors.php deleted file mode 100644 index b3d0c2a07539135b1c2c41a6513976d0ccad38d9..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/errors.php +++ /dev/null @@ -1,267 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: errors.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/**#@+ - * Includes SimpleTest files. - */ -require_once dirname(__FILE__) . '/invoker.php'; -require_once dirname(__FILE__) . '/test_case.php'; -require_once dirname(__FILE__) . '/expectation.php'; -/**#@-*/ - -/** - * Extension that traps errors into an error queue. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleErrorTrappingInvoker extends SimpleInvokerDecorator { - - /** - * Stores the invoker to wrap. - * @param SimpleInvoker $invoker Test method runner. - */ - function __construct($invoker) { - parent::__construct($invoker); - } - - /** - * Invokes a test method and dispatches any - * untrapped errors. Called back from - * the visiting runner. - * @param string $method Test method to call. - * @access public - */ - function invoke($method) { - $queue = $this->createErrorQueue(); - set_error_handler('SimpleTestErrorHandler'); - parent::invoke($method); - restore_error_handler(); - $queue->tally(); - } - - /** - * Wires up the error queue for a single test. - * @return SimpleErrorQueue Queue connected to the test. - * @access private - */ - protected function createErrorQueue() { - $context = SimpleTest::getContext(); - $test = $this->getTestCase(); - $queue = $context->get('SimpleErrorQueue'); - $queue->setTestCase($test); - return $queue; - } -} - -/** - * Error queue used to record trapped - * errors. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleErrorQueue { - private $queue; - private $expectation_queue; - private $test; - private $using_expect_style = false; - - /** - * Starts with an empty queue. - */ - function __construct() { - $this->clear(); - } - - /** - * Discards the contents of the error queue. - * @access public - */ - function clear() { - $this->queue = array(); - $this->expectation_queue = array(); - } - - /** - * Sets the currently running test case. - * @param SimpleTestCase $test Test case to send messages to. - * @access public - */ - function setTestCase($test) { - $this->test = $test; - } - - /** - * Sets up an expectation of an error. If this is - * not fulfilled at the end of the test, a failure - * will occour. If the error does happen, then this - * will cancel it out and send a pass message. - * @param SimpleExpectation $expected Expected error match. - * @param string $message Message to display. - * @access public - */ - function expectError($expected, $message) { - array_push($this->expectation_queue, array($expected, $message)); - } - - /** - * Adds an error to the front of the queue. - * @param integer $severity PHP error code. - * @param string $content Text of error. - * @param string $filename File error occoured in. - * @param integer $line Line number of error. - * @access public - */ - function add($severity, $content, $filename, $line) { - $content = str_replace('%', '%%', $content); - $this->testLatestError($severity, $content, $filename, $line); - } - - /** - * Any errors still in the queue are sent to the test - * case. Any unfulfilled expectations trigger failures. - * @access public - */ - function tally() { - while (list($severity, $message, $file, $line) = $this->extract()) { - $severity = $this->getSeverityAsString($severity); - $this->test->error($severity, $message, $file, $line); - } - while (list($expected, $message) = $this->extractExpectation()) { - $this->test->assert($expected, false, "%s -> Expected error not caught"); - } - } - - /** - * Tests the error against the most recent expected - * error. - * @param integer $severity PHP error code. - * @param string $content Text of error. - * @param string $filename File error occoured in. - * @param integer $line Line number of error. - * @access private - */ - protected function testLatestError($severity, $content, $filename, $line) { - if ($expectation = $this->extractExpectation()) { - list($expected, $message) = $expectation; - $this->test->assert($expected, $content, sprintf( - $message, - "%s -> PHP error [$content] severity [" . - $this->getSeverityAsString($severity) . - "] in [$filename] line [$line]")); - } else { - $this->test->error($severity, $content, $filename, $line); - } - } - - /** - * Pulls the earliest error from the queue. - * @return mixed False if none, or a list of error - * information. Elements are: severity - * as the PHP error code, the error message, - * the file with the error, the line number - * and a list of PHP super global arrays. - * @access public - */ - function extract() { - if (count($this->queue)) { - return array_shift($this->queue); - } - return false; - } - - /** - * Pulls the earliest expectation from the queue. - * @return SimpleExpectation False if none. - * @access private - */ - protected function extractExpectation() { - if (count($this->expectation_queue)) { - return array_shift($this->expectation_queue); - } - return false; - } - - /** - * Converts an error code into it's string - * representation. - * @param $severity PHP integer error code. - * @return String version of error code. - * @access public - */ - static function getSeverityAsString($severity) { - static $map = array( - E_STRICT => 'E_STRICT', - E_ERROR => 'E_ERROR', - E_WARNING => 'E_WARNING', - E_PARSE => 'E_PARSE', - E_NOTICE => 'E_NOTICE', - E_CORE_ERROR => 'E_CORE_ERROR', - E_CORE_WARNING => 'E_CORE_WARNING', - E_COMPILE_ERROR => 'E_COMPILE_ERROR', - E_COMPILE_WARNING => 'E_COMPILE_WARNING', - E_USER_ERROR => 'E_USER_ERROR', - E_USER_WARNING => 'E_USER_WARNING', - E_USER_NOTICE => 'E_USER_NOTICE'); - if (defined('E_RECOVERABLE_ERROR')) { - $map[E_RECOVERABLE_ERROR] = 'E_RECOVERABLE_ERROR'; - } - if (defined('E_DEPRECATED')) { - $map[E_DEPRECATED] = 'E_DEPRECATED'; - } - return $map[$severity]; - } -} - -/** - * Error handler that simply stashes any errors into the global - * error queue. Simulates the existing behaviour with respect to - * logging errors, but this feature may be removed in future. - * @param $severity PHP error code. - * @param $message Text of error. - * @param $filename File error occoured in. - * @param $line Line number of error. - * @param $super_globals Hash of PHP super global arrays. - * @access public - */ -function SimpleTestErrorHandler($severity, $message, $filename = null, $line = null, $super_globals = null, $mask = null) { - $severity = $severity & error_reporting(); - if ($severity) { - restore_error_handler(); - if (IsNotCausedBySimpleTest($message) && IsNotTimeZoneNag($message)) { - if (ini_get('log_errors')) { - $label = SimpleErrorQueue::getSeverityAsString($severity); - error_log("$label: $message in $filename on line $line"); - } - $queue = SimpleTest::getContext()->get('SimpleErrorQueue'); - $queue->add($severity, $message, $filename, $line); - } - set_error_handler('SimpleTestErrorHandler'); - } - return true; -} - -/** - * Certain messages can be caused by the unit tester itself. - * These have to be filtered. - * @param string $message Message to filter. - * @return boolean True if genuine failure. - */ -function IsNotCausedBySimpleTest($message) { - return ! preg_match('/returned by reference/', $message); -} - -/** - * Certain messages caused by PHP are just noise. - * These have to be filtered. - * @param string $message Message to filter. - * @return boolean True if genuine failure. - */ -function IsNotTimeZoneNag($message) { - return ! preg_match('/not safe to rely .* timezone settings/', $message); -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/exceptions.php b/3rdparty/simpletest/exceptions.php deleted file mode 100755 index 2f469e93a45430348c5d5fd8b37cac4742a6cc33..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/exceptions.php +++ /dev/null @@ -1,226 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: exceptions.php 1882 2009-07-01 14:30:05Z lastcraft $ - */ - -/**#@+ - * Include required SimpleTest files - */ -require_once dirname(__FILE__) . '/invoker.php'; -require_once dirname(__FILE__) . '/expectation.php'; -/**#@-*/ - -/** - * Extension that traps exceptions and turns them into - * an error message. PHP5 only. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleExceptionTrappingInvoker extends SimpleInvokerDecorator { - - /** - * Stores the invoker to be wrapped. - * @param SimpleInvoker $invoker Test method runner. - */ - function __construct($invoker) { - parent::__construct($invoker); - } - - /** - * Invokes a test method whilst trapping expected - * exceptions. Any left over unthrown exceptions - * are then reported as failures. - * @param string $method Test method to call. - */ - function invoke($method) { - $trap = SimpleTest::getContext()->get('SimpleExceptionTrap'); - $trap->clear(); - try { - $has_thrown = false; - parent::invoke($method); - } catch (Exception $exception) { - $has_thrown = true; - if (! $trap->isExpected($this->getTestCase(), $exception)) { - $this->getTestCase()->exception($exception); - } - $trap->clear(); - } - if ($message = $trap->getOutstanding()) { - $this->getTestCase()->fail($message); - } - if ($has_thrown) { - try { - parent::getTestCase()->tearDown(); - } catch (Exception $e) { } - } - } -} - -/** - * Tests exceptions either by type or the exact - * exception. This could be improved to accept - * a pattern expectation to test the error - * message, but that will have to come later. - * @package SimpleTest - * @subpackage UnitTester - */ -class ExceptionExpectation extends SimpleExpectation { - private $expected; - - /** - * Sets up the conditions to test against. - * If the expected value is a string, then - * it will act as a test of the class name. - * An exception as the comparison will - * trigger an identical match. Writing this - * down now makes it look doubly dumb. I hope - * come up with a better scheme later. - * @param mixed $expected A class name or an actual - * exception to compare with. - * @param string $message Message to display. - */ - function __construct($expected, $message = '%s') { - $this->expected = $expected; - parent::__construct($message); - } - - /** - * Carry out the test. - * @param Exception $compare Value to check. - * @return boolean True if matched. - */ - function test($compare) { - if (is_string($this->expected)) { - return ($compare instanceof $this->expected); - } - if (get_class($compare) != get_class($this->expected)) { - return false; - } - return $compare->getMessage() == $this->expected->getMessage(); - } - - /** - * Create the message to display describing the test. - * @param Exception $compare Exception to match. - * @return string Final message. - */ - function testMessage($compare) { - if (is_string($this->expected)) { - return "Exception [" . $this->describeException($compare) . - "] should be type [" . $this->expected . "]"; - } - return "Exception [" . $this->describeException($compare) . - "] should match [" . - $this->describeException($this->expected) . "]"; - } - - /** - * Summary of an Exception object. - * @param Exception $compare Exception to describe. - * @return string Text description. - */ - protected function describeException($exception) { - return get_class($exception) . ": " . $exception->getMessage(); - } -} - -/** - * Stores expected exceptions for when they - * get thrown. Saves the irritating try...catch - * block. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleExceptionTrap { - private $expected; - private $ignored; - private $message; - - /** - * Clears down the queue ready for action. - */ - function __construct() { - $this->clear(); - } - - /** - * Sets up an expectation of an exception. - * This has the effect of intercepting an - * exception that matches. - * @param SimpleExpectation $expected Expected exception to match. - * @param string $message Message to display. - * @access public - */ - function expectException($expected = false, $message = '%s') { - $this->expected = $this->coerceToExpectation($expected); - $this->message = $message; - } - - /** - * Adds an exception to the ignore list. This is the list - * of exceptions that when thrown do not affect the test. - * @param SimpleExpectation $ignored Exception to skip. - * @access public - */ - function ignoreException($ignored) { - $this->ignored[] = $this->coerceToExpectation($ignored); - } - - /** - * Compares the expected exception with any - * in the queue. Issues a pass or fail and - * returns the state of the test. - * @param SimpleTestCase $test Test case to send messages to. - * @param Exception $exception Exception to compare. - * @return boolean False on no match. - */ - function isExpected($test, $exception) { - if ($this->expected) { - return $test->assert($this->expected, $exception, $this->message); - } - foreach ($this->ignored as $ignored) { - if ($ignored->test($exception)) { - return true; - } - } - return false; - } - - /** - * Turns an expected exception into a SimpleExpectation object. - * @param mixed $exception Exception, expectation or - * class name of exception. - * @return SimpleExpectation Expectation that will match the - * exception. - */ - private function coerceToExpectation($exception) { - if ($exception === false) { - return new AnythingExpectation(); - } - if (! SimpleExpectation::isExpectation($exception)) { - return new ExceptionExpectation($exception); - } - return $exception; - } - - /** - * Tests for any left over exception. - * @return string/false The failure message or false if none. - */ - function getOutstanding() { - return sprintf($this->message, 'Failed to trap exception'); - } - - /** - * Discards the contents of the error queue. - */ - function clear() { - $this->expected = false; - $this->message = false; - $this->ignored = array(); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/expectation.php b/3rdparty/simpletest/expectation.php deleted file mode 100755 index a480a366c5c592e5797a6a0199ce8061da61e433..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/expectation.php +++ /dev/null @@ -1,984 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: expectation.php 2009 2011-04-28 08:57:25Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/dumper.php'); -require_once(dirname(__FILE__) . '/compatibility.php'); -/**#@-*/ - -/** - * Assertion that can display failure information. - * Also includes various helper methods. - * @package SimpleTest - * @subpackage UnitTester - * @abstract - */ -class SimpleExpectation { - protected $dumper = false; - private $message; - - /** - * Creates a dumper for displaying values and sets - * the test message. - * @param string $message Customised message on failure. - */ - function __construct($message = '%s') { - $this->message = $message; - } - - /** - * Tests the expectation. True if correct. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - * @abstract - */ - function test($compare) { - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - * @abstract - */ - function testMessage($compare) { - } - - /** - * Overlays the generated message onto the stored user - * message. An additional message can be interjected. - * @param mixed $compare Comparison value. - * @param SimpleDumper $dumper For formatting the results. - * @return string Description of success - * or failure. - * @access public - */ - function overlayMessage($compare, $dumper) { - $this->dumper = $dumper; - return sprintf($this->message, $this->testMessage($compare)); - } - - /** - * Accessor for the dumper. - * @return SimpleDumper Current value dumper. - * @access protected - */ - protected function getDumper() { - if (! $this->dumper) { - $dumper = new SimpleDumper(); - return $dumper; - } - return $this->dumper; - } - - /** - * Test to see if a value is an expectation object. - * A useful utility method. - * @param mixed $expectation Hopefully an Expectation - * class. - * @return boolean True if descended from - * this class. - * @access public - */ - static function isExpectation($expectation) { - return is_object($expectation) && - SimpleTestCompatibility::isA($expectation, 'SimpleExpectation'); - } -} - -/** - * A wildcard expectation always matches. - * @package SimpleTest - * @subpackage MockObjects - */ -class AnythingExpectation extends SimpleExpectation { - - /** - * Tests the expectation. Always true. - * @param mixed $compare Ignored. - * @return boolean True. - * @access public - */ - function test($compare) { - return true; - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = $this->getDumper(); - return 'Anything always matches [' . $dumper->describeValue($compare) . ']'; - } -} - -/** - * An expectation that never matches. - * @package SimpleTest - * @subpackage MockObjects - */ -class FailedExpectation extends SimpleExpectation { - - /** - * Tests the expectation. Always false. - * @param mixed $compare Ignored. - * @return boolean True. - * @access public - */ - function test($compare) { - return false; - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of failure. - * @access public - */ - function testMessage($compare) { - $dumper = $this->getDumper(); - return 'Failed expectation never matches [' . $dumper->describeValue($compare) . ']'; - } -} - -/** - * An expectation that passes on boolean true. - * @package SimpleTest - * @subpackage MockObjects - */ -class TrueExpectation extends SimpleExpectation { - - /** - * Tests the expectation. - * @param mixed $compare Should be true. - * @return boolean True on match. - * @access public - */ - function test($compare) { - return (boolean)$compare; - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = $this->getDumper(); - return 'Expected true, got [' . $dumper->describeValue($compare) . ']'; - } -} - -/** - * An expectation that passes on boolean false. - * @package SimpleTest - * @subpackage MockObjects - */ -class FalseExpectation extends SimpleExpectation { - - /** - * Tests the expectation. - * @param mixed $compare Should be false. - * @return boolean True on match. - * @access public - */ - function test($compare) { - return ! (boolean)$compare; - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = $this->getDumper(); - return 'Expected false, got [' . $dumper->describeValue($compare) . ']'; - } -} - -/** - * Test for equality. - * @package SimpleTest - * @subpackage UnitTester - */ -class EqualExpectation extends SimpleExpectation { - private $value; - - /** - * Sets the value to compare against. - * @param mixed $value Test value to match. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($value, $message = '%s') { - parent::__construct($message); - $this->value = $value; - } - - /** - * Tests the expectation. True if it matches the - * held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return (($this->value == $compare) && ($compare == $this->value)); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - return "Equal expectation [" . $this->dumper->describeValue($this->value) . "]"; - } else { - return "Equal expectation fails " . - $this->dumper->describeDifference($this->value, $compare); - } - } - - /** - * Accessor for comparison value. - * @return mixed Held value to compare with. - * @access protected - */ - protected function getValue() { - return $this->value; - } -} - -/** - * Test for inequality. - * @package SimpleTest - * @subpackage UnitTester - */ -class NotEqualExpectation extends EqualExpectation { - - /** - * Sets the value to compare against. - * @param mixed $value Test value to match. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($value, $message = '%s') { - parent::__construct($value, $message); - } - - /** - * Tests the expectation. True if it differs from the - * held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = $this->getDumper(); - if ($this->test($compare)) { - return "Not equal expectation passes " . - $dumper->describeDifference($this->getValue(), $compare); - } else { - return "Not equal expectation fails [" . - $dumper->describeValue($this->getValue()) . - "] matches"; - } - } -} - -/** - * Test for being within a range. - * @package SimpleTest - * @subpackage UnitTester - */ -class WithinMarginExpectation extends SimpleExpectation { - private $upper; - private $lower; - - /** - * Sets the value to compare against and the fuzziness of - * the match. Used for comparing floating point values. - * @param mixed $value Test value to match. - * @param mixed $margin Fuzziness of match. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($value, $margin, $message = '%s') { - parent::__construct($message); - $this->upper = $value + $margin; - $this->lower = $value - $margin; - } - - /** - * Tests the expectation. True if it matches the - * held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return (($compare <= $this->upper) && ($compare >= $this->lower)); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - return $this->withinMessage($compare); - } else { - return $this->outsideMessage($compare); - } - } - - /** - * Creates a the message for being within the range. - * @param mixed $compare Value being tested. - * @access private - */ - protected function withinMessage($compare) { - return "Within expectation [" . $this->dumper->describeValue($this->lower) . "] and [" . - $this->dumper->describeValue($this->upper) . "]"; - } - - /** - * Creates a the message for being within the range. - * @param mixed $compare Value being tested. - * @access private - */ - protected function outsideMessage($compare) { - if ($compare > $this->upper) { - return "Outside expectation " . - $this->dumper->describeDifference($compare, $this->upper); - } else { - return "Outside expectation " . - $this->dumper->describeDifference($compare, $this->lower); - } - } -} - -/** - * Test for being outside of a range. - * @package SimpleTest - * @subpackage UnitTester - */ -class OutsideMarginExpectation extends WithinMarginExpectation { - - /** - * Sets the value to compare against and the fuzziness of - * the match. Used for comparing floating point values. - * @param mixed $value Test value to not match. - * @param mixed $margin Fuzziness of match. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($value, $margin, $message = '%s') { - parent::__construct($value, $margin, $message); - } - - /** - * Tests the expectation. True if it matches the - * held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if (! $this->test($compare)) { - return $this->withinMessage($compare); - } else { - return $this->outsideMessage($compare); - } - } -} - -/** - * Test for reference. - * @package SimpleTest - * @subpackage UnitTester - */ -class ReferenceExpectation { - private $value; - - /** - * Sets the reference value to compare against. - * @param mixed $value Test reference to match. - * @param string $message Customised message on failure. - * @access public - */ - function __construct(&$value, $message = '%s') { - $this->message = $message; - $this->value = &$value; - } - - /** - * Tests the expectation. True if it exactly - * references the held value. - * @param mixed $compare Comparison reference. - * @return boolean True if correct. - * @access public - */ - function test(&$compare) { - return SimpleTestCompatibility::isReference($this->value, $compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - return "Reference expectation [" . $this->dumper->describeValue($this->value) . "]"; - } else { - return "Reference expectation fails " . - $this->dumper->describeDifference($this->value, $compare); - } - } - - /** - * Overlays the generated message onto the stored user - * message. An additional message can be interjected. - * @param mixed $compare Comparison value. - * @param SimpleDumper $dumper For formatting the results. - * @return string Description of success - * or failure. - * @access public - */ - function overlayMessage($compare, $dumper) { - $this->dumper = $dumper; - return sprintf($this->message, $this->testMessage($compare)); - } - - /** - * Accessor for the dumper. - * @return SimpleDumper Current value dumper. - * @access protected - */ - protected function getDumper() { - if (! $this->dumper) { - $dumper = new SimpleDumper(); - return $dumper; - } - return $this->dumper; - } -} - -/** - * Test for identity. - * @package SimpleTest - * @subpackage UnitTester - */ -class IdenticalExpectation extends EqualExpectation { - - /** - * Sets the value to compare against. - * @param mixed $value Test value to match. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($value, $message = '%s') { - parent::__construct($value, $message); - } - - /** - * Tests the expectation. True if it exactly - * matches the held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return SimpleTestCompatibility::isIdentical($this->getValue(), $compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = $this->getDumper(); - if ($this->test($compare)) { - return "Identical expectation [" . $dumper->describeValue($this->getValue()) . "]"; - } else { - return "Identical expectation [" . $dumper->describeValue($this->getValue()) . - "] fails with [" . - $dumper->describeValue($compare) . "] " . - $dumper->describeDifference($this->getValue(), $compare, TYPE_MATTERS); - } - } -} - -/** - * Test for non-identity. - * @package SimpleTest - * @subpackage UnitTester - */ -class NotIdenticalExpectation extends IdenticalExpectation { - - /** - * Sets the value to compare against. - * @param mixed $value Test value to match. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($value, $message = '%s') { - parent::__construct($value, $message); - } - - /** - * Tests the expectation. True if it differs from the - * held value. - * @param mixed $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = $this->getDumper(); - if ($this->test($compare)) { - return "Not identical expectation passes " . - $dumper->describeDifference($this->getValue(), $compare, TYPE_MATTERS); - } else { - return "Not identical expectation [" . $dumper->describeValue($this->getValue()) . "] matches"; - } - } -} - -/** - * Test for a pattern using Perl regex rules. - * @package SimpleTest - * @subpackage UnitTester - */ -class PatternExpectation extends SimpleExpectation { - private $pattern; - - /** - * Sets the value to compare against. - * @param string $pattern Pattern to search for. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($pattern, $message = '%s') { - parent::__construct($message); - $this->pattern = $pattern; - } - - /** - * Accessor for the pattern. - * @return string Perl regex as string. - * @access protected - */ - protected function getPattern() { - return $this->pattern; - } - - /** - * Tests the expectation. True if the Perl regex - * matches the comparison value. - * @param string $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return (boolean)preg_match($this->getPattern(), $compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - return $this->describePatternMatch($this->getPattern(), $compare); - } else { - $dumper = $this->getDumper(); - return "Pattern [" . $this->getPattern() . - "] not detected in [" . - $dumper->describeValue($compare) . "]"; - } - } - - /** - * Describes a pattern match including the string - * found and it's position. - * @param string $pattern Regex to match against. - * @param string $subject Subject to search. - * @access protected - */ - protected function describePatternMatch($pattern, $subject) { - preg_match($pattern, $subject, $matches); - $position = strpos($subject, $matches[0]); - $dumper = $this->getDumper(); - return "Pattern [$pattern] detected at character [$position] in [" . - $dumper->describeValue($subject) . "] as [" . - $matches[0] . "] in region [" . - $dumper->clipString($subject, 100, $position) . "]"; - } -} - -/** - * Fail if a pattern is detected within the - * comparison. - * @package SimpleTest - * @subpackage UnitTester - */ -class NoPatternExpectation extends PatternExpectation { - - /** - * Sets the reject pattern - * @param string $pattern Pattern to search for. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($pattern, $message = '%s') { - parent::__construct($pattern, $message); - } - - /** - * Tests the expectation. False if the Perl regex - * matches the comparison value. - * @param string $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param string $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - $dumper = $this->getDumper(); - return "Pattern [" . $this->getPattern() . - "] not detected in [" . - $dumper->describeValue($compare) . "]"; - } else { - return $this->describePatternMatch($this->getPattern(), $compare); - } - } -} - -/** - * Tests either type or class name if it's an object. - * @package SimpleTest - * @subpackage UnitTester - */ -class IsAExpectation extends SimpleExpectation { - private $type; - - /** - * Sets the type to compare with. - * @param string $type Type or class name. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($type, $message = '%s') { - parent::__construct($message); - $this->type = $type; - } - - /** - * Accessor for type to check against. - * @return string Type or class name. - * @access protected - */ - protected function getType() { - return $this->type; - } - - /** - * Tests the expectation. True if the type or - * class matches the string value. - * @param string $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - if (is_object($compare)) { - return SimpleTestCompatibility::isA($compare, $this->type); - } else { - $function = 'is_'.$this->canonicalType($this->type); - if (is_callable($function)) { - return $function($compare); - } - return false; - } - } - - /** - * Coerces type name into a is_*() match. - * @param string $type User type. - * @return string Simpler type. - * @access private - */ - protected function canonicalType($type) { - $type = strtolower($type); - $map = array('boolean' => 'bool'); - if (isset($map[$type])) { - $type = $map[$type]; - } - return $type; - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = $this->getDumper(); - return "Value [" . $dumper->describeValue($compare) . - "] should be type [" . $this->type . "]"; - } -} - -/** - * Tests either type or class name if it's an object. - * Will succeed if the type does not match. - * @package SimpleTest - * @subpackage UnitTester - */ -class NotAExpectation extends IsAExpectation { - private $type; - - /** - * Sets the type to compare with. - * @param string $type Type or class name. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($type, $message = '%s') { - parent::__construct($type, $message); - } - - /** - * Tests the expectation. False if the type or - * class matches the string value. - * @param string $compare Comparison value. - * @return boolean True if different. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = $this->getDumper(); - return "Value [" . $dumper->describeValue($compare) . - "] should not be type [" . $this->getType() . "]"; - } -} - -/** - * Tests for existance of a method in an object - * @package SimpleTest - * @subpackage UnitTester - */ -class MethodExistsExpectation extends SimpleExpectation { - private $method; - - /** - * Sets the value to compare against. - * @param string $method Method to check. - * @param string $message Customised message on failure. - * @return void - */ - function __construct($method, $message = '%s') { - parent::__construct($message); - $this->method = &$method; - } - - /** - * Tests the expectation. True if the method exists in the test object. - * @param string $compare Comparison method name. - * @return boolean True if correct. - */ - function test($compare) { - return (boolean)(is_object($compare) && method_exists($compare, $this->method)); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - */ - function testMessage($compare) { - $dumper = $this->getDumper(); - if (! is_object($compare)) { - return 'No method on non-object [' . $dumper->describeValue($compare) . ']'; - } - $method = $this->method; - return "Object [" . $dumper->describeValue($compare) . - "] should contain method [$method]"; - } -} - -/** - * Compares an object member's value even if private. - * @package SimpleTest - * @subpackage UnitTester - */ -class MemberExpectation extends IdenticalExpectation { - private $name; - - /** - * Sets the value to compare against. - * @param string $method Method to check. - * @param string $message Customised message on failure. - * @return void - */ - function __construct($name, $expected) { - $this->name = $name; - parent::__construct($expected); - } - - /** - * Tests the expectation. True if the property value is identical. - * @param object $actual Comparison object. - * @return boolean True if identical. - */ - function test($actual) { - if (! is_object($actual)) { - return false; - } - return parent::test($this->getProperty($this->name, $actual)); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - */ - function testMessage($actual) { - return parent::testMessage($this->getProperty($this->name, $actual)); - } - - /** - * Extracts the member value even if private using reflection. - * @param string $name Property name. - * @param object $object Object to read. - * @return mixed Value of property. - */ - private function getProperty($name, $object) { - $reflection = new ReflectionObject($object); - $property = $reflection->getProperty($name); - if (method_exists($property, 'setAccessible')) { - $property->setAccessible(true); - } - try { - return $property->getValue($object); - } catch (ReflectionException $e) { - return $this->getPrivatePropertyNoMatterWhat($name, $object); - } - } - - /** - * Extracts a private member's value when reflection won't play ball. - * @param string $name Property name. - * @param object $object Object to read. - * @return mixed Value of property. - */ - private function getPrivatePropertyNoMatterWhat($name, $object) { - foreach ((array)$object as $mangled_name => $value) { - if ($this->unmangle($mangled_name) == $name) { - return $value; - } - } - } - - /** - * Removes crud from property name after it's been converted - * to an array. - * @param string $mangled Name from array cast. - * @return string Cleaned up name. - */ - function unmangle($mangled) { - $parts = preg_split('/[^a-zA-Z0-9_\x7f-\xff]+/', $mangled); - return array_pop($parts); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/extensions/pear_test_case.php b/3rdparty/simpletest/extensions/pear_test_case.php deleted file mode 100755 index 71657ae4ceaf14029ac36e2f3d9107b3c78460af..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/extensions/pear_test_case.php +++ /dev/null @@ -1,196 +0,0 @@ -<?php - /** - * adapter for SimpleTest to use PEAR PHPUnit test cases - * @package SimpleTest - * @subpackage Extensions - * @version $Id: pear_test_case.php 1836 2008-12-21 00:02:26Z edwardzyang $ - */ - - /**#@+ - * include SimpleTest files - */ - require_once(dirname(__FILE__) . '/../dumper.php'); - require_once(dirname(__FILE__) . '/../compatibility.php'); - require_once(dirname(__FILE__) . '/../test_case.php'); - require_once(dirname(__FILE__) . '/../expectation.php'); - /**#@-*/ - - /** - * Adapter for PEAR PHPUnit test case to allow - * legacy PEAR test cases to be used with SimpleTest. - * @package SimpleTest - * @subpackage Extensions - */ - class PHPUnit_TestCase extends SimpleTestCase { - private $_loosely_typed; - - /** - * Constructor. Sets the test name. - * @param $label Test name to display. - * @public - */ - function __construct($label = false) { - parent::__construct($label); - $this->_loosely_typed = false; - } - - /** - * Will test straight equality if set to loose - * typing, or identity if not. - * @param $first First value. - * @param $second Comparison value. - * @param $message Message to display. - * @public - */ - function assertEquals($first, $second, $message = "%s", $delta = 0) { - if ($this->_loosely_typed) { - $expectation = new EqualExpectation($first); - } else { - $expectation = new IdenticalExpectation($first); - } - $this->assert($expectation, $second, $message); - } - - /** - * Passes if the value tested is not null. - * @param $value Value to test against. - * @param $message Message to display. - * @public - */ - function assertNotNull($value, $message = "%s") { - parent::assert(new TrueExpectation(), isset($value), $message); - } - - /** - * Passes if the value tested is null. - * @param $value Value to test against. - * @param $message Message to display. - * @public - */ - function assertNull($value, $message = "%s") { - parent::assert(new TrueExpectation(), !isset($value), $message); - } - - /** - * Identity test tests for the same object. - * @param $first First object handle. - * @param $second Hopefully the same handle. - * @param $message Message to display. - * @public - */ - function assertSame($first, $second, $message = "%s") { - $dumper = new SimpleDumper(); - $message = sprintf( - $message, - "[" . $dumper->describeValue($first) . - "] and [" . $dumper->describeValue($second) . - "] should reference the same object"); - return $this->assert( - new TrueExpectation(), - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * Inverted identity test. - * @param $first First object handle. - * @param $second Hopefully a different handle. - * @param $message Message to display. - * @public - */ - function assertNotSame($first, $second, $message = "%s") { - $dumper = new SimpleDumper(); - $message = sprintf( - $message, - "[" . $dumper->describeValue($first) . - "] and [" . $dumper->describeValue($second) . - "] should not be the same object"); - return $this->assert( - new falseExpectation(), - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * Sends pass if the test condition resolves true, - * a fail otherwise. - * @param $condition Condition to test true. - * @param $message Message to display. - * @public - */ - function assertTrue($condition, $message = "%s") { - parent::assert(new TrueExpectation(), $condition, $message); - } - - /** - * Sends pass if the test condition resolves false, - * a fail otherwise. - * @param $condition Condition to test false. - * @param $message Message to display. - * @public - */ - function assertFalse($condition, $message = "%s") { - parent::assert(new FalseExpectation(), $condition, $message); - } - - /** - * Tests a regex match. Needs refactoring. - * @param $pattern Regex to match. - * @param $subject String to search in. - * @param $message Message to display. - * @public - */ - function assertRegExp($pattern, $subject, $message = "%s") { - $this->assert(new PatternExpectation($pattern), $subject, $message); - } - - /** - * Tests the type of a value. - * @param $value Value to take type of. - * @param $type Hoped for type. - * @param $message Message to display. - * @public - */ - function assertType($value, $type, $message = "%s") { - parent::assert(new TrueExpectation(), gettype($value) == strtolower($type), $message); - } - - /** - * Sets equality operation to act as a simple equal - * comparison only, allowing a broader range of - * matches. - * @param $loosely_typed True for broader comparison. - * @public - */ - function setLooselyTyped($loosely_typed) { - $this->_loosely_typed = $loosely_typed; - } - - /** - * For progress indication during - * a test amongst other things. - * @return Usually one. - * @public - */ - function countTestCases() { - return $this->getSize(); - } - - /** - * Accessor for name, normally just the class - * name. - * @public - */ - function getName() { - return $this->getLabel(); - } - - /** - * Does nothing. For compatibility only. - * @param $name Dummy - * @public - */ - function setName($name) { - } - } -?> \ No newline at end of file diff --git a/3rdparty/simpletest/extensions/testdox.php b/3rdparty/simpletest/extensions/testdox.php deleted file mode 100755 index 5cf32f3516249c33abb7bd6c10505425615c1029..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/extensions/testdox.php +++ /dev/null @@ -1,53 +0,0 @@ -<?php -/** - * Extension for a TestDox reporter - * @package SimpleTest - * @subpackage Extensions - * @version $Id: testdox.php 2004 2010-10-31 13:44:14Z jsweat $ - */ - -/** - * TestDox reporter - * @package SimpleTest - * @subpackage Extensions - */ -class TestDoxReporter extends SimpleReporter -{ - var $_test_case_pattern = '/^TestOf(.*)$/'; - - function __construct($test_case_pattern = '/^TestOf(.*)$/') { - parent::__construct(); - $this->_test_case_pattern = empty($test_case_pattern) ? '/^(.*)$/' : $test_case_pattern; - } - - function paintCaseStart($test_name) { - preg_match($this->_test_case_pattern, $test_name, $matches); - if (!empty($matches[1])) { - echo $matches[1] . "\n"; - } else { - echo $test_name . "\n"; - } - } - - function paintCaseEnd($test_name) { - echo "\n"; - } - - function paintMethodStart($test_name) { - if (!preg_match('/^test(.*)$/i', $test_name, $matches)) { - return; - } - $test_name = $matches[1]; - $test_name = preg_replace('/([A-Z])([A-Z])/', '$1 $2', $test_name); - echo '- ' . strtolower(preg_replace('/([a-zA-Z])([A-Z0-9])/', '$1 $2', $test_name)); - } - - function paintMethodEnd($test_name) { - echo "\n"; - } - - function paintFail($message) { - echo " [FAILED]"; - } -} -?> diff --git a/3rdparty/simpletest/extensions/testdox/test.php b/3rdparty/simpletest/extensions/testdox/test.php deleted file mode 100755 index b03abe510ab5b970f41f6aa27c0e6d051830df24..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/extensions/testdox/test.php +++ /dev/null @@ -1,107 +0,0 @@ -<?php -// $Id: test.php 1748 2008-04-14 01:50:41Z lastcraft $ -require_once dirname(__FILE__) . '/../../autorun.php'; -require_once dirname(__FILE__) . '/../testdox.php'; - -// uncomment to see test dox in action -//SimpleTest::prefer(new TestDoxReporter()); - -class TestOfTestDoxReporter extends UnitTestCase -{ - function testIsAnInstanceOfSimpleScorerAndReporter() { - $dox = new TestDoxReporter(); - $this->assertIsA($dox, 'SimpleScorer'); - $this->assertIsA($dox, 'SimpleReporter'); - } - - function testOutputsNameOfTestCase() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintCaseStart('TestOfTestDoxReporter'); - $buffer = ob_get_clean(); - $this->assertPattern('/^TestDoxReporter/', $buffer); - } - - function testOutputOfTestCaseNameFilteredByConstructParameter() { - $dox = new TestDoxReporter('/^(.*)Test$/'); - ob_start(); - $dox->paintCaseStart('SomeGreatWidgetTest'); - $buffer = ob_get_clean(); - $this->assertPattern('/^SomeGreatWidget/', $buffer); - } - - function testIfTest_case_patternIsEmptyAssumeEverythingMatches() { - $dox = new TestDoxReporter(''); - ob_start(); - $dox->paintCaseStart('TestOfTestDoxReporter'); - $buffer = ob_get_clean(); - $this->assertPattern('/^TestOfTestDoxReporter/', $buffer); - } - - function testEmptyLineInsertedWhenCaseEnds() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintCaseEnd('TestOfTestDoxReporter'); - $buffer = ob_get_clean(); - $this->assertEqual("\n", $buffer); - } - - function testPaintsTestMethodInTestDoxFormat() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('testSomeGreatTestCase'); - $buffer = ob_get_clean(); - $this->assertEqual("- some great test case", $buffer); - unset($buffer); - - $random = rand(100, 200); - ob_start(); - $dox->paintMethodStart("testRandomNumberIs{$random}"); - $buffer = ob_get_clean(); - $this->assertEqual("- random number is {$random}", $buffer); - } - - function testDoesNotOutputAnythingOnNoneTestMethods() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('nonMatchingMethod'); - $buffer = ob_get_clean(); - $this->assertEqual('', $buffer); - } - - function testPaintMethodAddLineBreak() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodEnd('someMethod'); - $buffer = ob_get_clean(); - $this->assertEqual("\n", $buffer); - } - - function testProperlySpacesSingleLettersInMethodName() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('testAVerySimpleAgainAVerySimpleMethod'); - $buffer = ob_get_clean(); - $this->assertEqual('- a very simple again a very simple method', $buffer); - } - - function testOnFailureThisPrintsFailureNotice() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintFail(''); - $buffer = ob_get_clean(); - $this->assertEqual(' [FAILED]', $buffer); - } - - function testWhenMatchingMethodNamesTestPrefixIsCaseInsensitive() { - $dox = new TestDoxReporter(); - ob_start(); - $dox->paintMethodStart('TESTSupportsAllUppercaseTestPrefixEvenThoughIDoNotKnowWhyYouWouldDoThat'); - $buffer = ob_get_clean(); - $this->assertEqual( - '- supports all uppercase test prefix even though i do not know why you would do that', - $buffer - ); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/form.php b/3rdparty/simpletest/form.php deleted file mode 100644 index 5e423a9df8278c098fb3b02f1da88e1a6b423815..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/form.php +++ /dev/null @@ -1,361 +0,0 @@ -<?php -/** - * Base include file for SimpleTest. - * @package SimpleTest - * @subpackage WebTester - * @version $Id: form.php 2013 2011-04-29 09:29:45Z pp11 $ - */ - -/**#@+ - * include SimpleTest files - */ -require_once(dirname(__FILE__) . '/tag.php'); -require_once(dirname(__FILE__) . '/encoding.php'); -require_once(dirname(__FILE__) . '/selector.php'); -/**#@-*/ - -/** - * Form tag class to hold widget values. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleForm { - private $method; - private $action; - private $encoding; - private $default_target; - private $id; - private $buttons; - private $images; - private $widgets; - private $radios; - private $checkboxes; - - /** - * Starts with no held controls/widgets. - * @param SimpleTag $tag Form tag to read. - * @param SimplePage $page Holding page. - */ - function __construct($tag, $page) { - $this->method = $tag->getAttribute('method'); - $this->action = $this->createAction($tag->getAttribute('action'), $page); - $this->encoding = $this->setEncodingClass($tag); - $this->default_target = false; - $this->id = $tag->getAttribute('id'); - $this->buttons = array(); - $this->images = array(); - $this->widgets = array(); - $this->radios = array(); - $this->checkboxes = array(); - } - - /** - * Creates the request packet to be sent by the form. - * @param SimpleTag $tag Form tag to read. - * @return string Packet class. - * @access private - */ - protected function setEncodingClass($tag) { - if (strtolower($tag->getAttribute('method')) == 'post') { - if (strtolower($tag->getAttribute('enctype')) == 'multipart/form-data') { - return 'SimpleMultipartEncoding'; - } - return 'SimplePostEncoding'; - } - return 'SimpleGetEncoding'; - } - - /** - * Sets the frame target within a frameset. - * @param string $frame Name of frame. - * @access public - */ - function setDefaultTarget($frame) { - $this->default_target = $frame; - } - - /** - * Accessor for method of form submission. - * @return string Either get or post. - * @access public - */ - function getMethod() { - return ($this->method ? strtolower($this->method) : 'get'); - } - - /** - * Combined action attribute with current location - * to get an absolute form target. - * @param string $action Action attribute from form tag. - * @param SimpleUrl $base Page location. - * @return SimpleUrl Absolute form target. - */ - protected function createAction($action, $page) { - if (($action === '') || ($action === false)) { - return $page->expandUrl($page->getUrl()); - } - return $page->expandUrl(new SimpleUrl($action));; - } - - /** - * Absolute URL of the target. - * @return SimpleUrl URL target. - * @access public - */ - function getAction() { - $url = $this->action; - if ($this->default_target && ! $url->getTarget()) { - $url->setTarget($this->default_target); - } - if ($this->getMethod() == 'get') { - $url->clearRequest(); - } - return $url; - } - - /** - * Creates the encoding for the current values in the - * form. - * @return SimpleFormEncoding Request to submit. - * @access private - */ - protected function encode() { - $class = $this->encoding; - $encoding = new $class(); - for ($i = 0, $count = count($this->widgets); $i < $count; $i++) { - $this->widgets[$i]->write($encoding); - } - return $encoding; - } - - /** - * ID field of form for unique identification. - * @return string Unique tag ID. - * @access public - */ - function getId() { - return $this->id; - } - - /** - * Adds a tag contents to the form. - * @param SimpleWidget $tag Input tag to add. - */ - function addWidget($tag) { - if (strtolower($tag->getAttribute('type')) == 'submit') { - $this->buttons[] = $tag; - } elseif (strtolower($tag->getAttribute('type')) == 'image') { - $this->images[] = $tag; - } elseif ($tag->getName()) { - $this->setWidget($tag); - } - } - - /** - * Sets the widget into the form, grouping radio - * buttons if any. - * @param SimpleWidget $tag Incoming form control. - * @access private - */ - protected function setWidget($tag) { - if (strtolower($tag->getAttribute('type')) == 'radio') { - $this->addRadioButton($tag); - } elseif (strtolower($tag->getAttribute('type')) == 'checkbox') { - $this->addCheckbox($tag); - } else { - $this->widgets[] = &$tag; - } - } - - /** - * Adds a radio button, building a group if necessary. - * @param SimpleRadioButtonTag $tag Incoming form control. - * @access private - */ - protected function addRadioButton($tag) { - if (! isset($this->radios[$tag->getName()])) { - $this->widgets[] = new SimpleRadioGroup(); - $this->radios[$tag->getName()] = count($this->widgets) - 1; - } - $this->widgets[$this->radios[$tag->getName()]]->addWidget($tag); - } - - /** - * Adds a checkbox, making it a group on a repeated name. - * @param SimpleCheckboxTag $tag Incoming form control. - * @access private - */ - protected function addCheckbox($tag) { - if (! isset($this->checkboxes[$tag->getName()])) { - $this->widgets[] = $tag; - $this->checkboxes[$tag->getName()] = count($this->widgets) - 1; - } else { - $index = $this->checkboxes[$tag->getName()]; - if (! SimpleTestCompatibility::isA($this->widgets[$index], 'SimpleCheckboxGroup')) { - $previous = $this->widgets[$index]; - $this->widgets[$index] = new SimpleCheckboxGroup(); - $this->widgets[$index]->addWidget($previous); - } - $this->widgets[$index]->addWidget($tag); - } - } - - /** - * Extracts current value from form. - * @param SimpleSelector $selector Criteria to apply. - * @return string/array Value(s) as string or null - * if not set. - * @access public - */ - function getValue($selector) { - for ($i = 0, $count = count($this->widgets); $i < $count; $i++) { - if ($selector->isMatch($this->widgets[$i])) { - return $this->widgets[$i]->getValue(); - } - } - foreach ($this->buttons as $button) { - if ($selector->isMatch($button)) { - return $button->getValue(); - } - } - return null; - } - - /** - * Sets a widget value within the form. - * @param SimpleSelector $selector Criteria to apply. - * @param string $value Value to input into the widget. - * @return boolean True if value is legal, false - * otherwise. If the field is not - * present, nothing will be set. - * @access public - */ - function setField($selector, $value, $position=false) { - $success = false; - $_position = 0; - for ($i = 0, $count = count($this->widgets); $i < $count; $i++) { - if ($selector->isMatch($this->widgets[$i])) { - $_position++; - if ($position === false or $_position === (int)$position) { - if ($this->widgets[$i]->setValue($value)) { - $success = true; - } - } - } - } - return $success; - } - - /** - * Used by the page object to set widgets labels to - * external label tags. - * @param SimpleSelector $selector Criteria to apply. - * @access public - */ - function attachLabelBySelector($selector, $label) { - for ($i = 0, $count = count($this->widgets); $i < $count; $i++) { - if ($selector->isMatch($this->widgets[$i])) { - if (method_exists($this->widgets[$i], 'setLabel')) { - $this->widgets[$i]->setLabel($label); - return; - } - } - } - } - - /** - * Test to see if a form has a submit button. - * @param SimpleSelector $selector Criteria to apply. - * @return boolean True if present. - * @access public - */ - function hasSubmit($selector) { - foreach ($this->buttons as $button) { - if ($selector->isMatch($button)) { - return true; - } - } - return false; - } - - /** - * Test to see if a form has an image control. - * @param SimpleSelector $selector Criteria to apply. - * @return boolean True if present. - * @access public - */ - function hasImage($selector) { - foreach ($this->images as $image) { - if ($selector->isMatch($image)) { - return true; - } - } - return false; - } - - /** - * Gets the submit values for a selected button. - * @param SimpleSelector $selector Criteria to apply. - * @param hash $additional Additional data for the form. - * @return SimpleEncoding Submitted values or false - * if there is no such button - * in the form. - * @access public - */ - function submitButton($selector, $additional = false) { - $additional = $additional ? $additional : array(); - foreach ($this->buttons as $button) { - if ($selector->isMatch($button)) { - $encoding = $this->encode(); - $button->write($encoding); - if ($additional) { - $encoding->merge($additional); - } - return $encoding; - } - } - return false; - } - - /** - * Gets the submit values for an image. - * @param SimpleSelector $selector Criteria to apply. - * @param integer $x X-coordinate of click. - * @param integer $y Y-coordinate of click. - * @param hash $additional Additional data for the form. - * @return SimpleEncoding Submitted values or false - * if there is no such button in the - * form. - * @access public - */ - function submitImage($selector, $x, $y, $additional = false) { - $additional = $additional ? $additional : array(); - foreach ($this->images as $image) { - if ($selector->isMatch($image)) { - $encoding = $this->encode(); - $image->write($encoding, $x, $y); - if ($additional) { - $encoding->merge($additional); - } - return $encoding; - } - } - return false; - } - - /** - * Simply submits the form without the submit button - * value. Used when there is only one button or it - * is unimportant. - * @return hash Submitted values. - * @access public - */ - function submit($additional = false) { - $encoding = $this->encode(); - if ($additional) { - $encoding->merge($additional); - } - return $encoding; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/frames.php b/3rdparty/simpletest/frames.php deleted file mode 100755 index d6d8e96fd0c191c6eaf54895b260278040d818e4..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/frames.php +++ /dev/null @@ -1,592 +0,0 @@ -<?php -/** - * Base include file for SimpleTest - * @package SimpleTest - * @subpackage WebTester - * @version $Id: frames.php 1784 2008-04-26 13:07:14Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/page.php'); -require_once(dirname(__FILE__) . '/user_agent.php'); -/**#@-*/ - -/** - * A composite page. Wraps a frameset page and - * adds subframes. The original page will be - * mostly ignored. Implements the SimplePage - * interface so as to be interchangeable. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleFrameset { - private $frameset; - private $frames; - private $focus; - private $names; - - /** - * Stashes the frameset page. Will make use of the - * browser to fetch the sub frames recursively. - * @param SimplePage $page Frameset page. - */ - function __construct($page) { - $this->frameset = $page; - $this->frames = array(); - $this->focus = false; - $this->names = array(); - } - - /** - * Adds a parsed page to the frameset. - * @param SimplePage $page Frame page. - * @param string $name Name of frame in frameset. - * @access public - */ - function addFrame($page, $name = false) { - $this->frames[] = $page; - if ($name) { - $this->names[$name] = count($this->frames) - 1; - } - } - - /** - * Replaces existing frame with another. If the - * frame is nested, then the call is passed down - * one level. - * @param array $path Path of frame in frameset. - * @param SimplePage $page Frame source. - * @access public - */ - function setFrame($path, $page) { - $name = array_shift($path); - if (isset($this->names[$name])) { - $index = $this->names[$name]; - } else { - $index = $name - 1; - } - if (count($path) == 0) { - $this->frames[$index] = &$page; - return; - } - $this->frames[$index]->setFrame($path, $page); - } - - /** - * Accessor for current frame focus. Will be - * false if no frame has focus. Will have the nested - * frame focus if any. - * @return array Labels or indexes of nested frames. - * @access public - */ - function getFrameFocus() { - if ($this->focus === false) { - return array(); - } - return array_merge( - array($this->getPublicNameFromIndex($this->focus)), - $this->frames[$this->focus]->getFrameFocus()); - } - - /** - * Turns an internal array index into the frames list - * into a public name, or if none, then a one offset - * index. - * @param integer $subject Internal index. - * @return integer/string Public name. - * @access private - */ - protected function getPublicNameFromIndex($subject) { - foreach ($this->names as $name => $index) { - if ($subject == $index) { - return $name; - } - } - return $subject + 1; - } - - /** - * Sets the focus by index. The integer index starts from 1. - * If already focused and the target frame also has frames, - * then the nested frame will be focused. - * @param integer $choice Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocusByIndex($choice) { - if (is_integer($this->focus)) { - if ($this->frames[$this->focus]->hasFrames()) { - return $this->frames[$this->focus]->setFrameFocusByIndex($choice); - } - } - if (($choice < 1) || ($choice > count($this->frames))) { - return false; - } - $this->focus = $choice - 1; - return true; - } - - /** - * Sets the focus by name. If already focused and the - * target frame also has frames, then the nested frame - * will be focused. - * @param string $name Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocus($name) { - if (is_integer($this->focus)) { - if ($this->frames[$this->focus]->hasFrames()) { - return $this->frames[$this->focus]->setFrameFocus($name); - } - } - if (in_array($name, array_keys($this->names))) { - $this->focus = $this->names[$name]; - return true; - } - return false; - } - - /** - * Clears the frame focus. - * @access public - */ - function clearFrameFocus() { - $this->focus = false; - $this->clearNestedFramesFocus(); - } - - /** - * Clears the frame focus for any nested frames. - * @access private - */ - protected function clearNestedFramesFocus() { - for ($i = 0; $i < count($this->frames); $i++) { - $this->frames[$i]->clearFrameFocus(); - } - } - - /** - * Test for the presence of a frameset. - * @return boolean Always true. - * @access public - */ - function hasFrames() { - return true; - } - - /** - * Accessor for frames information. - * @return array/string Recursive hash of frame URL strings. - * The key is either a numerical - * index or the name attribute. - * @access public - */ - function getFrames() { - $report = array(); - for ($i = 0; $i < count($this->frames); $i++) { - $report[$this->getPublicNameFromIndex($i)] = - $this->frames[$i]->getFrames(); - } - return $report; - } - - /** - * Accessor for raw text of either all the pages or - * the frame in focus. - * @return string Raw unparsed content. - * @access public - */ - function getRaw() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getRaw(); - } - $raw = ''; - for ($i = 0; $i < count($this->frames); $i++) { - $raw .= $this->frames[$i]->getRaw(); - } - return $raw; - } - - /** - * Accessor for plain text of either all the pages or - * the frame in focus. - * @return string Plain text content. - * @access public - */ - function getText() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getText(); - } - $raw = ''; - for ($i = 0; $i < count($this->frames); $i++) { - $raw .= ' ' . $this->frames[$i]->getText(); - } - return trim($raw); - } - - /** - * Accessor for last error. - * @return string Error from last response. - * @access public - */ - function getTransportError() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getTransportError(); - } - return $this->frameset->getTransportError(); - } - - /** - * Request method used to fetch this frame. - * @return string GET, POST or HEAD. - * @access public - */ - function getMethod() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getMethod(); - } - return $this->frameset->getMethod(); - } - - /** - * Original resource name. - * @return SimpleUrl Current url. - * @access public - */ - function getUrl() { - if (is_integer($this->focus)) { - $url = $this->frames[$this->focus]->getUrl(); - $url->setTarget($this->getPublicNameFromIndex($this->focus)); - } else { - $url = $this->frameset->getUrl(); - } - return $url; - } - - /** - * Page base URL. - * @return SimpleUrl Current url. - * @access public - */ - function getBaseUrl() { - if (is_integer($this->focus)) { - $url = $this->frames[$this->focus]->getBaseUrl(); - } else { - $url = $this->frameset->getBaseUrl(); - } - return $url; - } - - /** - * Expands expandomatic URLs into fully qualified - * URLs for the frameset page. - * @param SimpleUrl $url Relative URL. - * @return SimpleUrl Absolute URL. - * @access public - */ - function expandUrl($url) { - return $this->frameset->expandUrl($url); - } - - /** - * Original request data. - * @return mixed Sent content. - * @access public - */ - function getRequestData() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getRequestData(); - } - return $this->frameset->getRequestData(); - } - - /** - * Accessor for current MIME type. - * @return string MIME type as string; e.g. 'text/html' - * @access public - */ - function getMimeType() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getMimeType(); - } - return $this->frameset->getMimeType(); - } - - /** - * Accessor for last response code. - * @return integer Last HTTP response code received. - * @access public - */ - function getResponseCode() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getResponseCode(); - } - return $this->frameset->getResponseCode(); - } - - /** - * Accessor for last Authentication type. Only valid - * straight after a challenge (401). - * @return string Description of challenge type. - * @access public - */ - function getAuthentication() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getAuthentication(); - } - return $this->frameset->getAuthentication(); - } - - /** - * Accessor for last Authentication realm. Only valid - * straight after a challenge (401). - * @return string Name of security realm. - * @access public - */ - function getRealm() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getRealm(); - } - return $this->frameset->getRealm(); - } - - /** - * Accessor for outgoing header information. - * @return string Header block. - * @access public - */ - function getRequest() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getRequest(); - } - return $this->frameset->getRequest(); - } - - /** - * Accessor for raw header information. - * @return string Header block. - * @access public - */ - function getHeaders() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getHeaders(); - } - return $this->frameset->getHeaders(); - } - - /** - * Accessor for parsed title. - * @return string Title or false if no title is present. - * @access public - */ - function getTitle() { - return $this->frameset->getTitle(); - } - - /** - * Accessor for a list of all fixed links. - * @return array List of urls as strings. - * @access public - */ - function getUrls() { - if (is_integer($this->focus)) { - return $this->frames[$this->focus]->getUrls(); - } - $urls = array(); - foreach ($this->frames as $frame) { - $urls = array_merge($urls, $frame->getUrls()); - } - return array_values(array_unique($urls)); - } - - /** - * Accessor for URLs by the link label. Label will match - * regardess of whitespace issues and case. - * @param string $label Text of link. - * @return array List of links with that label. - * @access public - */ - function getUrlsByLabel($label) { - if (is_integer($this->focus)) { - return $this->tagUrlsWithFrame( - $this->frames[$this->focus]->getUrlsByLabel($label), - $this->focus); - } - $urls = array(); - foreach ($this->frames as $index => $frame) { - $urls = array_merge( - $urls, - $this->tagUrlsWithFrame( - $frame->getUrlsByLabel($label), - $index)); - } - return $urls; - } - - /** - * Accessor for a URL by the id attribute. If in a frameset - * then the first link found with that ID attribute is - * returned only. Focus on a frame if you want one from - * a specific part of the frameset. - * @param string $id Id attribute of link. - * @return string URL with that id. - * @access public - */ - function getUrlById($id) { - foreach ($this->frames as $index => $frame) { - if ($url = $frame->getUrlById($id)) { - if (! $url->gettarget()) { - $url->setTarget($this->getPublicNameFromIndex($index)); - } - return $url; - } - } - return false; - } - - /** - * Attaches the intended frame index to a list of URLs. - * @param array $urls List of SimpleUrls. - * @param string $frame Name of frame or index. - * @return array List of tagged URLs. - * @access private - */ - protected function tagUrlsWithFrame($urls, $frame) { - $tagged = array(); - foreach ($urls as $url) { - if (! $url->getTarget()) { - $url->setTarget($this->getPublicNameFromIndex($frame)); - } - $tagged[] = $url; - } - return $tagged; - } - - /** - * Finds a held form by button label. Will only - * search correctly built forms. - * @param SimpleSelector $selector Button finder. - * @return SimpleForm Form object containing - * the button. - * @access public - */ - function getFormBySubmit($selector) { - return $this->findForm('getFormBySubmit', $selector); - } - - /** - * Finds a held form by image using a selector. - * Will only search correctly built forms. The first - * form found either within the focused frame, or - * across frames, will be the one returned. - * @param SimpleSelector $selector Image finder. - * @return SimpleForm Form object containing - * the image. - * @access public - */ - function getFormByImage($selector) { - return $this->findForm('getFormByImage', $selector); - } - - /** - * Finds a held form by the form ID. A way of - * identifying a specific form when we have control - * of the HTML code. The first form found - * either within the focused frame, or across frames, - * will be the one returned. - * @param string $id Form label. - * @return SimpleForm Form object containing the matching ID. - * @access public - */ - function getFormById($id) { - return $this->findForm('getFormById', $id); - } - - /** - * General form finder. Will search all the frames or - * just the one in focus. - * @param string $method Method to use to find in a page. - * @param string $attribute Label, name or ID. - * @return SimpleForm Form object containing the matching ID. - * @access private - */ - protected function findForm($method, $attribute) { - if (is_integer($this->focus)) { - return $this->findFormInFrame( - $this->frames[$this->focus], - $this->focus, - $method, - $attribute); - } - for ($i = 0; $i < count($this->frames); $i++) { - $form = $this->findFormInFrame( - $this->frames[$i], - $i, - $method, - $attribute); - if ($form) { - return $form; - } - } - $null = null; - return $null; - } - - /** - * Finds a form in a page using a form finding method. Will - * also tag the form with the frame name it belongs in. - * @param SimplePage $page Page content of frame. - * @param integer $index Internal frame representation. - * @param string $method Method to use to find in a page. - * @param string $attribute Label, name or ID. - * @return SimpleForm Form object containing the matching ID. - * @access private - */ - protected function findFormInFrame($page, $index, $method, $attribute) { - $form = $this->frames[$index]->$method($attribute); - if (isset($form)) { - $form->setDefaultTarget($this->getPublicNameFromIndex($index)); - } - return $form; - } - - /** - * Sets a field on each form in which the field is - * available. - * @param SimpleSelector $selector Field finder. - * @param string $value Value to set field to. - * @return boolean True if value is valid. - * @access public - */ - function setField($selector, $value) { - if (is_integer($this->focus)) { - $this->frames[$this->focus]->setField($selector, $value); - } else { - for ($i = 0; $i < count($this->frames); $i++) { - $this->frames[$i]->setField($selector, $value); - } - } - } - - /** - * Accessor for a form element value within a page. - * @param SimpleSelector $selector Field finder. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getField($selector) { - for ($i = 0; $i < count($this->frames); $i++) { - $value = $this->frames[$i]->getField($selector); - if (isset($value)) { - return $value; - } - } - return null; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/http.php b/3rdparty/simpletest/http.php deleted file mode 100644 index 1bd74031a480ff96298745f78aec2bfa4ba0e7d2..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/http.php +++ /dev/null @@ -1,628 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage WebTester - * @version $Id: http.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/socket.php'); -require_once(dirname(__FILE__) . '/cookies.php'); -require_once(dirname(__FILE__) . '/url.php'); -/**#@-*/ - -/** - * Creates HTTP headers for the end point of - * a HTTP request. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleRoute { - private $url; - - /** - * Sets the target URL. - * @param SimpleUrl $url URL as object. - * @access public - */ - function __construct($url) { - $this->url = $url; - } - - /** - * Resource name. - * @return SimpleUrl Current url. - * @access protected - */ - function getUrl() { - return $this->url; - } - - /** - * Creates the first line which is the actual request. - * @param string $method HTTP request method, usually GET. - * @return string Request line content. - * @access protected - */ - protected function getRequestLine($method) { - return $method . ' ' . $this->url->getPath() . - $this->url->getEncodedRequest() . ' HTTP/1.0'; - } - - /** - * Creates the host part of the request. - * @return string Host line content. - * @access protected - */ - protected function getHostLine() { - $line = 'Host: ' . $this->url->getHost(); - if ($this->url->getPort()) { - $line .= ':' . $this->url->getPort(); - } - return $line; - } - - /** - * Opens a socket to the route. - * @param string $method HTTP request method, usually GET. - * @param integer $timeout Connection timeout. - * @return SimpleSocket New socket. - * @access public - */ - function createConnection($method, $timeout) { - $default_port = ('https' == $this->url->getScheme()) ? 443 : 80; - $socket = $this->createSocket( - $this->url->getScheme() ? $this->url->getScheme() : 'http', - $this->url->getHost(), - $this->url->getPort() ? $this->url->getPort() : $default_port, - $timeout); - if (! $socket->isError()) { - $socket->write($this->getRequestLine($method) . "\r\n"); - $socket->write($this->getHostLine() . "\r\n"); - $socket->write("Connection: close\r\n"); - } - return $socket; - } - - /** - * Factory for socket. - * @param string $scheme Protocol to use. - * @param string $host Hostname to connect to. - * @param integer $port Remote port. - * @param integer $timeout Connection timeout. - * @return SimpleSocket/SimpleSecureSocket New socket. - * @access protected - */ - protected function createSocket($scheme, $host, $port, $timeout) { - if (in_array($scheme, array('file'))) { - return new SimpleFileSocket($this->url); - } elseif (in_array($scheme, array('https'))) { - return new SimpleSecureSocket($host, $port, $timeout); - } else { - return new SimpleSocket($host, $port, $timeout); - } - } -} - -/** - * Creates HTTP headers for the end point of - * a HTTP request via a proxy server. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleProxyRoute extends SimpleRoute { - private $proxy; - private $username; - private $password; - - /** - * Stashes the proxy address. - * @param SimpleUrl $url URL as object. - * @param string $proxy Proxy URL. - * @param string $username Username for autentication. - * @param string $password Password for autentication. - * @access public - */ - function __construct($url, $proxy, $username = false, $password = false) { - parent::__construct($url); - $this->proxy = $proxy; - $this->username = $username; - $this->password = $password; - } - - /** - * Creates the first line which is the actual request. - * @param string $method HTTP request method, usually GET. - * @param SimpleUrl $url URL as object. - * @return string Request line content. - * @access protected - */ - function getRequestLine($method) { - $url = $this->getUrl(); - $scheme = $url->getScheme() ? $url->getScheme() : 'http'; - $port = $url->getPort() ? ':' . $url->getPort() : ''; - return $method . ' ' . $scheme . '://' . $url->getHost() . $port . - $url->getPath() . $url->getEncodedRequest() . ' HTTP/1.0'; - } - - /** - * Creates the host part of the request. - * @param SimpleUrl $url URL as object. - * @return string Host line content. - * @access protected - */ - function getHostLine() { - $host = 'Host: ' . $this->proxy->getHost(); - $port = $this->proxy->getPort() ? $this->proxy->getPort() : 8080; - return "$host:$port"; - } - - /** - * Opens a socket to the route. - * @param string $method HTTP request method, usually GET. - * @param integer $timeout Connection timeout. - * @return SimpleSocket New socket. - * @access public - */ - function createConnection($method, $timeout) { - $socket = $this->createSocket( - $this->proxy->getScheme() ? $this->proxy->getScheme() : 'http', - $this->proxy->getHost(), - $this->proxy->getPort() ? $this->proxy->getPort() : 8080, - $timeout); - if ($socket->isError()) { - return $socket; - } - $socket->write($this->getRequestLine($method) . "\r\n"); - $socket->write($this->getHostLine() . "\r\n"); - if ($this->username && $this->password) { - $socket->write('Proxy-Authorization: Basic ' . - base64_encode($this->username . ':' . $this->password) . - "\r\n"); - } - $socket->write("Connection: close\r\n"); - return $socket; - } -} - -/** - * HTTP request for a web page. Factory for - * HttpResponse object. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHttpRequest { - private $route; - private $encoding; - private $headers; - private $cookies; - - /** - * Builds the socket request from the different pieces. - * These include proxy information, URL, cookies, headers, - * request method and choice of encoding. - * @param SimpleRoute $route Request route. - * @param SimpleFormEncoding $encoding Content to send with - * request. - * @access public - */ - function __construct($route, $encoding) { - $this->route = $route; - $this->encoding = $encoding; - $this->headers = array(); - $this->cookies = array(); - } - - /** - * Dispatches the content to the route's socket. - * @param integer $timeout Connection timeout. - * @return SimpleHttpResponse A response which may only have - * an error, but hopefully has a - * complete web page. - * @access public - */ - function fetch($timeout) { - $socket = $this->route->createConnection($this->encoding->getMethod(), $timeout); - if (! $socket->isError()) { - $this->dispatchRequest($socket, $this->encoding); - } - return $this->createResponse($socket); - } - - /** - * Sends the headers. - * @param SimpleSocket $socket Open socket. - * @param string $method HTTP request method, - * usually GET. - * @param SimpleFormEncoding $encoding Content to send with request. - * @access private - */ - protected function dispatchRequest($socket, $encoding) { - foreach ($this->headers as $header_line) { - $socket->write($header_line . "\r\n"); - } - if (count($this->cookies) > 0) { - $socket->write("Cookie: " . implode(";", $this->cookies) . "\r\n"); - } - $encoding->writeHeadersTo($socket); - $socket->write("\r\n"); - $encoding->writeTo($socket); - } - - /** - * Adds a header line to the request. - * @param string $header_line Text of full header line. - * @access public - */ - function addHeaderLine($header_line) { - $this->headers[] = $header_line; - } - - /** - * Reads all the relevant cookies from the - * cookie jar. - * @param SimpleCookieJar $jar Jar to read - * @param SimpleUrl $url Url to use for scope. - * @access public - */ - function readCookiesFromJar($jar, $url) { - $this->cookies = $jar->selectAsPairs($url); - } - - /** - * Wraps the socket in a response parser. - * @param SimpleSocket $socket Responding socket. - * @return SimpleHttpResponse Parsed response object. - * @access protected - */ - protected function createResponse($socket) { - $response = new SimpleHttpResponse( - $socket, - $this->route->getUrl(), - $this->encoding); - $socket->close(); - return $response; - } -} - -/** - * Collection of header lines in the response. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHttpHeaders { - private $raw_headers; - private $response_code; - private $http_version; - private $mime_type; - private $location; - private $cookies; - private $authentication; - private $realm; - - /** - * Parses the incoming header block. - * @param string $headers Header block. - * @access public - */ - function __construct($headers) { - $this->raw_headers = $headers; - $this->response_code = false; - $this->http_version = false; - $this->mime_type = ''; - $this->location = false; - $this->cookies = array(); - $this->authentication = false; - $this->realm = false; - foreach (explode("\r\n", $headers) as $header_line) { - $this->parseHeaderLine($header_line); - } - } - - /** - * Accessor for parsed HTTP protocol version. - * @return integer HTTP error code. - * @access public - */ - function getHttpVersion() { - return $this->http_version; - } - - /** - * Accessor for raw header block. - * @return string All headers as raw string. - * @access public - */ - function getRaw() { - return $this->raw_headers; - } - - /** - * Accessor for parsed HTTP error code. - * @return integer HTTP error code. - * @access public - */ - function getResponseCode() { - return (integer)$this->response_code; - } - - /** - * Returns the redirected URL or false if - * no redirection. - * @return string URL or false for none. - * @access public - */ - function getLocation() { - return $this->location; - } - - /** - * Test to see if the response is a valid redirect. - * @return boolean True if valid redirect. - * @access public - */ - function isRedirect() { - return in_array($this->response_code, array(301, 302, 303, 307)) && - (boolean)$this->getLocation(); - } - - /** - * Test to see if the response is an authentication - * challenge. - * @return boolean True if challenge. - * @access public - */ - function isChallenge() { - return ($this->response_code == 401) && - (boolean)$this->authentication && - (boolean)$this->realm; - } - - /** - * Accessor for MIME type header information. - * @return string MIME type. - * @access public - */ - function getMimeType() { - return $this->mime_type; - } - - /** - * Accessor for authentication type. - * @return string Type. - * @access public - */ - function getAuthentication() { - return $this->authentication; - } - - /** - * Accessor for security realm. - * @return string Realm. - * @access public - */ - function getRealm() { - return $this->realm; - } - - /** - * Writes new cookies to the cookie jar. - * @param SimpleCookieJar $jar Jar to write to. - * @param SimpleUrl $url Host and path to write under. - * @access public - */ - function writeCookiesToJar($jar, $url) { - foreach ($this->cookies as $cookie) { - $jar->setCookie( - $cookie->getName(), - $cookie->getValue(), - $url->getHost(), - $cookie->getPath(), - $cookie->getExpiry()); - } - } - - /** - * Called on each header line to accumulate the held - * data within the class. - * @param string $header_line One line of header. - * @access protected - */ - protected function parseHeaderLine($header_line) { - if (preg_match('/HTTP\/(\d+\.\d+)\s+(\d+)/i', $header_line, $matches)) { - $this->http_version = $matches[1]; - $this->response_code = $matches[2]; - } - if (preg_match('/Content-type:\s*(.*)/i', $header_line, $matches)) { - $this->mime_type = trim($matches[1]); - } - if (preg_match('/Location:\s*(.*)/i', $header_line, $matches)) { - $this->location = trim($matches[1]); - } - if (preg_match('/Set-cookie:(.*)/i', $header_line, $matches)) { - $this->cookies[] = $this->parseCookie($matches[1]); - } - if (preg_match('/WWW-Authenticate:\s+(\S+)\s+realm=\"(.*?)\"/i', $header_line, $matches)) { - $this->authentication = $matches[1]; - $this->realm = trim($matches[2]); - } - } - - /** - * Parse the Set-cookie content. - * @param string $cookie_line Text after "Set-cookie:" - * @return SimpleCookie New cookie object. - * @access private - */ - protected function parseCookie($cookie_line) { - $parts = explode(";", $cookie_line); - $cookie = array(); - preg_match('/\s*(.*?)\s*=(.*)/', array_shift($parts), $cookie); - foreach ($parts as $part) { - if (preg_match('/\s*(.*?)\s*=(.*)/', $part, $matches)) { - $cookie[$matches[1]] = trim($matches[2]); - } - } - return new SimpleCookie( - $cookie[1], - trim($cookie[2]), - isset($cookie["path"]) ? $cookie["path"] : "", - isset($cookie["expires"]) ? $cookie["expires"] : false); - } -} - -/** - * Basic HTTP response. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHttpResponse extends SimpleStickyError { - private $url; - private $encoding; - private $sent; - private $content; - private $headers; - - /** - * Constructor. Reads and parses the incoming - * content and headers. - * @param SimpleSocket $socket Network connection to fetch - * response text from. - * @param SimpleUrl $url Resource name. - * @param mixed $encoding Record of content sent. - * @access public - */ - function __construct($socket, $url, $encoding) { - parent::__construct(); - $this->url = $url; - $this->encoding = $encoding; - $this->sent = $socket->getSent(); - $this->content = false; - $raw = $this->readAll($socket); - if ($socket->isError()) { - $this->setError('Error reading socket [' . $socket->getError() . ']'); - return; - } - $this->parse($raw); - } - - /** - * Splits up the headers and the rest of the content. - * @param string $raw Content to parse. - * @access private - */ - protected function parse($raw) { - if (! $raw) { - $this->setError('Nothing fetched'); - $this->headers = new SimpleHttpHeaders(''); - } elseif ('file' == $this->url->getScheme()) { - $this->headers = new SimpleHttpHeaders(''); - $this->content = $raw; - } elseif (! strstr($raw, "\r\n\r\n")) { - $this->setError('Could not split headers from content'); - $this->headers = new SimpleHttpHeaders($raw); - } else { - list($headers, $this->content) = explode("\r\n\r\n", $raw, 2); - $this->headers = new SimpleHttpHeaders($headers); - } - } - - /** - * Original request method. - * @return string GET, POST or HEAD. - * @access public - */ - function getMethod() { - return $this->encoding->getMethod(); - } - - /** - * Resource name. - * @return SimpleUrl Current url. - * @access public - */ - function getUrl() { - return $this->url; - } - - /** - * Original request data. - * @return mixed Sent content. - * @access public - */ - function getRequestData() { - return $this->encoding; - } - - /** - * Raw request that was sent down the wire. - * @return string Bytes actually sent. - * @access public - */ - function getSent() { - return $this->sent; - } - - /** - * Accessor for the content after the last - * header line. - * @return string All content. - * @access public - */ - function getContent() { - return $this->content; - } - - /** - * Accessor for header block. The response is the - * combination of this and the content. - * @return SimpleHeaders Wrapped header block. - * @access public - */ - function getHeaders() { - return $this->headers; - } - - /** - * Accessor for any new cookies. - * @return array List of new cookies. - * @access public - */ - function getNewCookies() { - return $this->headers->getNewCookies(); - } - - /** - * Reads the whole of the socket output into a - * single string. - * @param SimpleSocket $socket Unread socket. - * @return string Raw output if successful - * else false. - * @access private - */ - protected function readAll($socket) { - $all = ''; - while (! $this->isLastPacket($next = $socket->read())) { - $all .= $next; - } - return $all; - } - - /** - * Test to see if the packet from the socket is the - * last one. - * @param string $packet Chunk to interpret. - * @return boolean True if empty or EOF. - * @access private - */ - protected function isLastPacket($packet) { - if (is_string($packet)) { - return $packet === ''; - } - return ! $packet; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/invoker.php b/3rdparty/simpletest/invoker.php deleted file mode 100755 index ee310343fc74a7f99fcc193d1c14086888a765ac..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/invoker.php +++ /dev/null @@ -1,139 +0,0 @@ -<?php -/** - * Base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: invoker.php 1785 2008-04-26 13:56:41Z pp11 $ - */ - -/**#@+ - * Includes SimpleTest files and defined the root constant - * for dependent libraries. - */ -require_once(dirname(__FILE__) . '/errors.php'); -require_once(dirname(__FILE__) . '/compatibility.php'); -require_once(dirname(__FILE__) . '/scorer.php'); -require_once(dirname(__FILE__) . '/expectation.php'); -require_once(dirname(__FILE__) . '/dumper.php'); -if (! defined('SIMPLE_TEST')) { - define('SIMPLE_TEST', dirname(__FILE__) . '/'); -} -/**#@-*/ - -/** - * This is called by the class runner to run a - * single test method. Will also run the setUp() - * and tearDown() methods. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleInvoker { - private $test_case; - - /** - * Stashes the test case for later. - * @param SimpleTestCase $test_case Test case to run. - */ - function __construct($test_case) { - $this->test_case = $test_case; - } - - /** - * Accessor for test case being run. - * @return SimpleTestCase Test case. - * @access public - */ - function getTestCase() { - return $this->test_case; - } - - /** - * Runs test level set up. Used for changing - * the mechanics of base test cases. - * @param string $method Test method to call. - * @access public - */ - function before($method) { - $this->test_case->before($method); - } - - /** - * Invokes a test method and buffered with setUp() - * and tearDown() calls. - * @param string $method Test method to call. - * @access public - */ - function invoke($method) { - $this->test_case->setUp(); - $this->test_case->$method(); - $this->test_case->tearDown(); - } - - /** - * Runs test level clean up. Used for changing - * the mechanics of base test cases. - * @param string $method Test method to call. - * @access public - */ - function after($method) { - $this->test_case->after($method); - } -} - -/** - * Do nothing decorator. Just passes the invocation - * straight through. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleInvokerDecorator { - private $invoker; - - /** - * Stores the invoker to wrap. - * @param SimpleInvoker $invoker Test method runner. - */ - function __construct($invoker) { - $this->invoker = $invoker; - } - - /** - * Accessor for test case being run. - * @return SimpleTestCase Test case. - * @access public - */ - function getTestCase() { - return $this->invoker->getTestCase(); - } - - /** - * Runs test level set up. Used for changing - * the mechanics of base test cases. - * @param string $method Test method to call. - * @access public - */ - function before($method) { - $this->invoker->before($method); - } - - /** - * Invokes a test method and buffered with setUp() - * and tearDown() calls. - * @param string $method Test method to call. - * @access public - */ - function invoke($method) { - $this->invoker->invoke($method); - } - - /** - * Runs test level clean up. Used for changing - * the mechanics of base test cases. - * @param string $method Test method to call. - * @access public - */ - function after($method) { - $this->invoker->after($method); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/mock_objects.php b/3rdparty/simpletest/mock_objects.php deleted file mode 100755 index 93a827b6c0238101235be3126dd0231f00c499f0..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/mock_objects.php +++ /dev/null @@ -1,1641 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage MockObjects - * @version $Id: mock_objects.php 1973 2009-12-22 01:16:59Z lastcraft $ - */ - -/**#@+ - * include SimpleTest files - */ -require_once(dirname(__FILE__) . '/expectation.php'); -require_once(dirname(__FILE__) . '/simpletest.php'); -require_once(dirname(__FILE__) . '/dumper.php'); -require_once(dirname(__FILE__) . '/reflection_php5.php'); -/**#@-*/ - -/** - * Default character simpletest will substitute for any value - */ -if (! defined('MOCK_ANYTHING')) { - define('MOCK_ANYTHING', '*'); -} - -/** - * Parameter comparison assertion. - * @package SimpleTest - * @subpackage MockObjects - */ -class ParametersExpectation extends SimpleExpectation { - private $expected; - - /** - * Sets the expected parameter list. - * @param array $parameters Array of parameters including - * those that are wildcarded. - * If the value is not an array - * then it is considered to match any. - * @param string $message Customised message on failure. - */ - function __construct($expected = false, $message = '%s') { - parent::__construct($message); - $this->expected = $expected; - } - - /** - * Tests the assertion. True if correct. - * @param array $parameters Comparison values. - * @return boolean True if correct. - */ - function test($parameters) { - if (! is_array($this->expected)) { - return true; - } - if (count($this->expected) != count($parameters)) { - return false; - } - for ($i = 0; $i < count($this->expected); $i++) { - if (! $this->testParameter($parameters[$i], $this->expected[$i])) { - return false; - } - } - return true; - } - - /** - * Tests an individual parameter. - * @param mixed $parameter Value to test. - * @param mixed $expected Comparison value. - * @return boolean True if expectation - * fulfilled. - */ - protected function testParameter($parameter, $expected) { - $comparison = $this->coerceToExpectation($expected); - return $comparison->test($parameter); - } - - /** - * Returns a human readable test message. - * @param array $comparison Incoming parameter list. - * @return string Description of success - * or failure. - */ - function testMessage($parameters) { - if ($this->test($parameters)) { - return "Expectation of " . count($this->expected) . - " arguments of [" . $this->renderArguments($this->expected) . - "] is correct"; - } else { - return $this->describeDifference($this->expected, $parameters); - } - } - - /** - * Message to display if expectation differs from - * the parameters actually received. - * @param array $expected Expected parameters as list. - * @param array $parameters Actual parameters received. - * @return string Description of difference. - */ - protected function describeDifference($expected, $parameters) { - if (count($expected) != count($parameters)) { - return "Expected " . count($expected) . - " arguments of [" . $this->renderArguments($expected) . - "] but got " . count($parameters) . - " arguments of [" . $this->renderArguments($parameters) . "]"; - } - $messages = array(); - for ($i = 0; $i < count($expected); $i++) { - $comparison = $this->coerceToExpectation($expected[$i]); - if (! $comparison->test($parameters[$i])) { - $messages[] = "parameter " . ($i + 1) . " with [" . - $comparison->overlayMessage($parameters[$i], $this->getDumper()) . "]"; - } - } - return "Parameter expectation differs at " . implode(" and ", $messages); - } - - /** - * Creates an identical expectation if the - * object/value is not already some type - * of expectation. - * @param mixed $expected Expected value. - * @return SimpleExpectation Expectation object. - */ - protected function coerceToExpectation($expected) { - if (SimpleExpectation::isExpectation($expected)) { - return $expected; - } - return new IdenticalExpectation($expected); - } - - /** - * Renders the argument list as a string for - * messages. - * @param array $args Incoming arguments. - * @return string Simple description of type and value. - */ - protected function renderArguments($args) { - $descriptions = array(); - if (is_array($args)) { - foreach ($args as $arg) { - $dumper = new SimpleDumper(); - $descriptions[] = $dumper->describeValue($arg); - } - } - return implode(', ', $descriptions); - } -} - -/** - * Confirms that the number of calls on a method is as expected. - * @package SimpleTest - * @subpackage MockObjects - */ -class CallCountExpectation extends SimpleExpectation { - private $method; - private $count; - - /** - * Stashes the method and expected count for later - * reporting. - * @param string $method Name of method to confirm against. - * @param integer $count Expected number of calls. - * @param string $message Custom error message. - */ - function __construct($method, $count, $message = '%s') { - $this->method = $method; - $this->count = $count; - parent::__construct($message); - } - - /** - * Tests the assertion. True if correct. - * @param integer $compare Measured call count. - * @return boolean True if expected. - */ - function test($compare) { - return ($this->count == $compare); - } - - /** - * Reports the comparison. - * @param integer $compare Measured call count. - * @return string Message to show. - */ - function testMessage($compare) { - return 'Expected call count for [' . $this->method . - '] was [' . $this->count . - '] got [' . $compare . ']'; - } -} - -/** - * Confirms that the number of calls on a method is as expected. - * @package SimpleTest - * @subpackage MockObjects - */ -class MinimumCallCountExpectation extends SimpleExpectation { - private $method; - private $count; - - /** - * Stashes the method and expected count for later - * reporting. - * @param string $method Name of method to confirm against. - * @param integer $count Minimum number of calls. - * @param string $message Custom error message. - */ - function __construct($method, $count, $message = '%s') { - $this->method = $method; - $this->count = $count; - parent::__construct($message); - } - - /** - * Tests the assertion. True if correct. - * @param integer $compare Measured call count. - * @return boolean True if enough. - */ - function test($compare) { - return ($this->count <= $compare); - } - - /** - * Reports the comparison. - * @param integer $compare Measured call count. - * @return string Message to show. - */ - function testMessage($compare) { - return 'Minimum call count for [' . $this->method . - '] was [' . $this->count . - '] got [' . $compare . ']'; - } -} - -/** - * Confirms that the number of calls on a method is as expected. - * @package SimpleTest - * @subpackage MockObjects - */ -class MaximumCallCountExpectation extends SimpleExpectation { - private $method; - private $count; - - /** - * Stashes the method and expected count for later - * reporting. - * @param string $method Name of method to confirm against. - * @param integer $count Minimum number of calls. - * @param string $message Custom error message. - */ - function __construct($method, $count, $message = '%s') { - $this->method = $method; - $this->count = $count; - parent::__construct($message); - } - - /** - * Tests the assertion. True if correct. - * @param integer $compare Measured call count. - * @return boolean True if not over. - */ - function test($compare) { - return ($this->count >= $compare); - } - - /** - * Reports the comparison. - * @param integer $compare Measured call count. - * @return string Message to show. - */ - function testMessage($compare) { - return 'Maximum call count for [' . $this->method . - '] was [' . $this->count . - '] got [' . $compare . ']'; - } -} - -/** - * Retrieves method actions by searching the - * parameter lists until an expected match is found. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleSignatureMap { - private $map; - - /** - * Creates an empty call map. - */ - function __construct() { - $this->map = array(); - } - - /** - * Stashes a reference against a method call. - * @param array $parameters Array of arguments (including wildcards). - * @param mixed $action Reference placed in the map. - */ - function add($parameters, $action) { - $place = count($this->map); - $this->map[$place] = array(); - $this->map[$place]['params'] = new ParametersExpectation($parameters); - $this->map[$place]['content'] = $action; - } - - /** - * Searches the call list for a matching parameter - * set. Returned by reference. - * @param array $parameters Parameters to search by - * without wildcards. - * @return object Object held in the first matching - * slot, otherwise null. - */ - function &findFirstAction($parameters) { - $slot = $this->findFirstSlot($parameters); - if (isset($slot) && isset($slot['content'])) { - return $slot['content']; - } - $null = null; - return $null; - } - - /** - * Searches the call list for a matching parameter - * set. True if successful. - * @param array $parameters Parameters to search by - * without wildcards. - * @return boolean True if a match is present. - */ - function isMatch($parameters) { - return ($this->findFirstSlot($parameters) != null); - } - - /** - * Compares the incoming parameters with the - * internal expectation. Uses the incoming $test - * to dispatch the test message. - * @param SimpleTestCase $test Test to dispatch to. - * @param array $parameters The actual calling arguments. - * @param string $message The message to overlay. - */ - function test($test, $parameters, $message) { - } - - /** - * Searches the map for a matching item. - * @param array $parameters Parameters to search by - * without wildcards. - * @return array Reference to slot or null. - */ - function &findFirstSlot($parameters) { - $count = count($this->map); - for ($i = 0; $i < $count; $i++) { - if ($this->map[$i]["params"]->test($parameters)) { - return $this->map[$i]; - } - } - $null = null; - return $null; - } -} - -/** - * Allows setting of actions against call signatures either - * at a specific time, or always. Specific time settings - * trump lasting ones, otherwise the most recently added - * will mask an earlier match. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleCallSchedule { - private $wildcard = MOCK_ANYTHING; - private $always; - private $at; - - /** - * Sets up an empty response schedule. - * Creates an empty call map. - */ - function __construct() { - $this->always = array(); - $this->at = array(); - } - - /** - * Stores an action against a signature that - * will always fire unless masked by a time - * specific one. - * @param string $method Method name. - * @param array $args Calling parameters. - * @param SimpleAction $action Actually simpleByValue, etc. - */ - function register($method, $args, $action) { - $args = $this->replaceWildcards($args); - $method = strtolower($method); - if (! isset($this->always[$method])) { - $this->always[$method] = new SimpleSignatureMap(); - } - $this->always[$method]->add($args, $action); - } - - /** - * Stores an action against a signature that - * will fire at a specific time in the future. - * @param integer $step delay of calls to this method, - * 0 is next. - * @param string $method Method name. - * @param array $args Calling parameters. - * @param SimpleAction $action Actually SimpleByValue, etc. - */ - function registerAt($step, $method, $args, $action) { - $args = $this->replaceWildcards($args); - $method = strtolower($method); - if (! isset($this->at[$method])) { - $this->at[$method] = array(); - } - if (! isset($this->at[$method][$step])) { - $this->at[$method][$step] = new SimpleSignatureMap(); - } - $this->at[$method][$step]->add($args, $action); - } - - /** - * Sets up an expectation on the argument list. - * @param string $method Method to test. - * @param array $args Bare arguments or list of - * expectation objects. - * @param string $message Failure message. - */ - function expectArguments($method, $args, $message) { - $args = $this->replaceWildcards($args); - $message .= Mock::getExpectationLine(); - $this->expected_args[strtolower($method)] = - new ParametersExpectation($args, $message); - - } - - /** - * Actually carry out the action stored previously, - * if the parameters match. - * @param integer $step Time of call. - * @param string $method Method name. - * @param array $args The parameters making up the - * rest of the call. - * @return mixed The result of the action. - */ - function &respond($step, $method, $args) { - $method = strtolower($method); - if (isset($this->at[$method][$step])) { - if ($this->at[$method][$step]->isMatch($args)) { - $action = $this->at[$method][$step]->findFirstAction($args); - if (isset($action)) { - return $action->act(); - } - } - } - if (isset($this->always[$method])) { - $action = $this->always[$method]->findFirstAction($args); - if (isset($action)) { - return $action->act(); - } - } - $null = null; - return $null; - } - - /** - * Replaces wildcard matches with wildcard - * expectations in the argument list. - * @param array $args Raw argument list. - * @return array Argument list with - * expectations. - */ - protected function replaceWildcards($args) { - if ($args === false) { - return false; - } - for ($i = 0; $i < count($args); $i++) { - if ($args[$i] === $this->wildcard) { - $args[$i] = new AnythingExpectation(); - } - } - return $args; - } -} - -/** - * A type of SimpleMethodAction. - * Stashes a value for returning later. Follows usual - * PHP5 semantics of objects being returned by reference. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleReturn { - private $value; - - /** - * Stashes it for later. - * @param mixed $value You need to clone objects - * if you want copy semantics - * for these. - */ - function __construct($value) { - $this->value = $value; - } - - /** - * Returns the value stored earlier. - * @return mixed Whatever was stashed. - */ - function act() { - return $this->value; - } -} - -/** - * A type of SimpleMethodAction. - * Stashes a reference for returning later. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleByReference { - private $reference; - - /** - * Stashes it for later. - * @param mixed $reference Actual PHP4 style reference. - */ - function __construct(&$reference) { - $this->reference = &$reference; - } - - /** - * Returns the reference stored earlier. - * @return mixed Whatever was stashed. - */ - function &act() { - return $this->reference; - } -} - -/** - * A type of SimpleMethodAction. - * Stashes a value for returning later. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleByValue { - private $value; - - /** - * Stashes it for later. - * @param mixed $value You need to clone objects - * if you want copy semantics - * for these. - */ - function __construct($value) { - $this->value = $value; - } - - /** - * Returns the value stored earlier. - * @return mixed Whatever was stashed. - */ - function &act() { - $dummy = $this->value; - return $dummy; - } -} - -/** - * A type of SimpleMethodAction. - * Stashes an exception for throwing later. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleThrower { - private $exception; - - /** - * Stashes it for later. - * @param Exception $exception The exception object to throw. - */ - function __construct($exception) { - $this->exception = $exception; - } - - /** - * Throws the exceptins stashed earlier. - */ - function act() { - throw $this->exception; - } -} - -/** - * A type of SimpleMethodAction. - * Stashes an error for emitting later. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleErrorThrower { - private $error; - private $severity; - - /** - * Stashes an error to throw later. - * @param string $error Error message. - * @param integer $severity PHP error constant, e.g E_USER_ERROR. - */ - function __construct($error, $severity) { - $this->error = $error; - $this->severity = $severity; - } - - /** - * Triggers the stashed error. - */ - function &act() { - trigger_error($this->error, $this->severity); - $null = null; - return $null; - } -} - -/** - * A base class or delegate that extends an - * empty collection of methods that can have their - * return values set and expectations made of the - * calls upon them. The mock will assert the - * expectations against it's attached test case in - * addition to the server stub behaviour or returning - * preprogrammed responses. - * @package SimpleTest - * @subpackage MockObjects - */ -class SimpleMock { - private $actions; - private $expectations; - private $wildcard = MOCK_ANYTHING; - private $is_strict = true; - private $call_counts; - private $expected_counts; - private $max_counts; - private $expected_args; - private $expected_args_at; - - /** - * Creates an empty action list and expectation list. - * All call counts are set to zero. - */ - function SimpleMock() { - $this->actions = new SimpleCallSchedule(); - $this->expectations = new SimpleCallSchedule(); - $this->call_counts = array(); - $this->expected_counts = array(); - $this->max_counts = array(); - $this->expected_args = array(); - $this->expected_args_at = array(); - $this->getCurrentTestCase()->tell($this); - } - - /** - * Disables a name check when setting expectations. - * This hack is needed for the partial mocks. - */ - function disableExpectationNameChecks() { - $this->is_strict = false; - } - - /** - * Finds currently running test. - * @return SimpeTestCase Current test case. - */ - protected function getCurrentTestCase() { - return SimpleTest::getContext()->getTest(); - } - - /** - * Die if bad arguments array is passed. - * @param mixed $args The arguments value to be checked. - * @param string $task Description of task attempt. - * @return boolean Valid arguments - */ - protected function checkArgumentsIsArray($args, $task) { - if (! is_array($args)) { - trigger_error( - "Cannot $task as \$args parameter is not an array", - E_USER_ERROR); - } - } - - /** - * Triggers a PHP error if the method is not part - * of this object. - * @param string $method Name of method. - * @param string $task Description of task attempt. - */ - protected function dieOnNoMethod($method, $task) { - if ($this->is_strict && ! method_exists($this, $method)) { - trigger_error( - "Cannot $task as no ${method}() in class " . get_class($this), - E_USER_ERROR); - } - } - - /** - * Replaces wildcard matches with wildcard - * expectations in the argument list. - * @param array $args Raw argument list. - * @return array Argument list with - * expectations. - */ - function replaceWildcards($args) { - if ($args === false) { - return false; - } - for ($i = 0; $i < count($args); $i++) { - if ($args[$i] === $this->wildcard) { - $args[$i] = new AnythingExpectation(); - } - } - return $args; - } - - /** - * Adds one to the call count of a method. - * @param string $method Method called. - * @param array $args Arguments as an array. - */ - protected function addCall($method, $args) { - if (! isset($this->call_counts[$method])) { - $this->call_counts[$method] = 0; - } - $this->call_counts[$method]++; - } - - /** - * Fetches the call count of a method so far. - * @param string $method Method name called. - * @return integer Number of calls so far. - */ - function getCallCount($method) { - $this->dieOnNoMethod($method, "get call count"); - $method = strtolower($method); - if (! isset($this->call_counts[$method])) { - return 0; - } - return $this->call_counts[$method]; - } - - /** - * Sets a return for a parameter list that will - * be passed on by all calls to this method that match. - * @param string $method Method name. - * @param mixed $value Result of call by value/handle. - * @param array $args List of parameters to match - * including wildcards. - */ - function returns($method, $value, $args = false) { - $this->dieOnNoMethod($method, "set return"); - $this->actions->register($method, $args, new SimpleReturn($value)); - } - - /** - * Sets a return for a parameter list that will - * be passed only when the required call count - * is reached. - * @param integer $timing Number of calls in the future - * to which the result applies. If - * not set then all calls will return - * the value. - * @param string $method Method name. - * @param mixed $value Result of call passed. - * @param array $args List of parameters to match - * including wildcards. - */ - function returnsAt($timing, $method, $value, $args = false) { - $this->dieOnNoMethod($method, "set return value sequence"); - $this->actions->registerAt($timing, $method, $args, new SimpleReturn($value)); - } - - /** - * Sets a return for a parameter list that will - * be passed by value for all calls to this method. - * @param string $method Method name. - * @param mixed $value Result of call passed by value. - * @param array $args List of parameters to match - * including wildcards. - */ - function returnsByValue($method, $value, $args = false) { - $this->dieOnNoMethod($method, "set return value"); - $this->actions->register($method, $args, new SimpleByValue($value)); - } - - /** @deprecated */ - function setReturnValue($method, $value, $args = false) { - $this->returnsByValue($method, $value, $args); - } - - /** - * Sets a return for a parameter list that will - * be passed by value only when the required call count - * is reached. - * @param integer $timing Number of calls in the future - * to which the result applies. If - * not set then all calls will return - * the value. - * @param string $method Method name. - * @param mixed $value Result of call passed by value. - * @param array $args List of parameters to match - * including wildcards. - */ - function returnsByValueAt($timing, $method, $value, $args = false) { - $this->dieOnNoMethod($method, "set return value sequence"); - $this->actions->registerAt($timing, $method, $args, new SimpleByValue($value)); - } - - /** @deprecated */ - function setReturnValueAt($timing, $method, $value, $args = false) { - $this->returnsByValueAt($timing, $method, $value, $args); - } - - /** - * Sets a return for a parameter list that will - * be passed by reference for all calls. - * @param string $method Method name. - * @param mixed $reference Result of the call will be this object. - * @param array $args List of parameters to match - * including wildcards. - */ - function returnsByReference($method, &$reference, $args = false) { - $this->dieOnNoMethod($method, "set return reference"); - $this->actions->register($method, $args, new SimpleByReference($reference)); - } - - /** @deprecated */ - function setReturnReference($method, &$reference, $args = false) { - $this->returnsByReference($method, $reference, $args); - } - - /** - * Sets a return for a parameter list that will - * be passed by value only when the required call count - * is reached. - * @param integer $timing Number of calls in the future - * to which the result applies. If - * not set then all calls will return - * the value. - * @param string $method Method name. - * @param mixed $reference Result of the call will be this object. - * @param array $args List of parameters to match - * including wildcards. - */ - function returnsByReferenceAt($timing, $method, &$reference, $args = false) { - $this->dieOnNoMethod($method, "set return reference sequence"); - $this->actions->registerAt($timing, $method, $args, new SimpleByReference($reference)); - } - - /** @deprecated */ - function setReturnReferenceAt($timing, $method, &$reference, $args = false) { - $this->returnsByReferenceAt($timing, $method, $reference, $args); - } - - /** - * Sets up an expected call with a set of - * expected parameters in that call. All - * calls will be compared to these expectations - * regardless of when the call is made. - * @param string $method Method call to test. - * @param array $args Expected parameters for the call - * including wildcards. - * @param string $message Overridden message. - */ - function expect($method, $args, $message = '%s') { - $this->dieOnNoMethod($method, 'set expected arguments'); - $this->checkArgumentsIsArray($args, 'set expected arguments'); - $this->expectations->expectArguments($method, $args, $message); - $args = $this->replaceWildcards($args); - $message .= Mock::getExpectationLine(); - $this->expected_args[strtolower($method)] = - new ParametersExpectation($args, $message); - } - - /** - * Sets up an expected call with a set of - * expected parameters in that call. The - * expected call count will be adjusted if it - * is set too low to reach this call. - * @param integer $timing Number of calls in the future at - * which to test. Next call is 0. - * @param string $method Method call to test. - * @param array $args Expected parameters for the call - * including wildcards. - * @param string $message Overridden message. - */ - function expectAt($timing, $method, $args, $message = '%s') { - $this->dieOnNoMethod($method, 'set expected arguments at time'); - $this->checkArgumentsIsArray($args, 'set expected arguments at time'); - $args = $this->replaceWildcards($args); - if (! isset($this->expected_args_at[$timing])) { - $this->expected_args_at[$timing] = array(); - } - $method = strtolower($method); - $message .= Mock::getExpectationLine(); - $this->expected_args_at[$timing][$method] = - new ParametersExpectation($args, $message); - } - - /** - * Sets an expectation for the number of times - * a method will be called. The tally method - * is used to check this. - * @param string $method Method call to test. - * @param integer $count Number of times it should - * have been called at tally. - * @param string $message Overridden message. - */ - function expectCallCount($method, $count, $message = '%s') { - $this->dieOnNoMethod($method, 'set expected call count'); - $message .= Mock::getExpectationLine(); - $this->expected_counts[strtolower($method)] = - new CallCountExpectation($method, $count, $message); - } - - /** - * Sets the number of times a method may be called - * before a test failure is triggered. - * @param string $method Method call to test. - * @param integer $count Most number of times it should - * have been called. - * @param string $message Overridden message. - */ - function expectMaximumCallCount($method, $count, $message = '%s') { - $this->dieOnNoMethod($method, 'set maximum call count'); - $message .= Mock::getExpectationLine(); - $this->max_counts[strtolower($method)] = - new MaximumCallCountExpectation($method, $count, $message); - } - - /** - * Sets the number of times to call a method to prevent - * a failure on the tally. - * @param string $method Method call to test. - * @param integer $count Least number of times it should - * have been called. - * @param string $message Overridden message. - */ - function expectMinimumCallCount($method, $count, $message = '%s') { - $this->dieOnNoMethod($method, 'set minimum call count'); - $message .= Mock::getExpectationLine(); - $this->expected_counts[strtolower($method)] = - new MinimumCallCountExpectation($method, $count, $message); - } - - /** - * Convenience method for barring a method - * call. - * @param string $method Method call to ban. - * @param string $message Overridden message. - */ - function expectNever($method, $message = '%s') { - $this->expectMaximumCallCount($method, 0, $message); - } - - /** - * Convenience method for a single method - * call. - * @param string $method Method call to track. - * @param array $args Expected argument list or - * false for any arguments. - * @param string $message Overridden message. - */ - function expectOnce($method, $args = false, $message = '%s') { - $this->expectCallCount($method, 1, $message); - if ($args !== false) { - $this->expect($method, $args, $message); - } - } - - /** - * Convenience method for requiring a method - * call. - * @param string $method Method call to track. - * @param array $args Expected argument list or - * false for any arguments. - * @param string $message Overridden message. - */ - function expectAtLeastOnce($method, $args = false, $message = '%s') { - $this->expectMinimumCallCount($method, 1, $message); - if ($args !== false) { - $this->expect($method, $args, $message); - } - } - - /** - * Sets up a trigger to throw an exception upon the - * method call. - * @param string $method Method name to throw on. - * @param object $exception Exception object to throw. - * If not given then a simple - * Exception object is thrown. - * @param array $args Optional argument list filter. - * If given then the exception - * will only be thrown if the - * method call matches the arguments. - */ - function throwOn($method, $exception = false, $args = false) { - $this->dieOnNoMethod($method, "throw on"); - $this->actions->register($method, $args, - new SimpleThrower($exception ? $exception : new Exception())); - } - - /** - * Sets up a trigger to throw an exception upon the - * method call. - * @param integer $timing When to throw the exception. A - * value of 0 throws immediately. - * A value of 1 actually allows one call - * to this method before throwing. 2 - * will allow two calls before throwing - * and so on. - * @param string $method Method name to throw on. - * @param object $exception Exception object to throw. - * If not given then a simple - * Exception object is thrown. - * @param array $args Optional argument list filter. - * If given then the exception - * will only be thrown if the - * method call matches the arguments. - */ - function throwAt($timing, $method, $exception = false, $args = false) { - $this->dieOnNoMethod($method, "throw at"); - $this->actions->registerAt($timing, $method, $args, - new SimpleThrower($exception ? $exception : new Exception())); - } - - /** - * Sets up a trigger to throw an error upon the - * method call. - * @param string $method Method name to throw on. - * @param object $error Error message to trigger. - * @param array $args Optional argument list filter. - * If given then the exception - * will only be thrown if the - * method call matches the arguments. - * @param integer $severity The PHP severity level. Defaults - * to E_USER_ERROR. - */ - function errorOn($method, $error = 'A mock error', $args = false, $severity = E_USER_ERROR) { - $this->dieOnNoMethod($method, "error on"); - $this->actions->register($method, $args, new SimpleErrorThrower($error, $severity)); - } - - /** - * Sets up a trigger to throw an error upon a specific - * method call. - * @param integer $timing When to throw the exception. A - * value of 0 throws immediately. - * A value of 1 actually allows one call - * to this method before throwing. 2 - * will allow two calls before throwing - * and so on. - * @param string $method Method name to throw on. - * @param object $error Error message to trigger. - * @param array $args Optional argument list filter. - * If given then the exception - * will only be thrown if the - * method call matches the arguments. - * @param integer $severity The PHP severity level. Defaults - * to E_USER_ERROR. - */ - function errorAt($timing, $method, $error = 'A mock error', $args = false, $severity = E_USER_ERROR) { - $this->dieOnNoMethod($method, "error at"); - $this->actions->registerAt($timing, $method, $args, new SimpleErrorThrower($error, $severity)); - } - - /** - * Receives event from unit test that the current - * test method has finished. Totals up the call - * counts and triggers a test assertion if a test - * is present for expected call counts. - * @param string $test_method Current method name. - * @param SimpleTestCase $test Test to send message to. - */ - function atTestEnd($test_method, &$test) { - foreach ($this->expected_counts as $method => $expectation) { - $test->assert($expectation, $this->getCallCount($method)); - } - foreach ($this->max_counts as $method => $expectation) { - if ($expectation->test($this->getCallCount($method))) { - $test->assert($expectation, $this->getCallCount($method)); - } - } - } - - /** - * Returns the expected value for the method name - * and checks expectations. Will generate any - * test assertions as a result of expectations - * if there is a test present. - * @param string $method Name of method to simulate. - * @param array $args Arguments as an array. - * @return mixed Stored return. - */ - function &invoke($method, $args) { - $method = strtolower($method); - $step = $this->getCallCount($method); - $this->addCall($method, $args); - $this->checkExpectations($method, $args, $step); - $was = $this->disableEStrict(); - try { - $result = &$this->emulateCall($method, $args, $step); - } catch (Exception $e) { - $this->restoreEStrict($was); - throw $e; - } - $this->restoreEStrict($was); - return $result; - } - - /** - * Finds the return value matching the incoming - * arguments. If there is no matching value found - * then an error is triggered. - * @param string $method Method name. - * @param array $args Calling arguments. - * @param integer $step Current position in the - * call history. - * @return mixed Stored return or other action. - */ - protected function &emulateCall($method, $args, $step) { - return $this->actions->respond($step, $method, $args); - } - - /** - * Tests the arguments against expectations. - * @param string $method Method to check. - * @param array $args Argument list to match. - * @param integer $timing The position of this call - * in the call history. - */ - protected function checkExpectations($method, $args, $timing) { - $test = $this->getCurrentTestCase(); - if (isset($this->max_counts[$method])) { - if (! $this->max_counts[$method]->test($timing + 1)) { - $test->assert($this->max_counts[$method], $timing + 1); - } - } - if (isset($this->expected_args_at[$timing][$method])) { - $test->assert( - $this->expected_args_at[$timing][$method], - $args, - "Mock method [$method] at [$timing] -> %s"); - } elseif (isset($this->expected_args[$method])) { - $test->assert( - $this->expected_args[$method], - $args, - "Mock method [$method] -> %s"); - } - } - - /** - * Our mock has to be able to return anything, including - * variable references. To allow for these mixed returns - * we have to disable the E_STRICT warnings while the - * method calls are emulated. - */ - private function disableEStrict() { - $was = error_reporting(); - error_reporting($was & ~E_STRICT); - return $was; - } - - /** - * Restores the E_STRICT level if it was previously set. - * @param integer $was Previous error reporting level. - */ - private function restoreEStrict($was) { - error_reporting($was); - } -} - -/** - * Static methods only service class for code generation of - * mock objects. - * @package SimpleTest - * @subpackage MockObjects - */ -class Mock { - - /** - * Factory for mock object classes. - */ - function __construct() { - trigger_error('Mock factory methods are static.'); - } - - /** - * Clones a class' interface and creates a mock version - * that can have return values and expectations set. - * @param string $class Class to clone. - * @param string $mock_class New class name. Default is - * the old name with "Mock" - * prepended. - * @param array $methods Additional methods to add beyond - * those in the cloned class. Use this - * to emulate the dynamic addition of - * methods in the cloned class or when - * the class hasn't been written yet.sta - */ - static function generate($class, $mock_class = false, $methods = false) { - $generator = new MockGenerator($class, $mock_class); - return @$generator->generateSubclass($methods); - } - - /** - * Generates a version of a class with selected - * methods mocked only. Inherits the old class - * and chains the mock methods of an aggregated - * mock object. - * @param string $class Class to clone. - * @param string $mock_class New class name. - * @param array $methods Methods to be overridden - * with mock versions. - */ - static function generatePartial($class, $mock_class, $methods) { - $generator = new MockGenerator($class, $mock_class); - return @$generator->generatePartial($methods); - } - - /** - * Uses a stack trace to find the line of an assertion. - */ - static function getExpectationLine() { - $trace = new SimpleStackTrace(array('expect')); - return $trace->traceMethod(); - } -} - -/** - * Service class for code generation of mock objects. - * @package SimpleTest - * @subpackage MockObjects - */ -class MockGenerator { - private $class; - private $mock_class; - private $mock_base; - private $reflection; - - /** - * Builds initial reflection object. - * @param string $class Class to be mocked. - * @param string $mock_class New class with identical interface, - * but no behaviour. - */ - function __construct($class, $mock_class) { - $this->class = $class; - $this->mock_class = $mock_class; - if (! $this->mock_class) { - $this->mock_class = 'Mock' . $this->class; - } - $this->mock_base = SimpleTest::getMockBaseClass(); - $this->reflection = new SimpleReflection($this->class); - } - - /** - * Clones a class' interface and creates a mock version - * that can have return values and expectations set. - * @param array $methods Additional methods to add beyond - * those in th cloned class. Use this - * to emulate the dynamic addition of - * methods in the cloned class or when - * the class hasn't been written yet. - */ - function generate($methods) { - if (! $this->reflection->classOrInterfaceExists()) { - return false; - } - $mock_reflection = new SimpleReflection($this->mock_class); - if ($mock_reflection->classExistsSansAutoload()) { - return false; - } - $code = $this->createClassCode($methods ? $methods : array()); - return eval("$code return \$code;"); - } - - /** - * Subclasses a class and overrides every method with a mock one - * that can have return values and expectations set. Chains - * to an aggregated SimpleMock. - * @param array $methods Additional methods to add beyond - * those in the cloned class. Use this - * to emulate the dynamic addition of - * methods in the cloned class or when - * the class hasn't been written yet. - */ - function generateSubclass($methods) { - if (! $this->reflection->classOrInterfaceExists()) { - return false; - } - $mock_reflection = new SimpleReflection($this->mock_class); - if ($mock_reflection->classExistsSansAutoload()) { - return false; - } - if ($this->reflection->isInterface() || $this->reflection->hasFinal()) { - $code = $this->createClassCode($methods ? $methods : array()); - return eval("$code return \$code;"); - } else { - $code = $this->createSubclassCode($methods ? $methods : array()); - return eval("$code return \$code;"); - } - } - - /** - * Generates a version of a class with selected - * methods mocked only. Inherits the old class - * and chains the mock methods of an aggregated - * mock object. - * @param array $methods Methods to be overridden - * with mock versions. - */ - function generatePartial($methods) { - if (! $this->reflection->classExists($this->class)) { - return false; - } - $mock_reflection = new SimpleReflection($this->mock_class); - if ($mock_reflection->classExistsSansAutoload()) { - trigger_error('Partial mock class [' . $this->mock_class . '] already exists'); - return false; - } - $code = $this->extendClassCode($methods); - return eval("$code return \$code;"); - } - - /** - * The new mock class code as a string. - * @param array $methods Additional methods. - * @return string Code for new mock class. - */ - protected function createClassCode($methods) { - $implements = ''; - $interfaces = $this->reflection->getInterfaces(); - if (function_exists('spl_classes')) { - $interfaces = array_diff($interfaces, array('Traversable')); - } - if (count($interfaces) > 0) { - $implements = 'implements ' . implode(', ', $interfaces); - } - $code = "class " . $this->mock_class . " extends " . $this->mock_base . " $implements {\n"; - $code .= " function " . $this->mock_class . "() {\n"; - $code .= " \$this->" . $this->mock_base . "();\n"; - $code .= " }\n"; - if (in_array('__construct', $this->reflection->getMethods())) { - $code .= " function __construct() {\n"; - $code .= " \$this->" . $this->mock_base . "();\n"; - $code .= " }\n"; - } - $code .= $this->createHandlerCode($methods); - $code .= "}\n"; - return $code; - } - - /** - * The new mock class code as a string. The mock will - * be a subclass of the original mocked class. - * @param array $methods Additional methods. - * @return string Code for new mock class. - */ - protected function createSubclassCode($methods) { - $code = "class " . $this->mock_class . " extends " . $this->class . " {\n"; - $code .= " public \$mock;\n"; - $code .= $this->addMethodList(array_merge($methods, $this->reflection->getMethods())); - $code .= "\n"; - $code .= " function " . $this->mock_class . "() {\n"; - $code .= " \$this->mock = new " . $this->mock_base . "();\n"; - $code .= " \$this->mock->disableExpectationNameChecks();\n"; - $code .= " }\n"; - $code .= $this->chainMockReturns(); - $code .= $this->chainMockExpectations(); - $code .= $this->chainThrowMethods(); - $code .= $this->overrideMethods($this->reflection->getMethods()); - $code .= $this->createNewMethodCode($methods); - $code .= "}\n"; - return $code; - } - - /** - * The extension class code as a string. The class - * composites a mock object and chains mocked methods - * to it. - * @param array $methods Mocked methods. - * @return string Code for a new class. - */ - protected function extendClassCode($methods) { - $code = "class " . $this->mock_class . " extends " . $this->class . " {\n"; - $code .= " protected \$mock;\n"; - $code .= $this->addMethodList($methods); - $code .= "\n"; - $code .= " function " . $this->mock_class . "() {\n"; - $code .= " \$this->mock = new " . $this->mock_base . "();\n"; - $code .= " \$this->mock->disableExpectationNameChecks();\n"; - $code .= " }\n"; - $code .= $this->chainMockReturns(); - $code .= $this->chainMockExpectations(); - $code .= $this->chainThrowMethods(); - $code .= $this->overrideMethods($methods); - $code .= "}\n"; - return $code; - } - - /** - * Creates code within a class to generate replaced - * methods. All methods call the invoke() handler - * with the method name and the arguments in an - * array. - * @param array $methods Additional methods. - */ - protected function createHandlerCode($methods) { - $code = ''; - $methods = array_merge($methods, $this->reflection->getMethods()); - foreach ($methods as $method) { - if ($this->isConstructor($method)) { - continue; - } - $mock_reflection = new SimpleReflection($this->mock_base); - if (in_array($method, $mock_reflection->getMethods())) { - continue; - } - $code .= " " . $this->reflection->getSignature($method) . " {\n"; - $code .= " \$args = func_get_args();\n"; - $code .= " \$result = &\$this->invoke(\"$method\", \$args);\n"; - $code .= " return \$result;\n"; - $code .= " }\n"; - } - return $code; - } - - /** - * Creates code within a class to generate a new - * methods. All methods call the invoke() handler - * on the internal mock with the method name and - * the arguments in an array. - * @param array $methods Additional methods. - */ - protected function createNewMethodCode($methods) { - $code = ''; - foreach ($methods as $method) { - if ($this->isConstructor($method)) { - continue; - } - $mock_reflection = new SimpleReflection($this->mock_base); - if (in_array($method, $mock_reflection->getMethods())) { - continue; - } - $code .= " " . $this->reflection->getSignature($method) . " {\n"; - $code .= " \$args = func_get_args();\n"; - $code .= " \$result = &\$this->mock->invoke(\"$method\", \$args);\n"; - $code .= " return \$result;\n"; - $code .= " }\n"; - } - return $code; - } - - /** - * Tests to see if a special PHP method is about to - * be stubbed by mistake. - * @param string $method Method name. - * @return boolean True if special. - */ - protected function isConstructor($method) { - return in_array( - strtolower($method), - array('__construct', '__destruct')); - } - - /** - * Creates a list of mocked methods for error checking. - * @param array $methods Mocked methods. - * @return string Code for a method list. - */ - protected function addMethodList($methods) { - return " protected \$mocked_methods = array('" . - implode("', '", array_map('strtolower', $methods)) . - "');\n"; - } - - /** - * Creates code to abandon the expectation if not mocked. - * @param string $alias Parameter name of method name. - * @return string Code for bail out. - */ - protected function bailOutIfNotMocked($alias) { - $code = " if (! in_array(strtolower($alias), \$this->mocked_methods)) {\n"; - $code .= " trigger_error(\"Method [$alias] is not mocked\");\n"; - $code .= " \$null = null;\n"; - $code .= " return \$null;\n"; - $code .= " }\n"; - return $code; - } - - /** - * Creates source code for chaining to the composited - * mock object. - * @return string Code for mock set up. - */ - protected function chainMockReturns() { - $code = " function returns(\$method, \$value, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->returns(\$method, \$value, \$args);\n"; - $code .= " }\n"; - $code .= " function returnsAt(\$timing, \$method, \$value, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->returnsAt(\$timing, \$method, \$value, \$args);\n"; - $code .= " }\n"; - $code .= " function returnsByValue(\$method, \$value, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->setReturnValue(\$method, \$value, \$args);\n"; - $code .= " }\n"; - $code .= " function returnsByValueAt(\$timing, \$method, \$value, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n"; - $code .= " }\n"; - $code .= " function returnsByReference(\$method, &\$ref, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->setReturnReference(\$method, \$ref, \$args);\n"; - $code .= " }\n"; - $code .= " function returnsByReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->setReturnReferenceAt(\$timing, \$method, \$ref, \$args);\n"; - $code .= " }\n"; - $code .= " function setReturnValue(\$method, \$value, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->setReturnValue(\$method, \$value, \$args);\n"; - $code .= " }\n"; - $code .= " function setReturnValueAt(\$timing, \$method, \$value, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->setReturnValueAt(\$timing, \$method, \$value, \$args);\n"; - $code .= " }\n"; - $code .= " function setReturnReference(\$method, &\$ref, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->setReturnReference(\$method, \$ref, \$args);\n"; - $code .= " }\n"; - $code .= " function setReturnReferenceAt(\$timing, \$method, &\$ref, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->setReturnReferenceAt(\$timing, \$method, \$ref, \$args);\n"; - $code .= " }\n"; - return $code; - } - - /** - * Creates source code for chaining to an aggregated - * mock object. - * @return string Code for expectations. - */ - protected function chainMockExpectations() { - $code = " function expect(\$method, \$args = false, \$msg = '%s') {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->expect(\$method, \$args, \$msg);\n"; - $code .= " }\n"; - $code .= " function expectAt(\$timing, \$method, \$args = false, \$msg = '%s') {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->expectAt(\$timing, \$method, \$args, \$msg);\n"; - $code .= " }\n"; - $code .= " function expectCallCount(\$method, \$count) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->expectCallCount(\$method, \$count, \$msg = '%s');\n"; - $code .= " }\n"; - $code .= " function expectMaximumCallCount(\$method, \$count, \$msg = '%s') {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->expectMaximumCallCount(\$method, \$count, \$msg = '%s');\n"; - $code .= " }\n"; - $code .= " function expectMinimumCallCount(\$method, \$count, \$msg = '%s') {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->expectMinimumCallCount(\$method, \$count, \$msg = '%s');\n"; - $code .= " }\n"; - $code .= " function expectNever(\$method) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->expectNever(\$method);\n"; - $code .= " }\n"; - $code .= " function expectOnce(\$method, \$args = false, \$msg = '%s') {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->expectOnce(\$method, \$args, \$msg);\n"; - $code .= " }\n"; - $code .= " function expectAtLeastOnce(\$method, \$args = false, \$msg = '%s') {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->expectAtLeastOnce(\$method, \$args, \$msg);\n"; - $code .= " }\n"; - return $code; - } - - /** - * Adds code for chaining the throw methods. - * @return string Code for chains. - */ - protected function chainThrowMethods() { - $code = " function throwOn(\$method, \$exception = false, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->throwOn(\$method, \$exception, \$args);\n"; - $code .= " }\n"; - $code .= " function throwAt(\$timing, \$method, \$exception = false, \$args = false) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->throwAt(\$timing, \$method, \$exception, \$args);\n"; - $code .= " }\n"; - $code .= " function errorOn(\$method, \$error = 'A mock error', \$args = false, \$severity = E_USER_ERROR) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->errorOn(\$method, \$error, \$args, \$severity);\n"; - $code .= " }\n"; - $code .= " function errorAt(\$timing, \$method, \$error = 'A mock error', \$args = false, \$severity = E_USER_ERROR) {\n"; - $code .= $this->bailOutIfNotMocked("\$method"); - $code .= " \$this->mock->errorAt(\$timing, \$method, \$error, \$args, \$severity);\n"; - $code .= " }\n"; - return $code; - } - - /** - * Creates source code to override a list of methods - * with mock versions. - * @param array $methods Methods to be overridden - * with mock versions. - * @return string Code for overridden chains. - */ - protected function overrideMethods($methods) { - $code = ""; - foreach ($methods as $method) { - if ($this->isConstructor($method)) { - continue; - } - $code .= " " . $this->reflection->getSignature($method) . " {\n"; - $code .= " \$args = func_get_args();\n"; - $code .= " \$result = &\$this->mock->invoke(\"$method\", \$args);\n"; - $code .= " return \$result;\n"; - $code .= " }\n"; - } - return $code; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/page.php b/3rdparty/simpletest/page.php deleted file mode 100755 index 5c0bce7079d53e6996e01c80c364e18f88fc4bf2..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/page.php +++ /dev/null @@ -1,542 +0,0 @@ -<?php -/** - * Base include file for SimpleTest - * @package SimpleTest - * @subpackage WebTester - * @version $Id: page.php 1938 2009-08-05 17:16:23Z dgheath $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/http.php'); -require_once(dirname(__FILE__) . '/php_parser.php'); -require_once(dirname(__FILE__) . '/tag.php'); -require_once(dirname(__FILE__) . '/form.php'); -require_once(dirname(__FILE__) . '/selector.php'); -/**#@-*/ - -/** - * A wrapper for a web page. - * @package SimpleTest - * @subpackage WebTester - */ -class SimplePage { - private $links = array(); - private $title = false; - private $last_widget; - private $label; - private $forms = array(); - private $frames = array(); - private $transport_error; - private $raw; - private $text = false; - private $sent; - private $headers; - private $method; - private $url; - private $base = false; - private $request_data; - - /** - * Parses a page ready to access it's contents. - * @param SimpleHttpResponse $response Result of HTTP fetch. - * @access public - */ - function __construct($response = false) { - if ($response) { - $this->extractResponse($response); - } else { - $this->noResponse(); - } - } - - /** - * Extracts all of the response information. - * @param SimpleHttpResponse $response Response being parsed. - * @access private - */ - protected function extractResponse($response) { - $this->transport_error = $response->getError(); - $this->raw = $response->getContent(); - $this->sent = $response->getSent(); - $this->headers = $response->getHeaders(); - $this->method = $response->getMethod(); - $this->url = $response->getUrl(); - $this->request_data = $response->getRequestData(); - } - - /** - * Sets up a missing response. - * @access private - */ - protected function noResponse() { - $this->transport_error = 'No page fetched yet'; - $this->raw = false; - $this->sent = false; - $this->headers = false; - $this->method = 'GET'; - $this->url = false; - $this->request_data = false; - } - - /** - * Original request as bytes sent down the wire. - * @return mixed Sent content. - * @access public - */ - function getRequest() { - return $this->sent; - } - - /** - * Accessor for raw text of page. - * @return string Raw unparsed content. - * @access public - */ - function getRaw() { - return $this->raw; - } - - /** - * Accessor for plain text of page as a text browser - * would see it. - * @return string Plain text of page. - * @access public - */ - function getText() { - if (! $this->text) { - $this->text = SimplePage::normalise($this->raw); - } - return $this->text; - } - - /** - * Accessor for raw headers of page. - * @return string Header block as text. - * @access public - */ - function getHeaders() { - if ($this->headers) { - return $this->headers->getRaw(); - } - return false; - } - - /** - * Original request method. - * @return string GET, POST or HEAD. - * @access public - */ - function getMethod() { - return $this->method; - } - - /** - * Original resource name. - * @return SimpleUrl Current url. - * @access public - */ - function getUrl() { - return $this->url; - } - - /** - * Base URL if set via BASE tag page url otherwise - * @return SimpleUrl Base url. - * @access public - */ - function getBaseUrl() { - return $this->base; - } - - /** - * Original request data. - * @return mixed Sent content. - * @access public - */ - function getRequestData() { - return $this->request_data; - } - - /** - * Accessor for last error. - * @return string Error from last response. - * @access public - */ - function getTransportError() { - return $this->transport_error; - } - - /** - * Accessor for current MIME type. - * @return string MIME type as string; e.g. 'text/html' - * @access public - */ - function getMimeType() { - if ($this->headers) { - return $this->headers->getMimeType(); - } - return false; - } - - /** - * Accessor for HTTP response code. - * @return integer HTTP response code received. - * @access public - */ - function getResponseCode() { - if ($this->headers) { - return $this->headers->getResponseCode(); - } - return false; - } - - /** - * Accessor for last Authentication type. Only valid - * straight after a challenge (401). - * @return string Description of challenge type. - * @access public - */ - function getAuthentication() { - if ($this->headers) { - return $this->headers->getAuthentication(); - } - return false; - } - - /** - * Accessor for last Authentication realm. Only valid - * straight after a challenge (401). - * @return string Name of security realm. - * @access public - */ - function getRealm() { - if ($this->headers) { - return $this->headers->getRealm(); - } - return false; - } - - /** - * Accessor for current frame focus. Will be - * false as no frames. - * @return array Always empty. - * @access public - */ - function getFrameFocus() { - return array(); - } - - /** - * Sets the focus by index. The integer index starts from 1. - * @param integer $choice Chosen frame. - * @return boolean Always false. - * @access public - */ - function setFrameFocusByIndex($choice) { - return false; - } - - /** - * Sets the focus by name. Always fails for a leaf page. - * @param string $name Chosen frame. - * @return boolean False as no frames. - * @access public - */ - function setFrameFocus($name) { - return false; - } - - /** - * Clears the frame focus. Does nothing for a leaf page. - * @access public - */ - function clearFrameFocus() { - } - - /** - * TODO: write docs - */ - function setFrames($frames) { - $this->frames = $frames; - } - - /** - * Test to see if link is an absolute one. - * @param string $url Url to test. - * @return boolean True if absolute. - * @access protected - */ - protected function linkIsAbsolute($url) { - $parsed = new SimpleUrl($url); - return (boolean)($parsed->getScheme() && $parsed->getHost()); - } - - /** - * Adds a link to the page. - * @param SimpleAnchorTag $tag Link to accept. - */ - function addLink($tag) { - $this->links[] = $tag; - } - - /** - * Set the forms - * @param array $forms An array of SimpleForm objects - */ - function setForms($forms) { - $this->forms = $forms; - } - - /** - * Test for the presence of a frameset. - * @return boolean True if frameset. - * @access public - */ - function hasFrames() { - return count($this->frames) > 0; - } - - /** - * Accessor for frame name and source URL for every frame that - * will need to be loaded. Immediate children only. - * @return boolean/array False if no frameset or - * otherwise a hash of frame URLs. - * The key is either a numerical - * base one index or the name attribute. - * @access public - */ - function getFrameset() { - if (! $this->hasFrames()) { - return false; - } - $urls = array(); - for ($i = 0; $i < count($this->frames); $i++) { - $name = $this->frames[$i]->getAttribute('name'); - $url = new SimpleUrl($this->frames[$i]->getAttribute('src')); - $urls[$name ? $name : $i + 1] = $this->expandUrl($url); - } - return $urls; - } - - /** - * Fetches a list of loaded frames. - * @return array/string Just the URL for a single page. - * @access public - */ - function getFrames() { - $url = $this->expandUrl($this->getUrl()); - return $url->asString(); - } - - /** - * Accessor for a list of all links. - * @return array List of urls with scheme of - * http or https and hostname. - * @access public - */ - function getUrls() { - $all = array(); - foreach ($this->links as $link) { - $url = $this->getUrlFromLink($link); - $all[] = $url->asString(); - } - return $all; - } - - /** - * Accessor for URLs by the link label. Label will match - * regardess of whitespace issues and case. - * @param string $label Text of link. - * @return array List of links with that label. - * @access public - */ - function getUrlsByLabel($label) { - $matches = array(); - foreach ($this->links as $link) { - if ($link->getText() == $label) { - $matches[] = $this->getUrlFromLink($link); - } - } - return $matches; - } - - /** - * Accessor for a URL by the id attribute. - * @param string $id Id attribute of link. - * @return SimpleUrl URL with that id of false if none. - * @access public - */ - function getUrlById($id) { - foreach ($this->links as $link) { - if ($link->getAttribute('id') === (string)$id) { - return $this->getUrlFromLink($link); - } - } - return false; - } - - /** - * Converts a link tag into a target URL. - * @param SimpleAnchor $link Parsed link. - * @return SimpleUrl URL with frame target if any. - * @access private - */ - protected function getUrlFromLink($link) { - $url = $this->expandUrl($link->getHref()); - if ($link->getAttribute('target')) { - $url->setTarget($link->getAttribute('target')); - } - return $url; - } - - /** - * Expands expandomatic URLs into fully qualified - * URLs. - * @param SimpleUrl $url Relative URL. - * @return SimpleUrl Absolute URL. - * @access public - */ - function expandUrl($url) { - if (! is_object($url)) { - $url = new SimpleUrl($url); - } - $location = $this->getBaseUrl() ? $this->getBaseUrl() : new SimpleUrl(); - return $url->makeAbsolute($location->makeAbsolute($this->getUrl())); - } - - /** - * Sets the base url for the page. - * @param string $url Base URL for page. - */ - function setBase($url) { - $this->base = new SimpleUrl($url); - } - - /** - * Sets the title tag contents. - * @param SimpleTitleTag $tag Title of page. - */ - function setTitle($tag) { - $this->title = $tag; - } - - /** - * Accessor for parsed title. - * @return string Title or false if no title is present. - * @access public - */ - function getTitle() { - if ($this->title) { - return $this->title->getText(); - } - return false; - } - - /** - * Finds a held form by button label. Will only - * search correctly built forms. - * @param SimpleSelector $selector Button finder. - * @return SimpleForm Form object containing - * the button. - * @access public - */ - function getFormBySubmit($selector) { - for ($i = 0; $i < count($this->forms); $i++) { - if ($this->forms[$i]->hasSubmit($selector)) { - return $this->forms[$i]; - } - } - return null; - } - - /** - * Finds a held form by image using a selector. - * Will only search correctly built forms. - * @param SimpleSelector $selector Image finder. - * @return SimpleForm Form object containing - * the image. - * @access public - */ - function getFormByImage($selector) { - for ($i = 0; $i < count($this->forms); $i++) { - if ($this->forms[$i]->hasImage($selector)) { - return $this->forms[$i]; - } - } - return null; - } - - /** - * Finds a held form by the form ID. A way of - * identifying a specific form when we have control - * of the HTML code. - * @param string $id Form label. - * @return SimpleForm Form object containing the matching ID. - * @access public - */ - function getFormById($id) { - for ($i = 0; $i < count($this->forms); $i++) { - if ($this->forms[$i]->getId() == $id) { - return $this->forms[$i]; - } - } - return null; - } - - /** - * Sets a field on each form in which the field is - * available. - * @param SimpleSelector $selector Field finder. - * @param string $value Value to set field to. - * @return boolean True if value is valid. - * @access public - */ - function setField($selector, $value, $position=false) { - $is_set = false; - for ($i = 0; $i < count($this->forms); $i++) { - if ($this->forms[$i]->setField($selector, $value, $position)) { - $is_set = true; - } - } - return $is_set; - } - - /** - * Accessor for a form element value within a page. - * @param SimpleSelector $selector Field finder. - * @return string/boolean A string if the field is - * present, false if unchecked - * and null if missing. - * @access public - */ - function getField($selector) { - for ($i = 0; $i < count($this->forms); $i++) { - $value = $this->forms[$i]->getValue($selector); - if (isset($value)) { - return $value; - } - } - return null; - } - - /** - * Turns HTML into text browser visible text. Images - * are converted to their alt text and tags are supressed. - * Entities are converted to their visible representation. - * @param string $html HTML to convert. - * @return string Plain text. - * @access public - */ - static function normalise($html) { - $text = preg_replace('#<!--.*?-->#si', '', $html); - $text = preg_replace('#<(script|option|textarea)[^>]*>.*?</\1>#si', '', $text); - $text = preg_replace('#<img[^>]*alt\s*=\s*("([^"]*)"|\'([^\']*)\'|([a-zA-Z_]+))[^>]*>#', ' \2\3\4 ', $text); - $text = preg_replace('#<[^>]*>#', '', $text); - $text = html_entity_decode($text, ENT_QUOTES); - $text = preg_replace('#\s+#', ' ', $text); - return trim(trim($text), "\xA0"); // TODO: The \xAO is a . Add a test for this. - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/php_parser.php b/3rdparty/simpletest/php_parser.php deleted file mode 100755 index 4c5b8f00baea25941bb5cafa6b86eed101de9531..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/php_parser.php +++ /dev/null @@ -1,1054 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage WebTester - * @version $Id: php_parser.php 1927 2009-07-31 12:45:36Z dgheath $ - */ - -/**#@+ - * Lexer mode stack constants - */ -foreach (array('LEXER_ENTER', 'LEXER_MATCHED', - 'LEXER_UNMATCHED', 'LEXER_EXIT', - 'LEXER_SPECIAL') as $i => $constant) { - if (! defined($constant)) { - define($constant, $i + 1); - } -} -/**#@-*/ - -/** - * Compounded regular expression. Any of - * the contained patterns could match and - * when one does, it's label is returned. - * @package SimpleTest - * @subpackage WebTester - */ -class ParallelRegex { - private $patterns; - private $labels; - private $regex; - private $case; - - /** - * Constructor. Starts with no patterns. - * @param boolean $case True for case sensitive, false - * for insensitive. - * @access public - */ - function __construct($case) { - $this->case = $case; - $this->patterns = array(); - $this->labels = array(); - $this->regex = null; - } - - /** - * Adds a pattern with an optional label. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $label Label of regex to be returned - * on a match. - * @access public - */ - function addPattern($pattern, $label = true) { - $count = count($this->patterns); - $this->patterns[$count] = $pattern; - $this->labels[$count] = $label; - $this->regex = null; - } - - /** - * Attempts to match all patterns at once against - * a string. - * @param string $subject String to match against. - * @param string $match First matched portion of - * subject. - * @return boolean True on success. - * @access public - */ - function match($subject, &$match) { - if (count($this->patterns) == 0) { - return false; - } - if (! preg_match($this->getCompoundedRegex(), $subject, $matches)) { - $match = ''; - return false; - } - $match = $matches[0]; - for ($i = 1; $i < count($matches); $i++) { - if ($matches[$i]) { - return $this->labels[$i - 1]; - } - } - return true; - } - - /** - * Compounds the patterns into a single - * regular expression separated with the - * "or" operator. Caches the regex. - * Will automatically escape (, ) and / tokens. - * @param array $patterns List of patterns in order. - * @access private - */ - protected function getCompoundedRegex() { - if ($this->regex == null) { - for ($i = 0, $count = count($this->patterns); $i < $count; $i++) { - $this->patterns[$i] = '(' . str_replace( - array('/', '(', ')'), - array('\/', '\(', '\)'), - $this->patterns[$i]) . ')'; - } - $this->regex = "/" . implode("|", $this->patterns) . "/" . $this->getPerlMatchingFlags(); - } - return $this->regex; - } - - /** - * Accessor for perl regex mode flags to use. - * @return string Perl regex flags. - * @access private - */ - protected function getPerlMatchingFlags() { - return ($this->case ? "msS" : "msSi"); - } -} - -/** - * States for a stack machine. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleStateStack { - private $stack; - - /** - * Constructor. Starts in named state. - * @param string $start Starting state name. - * @access public - */ - function __construct($start) { - $this->stack = array($start); - } - - /** - * Accessor for current state. - * @return string State. - * @access public - */ - function getCurrent() { - return $this->stack[count($this->stack) - 1]; - } - - /** - * Adds a state to the stack and sets it - * to be the current state. - * @param string $state New state. - * @access public - */ - function enter($state) { - array_push($this->stack, $state); - } - - /** - * Leaves the current state and reverts - * to the previous one. - * @return boolean False if we drop off - * the bottom of the list. - * @access public - */ - function leave() { - if (count($this->stack) == 1) { - return false; - } - array_pop($this->stack); - return true; - } -} - -/** - * Accepts text and breaks it into tokens. - * Some optimisation to make the sure the - * content is only scanned by the PHP regex - * parser once. Lexer modes must not start - * with leading underscores. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleLexer { - private $regexes; - private $parser; - private $mode; - private $mode_handlers; - private $case; - - /** - * Sets up the lexer in case insensitive matching - * by default. - * @param SimpleSaxParser $parser Handling strategy by - * reference. - * @param string $start Starting handler. - * @param boolean $case True for case sensitive. - * @access public - */ - function __construct($parser, $start = "accept", $case = false) { - $this->case = $case; - $this->regexes = array(); - $this->parser = $parser; - $this->mode = new SimpleStateStack($start); - $this->mode_handlers = array($start => $start); - } - - /** - * Adds a token search pattern for a particular - * parsing mode. The pattern does not change the - * current mode. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Should only apply this - * pattern when dealing with - * this type of input. - * @access public - */ - function addPattern($pattern, $mode = "accept") { - if (! isset($this->regexes[$mode])) { - $this->regexes[$mode] = new ParallelRegex($this->case); - } - $this->regexes[$mode]->addPattern($pattern); - if (! isset($this->mode_handlers[$mode])) { - $this->mode_handlers[$mode] = $mode; - } - } - - /** - * Adds a pattern that will enter a new parsing - * mode. Useful for entering parenthesis, strings, - * tags, etc. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Should only apply this - * pattern when dealing with - * this type of input. - * @param string $new_mode Change parsing to this new - * nested mode. - * @access public - */ - function addEntryPattern($pattern, $mode, $new_mode) { - if (! isset($this->regexes[$mode])) { - $this->regexes[$mode] = new ParallelRegex($this->case); - } - $this->regexes[$mode]->addPattern($pattern, $new_mode); - if (! isset($this->mode_handlers[$new_mode])) { - $this->mode_handlers[$new_mode] = $new_mode; - } - } - - /** - * Adds a pattern that will exit the current mode - * and re-enter the previous one. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Mode to leave. - * @access public - */ - function addExitPattern($pattern, $mode) { - if (! isset($this->regexes[$mode])) { - $this->regexes[$mode] = new ParallelRegex($this->case); - } - $this->regexes[$mode]->addPattern($pattern, "__exit"); - if (! isset($this->mode_handlers[$mode])) { - $this->mode_handlers[$mode] = $mode; - } - } - - /** - * Adds a pattern that has a special mode. Acts as an entry - * and exit pattern in one go, effectively calling a special - * parser handler for this token only. - * @param string $pattern Perl style regex, but ( and ) - * lose the usual meaning. - * @param string $mode Should only apply this - * pattern when dealing with - * this type of input. - * @param string $special Use this mode for this one token. - * @access public - */ - function addSpecialPattern($pattern, $mode, $special) { - if (! isset($this->regexes[$mode])) { - $this->regexes[$mode] = new ParallelRegex($this->case); - } - $this->regexes[$mode]->addPattern($pattern, "_$special"); - if (! isset($this->mode_handlers[$special])) { - $this->mode_handlers[$special] = $special; - } - } - - /** - * Adds a mapping from a mode to another handler. - * @param string $mode Mode to be remapped. - * @param string $handler New target handler. - * @access public - */ - function mapHandler($mode, $handler) { - $this->mode_handlers[$mode] = $handler; - } - - /** - * Splits the page text into tokens. Will fail - * if the handlers report an error or if no - * content is consumed. If successful then each - * unparsed and parsed token invokes a call to the - * held listener. - * @param string $raw Raw HTML text. - * @return boolean True on success, else false. - * @access public - */ - function parse($raw) { - if (! isset($this->parser)) { - return false; - } - $length = strlen($raw); - while (is_array($parsed = $this->reduce($raw))) { - list($raw, $unmatched, $matched, $mode) = $parsed; - if (! $this->dispatchTokens($unmatched, $matched, $mode)) { - return false; - } - if ($raw === '') { - return true; - } - if (strlen($raw) == $length) { - return false; - } - $length = strlen($raw); - } - if (! $parsed) { - return false; - } - return $this->invokeParser($raw, LEXER_UNMATCHED); - } - - /** - * Sends the matched token and any leading unmatched - * text to the parser changing the lexer to a new - * mode if one is listed. - * @param string $unmatched Unmatched leading portion. - * @param string $matched Actual token match. - * @param string $mode Mode after match. A boolean - * false mode causes no change. - * @return boolean False if there was any error - * from the parser. - * @access private - */ - protected function dispatchTokens($unmatched, $matched, $mode = false) { - if (! $this->invokeParser($unmatched, LEXER_UNMATCHED)) { - return false; - } - if (is_bool($mode)) { - return $this->invokeParser($matched, LEXER_MATCHED); - } - if ($this->isModeEnd($mode)) { - if (! $this->invokeParser($matched, LEXER_EXIT)) { - return false; - } - return $this->mode->leave(); - } - if ($this->isSpecialMode($mode)) { - $this->mode->enter($this->decodeSpecial($mode)); - if (! $this->invokeParser($matched, LEXER_SPECIAL)) { - return false; - } - return $this->mode->leave(); - } - $this->mode->enter($mode); - return $this->invokeParser($matched, LEXER_ENTER); - } - - /** - * Tests to see if the new mode is actually to leave - * the current mode and pop an item from the matching - * mode stack. - * @param string $mode Mode to test. - * @return boolean True if this is the exit mode. - * @access private - */ - protected function isModeEnd($mode) { - return ($mode === "__exit"); - } - - /** - * Test to see if the mode is one where this mode - * is entered for this token only and automatically - * leaves immediately afterwoods. - * @param string $mode Mode to test. - * @return boolean True if this is the exit mode. - * @access private - */ - protected function isSpecialMode($mode) { - return (strncmp($mode, "_", 1) == 0); - } - - /** - * Strips the magic underscore marking single token - * modes. - * @param string $mode Mode to decode. - * @return string Underlying mode name. - * @access private - */ - protected function decodeSpecial($mode) { - return substr($mode, 1); - } - - /** - * Calls the parser method named after the current - * mode. Empty content will be ignored. The lexer - * has a parser handler for each mode in the lexer. - * @param string $content Text parsed. - * @param boolean $is_match Token is recognised rather - * than unparsed data. - * @access private - */ - protected function invokeParser($content, $is_match) { - if (($content === '') || ($content === false)) { - return true; - } - $handler = $this->mode_handlers[$this->mode->getCurrent()]; - return $this->parser->$handler($content, $is_match); - } - - /** - * Tries to match a chunk of text and if successful - * removes the recognised chunk and any leading - * unparsed data. Empty strings will not be matched. - * @param string $raw The subject to parse. This is the - * content that will be eaten. - * @return array/boolean Three item list of unparsed - * content followed by the - * recognised token and finally the - * action the parser is to take. - * True if no match, false if there - * is a parsing error. - * @access private - */ - protected function reduce($raw) { - if ($action = $this->regexes[$this->mode->getCurrent()]->match($raw, $match)) { - $unparsed_character_count = strpos($raw, $match); - $unparsed = substr($raw, 0, $unparsed_character_count); - $raw = substr($raw, $unparsed_character_count + strlen($match)); - return array($raw, $unparsed, $match, $action); - } - return true; - } -} - -/** - * Breaks HTML into SAX events. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHtmlLexer extends SimpleLexer { - - /** - * Sets up the lexer with case insensitive matching - * and adds the HTML handlers. - * @param SimpleSaxParser $parser Handling strategy by - * reference. - * @access public - */ - function __construct($parser) { - parent::__construct($parser, 'text'); - $this->mapHandler('text', 'acceptTextToken'); - $this->addSkipping(); - foreach ($this->getParsedTags() as $tag) { - $this->addTag($tag); - } - $this->addInTagTokens(); - } - - /** - * List of parsed tags. Others are ignored. - * @return array List of searched for tags. - * @access private - */ - protected function getParsedTags() { - return array('a', 'base', 'title', 'form', 'input', 'button', 'textarea', 'select', - 'option', 'frameset', 'frame', 'label'); - } - - /** - * The lexer has to skip certain sections such - * as server code, client code and styles. - * @access private - */ - protected function addSkipping() { - $this->mapHandler('css', 'ignore'); - $this->addEntryPattern('<style', 'text', 'css'); - $this->addExitPattern('</style>', 'css'); - $this->mapHandler('js', 'ignore'); - $this->addEntryPattern('<script', 'text', 'js'); - $this->addExitPattern('</script>', 'js'); - $this->mapHandler('comment', 'ignore'); - $this->addEntryPattern('<!--', 'text', 'comment'); - $this->addExitPattern('-->', 'comment'); - } - - /** - * Pattern matches to start and end a tag. - * @param string $tag Name of tag to scan for. - * @access private - */ - protected function addTag($tag) { - $this->addSpecialPattern("</$tag>", 'text', 'acceptEndToken'); - $this->addEntryPattern("<$tag", 'text', 'tag'); - } - - /** - * Pattern matches to parse the inside of a tag - * including the attributes and their quoting. - * @access private - */ - protected function addInTagTokens() { - $this->mapHandler('tag', 'acceptStartToken'); - $this->addSpecialPattern('\s+', 'tag', 'ignore'); - $this->addAttributeTokens(); - $this->addExitPattern('/>', 'tag'); - $this->addExitPattern('>', 'tag'); - } - - /** - * Matches attributes that are either single quoted, - * double quoted or unquoted. - * @access private - */ - protected function addAttributeTokens() { - $this->mapHandler('dq_attribute', 'acceptAttributeToken'); - $this->addEntryPattern('=\s*"', 'tag', 'dq_attribute'); - $this->addPattern("\\\\\"", 'dq_attribute'); - $this->addExitPattern('"', 'dq_attribute'); - $this->mapHandler('sq_attribute', 'acceptAttributeToken'); - $this->addEntryPattern("=\s*'", 'tag', 'sq_attribute'); - $this->addPattern("\\\\'", 'sq_attribute'); - $this->addExitPattern("'", 'sq_attribute'); - $this->mapHandler('uq_attribute', 'acceptAttributeToken'); - $this->addSpecialPattern('=\s*[^>\s]*', 'tag', 'uq_attribute'); - } -} - -/** - * Converts HTML tokens into selected SAX events. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleHtmlSaxParser { - private $lexer; - private $listener; - private $tag; - private $attributes; - private $current_attribute; - - /** - * Sets the listener. - * @param SimplePhpPageBuilder $listener SAX event handler. - * @access public - */ - function __construct($listener) { - $this->listener = $listener; - $this->lexer = $this->createLexer($this); - $this->tag = ''; - $this->attributes = array(); - $this->current_attribute = ''; - } - - /** - * Runs the content through the lexer which - * should call back to the acceptors. - * @param string $raw Page text to parse. - * @return boolean False if parse error. - * @access public - */ - function parse($raw) { - return $this->lexer->parse($raw); - } - - /** - * Sets up the matching lexer. Starts in 'text' mode. - * @param SimpleSaxParser $parser Event generator, usually $self. - * @return SimpleLexer Lexer suitable for this parser. - * @access public - */ - static function createLexer(&$parser) { - return new SimpleHtmlLexer($parser); - } - - /** - * Accepts a token from the tag mode. If the - * starting element completes then the element - * is dispatched and the current attributes - * set back to empty. The element or attribute - * name is converted to lower case. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function acceptStartToken($token, $event) { - if ($event == LEXER_ENTER) { - $this->tag = strtolower(substr($token, 1)); - return true; - } - if ($event == LEXER_EXIT) { - $success = $this->listener->startElement( - $this->tag, - $this->attributes); - $this->tag = ''; - $this->attributes = array(); - return $success; - } - if ($token != '=') { - $this->current_attribute = strtolower(html_entity_decode($token, ENT_QUOTES)); - $this->attributes[$this->current_attribute] = ''; - } - return true; - } - - /** - * Accepts a token from the end tag mode. - * The element name is converted to lower case. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function acceptEndToken($token, $event) { - if (! preg_match('/<\/(.*)>/', $token, $matches)) { - return false; - } - return $this->listener->endElement(strtolower($matches[1])); - } - - /** - * Part of the tag data. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function acceptAttributeToken($token, $event) { - if ($this->current_attribute) { - if ($event == LEXER_UNMATCHED) { - $this->attributes[$this->current_attribute] .= - html_entity_decode($token, ENT_QUOTES); - } - if ($event == LEXER_SPECIAL) { - $this->attributes[$this->current_attribute] .= - preg_replace('/^=\s*/' , '', html_entity_decode($token, ENT_QUOTES)); - } - } - return true; - } - - /** - * A character entity. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function acceptEntityToken($token, $event) { - } - - /** - * Character data between tags regarded as - * important. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function acceptTextToken($token, $event) { - return $this->listener->addContent($token); - } - - /** - * Incoming data to be ignored. - * @param string $token Incoming characters. - * @param integer $event Lexer event type. - * @return boolean False if parse error. - * @access public - */ - function ignore($token, $event) { - return true; - } -} - -/** - * SAX event handler. Maintains a list of - * open tags and dispatches them as they close. - * @package SimpleTest - * @subpackage WebTester - */ -class SimplePhpPageBuilder { - private $tags; - private $page; - private $private_content_tag; - private $open_forms = array(); - private $complete_forms = array(); - private $frameset = false; - private $loading_frames = array(); - private $frameset_nesting_level = 0; - private $left_over_labels = array(); - - /** - * Frees up any references so as to allow the PHP garbage - * collection from unset() to work. - * @access public - */ - function free() { - unset($this->tags); - unset($this->page); - unset($this->private_content_tags); - $this->open_forms = array(); - $this->complete_forms = array(); - $this->frameset = false; - $this->loading_frames = array(); - $this->frameset_nesting_level = 0; - $this->left_over_labels = array(); - } - - /** - * This builder is always available. - * @return boolean Always true. - */ - function can() { - return true; - } - - /** - * Reads the raw content and send events - * into the page to be built. - * @param $response SimpleHttpResponse Fetched response. - * @return SimplePage Newly parsed page. - * @access public - */ - function parse($response) { - $this->tags = array(); - $this->page = $this->createPage($response); - $parser = $this->createParser($this); - $parser->parse($response->getContent()); - $this->acceptPageEnd(); - $page = $this->page; - $this->free(); - return $page; - } - - /** - * Creates an empty page. - * @return SimplePage New unparsed page. - * @access protected - */ - protected function createPage($response) { - return new SimplePage($response); - } - - /** - * Creates the parser used with the builder. - * @param SimplePhpPageBuilder $listener Target of parser. - * @return SimpleSaxParser Parser to generate - * events for the builder. - * @access protected - */ - protected function createParser(&$listener) { - return new SimpleHtmlSaxParser($listener); - } - - /** - * Start of element event. Opens a new tag. - * @param string $name Element name. - * @param hash $attributes Attributes without content - * are marked as true. - * @return boolean False on parse error. - * @access public - */ - function startElement($name, $attributes) { - $factory = new SimpleTagBuilder(); - $tag = $factory->createTag($name, $attributes); - if (! $tag) { - return true; - } - if ($tag->getTagName() == 'label') { - $this->acceptLabelStart($tag); - $this->openTag($tag); - return true; - } - if ($tag->getTagName() == 'form') { - $this->acceptFormStart($tag); - return true; - } - if ($tag->getTagName() == 'frameset') { - $this->acceptFramesetStart($tag); - return true; - } - if ($tag->getTagName() == 'frame') { - $this->acceptFrame($tag); - return true; - } - if ($tag->isPrivateContent() && ! isset($this->private_content_tag)) { - $this->private_content_tag = &$tag; - } - if ($tag->expectEndTag()) { - $this->openTag($tag); - return true; - } - $this->acceptTag($tag); - return true; - } - - /** - * End of element event. - * @param string $name Element name. - * @return boolean False on parse error. - * @access public - */ - function endElement($name) { - if ($name == 'label') { - $this->acceptLabelEnd(); - return true; - } - if ($name == 'form') { - $this->acceptFormEnd(); - return true; - } - if ($name == 'frameset') { - $this->acceptFramesetEnd(); - return true; - } - if ($this->hasNamedTagOnOpenTagStack($name)) { - $tag = array_pop($this->tags[$name]); - if ($tag->isPrivateContent() && $this->private_content_tag->getTagName() == $name) { - unset($this->private_content_tag); - } - $this->addContentTagToOpenTags($tag); - $this->acceptTag($tag); - return true; - } - return true; - } - - /** - * Test to see if there are any open tags awaiting - * closure that match the tag name. - * @param string $name Element name. - * @return boolean True if any are still open. - * @access private - */ - protected function hasNamedTagOnOpenTagStack($name) { - return isset($this->tags[$name]) && (count($this->tags[$name]) > 0); - } - - /** - * Unparsed, but relevant data. The data is added - * to every open tag. - * @param string $text May include unparsed tags. - * @return boolean False on parse error. - * @access public - */ - function addContent($text) { - if (isset($this->private_content_tag)) { - $this->private_content_tag->addContent($text); - } else { - $this->addContentToAllOpenTags($text); - } - return true; - } - - /** - * Any content fills all currently open tags unless it - * is part of an option tag. - * @param string $text May include unparsed tags. - * @access private - */ - protected function addContentToAllOpenTags($text) { - foreach (array_keys($this->tags) as $name) { - for ($i = 0, $count = count($this->tags[$name]); $i < $count; $i++) { - $this->tags[$name][$i]->addContent($text); - } - } - } - - /** - * Parsed data in tag form. The parsed tag is added - * to every open tag. Used for adding options to select - * fields only. - * @param SimpleTag $tag Option tags only. - * @access private - */ - protected function addContentTagToOpenTags(&$tag) { - if ($tag->getTagName() != 'option') { - return; - } - foreach (array_keys($this->tags) as $name) { - for ($i = 0, $count = count($this->tags[$name]); $i < $count; $i++) { - $this->tags[$name][$i]->addTag($tag); - } - } - } - - /** - * Opens a tag for receiving content. Multiple tags - * will be receiving input at the same time. - * @param SimpleTag $tag New content tag. - * @access private - */ - protected function openTag($tag) { - $name = $tag->getTagName(); - if (! in_array($name, array_keys($this->tags))) { - $this->tags[$name] = array(); - } - $this->tags[$name][] = $tag; - } - - /** - * Adds a tag to the page. - * @param SimpleTag $tag Tag to accept. - * @access public - */ - protected function acceptTag($tag) { - if ($tag->getTagName() == "a") { - $this->page->addLink($tag); - } elseif ($tag->getTagName() == "base") { - $this->page->setBase($tag->getAttribute('href')); - } elseif ($tag->getTagName() == "title") { - $this->page->setTitle($tag); - } elseif ($this->isFormElement($tag->getTagName())) { - for ($i = 0; $i < count($this->open_forms); $i++) { - $this->open_forms[$i]->addWidget($tag); - } - $this->last_widget = $tag; - } - } - - /** - * Opens a label for a described widget. - * @param SimpleFormTag $tag Tag to accept. - * @access public - */ - protected function acceptLabelStart($tag) { - $this->label = $tag; - unset($this->last_widget); - } - - /** - * Closes the most recently opened label. - * @access public - */ - protected function acceptLabelEnd() { - if (isset($this->label)) { - if (isset($this->last_widget)) { - $this->last_widget->setLabel($this->label->getText()); - unset($this->last_widget); - } else { - $this->left_over_labels[] = SimpleTestCompatibility::copy($this->label); - } - unset($this->label); - } - } - - /** - * Tests to see if a tag is a possible form - * element. - * @param string $name HTML element name. - * @return boolean True if form element. - * @access private - */ - protected function isFormElement($name) { - return in_array($name, array('input', 'button', 'textarea', 'select')); - } - - /** - * Opens a form. New widgets go here. - * @param SimpleFormTag $tag Tag to accept. - * @access public - */ - protected function acceptFormStart($tag) { - $this->open_forms[] = new SimpleForm($tag, $this->page); - } - - /** - * Closes the most recently opened form. - * @access public - */ - protected function acceptFormEnd() { - if (count($this->open_forms)) { - $this->complete_forms[] = array_pop($this->open_forms); - } - } - - /** - * Opens a frameset. A frameset may contain nested - * frameset tags. - * @param SimpleFramesetTag $tag Tag to accept. - * @access public - */ - protected function acceptFramesetStart($tag) { - if (! $this->isLoadingFrames()) { - $this->frameset = $tag; - } - $this->frameset_nesting_level++; - } - - /** - * Closes the most recently opened frameset. - * @access public - */ - protected function acceptFramesetEnd() { - if ($this->isLoadingFrames()) { - $this->frameset_nesting_level--; - } - } - - /** - * Takes a single frame tag and stashes it in - * the current frame set. - * @param SimpleFrameTag $tag Tag to accept. - * @access public - */ - protected function acceptFrame($tag) { - if ($this->isLoadingFrames()) { - if ($tag->getAttribute('src')) { - $this->loading_frames[] = $tag; - } - } - } - - /** - * Test to see if in the middle of reading - * a frameset. - * @return boolean True if inframeset. - * @access private - */ - protected function isLoadingFrames() { - return $this->frameset and $this->frameset_nesting_level > 0; - } - - /** - * Marker for end of complete page. Any work in - * progress can now be closed. - * @access public - */ - protected function acceptPageEnd() { - while (count($this->open_forms)) { - $this->complete_forms[] = array_pop($this->open_forms); - } - foreach ($this->left_over_labels as $label) { - for ($i = 0, $count = count($this->complete_forms); $i < $count; $i++) { - $this->complete_forms[$i]->attachLabelBySelector( - new SimpleById($label->getFor()), - $label->getText()); - } - } - $this->page->setForms($this->complete_forms); - $this->page->setFrames($this->loading_frames); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/recorder.php b/3rdparty/simpletest/recorder.php deleted file mode 100644 index b3d0d01c62555a4b9fb4f493529649a282c26bcf..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/recorder.php +++ /dev/null @@ -1,101 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage Extensions - * @author Rene vd O (original code) - * @author Perrick Penet - * @author Marcus Baker - * @version $Id: recorder.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/** - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/scorer.php'); - -/** - * A single test result. - * @package SimpleTest - * @subpackage Extensions - */ -abstract class SimpleResult { - public $time; - public $breadcrumb; - public $message; - - /** - * Records the test result as public members. - * @param array $breadcrumb Test stack at the time of the event. - * @param string $message The messsage to the human. - */ - function __construct($breadcrumb, $message) { - list($this->time, $this->breadcrumb, $this->message) = - array(time(), $breadcrumb, $message); - } -} - -/** - * A single pass captured for later. - * @package SimpleTest - * @subpackage Extensions - */ -class SimpleResultOfPass extends SimpleResult { } - -/** - * A single failure captured for later. - * @package SimpleTest - * @subpackage Extensions - */ -class SimpleResultOfFail extends SimpleResult { } - -/** - * A single exception captured for later. - * @package SimpleTest - * @subpackage Extensions - */ -class SimpleResultOfException extends SimpleResult { } - -/** - * Array-based test recorder. Returns an array - * with timestamp, status, test name and message for each pass and failure. - * @package SimpleTest - * @subpackage Extensions - */ -class Recorder extends SimpleReporterDecorator { - public $results = array(); - - /** - * Stashes the pass as a SimpleResultOfPass - * for later retrieval. - * @param string $message Pass message to be displayed - * eventually. - */ - function paintPass($message) { - parent::paintPass($message); - $this->results[] = new SimpleResultOfPass(parent::getTestList(), $message); - } - - /** - * Stashes the fail as a SimpleResultOfFail - * for later retrieval. - * @param string $message Failure message to be displayed - * eventually. - */ - function paintFail($message) { - parent::paintFail($message); - $this->results[] = new SimpleResultOfFail(parent::getTestList(), $message); - } - - /** - * Stashes the exception as a SimpleResultOfException - * for later retrieval. - * @param string $message Exception message to be displayed - * eventually. - */ - function paintException($message) { - parent::paintException($message); - $this->results[] = new SimpleResultOfException(parent::getTestList(), $message); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/reflection_php4.php b/3rdparty/simpletest/reflection_php4.php deleted file mode 100644 index 39801ea1bdbac0932187a41eb6bfd1d90647dabe..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/reflection_php4.php +++ /dev/null @@ -1,136 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: reflection_php4.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/** - * Version specific reflection API. - * @package SimpleTest - * @subpackage UnitTester - * @ignore duplicate with reflection_php5.php - */ -class SimpleReflection { - var $_interface; - - /** - * Stashes the class/interface. - * @param string $interface Class or interface - * to inspect. - */ - function SimpleReflection($interface) { - $this->_interface = $interface; - } - - /** - * Checks that a class has been declared. - * @return boolean True if defined. - * @access public - */ - function classExists() { - return class_exists($this->_interface); - } - - /** - * Needed to kill the autoload feature in PHP5 - * for classes created dynamically. - * @return boolean True if defined. - * @access public - */ - function classExistsSansAutoload() { - return class_exists($this->_interface); - } - - /** - * Checks that a class or interface has been - * declared. - * @return boolean True if defined. - * @access public - */ - function classOrInterfaceExists() { - return class_exists($this->_interface); - } - - /** - * Needed to kill the autoload feature in PHP5 - * for classes created dynamically. - * @return boolean True if defined. - * @access public - */ - function classOrInterfaceExistsSansAutoload() { - return class_exists($this->_interface); - } - - /** - * Gets the list of methods on a class or - * interface. - * @returns array List of method names. - * @access public - */ - function getMethods() { - return get_class_methods($this->_interface); - } - - /** - * Gets the list of interfaces from a class. If the - * class name is actually an interface then just that - * interface is returned. - * @returns array List of interfaces. - * @access public - */ - function getInterfaces() { - return array(); - } - - /** - * Finds the parent class name. - * @returns string Parent class name. - * @access public - */ - function getParent() { - return strtolower(get_parent_class($this->_interface)); - } - - /** - * Determines if the class is abstract, which for PHP 4 - * will never be the case. - * @returns boolean True if abstract. - * @access public - */ - function isAbstract() { - return false; - } - - /** - * Determines if the the entity is an interface, which for PHP 4 - * will never be the case. - * @returns boolean True if interface. - * @access public - */ - function isInterface() { - return false; - } - - /** - * Scans for final methods, but as it's PHP 4 there - * aren't any. - * @returns boolean True if the class has a final method. - * @access public - */ - function hasFinal() { - return false; - } - - /** - * Gets the source code matching the declaration - * of a method. - * @param string $method Method name. - * @access public - */ - function getSignature($method) { - return "function &$method()"; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/reflection_php5.php b/3rdparty/simpletest/reflection_php5.php deleted file mode 100644 index 43d8a7b287f5b095aa1cb0a111a48607e996da68..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/reflection_php5.php +++ /dev/null @@ -1,386 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: reflection_php5.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/** - * Version specific reflection API. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleReflection { - private $interface; - - /** - * Stashes the class/interface. - * @param string $interface Class or interface - * to inspect. - */ - function __construct($interface) { - $this->interface = $interface; - } - - /** - * Checks that a class has been declared. Versions - * before PHP5.0.2 need a check that it's not really - * an interface. - * @return boolean True if defined. - * @access public - */ - function classExists() { - if (! class_exists($this->interface)) { - return false; - } - $reflection = new ReflectionClass($this->interface); - return ! $reflection->isInterface(); - } - - /** - * Needed to kill the autoload feature in PHP5 - * for classes created dynamically. - * @return boolean True if defined. - * @access public - */ - function classExistsSansAutoload() { - return class_exists($this->interface, false); - } - - /** - * Checks that a class or interface has been - * declared. - * @return boolean True if defined. - * @access public - */ - function classOrInterfaceExists() { - return $this->classOrInterfaceExistsWithAutoload($this->interface, true); - } - - /** - * Needed to kill the autoload feature in PHP5 - * for classes created dynamically. - * @return boolean True if defined. - * @access public - */ - function classOrInterfaceExistsSansAutoload() { - return $this->classOrInterfaceExistsWithAutoload($this->interface, false); - } - - /** - * Needed to select the autoload feature in PHP5 - * for classes created dynamically. - * @param string $interface Class or interface name. - * @param boolean $autoload True totriggerautoload. - * @return boolean True if interface defined. - * @access private - */ - protected function classOrInterfaceExistsWithAutoload($interface, $autoload) { - if (function_exists('interface_exists')) { - if (interface_exists($this->interface, $autoload)) { - return true; - } - } - return class_exists($this->interface, $autoload); - } - - /** - * Gets the list of methods on a class or - * interface. - * @returns array List of method names. - * @access public - */ - function getMethods() { - return array_unique(get_class_methods($this->interface)); - } - - /** - * Gets the list of interfaces from a class. If the - * class name is actually an interface then just that - * interface is returned. - * @returns array List of interfaces. - * @access public - */ - function getInterfaces() { - $reflection = new ReflectionClass($this->interface); - if ($reflection->isInterface()) { - return array($this->interface); - } - return $this->onlyParents($reflection->getInterfaces()); - } - - /** - * Gets the list of methods for the implemented - * interfaces only. - * @returns array List of enforced method signatures. - * @access public - */ - function getInterfaceMethods() { - $methods = array(); - foreach ($this->getInterfaces() as $interface) { - $methods = array_merge($methods, get_class_methods($interface)); - } - return array_unique($methods); - } - - /** - * Checks to see if the method signature has to be tightly - * specified. - * @param string $method Method name. - * @returns boolean True if enforced. - * @access private - */ - protected function isInterfaceMethod($method) { - return in_array($method, $this->getInterfaceMethods()); - } - - /** - * Finds the parent class name. - * @returns string Parent class name. - * @access public - */ - function getParent() { - $reflection = new ReflectionClass($this->interface); - $parent = $reflection->getParentClass(); - if ($parent) { - return $parent->getName(); - } - return false; - } - - /** - * Trivially determines if the class is abstract. - * @returns boolean True if abstract. - * @access public - */ - function isAbstract() { - $reflection = new ReflectionClass($this->interface); - return $reflection->isAbstract(); - } - - /** - * Trivially determines if the class is an interface. - * @returns boolean True if interface. - * @access public - */ - function isInterface() { - $reflection = new ReflectionClass($this->interface); - return $reflection->isInterface(); - } - - /** - * Scans for final methods, as they screw up inherited - * mocks by not allowing you to override them. - * @returns boolean True if the class has a final method. - * @access public - */ - function hasFinal() { - $reflection = new ReflectionClass($this->interface); - foreach ($reflection->getMethods() as $method) { - if ($method->isFinal()) { - return true; - } - } - return false; - } - - /** - * Whittles a list of interfaces down to only the - * necessary top level parents. - * @param array $interfaces Reflection API interfaces - * to reduce. - * @returns array List of parent interface names. - * @access private - */ - protected function onlyParents($interfaces) { - $parents = array(); - $blacklist = array(); - foreach ($interfaces as $interface) { - foreach($interfaces as $possible_parent) { - if ($interface->getName() == $possible_parent->getName()) { - continue; - } - if ($interface->isSubClassOf($possible_parent)) { - $blacklist[$possible_parent->getName()] = true; - } - } - if (!isset($blacklist[$interface->getName()])) { - $parents[] = $interface->getName(); - } - } - return $parents; - } - - /** - * Checks whether a method is abstract or not. - * @param string $name Method name. - * @return bool true if method is abstract, else false - * @access private - */ - protected function isAbstractMethod($name) { - $interface = new ReflectionClass($this->interface); - if (! $interface->hasMethod($name)) { - return false; - } - return $interface->getMethod($name)->isAbstract(); - } - - /** - * Checks whether a method is the constructor. - * @param string $name Method name. - * @return bool true if method is the constructor - * @access private - */ - protected function isConstructor($name) { - return ($name == '__construct') || ($name == $this->interface); - } - - /** - * Checks whether a method is abstract in all parents or not. - * @param string $name Method name. - * @return bool true if method is abstract in parent, else false - * @access private - */ - protected function isAbstractMethodInParents($name) { - $interface = new ReflectionClass($this->interface); - $parent = $interface->getParentClass(); - while($parent) { - if (! $parent->hasMethod($name)) { - return false; - } - if ($parent->getMethod($name)->isAbstract()) { - return true; - } - $parent = $parent->getParentClass(); - } - return false; - } - - /** - * Checks whether a method is static or not. - * @param string $name Method name - * @return bool true if method is static, else false - * @access private - */ - protected function isStaticMethod($name) { - $interface = new ReflectionClass($this->interface); - if (! $interface->hasMethod($name)) { - return false; - } - return $interface->getMethod($name)->isStatic(); - } - - /** - * Writes the source code matching the declaration - * of a method. - * @param string $name Method name. - * @return string Method signature up to last - * bracket. - * @access public - */ - function getSignature($name) { - if ($name == '__set') { - return 'function __set($key, $value)'; - } - if ($name == '__call') { - return 'function __call($method, $arguments)'; - } - if (version_compare(phpversion(), '5.1.0', '>=')) { - if (in_array($name, array('__get', '__isset', $name == '__unset'))) { - return "function {$name}(\$key)"; - } - } - if ($name == '__toString') { - return "function $name()"; - } - - // This wonky try-catch is a work around for a faulty method_exists() - // in early versions of PHP 5 which would return false for static - // methods. The Reflection classes work fine, but hasMethod() - // doesn't exist prior to PHP 5.1.0, so we need to use a more crude - // detection method. - try { - $interface = new ReflectionClass($this->interface); - $interface->getMethod($name); - } catch (ReflectionException $e) { - return "function $name()"; - } - return $this->getFullSignature($name); - } - - /** - * For a signature specified in an interface, full - * details must be replicated to be a valid implementation. - * @param string $name Method name. - * @return string Method signature up to last - * bracket. - * @access private - */ - protected function getFullSignature($name) { - $interface = new ReflectionClass($this->interface); - $method = $interface->getMethod($name); - $reference = $method->returnsReference() ? '&' : ''; - $static = $method->isStatic() ? 'static ' : ''; - return "{$static}function $reference$name(" . - implode(', ', $this->getParameterSignatures($method)) . - ")"; - } - - /** - * Gets the source code for each parameter. - * @param ReflectionMethod $method Method object from - * reflection API - * @return array List of strings, each - * a snippet of code. - * @access private - */ - protected function getParameterSignatures($method) { - $signatures = array(); - foreach ($method->getParameters() as $parameter) { - $signature = ''; - $type = $parameter->getClass(); - if (is_null($type) && version_compare(phpversion(), '5.1.0', '>=') && $parameter->isArray()) { - $signature .= 'array '; - } elseif (!is_null($type)) { - $signature .= $type->getName() . ' '; - } - if ($parameter->isPassedByReference()) { - $signature .= '&'; - } - $signature .= '$' . $this->suppressSpurious($parameter->getName()); - if ($this->isOptional($parameter)) { - $signature .= ' = null'; - } - $signatures[] = $signature; - } - return $signatures; - } - - /** - * The SPL library has problems with the - * Reflection library. In particular, you can - * get extra characters in parameter names :(. - * @param string $name Parameter name. - * @return string Cleaner name. - * @access private - */ - protected function suppressSpurious($name) { - return str_replace(array('[', ']', ' '), '', $name); - } - - /** - * Test of a reflection parameter being optional - * that works with early versions of PHP5. - * @param reflectionParameter $parameter Is this optional. - * @return boolean True if optional. - * @access private - */ - protected function isOptional($parameter) { - if (method_exists($parameter, 'isOptional')) { - return $parameter->isOptional(); - } - return false; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/remote.php b/3rdparty/simpletest/remote.php deleted file mode 100644 index 4bb37b7c51b1192f9a0882ba33ca55817ae01f4b..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/remote.php +++ /dev/null @@ -1,115 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: remote.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/browser.php'); -require_once(dirname(__FILE__) . '/xml.php'); -require_once(dirname(__FILE__) . '/test_case.php'); -/**#@-*/ - -/** - * Runs an XML formated test on a remote server. - * @package SimpleTest - * @subpackage UnitTester - */ -class RemoteTestCase { - private $url; - private $dry_url; - private $size; - - /** - * Sets the location of the remote test. - * @param string $url Test location. - * @param string $dry_url Location for dry run. - * @access public - */ - function __construct($url, $dry_url = false) { - $this->url = $url; - $this->dry_url = $dry_url ? $dry_url : $url; - $this->size = false; - } - - /** - * Accessor for the test name for subclasses. - * @return string Name of the test. - * @access public - */ - function getLabel() { - return $this->url; - } - - /** - * Runs the top level test for this class. Currently - * reads the data as a single chunk. I'll fix this - * once I have added iteration to the browser. - * @param SimpleReporter $reporter Target of test results. - * @returns boolean True if no failures. - * @access public - */ - function run($reporter) { - $browser = $this->createBrowser(); - $xml = $browser->get($this->url); - if (! $xml) { - trigger_error('Cannot read remote test URL [' . $this->url . ']'); - return false; - } - $parser = $this->createParser($reporter); - if (! $parser->parse($xml)) { - trigger_error('Cannot parse incoming XML from [' . $this->url . ']'); - return false; - } - return true; - } - - /** - * Creates a new web browser object for fetching - * the XML report. - * @return SimpleBrowser New browser. - * @access protected - */ - protected function createBrowser() { - return new SimpleBrowser(); - } - - /** - * Creates the XML parser. - * @param SimpleReporter $reporter Target of test results. - * @return SimpleTestXmlListener XML reader. - * @access protected - */ - protected function createParser($reporter) { - return new SimpleTestXmlParser($reporter); - } - - /** - * Accessor for the number of subtests. - * @return integer Number of test cases. - * @access public - */ - function getSize() { - if ($this->size === false) { - $browser = $this->createBrowser(); - $xml = $browser->get($this->dry_url); - if (! $xml) { - trigger_error('Cannot read remote test URL [' . $this->dry_url . ']'); - return false; - } - $reporter = new SimpleReporter(); - $parser = $this->createParser($reporter); - if (! $parser->parse($xml)) { - trigger_error('Cannot parse incoming XML from [' . $this->dry_url . ']'); - return false; - } - $this->size = $reporter->getTestCaseCount(); - } - return $this->size; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/reporter.php b/3rdparty/simpletest/reporter.php deleted file mode 100755 index bd4f3fa41dd2e4c569e07a88a66734851981dfc2..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/reporter.php +++ /dev/null @@ -1,445 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: reporter.php 2005 2010-11-02 14:09:34Z lastcraft $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/scorer.php'); -//require_once(dirname(__FILE__) . '/arguments.php'); -/**#@-*/ - -/** - * Sample minimal test displayer. Generates only - * failure messages and a pass count. - * @package SimpleTest - * @subpackage UnitTester - */ -class HtmlReporter extends SimpleReporter { - private $character_set; - - /** - * Does nothing yet. The first output will - * be sent on the first test start. For use - * by a web browser. - * @access public - */ - function __construct($character_set = 'ISO-8859-1') { - parent::__construct(); - $this->character_set = $character_set; - } - - /** - * Paints the top of the web page setting the - * title to the name of the starting test. - * @param string $test_name Name class of test. - * @access public - */ - function paintHeader($test_name) { - $this->sendNoCacheHeaders(); - print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"; - print "<html>\n<head>\n<title>$test_name</title>\n"; - print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" . - $this->character_set . "\">\n"; - print "<style type=\"text/css\">\n"; - print $this->getCss() . "\n"; - print "</style>\n"; - print "</head>\n<body>\n"; - print "<h1>$test_name</h1>\n"; - flush(); - } - - /** - * Send the headers necessary to ensure the page is - * reloaded on every request. Otherwise you could be - * scratching your head over out of date test data. - * @access public - */ - static function sendNoCacheHeaders() { - if (! headers_sent()) { - header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); - header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); - header("Cache-Control: no-store, no-cache, must-revalidate"); - header("Cache-Control: post-check=0, pre-check=0", false); - header("Pragma: no-cache"); - } - } - - /** - * Paints the CSS. Add additional styles here. - * @return string CSS code as text. - * @access protected - */ - protected function getCss() { - return ".fail { background-color: inherit; color: red; }" . - ".pass { background-color: inherit; color: green; }" . - " pre { background-color: lightgray; color: inherit; }"; - } - - /** - * Paints the end of the test with a summary of - * the passes and failures. - * @param string $test_name Name class of test. - * @access public - */ - function paintFooter($test_name) { - $colour = ($this->getFailCount() + $this->getExceptionCount() > 0 ? "red" : "green"); - print "<div style=\""; - print "padding: 8px; margin-top: 1em; background-color: $colour; color: white;"; - print "\">"; - print $this->getTestCaseProgress() . "/" . $this->getTestCaseCount(); - print " test cases complete:\n"; - print "<strong>" . $this->getPassCount() . "</strong> passes, "; - print "<strong>" . $this->getFailCount() . "</strong> fails and "; - print "<strong>" . $this->getExceptionCount() . "</strong> exceptions."; - print "</div>\n"; - print "</body>\n</html>\n"; - } - - /** - * Paints the test failure with a breadcrumbs - * trail of the nesting test suites below the - * top level test. - * @param string $message Failure message displayed in - * the context of the other tests. - */ - function paintFail($message) { - parent::paintFail($message); - print "<span class=\"fail\">Fail</span>: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . $this->htmlEntities($message) . "<br />\n"; - } - - /** - * Paints a PHP error. - * @param string $message Message is ignored. - * @access public - */ - function paintError($message) { - parent::paintError($message); - print "<span class=\"fail\">Exception</span>: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> <strong>" . $this->htmlEntities($message) . "</strong><br />\n"; - } - - /** - * Paints a PHP exception. - * @param Exception $exception Exception to display. - * @access public - */ - function paintException($exception) { - parent::paintException($exception); - print "<span class=\"fail\">Exception</span>: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - $message = 'Unexpected exception of type [' . get_class($exception) . - '] with message ['. $exception->getMessage() . - '] in ['. $exception->getFile() . - ' line ' . $exception->getLine() . ']'; - print " -> <strong>" . $this->htmlEntities($message) . "</strong><br />\n"; - } - - /** - * Prints the message for skipping tests. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { - parent::paintSkip($message); - print "<span class=\"pass\">Skipped</span>: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . $this->htmlEntities($message) . "<br />\n"; - } - - /** - * Paints formatted text such as dumped privateiables. - * @param string $message Text to show. - * @access public - */ - function paintFormattedMessage($message) { - print '<pre>' . $this->htmlEntities($message) . '</pre>'; - } - - /** - * Character set adjusted entity conversion. - * @param string $message Plain text or Unicode message. - * @return string Browser readable message. - * @access protected - */ - protected function htmlEntities($message) { - return htmlentities($message, ENT_COMPAT, $this->character_set); - } -} - -/** - * Sample minimal test displayer. Generates only - * failure messages and a pass count. For command - * line use. I've tried to make it look like JUnit, - * but I wanted to output the errors as they arrived - * which meant dropping the dots. - * @package SimpleTest - * @subpackage UnitTester - */ -class TextReporter extends SimpleReporter { - - /** - * Does nothing yet. The first output will - * be sent on the first test start. - */ - function __construct() { - parent::__construct(); - } - - /** - * Paints the title only. - * @param string $test_name Name class of test. - * @access public - */ - function paintHeader($test_name) { - if (! SimpleReporter::inCli()) { - header('Content-type: text/plain'); - } - print "$test_name\n"; - flush(); - } - - /** - * Paints the end of the test with a summary of - * the passes and failures. - * @param string $test_name Name class of test. - * @access public - */ - function paintFooter($test_name) { - if ($this->getFailCount() + $this->getExceptionCount() == 0) { - print "OK\n"; - } else { - print "FAILURES!!!\n"; - } - print "Test cases run: " . $this->getTestCaseProgress() . - "/" . $this->getTestCaseCount() . - ", Passes: " . $this->getPassCount() . - ", Failures: " . $this->getFailCount() . - ", Exceptions: " . $this->getExceptionCount() . "\n"; - } - - /** - * Paints the test failure as a stack trace. - * @param string $message Failure message displayed in - * the context of the other tests. - * @access public - */ - function paintFail($message) { - parent::paintFail($message); - print $this->getFailCount() . ") $message\n"; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); - print "\n"; - } - - /** - * Paints a PHP error or exception. - * @param string $message Message to be shown. - * @access public - * @abstract - */ - function paintError($message) { - parent::paintError($message); - print "Exception " . $this->getExceptionCount() . "!\n$message\n"; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); - print "\n"; - } - - /** - * Paints a PHP error or exception. - * @param Exception $exception Exception to describe. - * @access public - * @abstract - */ - function paintException($exception) { - parent::paintException($exception); - $message = 'Unexpected exception of type [' . get_class($exception) . - '] with message ['. $exception->getMessage() . - '] in ['. $exception->getFile() . - ' line ' . $exception->getLine() . ']'; - print "Exception " . $this->getExceptionCount() . "!\n$message\n"; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); - print "\n"; - } - - /** - * Prints the message for skipping tests. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { - parent::paintSkip($message); - print "Skip: $message\n"; - } - - /** - * Paints formatted text such as dumped privateiables. - * @param string $message Text to show. - * @access public - */ - function paintFormattedMessage($message) { - print "$message\n"; - flush(); - } -} - -/** - * Runs just a single test group, a single case or - * even a single test within that case. - * @package SimpleTest - * @subpackage UnitTester - */ -class SelectiveReporter extends SimpleReporterDecorator { - private $just_this_case = false; - private $just_this_test = false; - private $on; - - /** - * Selects the test case or group to be run, - * and optionally a specific test. - * @param SimpleScorer $reporter Reporter to receive events. - * @param string $just_this_case Only this case or group will run. - * @param string $just_this_test Only this test method will run. - */ - function __construct($reporter, $just_this_case = false, $just_this_test = false) { - if (isset($just_this_case) && $just_this_case) { - $this->just_this_case = strtolower($just_this_case); - $this->off(); - } else { - $this->on(); - } - if (isset($just_this_test) && $just_this_test) { - $this->just_this_test = strtolower($just_this_test); - } - parent::__construct($reporter); - } - - /** - * Compares criteria to actual the case/group name. - * @param string $test_case The incoming test. - * @return boolean True if matched. - * @access protected - */ - protected function matchesTestCase($test_case) { - return $this->just_this_case == strtolower($test_case); - } - - /** - * Compares criteria to actual the test name. If no - * name was specified at the beginning, then all tests - * can run. - * @param string $method The incoming test method. - * @return boolean True if matched. - * @access protected - */ - protected function shouldRunTest($test_case, $method) { - if ($this->isOn() || $this->matchesTestCase($test_case)) { - if ($this->just_this_test) { - return $this->just_this_test == strtolower($method); - } else { - return true; - } - } - return false; - } - - /** - * Switch on testing for the group or subgroup. - * @access private - */ - protected function on() { - $this->on = true; - } - - /** - * Switch off testing for the group or subgroup. - * @access private - */ - protected function off() { - $this->on = false; - } - - /** - * Is this group actually being tested? - * @return boolean True if the current test group is active. - * @access private - */ - protected function isOn() { - return $this->on; - } - - /** - * Veto everything that doesn't match the method wanted. - * @param string $test_case Name of test case. - * @param string $method Name of test method. - * @return boolean True if test should be run. - * @access public - */ - function shouldInvoke($test_case, $method) { - if ($this->shouldRunTest($test_case, $method)) { - return $this->reporter->shouldInvoke($test_case, $method); - } - return false; - } - - /** - * Paints the start of a group test. - * @param string $test_case Name of test or other label. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_case, $size) { - if ($this->just_this_case && $this->matchesTestCase($test_case)) { - $this->on(); - } - $this->reporter->paintGroupStart($test_case, $size); - } - - /** - * Paints the end of a group test. - * @param string $test_case Name of test or other label. - * @access public - */ - function paintGroupEnd($test_case) { - $this->reporter->paintGroupEnd($test_case); - if ($this->just_this_case && $this->matchesTestCase($test_case)) { - $this->off(); - } - } -} - -/** - * Suppresses skip messages. - * @package SimpleTest - * @subpackage UnitTester - */ -class NoSkipsReporter extends SimpleReporterDecorator { - - /** - * Does nothing. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/scorer.php b/3rdparty/simpletest/scorer.php deleted file mode 100644 index 27776f4b63156c06ec63e6b7a7882dae9ad77a27..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/scorer.php +++ /dev/null @@ -1,875 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: scorer.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/**#@+*/ -require_once(dirname(__FILE__) . '/invoker.php'); -/**#@-*/ - -/** - * Can receive test events and display them. Display - * is achieved by making display methods available - * and visiting the incoming event. - * @package SimpleTest - * @subpackage UnitTester - * @abstract - */ -class SimpleScorer { - private $passes; - private $fails; - private $exceptions; - private $is_dry_run; - - /** - * Starts the test run with no results. - * @access public - */ - function __construct() { - $this->passes = 0; - $this->fails = 0; - $this->exceptions = 0; - $this->is_dry_run = false; - } - - /** - * Signals that the next evaluation will be a dry - * run. That is, the structure events will be - * recorded, but no tests will be run. - * @param boolean $is_dry Dry run if true. - * @access public - */ - function makeDry($is_dry = true) { - $this->is_dry_run = $is_dry; - } - - /** - * The reporter has a veto on what should be run. - * @param string $test_case_name name of test case. - * @param string $method Name of test method. - * @access public - */ - function shouldInvoke($test_case_name, $method) { - return ! $this->is_dry_run; - } - - /** - * Can wrap the invoker in preperation for running - * a test. - * @param SimpleInvoker $invoker Individual test runner. - * @return SimpleInvoker Wrapped test runner. - * @access public - */ - function createInvoker($invoker) { - return $invoker; - } - - /** - * Accessor for current status. Will be false - * if there have been any failures or exceptions. - * Used for command line tools. - * @return boolean True if no failures. - * @access public - */ - function getStatus() { - if ($this->exceptions + $this->fails > 0) { - return false; - } - return true; - } - - /** - * Paints the start of a group test. - * @param string $test_name Name of test or other label. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_name, $size) { - } - - /** - * Paints the end of a group test. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintGroupEnd($test_name) { - } - - /** - * Paints the start of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseStart($test_name) { - } - - /** - * Paints the end of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseEnd($test_name) { - } - - /** - * Paints the start of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodStart($test_name) { - } - - /** - * Paints the end of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodEnd($test_name) { - } - - /** - * Increments the pass count. - * @param string $message Message is ignored. - * @access public - */ - function paintPass($message) { - $this->passes++; - } - - /** - * Increments the fail count. - * @param string $message Message is ignored. - * @access public - */ - function paintFail($message) { - $this->fails++; - } - - /** - * Deals with PHP 4 throwing an error. - * @param string $message Text of error formatted by - * the test case. - * @access public - */ - function paintError($message) { - $this->exceptions++; - } - - /** - * Deals with PHP 5 throwing an exception. - * @param Exception $exception The actual exception thrown. - * @access public - */ - function paintException($exception) { - $this->exceptions++; - } - - /** - * Prints the message for skipping tests. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { - } - - /** - * Accessor for the number of passes so far. - * @return integer Number of passes. - * @access public - */ - function getPassCount() { - return $this->passes; - } - - /** - * Accessor for the number of fails so far. - * @return integer Number of fails. - * @access public - */ - function getFailCount() { - return $this->fails; - } - - /** - * Accessor for the number of untrapped errors - * so far. - * @return integer Number of exceptions. - * @access public - */ - function getExceptionCount() { - return $this->exceptions; - } - - /** - * Paints a simple supplementary message. - * @param string $message Text to display. - * @access public - */ - function paintMessage($message) { - } - - /** - * Paints a formatted ASCII message such as a - * privateiable dump. - * @param string $message Text to display. - * @access public - */ - function paintFormattedMessage($message) { - } - - /** - * By default just ignores user generated events. - * @param string $type Event type as text. - * @param mixed $payload Message or object. - * @access public - */ - function paintSignal($type, $payload) { - } -} - -/** - * Recipient of generated test messages that can display - * page footers and headers. Also keeps track of the - * test nesting. This is the main base class on which - * to build the finished test (page based) displays. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleReporter extends SimpleScorer { - private $test_stack; - private $size; - private $progress; - - /** - * Starts the display with no results in. - * @access public - */ - function __construct() { - parent::__construct(); - $this->test_stack = array(); - $this->size = null; - $this->progress = 0; - } - - /** - * Gets the formatter for small generic data items. - * @return SimpleDumper Formatter. - * @access public - */ - function getDumper() { - return new SimpleDumper(); - } - - /** - * Paints the start of a group test. Will also paint - * the page header and footer if this is the - * first test. Will stash the size if the first - * start. - * @param string $test_name Name of test that is starting. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_name, $size) { - if (! isset($this->size)) { - $this->size = $size; - } - if (count($this->test_stack) == 0) { - $this->paintHeader($test_name); - } - $this->test_stack[] = $test_name; - } - - /** - * Paints the end of a group test. Will paint the page - * footer if the stack of tests has unwound. - * @param string $test_name Name of test that is ending. - * @param integer $progress Number of test cases ending. - * @access public - */ - function paintGroupEnd($test_name) { - array_pop($this->test_stack); - if (count($this->test_stack) == 0) { - $this->paintFooter($test_name); - } - } - - /** - * Paints the start of a test case. Will also paint - * the page header and footer if this is the - * first test. Will stash the size if the first - * start. - * @param string $test_name Name of test that is starting. - * @access public - */ - function paintCaseStart($test_name) { - if (! isset($this->size)) { - $this->size = 1; - } - if (count($this->test_stack) == 0) { - $this->paintHeader($test_name); - } - $this->test_stack[] = $test_name; - } - - /** - * Paints the end of a test case. Will paint the page - * footer if the stack of tests has unwound. - * @param string $test_name Name of test that is ending. - * @access public - */ - function paintCaseEnd($test_name) { - $this->progress++; - array_pop($this->test_stack); - if (count($this->test_stack) == 0) { - $this->paintFooter($test_name); - } - } - - /** - * Paints the start of a test method. - * @param string $test_name Name of test that is starting. - * @access public - */ - function paintMethodStart($test_name) { - $this->test_stack[] = $test_name; - } - - /** - * Paints the end of a test method. Will paint the page - * footer if the stack of tests has unwound. - * @param string $test_name Name of test that is ending. - * @access public - */ - function paintMethodEnd($test_name) { - array_pop($this->test_stack); - } - - /** - * Paints the test document header. - * @param string $test_name First test top level - * to start. - * @access public - * @abstract - */ - function paintHeader($test_name) { - } - - /** - * Paints the test document footer. - * @param string $test_name The top level test. - * @access public - * @abstract - */ - function paintFooter($test_name) { - } - - /** - * Accessor for internal test stack. For - * subclasses that need to see the whole test - * history for display purposes. - * @return array List of methods in nesting order. - * @access public - */ - function getTestList() { - return $this->test_stack; - } - - /** - * Accessor for total test size in number - * of test cases. Null until the first - * test is started. - * @return integer Total number of cases at start. - * @access public - */ - function getTestCaseCount() { - return $this->size; - } - - /** - * Accessor for the number of test cases - * completed so far. - * @return integer Number of ended cases. - * @access public - */ - function getTestCaseProgress() { - return $this->progress; - } - - /** - * Static check for running in the comand line. - * @return boolean True if CLI. - * @access public - */ - static function inCli() { - return php_sapi_name() == 'cli'; - } -} - -/** - * For modifying the behaviour of the visual reporters. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleReporterDecorator { - protected $reporter; - - /** - * Mediates between the reporter and the test case. - * @param SimpleScorer $reporter Reporter to receive events. - */ - function __construct($reporter) { - $this->reporter = $reporter; - } - - /** - * Signals that the next evaluation will be a dry - * run. That is, the structure events will be - * recorded, but no tests will be run. - * @param boolean $is_dry Dry run if true. - * @access public - */ - function makeDry($is_dry = true) { - $this->reporter->makeDry($is_dry); - } - - /** - * Accessor for current status. Will be false - * if there have been any failures or exceptions. - * Used for command line tools. - * @return boolean True if no failures. - * @access public - */ - function getStatus() { - return $this->reporter->getStatus(); - } - - /** - * The nesting of the test cases so far. Not - * all reporters have this facility. - * @return array Test list if accessible. - * @access public - */ - function getTestList() { - if (method_exists($this->reporter, 'getTestList')) { - return $this->reporter->getTestList(); - } else { - return array(); - } - } - - /** - * The reporter has a veto on what should be run. - * @param string $test_case_name Name of test case. - * @param string $method Name of test method. - * @return boolean True if test should be run. - * @access public - */ - function shouldInvoke($test_case_name, $method) { - return $this->reporter->shouldInvoke($test_case_name, $method); - } - - /** - * Can wrap the invoker in preparation for running - * a test. - * @param SimpleInvoker $invoker Individual test runner. - * @return SimpleInvoker Wrapped test runner. - * @access public - */ - function createInvoker($invoker) { - return $this->reporter->createInvoker($invoker); - } - - /** - * Gets the formatter for privateiables and other small - * generic data items. - * @return SimpleDumper Formatter. - * @access public - */ - function getDumper() { - return $this->reporter->getDumper(); - } - - /** - * Paints the start of a group test. - * @param string $test_name Name of test or other label. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_name, $size) { - $this->reporter->paintGroupStart($test_name, $size); - } - - /** - * Paints the end of a group test. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintGroupEnd($test_name) { - $this->reporter->paintGroupEnd($test_name); - } - - /** - * Paints the start of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseStart($test_name) { - $this->reporter->paintCaseStart($test_name); - } - - /** - * Paints the end of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseEnd($test_name) { - $this->reporter->paintCaseEnd($test_name); - } - - /** - * Paints the start of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodStart($test_name) { - $this->reporter->paintMethodStart($test_name); - } - - /** - * Paints the end of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodEnd($test_name) { - $this->reporter->paintMethodEnd($test_name); - } - - /** - * Chains to the wrapped reporter. - * @param string $message Message is ignored. - * @access public - */ - function paintPass($message) { - $this->reporter->paintPass($message); - } - - /** - * Chains to the wrapped reporter. - * @param string $message Message is ignored. - * @access public - */ - function paintFail($message) { - $this->reporter->paintFail($message); - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text of error formatted by - * the test case. - * @access public - */ - function paintError($message) { - $this->reporter->paintError($message); - } - - /** - * Chains to the wrapped reporter. - * @param Exception $exception Exception to show. - * @access public - */ - function paintException($exception) { - $this->reporter->paintException($exception); - } - - /** - * Prints the message for skipping tests. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { - $this->reporter->paintSkip($message); - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text to display. - * @access public - */ - function paintMessage($message) { - $this->reporter->paintMessage($message); - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text to display. - * @access public - */ - function paintFormattedMessage($message) { - $this->reporter->paintFormattedMessage($message); - } - - /** - * Chains to the wrapped reporter. - * @param string $type Event type as text. - * @param mixed $payload Message or object. - * @return boolean Should return false if this - * type of signal should fail the - * test suite. - * @access public - */ - function paintSignal($type, $payload) { - $this->reporter->paintSignal($type, $payload); - } -} - -/** - * For sending messages to multiple reporters at - * the same time. - * @package SimpleTest - * @subpackage UnitTester - */ -class MultipleReporter { - private $reporters = array(); - - /** - * Adds a reporter to the subscriber list. - * @param SimpleScorer $reporter Reporter to receive events. - * @access public - */ - function attachReporter($reporter) { - $this->reporters[] = $reporter; - } - - /** - * Signals that the next evaluation will be a dry - * run. That is, the structure events will be - * recorded, but no tests will be run. - * @param boolean $is_dry Dry run if true. - * @access public - */ - function makeDry($is_dry = true) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->makeDry($is_dry); - } - } - - /** - * Accessor for current status. Will be false - * if there have been any failures or exceptions. - * If any reporter reports a failure, the whole - * suite fails. - * @return boolean True if no failures. - * @access public - */ - function getStatus() { - for ($i = 0; $i < count($this->reporters); $i++) { - if (! $this->reporters[$i]->getStatus()) { - return false; - } - } - return true; - } - - /** - * The reporter has a veto on what should be run. - * It requires all reporters to want to run the method. - * @param string $test_case_name name of test case. - * @param string $method Name of test method. - * @access public - */ - function shouldInvoke($test_case_name, $method) { - for ($i = 0; $i < count($this->reporters); $i++) { - if (! $this->reporters[$i]->shouldInvoke($test_case_name, $method)) { - return false; - } - } - return true; - } - - /** - * Every reporter gets a chance to wrap the invoker. - * @param SimpleInvoker $invoker Individual test runner. - * @return SimpleInvoker Wrapped test runner. - * @access public - */ - function createInvoker($invoker) { - for ($i = 0; $i < count($this->reporters); $i++) { - $invoker = $this->reporters[$i]->createInvoker($invoker); - } - return $invoker; - } - - /** - * Gets the formatter for privateiables and other small - * generic data items. - * @return SimpleDumper Formatter. - * @access public - */ - function getDumper() { - return new SimpleDumper(); - } - - /** - * Paints the start of a group test. - * @param string $test_name Name of test or other label. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_name, $size) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintGroupStart($test_name, $size); - } - } - - /** - * Paints the end of a group test. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintGroupEnd($test_name) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintGroupEnd($test_name); - } - } - - /** - * Paints the start of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseStart($test_name) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintCaseStart($test_name); - } - } - - /** - * Paints the end of a test case. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintCaseEnd($test_name) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintCaseEnd($test_name); - } - } - - /** - * Paints the start of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodStart($test_name) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintMethodStart($test_name); - } - } - - /** - * Paints the end of a test method. - * @param string $test_name Name of test or other label. - * @access public - */ - function paintMethodEnd($test_name) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintMethodEnd($test_name); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $message Message is ignored. - * @access public - */ - function paintPass($message) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintPass($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $message Message is ignored. - * @access public - */ - function paintFail($message) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintFail($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text of error formatted by - * the test case. - * @access public - */ - function paintError($message) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintError($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param Exception $exception Exception to display. - * @access public - */ - function paintException($exception) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintException($exception); - } - } - - /** - * Prints the message for skipping tests. - * @param string $message Text of skip condition. - * @access public - */ - function paintSkip($message) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintSkip($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text to display. - * @access public - */ - function paintMessage($message) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintMessage($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $message Text to display. - * @access public - */ - function paintFormattedMessage($message) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintFormattedMessage($message); - } - } - - /** - * Chains to the wrapped reporter. - * @param string $type Event type as text. - * @param mixed $payload Message or object. - * @return boolean Should return false if this - * type of signal should fail the - * test suite. - * @access public - */ - function paintSignal($type, $payload) { - for ($i = 0; $i < count($this->reporters); $i++) { - $this->reporters[$i]->paintSignal($type, $payload); - } - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/selector.php b/3rdparty/simpletest/selector.php deleted file mode 100755 index ba2fed312a870dcfe46096406a89915fe7a2ad05..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/selector.php +++ /dev/null @@ -1,141 +0,0 @@ -<?php -/** - * Base include file for SimpleTest. - * @package SimpleTest - * @subpackage WebTester - * @version $Id: selector.php 1786 2008-04-26 17:32:20Z pp11 $ - */ - -/**#@+ - * include SimpleTest files - */ -require_once(dirname(__FILE__) . '/tag.php'); -require_once(dirname(__FILE__) . '/encoding.php'); -/**#@-*/ - -/** - * Used to extract form elements for testing against. - * Searches by name attribute. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleByName { - private $name; - - /** - * Stashes the name for later comparison. - * @param string $name Name attribute to match. - */ - function __construct($name) { - $this->name = $name; - } - - /** - * Accessor for name. - * @returns string $name Name to match. - */ - function getName() { - return $this->name; - } - - /** - * Compares with name attribute of widget. - * @param SimpleWidget $widget Control to compare. - * @access public - */ - function isMatch($widget) { - return ($widget->getName() == $this->name); - } -} - -/** - * Used to extract form elements for testing against. - * Searches by visible label or alt text. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleByLabel { - private $label; - - /** - * Stashes the name for later comparison. - * @param string $label Visible text to match. - */ - function __construct($label) { - $this->label = $label; - } - - /** - * Comparison. Compares visible text of widget or - * related label. - * @param SimpleWidget $widget Control to compare. - * @access public - */ - function isMatch($widget) { - if (! method_exists($widget, 'isLabel')) { - return false; - } - return $widget->isLabel($this->label); - } -} - -/** - * Used to extract form elements for testing against. - * Searches dy id attribute. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleById { - private $id; - - /** - * Stashes the name for later comparison. - * @param string $id ID atribute to match. - */ - function __construct($id) { - $this->id = $id; - } - - /** - * Comparison. Compares id attribute of widget. - * @param SimpleWidget $widget Control to compare. - * @access public - */ - function isMatch($widget) { - return $widget->isId($this->id); - } -} - -/** - * Used to extract form elements for testing against. - * Searches by visible label, name or alt text. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleByLabelOrName { - private $label; - - /** - * Stashes the name/label for later comparison. - * @param string $label Visible text to match. - */ - function __construct($label) { - $this->label = $label; - } - - /** - * Comparison. Compares visible text of widget or - * related label or name. - * @param SimpleWidget $widget Control to compare. - * @access public - */ - function isMatch($widget) { - if (method_exists($widget, 'isLabel')) { - if ($widget->isLabel($this->label)) { - return true; - } - } - return ($widget->getName() == $this->label); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/shell_tester.php b/3rdparty/simpletest/shell_tester.php deleted file mode 100644 index 9a3bd389eeb5b28970941fb37029ffd5fe2c79bb..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/shell_tester.php +++ /dev/null @@ -1,330 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: shell_tester.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/test_case.php'); -/**#@-*/ - -/** - * Wrapper for exec() functionality. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleShell { - private $output; - - /** - * Executes the shell comand and stashes the output. - * @access public - */ - function __construct() { - $this->output = false; - } - - /** - * Actually runs the command. Does not trap the - * error stream output as this need PHP 4.3+. - * @param string $command The actual command line - * to run. - * @return integer Exit code. - * @access public - */ - function execute($command) { - $this->output = false; - exec($command, $this->output, $ret); - return $ret; - } - - /** - * Accessor for the last output. - * @return string Output as text. - * @access public - */ - function getOutput() { - return implode("\n", $this->output); - } - - /** - * Accessor for the last output. - * @return array Output as array of lines. - * @access public - */ - function getOutputAsList() { - return $this->output; - } -} - -/** - * Test case for testing of command line scripts and - * utilities. Usually scripts that are external to the - * PHP code, but support it in some way. - * @package SimpleTest - * @subpackage UnitTester - */ -class ShellTestCase extends SimpleTestCase { - private $current_shell; - private $last_status; - private $last_command; - - /** - * Creates an empty test case. Should be subclassed - * with test methods for a functional test case. - * @param string $label Name of test case. Will use - * the class name if none specified. - * @access public - */ - function __construct($label = false) { - parent::__construct($label); - $this->current_shell = $this->createShell(); - $this->last_status = false; - $this->last_command = ''; - } - - /** - * Executes a command and buffers the results. - * @param string $command Command to run. - * @return boolean True if zero exit code. - * @access public - */ - function execute($command) { - $shell = $this->getShell(); - $this->last_status = $shell->execute($command); - $this->last_command = $command; - return ($this->last_status === 0); - } - - /** - * Dumps the output of the last command. - * @access public - */ - function dumpOutput() { - $this->dump($this->getOutput()); - } - - /** - * Accessor for the last output. - * @return string Output as text. - * @access public - */ - function getOutput() { - $shell = $this->getShell(); - return $shell->getOutput(); - } - - /** - * Accessor for the last output. - * @return array Output as array of lines. - * @access public - */ - function getOutputAsList() { - $shell = $this->getShell(); - return $shell->getOutputAsList(); - } - - /** - * Called from within the test methods to register - * passes and failures. - * @param boolean $result Pass on true. - * @param string $message Message to display describing - * the test state. - * @return boolean True on pass - * @access public - */ - function assertTrue($result, $message = false) { - return $this->assert(new TrueExpectation(), $result, $message); - } - - /** - * Will be true on false and vice versa. False - * is the PHP definition of false, so that null, - * empty strings, zero and an empty array all count - * as false. - * @param boolean $result Pass on false. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertFalse($result, $message = '%s') { - return $this->assert(new FalseExpectation(), $result, $message); - } - - /** - * Will trigger a pass if the two parameters have - * the same value only. Otherwise a fail. This - * is for testing hand extracted text, etc. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertEqual($first, $second, $message = "%s") { - return $this->assert( - new EqualExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * a different value. Otherwise a fail. This - * is for testing hand extracted text, etc. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNotEqual($first, $second, $message = "%s") { - return $this->assert( - new NotEqualExpectation($first), - $second, - $message); - } - - /** - * Tests the last status code from the shell. - * @param integer $status Expected status of last - * command. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertExitCode($status, $message = "%s") { - $message = sprintf($message, "Expected status code of [$status] from [" . - $this->last_command . "], but got [" . - $this->last_status . "]"); - return $this->assertTrue($status === $this->last_status, $message); - } - - /** - * Attempt to exactly match the combined STDERR and - * STDOUT output. - * @param string $expected Expected output. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertOutput($expected, $message = "%s") { - $shell = $this->getShell(); - return $this->assert( - new EqualExpectation($expected), - $shell->getOutput(), - $message); - } - - /** - * Scans the output for a Perl regex. If found - * anywhere it passes, else it fails. - * @param string $pattern Regex to search for. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertOutputPattern($pattern, $message = "%s") { - $shell = $this->getShell(); - return $this->assert( - new PatternExpectation($pattern), - $shell->getOutput(), - $message); - } - - /** - * If a Perl regex is found anywhere in the current - * output then a failure is generated, else a pass. - * @param string $pattern Regex to search for. - * @param $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoOutputPattern($pattern, $message = "%s") { - $shell = $this->getShell(); - return $this->assert( - new NoPatternExpectation($pattern), - $shell->getOutput(), - $message); - } - - /** - * File existence check. - * @param string $path Full filename and path. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertFileExists($path, $message = "%s") { - $message = sprintf($message, "File [$path] should exist"); - return $this->assertTrue(file_exists($path), $message); - } - - /** - * File non-existence check. - * @param string $path Full filename and path. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertFileNotExists($path, $message = "%s") { - $message = sprintf($message, "File [$path] should not exist"); - return $this->assertFalse(file_exists($path), $message); - } - - /** - * Scans a file for a Perl regex. If found - * anywhere it passes, else it fails. - * @param string $pattern Regex to search for. - * @param string $path Full filename and path. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertFilePattern($pattern, $path, $message = "%s") { - return $this->assert( - new PatternExpectation($pattern), - implode('', file($path)), - $message); - } - - /** - * If a Perl regex is found anywhere in the named - * file then a failure is generated, else a pass. - * @param string $pattern Regex to search for. - * @param string $path Full filename and path. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoFilePattern($pattern, $path, $message = "%s") { - return $this->assert( - new NoPatternExpectation($pattern), - implode('', file($path)), - $message); - } - - /** - * Accessor for current shell. Used for testing the - * the tester itself. - * @return Shell Current shell. - * @access protected - */ - protected function getShell() { - return $this->current_shell; - } - - /** - * Factory for the shell to run the command on. - * @return Shell New shell object. - * @access protected - */ - protected function createShell() { - return new SimpleShell(); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/simpletest.php b/3rdparty/simpletest/simpletest.php deleted file mode 100644 index 425c869a8253dd7b768b7bbf65b3ae2f78a940ec..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/simpletest.php +++ /dev/null @@ -1,391 +0,0 @@ -<?php -/** - * Global state for SimpleTest and kicker script in future versions. - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: simpletest.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/**#@+ - * include SimpleTest files - */ -require_once(dirname(__FILE__) . '/reflection_php5.php'); -require_once(dirname(__FILE__) . '/default_reporter.php'); -require_once(dirname(__FILE__) . '/compatibility.php'); -/**#@-*/ - -/** - * Registry and test context. Includes a few - * global options that I'm slowly getting rid of. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleTest { - - /** - * Reads the SimpleTest version from the release file. - * @return string Version string. - */ - static function getVersion() { - $content = file(dirname(__FILE__) . '/VERSION'); - return trim($content[0]); - } - - /** - * Sets the name of a test case to ignore, usually - * because the class is an abstract case that should - * @param string $class Add a class to ignore. - */ - static function ignore($class) { - $registry = &SimpleTest::getRegistry(); - $registry['IgnoreList'][strtolower($class)] = true; - } - - /** - * Scans the now complete ignore list, and adds - * all parent classes to the list. If a class - * is not a runnable test case, then it's parents - * wouldn't be either. This is syntactic sugar - * to cut down on ommissions of ignore()'s or - * missing abstract declarations. This cannot - * be done whilst loading classes wiithout forcing - * a particular order on the class declarations and - * the ignore() calls. It's just nice to have the ignore() - * calls at the top of the file before the actual declarations. - * @param array $classes Class names of interest. - */ - static function ignoreParentsIfIgnored($classes) { - $registry = &SimpleTest::getRegistry(); - foreach ($classes as $class) { - if (SimpleTest::isIgnored($class)) { - $reflection = new SimpleReflection($class); - if ($parent = $reflection->getParent()) { - SimpleTest::ignore($parent); - } - } - } - } - - /** - * Puts the object to the global pool of 'preferred' objects - * which can be retrieved with SimpleTest :: preferred() method. - * Instances of the same class are overwritten. - * @param object $object Preferred object - * @see preferred() - */ - static function prefer($object) { - $registry = &SimpleTest::getRegistry(); - $registry['Preferred'][] = $object; - } - - /** - * Retrieves 'preferred' objects from global pool. Class filter - * can be applied in order to retrieve the object of the specific - * class - * @param array|string $classes Allowed classes or interfaces. - * @return array|object|null - * @see prefer() - */ - static function preferred($classes) { - if (! is_array($classes)) { - $classes = array($classes); - } - $registry = &SimpleTest::getRegistry(); - for ($i = count($registry['Preferred']) - 1; $i >= 0; $i--) { - foreach ($classes as $class) { - if (SimpleTestCompatibility::isA($registry['Preferred'][$i], $class)) { - return $registry['Preferred'][$i]; - } - } - } - return null; - } - - /** - * Test to see if a test case is in the ignore - * list. Quite obviously the ignore list should - * be a separate object and will be one day. - * This method is internal to SimpleTest. Don't - * use it. - * @param string $class Class name to test. - * @return boolean True if should not be run. - */ - static function isIgnored($class) { - $registry = &SimpleTest::getRegistry(); - return isset($registry['IgnoreList'][strtolower($class)]); - } - - /** - * Sets proxy to use on all requests for when - * testing from behind a firewall. Set host - * to false to disable. This will take effect - * if there are no other proxy settings. - * @param string $proxy Proxy host as URL. - * @param string $username Proxy username for authentication. - * @param string $password Proxy password for authentication. - */ - static function useProxy($proxy, $username = false, $password = false) { - $registry = &SimpleTest::getRegistry(); - $registry['DefaultProxy'] = $proxy; - $registry['DefaultProxyUsername'] = $username; - $registry['DefaultProxyPassword'] = $password; - } - - /** - * Accessor for default proxy host. - * @return string Proxy URL. - */ - static function getDefaultProxy() { - $registry = &SimpleTest::getRegistry(); - return $registry['DefaultProxy']; - } - - /** - * Accessor for default proxy username. - * @return string Proxy username for authentication. - */ - static function getDefaultProxyUsername() { - $registry = &SimpleTest::getRegistry(); - return $registry['DefaultProxyUsername']; - } - - /** - * Accessor for default proxy password. - * @return string Proxy password for authentication. - */ - static function getDefaultProxyPassword() { - $registry = &SimpleTest::getRegistry(); - return $registry['DefaultProxyPassword']; - } - - /** - * Accessor for default HTML parsers. - * @return array List of parsers to try in - * order until one responds true - * to can(). - */ - static function getParsers() { - $registry = &SimpleTest::getRegistry(); - return $registry['Parsers']; - } - - /** - * Set the list of HTML parsers to attempt to use by default. - * @param array $parsers List of parsers to try in - * order until one responds true - * to can(). - */ - static function setParsers($parsers) { - $registry = &SimpleTest::getRegistry(); - $registry['Parsers'] = $parsers; - } - - /** - * Accessor for global registry of options. - * @return hash All stored values. - */ - protected static function &getRegistry() { - static $registry = false; - if (! $registry) { - $registry = SimpleTest::getDefaults(); - } - return $registry; - } - - /** - * Accessor for the context of the current - * test run. - * @return SimpleTestContext Current test run. - */ - static function getContext() { - static $context = false; - if (! $context) { - $context = new SimpleTestContext(); - } - return $context; - } - - /** - * Constant default values. - * @return hash All registry defaults. - */ - protected static function getDefaults() { - return array( - 'Parsers' => false, - 'MockBaseClass' => 'SimpleMock', - 'IgnoreList' => array(), - 'DefaultProxy' => false, - 'DefaultProxyUsername' => false, - 'DefaultProxyPassword' => false, - 'Preferred' => array(new HtmlReporter(), new TextReporter(), new XmlReporter())); - } - - /** - * @deprecated - */ - static function setMockBaseClass($mock_base) { - $registry = &SimpleTest::getRegistry(); - $registry['MockBaseClass'] = $mock_base; - } - - /** - * @deprecated - */ - static function getMockBaseClass() { - $registry = &SimpleTest::getRegistry(); - return $registry['MockBaseClass']; - } -} - -/** - * Container for all components for a specific - * test run. Makes things like error queues - * available to PHP event handlers, and also - * gets around some nasty reference issues in - * the mocks. - * @package SimpleTest - */ -class SimpleTestContext { - private $test; - private $reporter; - private $resources; - - /** - * Clears down the current context. - * @access public - */ - function clear() { - $this->resources = array(); - } - - /** - * Sets the current test case instance. This - * global instance can be used by the mock objects - * to send message to the test cases. - * @param SimpleTestCase $test Test case to register. - */ - function setTest($test) { - $this->clear(); - $this->test = $test; - } - - /** - * Accessor for currently running test case. - * @return SimpleTestCase Current test. - */ - function getTest() { - return $this->test; - } - - /** - * Sets the current reporter. This - * global instance can be used by the mock objects - * to send messages. - * @param SimpleReporter $reporter Reporter to register. - */ - function setReporter($reporter) { - $this->clear(); - $this->reporter = $reporter; - } - - /** - * Accessor for current reporter. - * @return SimpleReporter Current reporter. - */ - function getReporter() { - return $this->reporter; - } - - /** - * Accessor for the Singleton resource. - * @return object Global resource. - */ - function get($resource) { - if (! isset($this->resources[$resource])) { - $this->resources[$resource] = new $resource(); - } - return $this->resources[$resource]; - } -} - -/** - * Interrogates the stack trace to recover the - * failure point. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleStackTrace { - private $prefixes; - - /** - * Stashes the list of target prefixes. - * @param array $prefixes List of method prefixes - * to search for. - */ - function __construct($prefixes) { - $this->prefixes = $prefixes; - } - - /** - * Extracts the last method name that was not within - * Simpletest itself. Captures a stack trace if none given. - * @param array $stack List of stack frames. - * @return string Snippet of test report with line - * number and file. - */ - function traceMethod($stack = false) { - $stack = $stack ? $stack : $this->captureTrace(); - foreach ($stack as $frame) { - if ($this->frameLiesWithinSimpleTestFolder($frame)) { - continue; - } - if ($this->frameMatchesPrefix($frame)) { - return ' at [' . $frame['file'] . ' line ' . $frame['line'] . ']'; - } - } - return ''; - } - - /** - * Test to see if error is generated by SimpleTest itself. - * @param array $frame PHP stack frame. - * @return boolean True if a SimpleTest file. - */ - protected function frameLiesWithinSimpleTestFolder($frame) { - if (isset($frame['file'])) { - $path = substr(SIMPLE_TEST, 0, -1); - if (strpos($frame['file'], $path) === 0) { - if (dirname($frame['file']) == $path) { - return true; - } - } - } - return false; - } - - /** - * Tries to determine if the method call is an assert, etc. - * @param array $frame PHP stack frame. - * @return boolean True if matches a target. - */ - protected function frameMatchesPrefix($frame) { - foreach ($this->prefixes as $prefix) { - if (strncmp($frame['function'], $prefix, strlen($prefix)) == 0) { - return true; - } - } - return false; - } - - /** - * Grabs a current stack trace. - * @return array Fulle trace. - */ - protected function captureTrace() { - if (function_exists('debug_backtrace')) { - return array_reverse(debug_backtrace()); - } - return array(); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/socket.php b/3rdparty/simpletest/socket.php deleted file mode 100755 index 06e8ca62d0098ffe128d3d1854f15d5ba5157ab2..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/socket.php +++ /dev/null @@ -1,312 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage MockObjects - * @version $Id: socket.php 1953 2009-09-20 01:26:25Z jsweat $ - */ - -/**#@+ - * include SimpleTest files - */ -require_once(dirname(__FILE__) . '/compatibility.php'); -/**#@-*/ - -/** - * Stashes an error for later. Useful for constructors - * until PHP gets exceptions. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleStickyError { - private $error = 'Constructor not chained'; - - /** - * Sets the error to empty. - * @access public - */ - function __construct() { - $this->clearError(); - } - - /** - * Test for an outstanding error. - * @return boolean True if there is an error. - * @access public - */ - function isError() { - return ($this->error != ''); - } - - /** - * Accessor for an outstanding error. - * @return string Empty string if no error otherwise - * the error message. - * @access public - */ - function getError() { - return $this->error; - } - - /** - * Sets the internal error. - * @param string Error message to stash. - * @access protected - */ - function setError($error) { - $this->error = $error; - } - - /** - * Resets the error state to no error. - * @access protected - */ - function clearError() { - $this->setError(''); - } -} - -/** - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleFileSocket extends SimpleStickyError { - private $handle; - private $is_open = false; - private $sent = ''; - private $block_size; - - /** - * Opens a socket for reading and writing. - * @param SimpleUrl $file Target URI to fetch. - * @param integer $block_size Size of chunk to read. - * @access public - */ - function __construct($file, $block_size = 1024) { - parent::__construct(); - if (! ($this->handle = $this->openFile($file, $error))) { - $file_string = $file->asString(); - $this->setError("Cannot open [$file_string] with [$error]"); - return; - } - $this->is_open = true; - $this->block_size = $block_size; - } - - /** - * Writes some data to the socket and saves alocal copy. - * @param string $message String to send to socket. - * @return boolean True if successful. - * @access public - */ - function write($message) { - return true; - } - - /** - * Reads data from the socket. The error suppresion - * is a workaround for PHP4 always throwing a warning - * with a secure socket. - * @return integer/boolean Incoming bytes. False - * on error. - * @access public - */ - function read() { - $raw = @fread($this->handle, $this->block_size); - if ($raw === false) { - $this->setError('Cannot read from socket'); - $this->close(); - } - return $raw; - } - - /** - * Accessor for socket open state. - * @return boolean True if open. - * @access public - */ - function isOpen() { - return $this->is_open; - } - - /** - * Closes the socket preventing further reads. - * Cannot be reopened once closed. - * @return boolean True if successful. - * @access public - */ - function close() { - if (!$this->is_open) return false; - $this->is_open = false; - return fclose($this->handle); - } - - /** - * Accessor for content so far. - * @return string Bytes sent only. - * @access public - */ - function getSent() { - return $this->sent; - } - - /** - * Actually opens the low level socket. - * @param SimpleUrl $file SimpleUrl file target. - * @param string $error Recipient of error message. - * @param integer $timeout Maximum time to wait for connection. - * @access protected - */ - protected function openFile($file, &$error) { - return @fopen($file->asString(), 'r'); - } -} - -/** - * Wrapper for TCP/IP socket. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleSocket extends SimpleStickyError { - private $handle; - private $is_open = false; - private $sent = ''; - private $lock_size; - - /** - * Opens a socket for reading and writing. - * @param string $host Hostname to send request to. - * @param integer $port Port on remote machine to open. - * @param integer $timeout Connection timeout in seconds. - * @param integer $block_size Size of chunk to read. - * @access public - */ - function __construct($host, $port, $timeout, $block_size = 255) { - parent::__construct(); - if (! ($this->handle = $this->openSocket($host, $port, $error_number, $error, $timeout))) { - $this->setError("Cannot open [$host:$port] with [$error] within [$timeout] seconds"); - return; - } - $this->is_open = true; - $this->block_size = $block_size; - SimpleTestCompatibility::setTimeout($this->handle, $timeout); - } - - /** - * Writes some data to the socket and saves alocal copy. - * @param string $message String to send to socket. - * @return boolean True if successful. - * @access public - */ - function write($message) { - if ($this->isError() || ! $this->isOpen()) { - return false; - } - $count = fwrite($this->handle, $message); - if (! $count) { - if ($count === false) { - $this->setError('Cannot write to socket'); - $this->close(); - } - return false; - } - fflush($this->handle); - $this->sent .= $message; - return true; - } - - /** - * Reads data from the socket. The error suppresion - * is a workaround for PHP4 always throwing a warning - * with a secure socket. - * @return integer/boolean Incoming bytes. False - * on error. - * @access public - */ - function read() { - if ($this->isError() || ! $this->isOpen()) { - return false; - } - $raw = @fread($this->handle, $this->block_size); - if ($raw === false) { - $this->setError('Cannot read from socket'); - $this->close(); - } - return $raw; - } - - /** - * Accessor for socket open state. - * @return boolean True if open. - * @access public - */ - function isOpen() { - return $this->is_open; - } - - /** - * Closes the socket preventing further reads. - * Cannot be reopened once closed. - * @return boolean True if successful. - * @access public - */ - function close() { - $this->is_open = false; - return fclose($this->handle); - } - - /** - * Accessor for content so far. - * @return string Bytes sent only. - * @access public - */ - function getSent() { - return $this->sent; - } - - /** - * Actually opens the low level socket. - * @param string $host Host to connect to. - * @param integer $port Port on host. - * @param integer $error_number Recipient of error code. - * @param string $error Recipoent of error message. - * @param integer $timeout Maximum time to wait for connection. - * @access protected - */ - protected function openSocket($host, $port, &$error_number, &$error, $timeout) { - return @fsockopen($host, $port, $error_number, $error, $timeout); - } -} - -/** - * Wrapper for TCP/IP socket over TLS. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleSecureSocket extends SimpleSocket { - - /** - * Opens a secure socket for reading and writing. - * @param string $host Hostname to send request to. - * @param integer $port Port on remote machine to open. - * @param integer $timeout Connection timeout in seconds. - * @access public - */ - function __construct($host, $port, $timeout) { - parent::__construct($host, $port, $timeout); - } - - /** - * Actually opens the low level socket. - * @param string $host Host to connect to. - * @param integer $port Port on host. - * @param integer $error_number Recipient of error code. - * @param string $error Recipient of error message. - * @param integer $timeout Maximum time to wait for connection. - * @access protected - */ - function openSocket($host, $port, &$error_number, &$error, $timeout) { - return parent::openSocket("tls://$host", $port, $error_number, $error, $timeout); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/tag.php b/3rdparty/simpletest/tag.php deleted file mode 100644 index afe649ec5dd084627c343f22a3e3c26f5cbecdde..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/tag.php +++ /dev/null @@ -1,1527 +0,0 @@ -<?php -/** - * Base include file for SimpleTest. - * @package SimpleTest - * @subpackage WebTester - * @version $Id: tag.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/**#@+ - * include SimpleTest files - */ -require_once(dirname(__FILE__) . '/page.php'); -require_once(dirname(__FILE__) . '/encoding.php'); -/**#@-*/ - -/** - * Creates tags and widgets given HTML tag - * attributes. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleTagBuilder { - - /** - * Factory for the tag objects. Creates the - * appropriate tag object for the incoming tag name - * and attributes. - * @param string $name HTML tag name. - * @param hash $attributes Element attributes. - * @return SimpleTag Tag object. - * @access public - */ - function createTag($name, $attributes) { - static $map = array( - 'a' => 'SimpleAnchorTag', - 'title' => 'SimpleTitleTag', - 'base' => 'SimpleBaseTag', - 'button' => 'SimpleButtonTag', - 'textarea' => 'SimpleTextAreaTag', - 'option' => 'SimpleOptionTag', - 'label' => 'SimpleLabelTag', - 'form' => 'SimpleFormTag', - 'frame' => 'SimpleFrameTag'); - $attributes = $this->keysToLowerCase($attributes); - if (array_key_exists($name, $map)) { - $tag_class = $map[$name]; - return new $tag_class($attributes); - } elseif ($name == 'select') { - return $this->createSelectionTag($attributes); - } elseif ($name == 'input') { - return $this->createInputTag($attributes); - } - return new SimpleTag($name, $attributes); - } - - /** - * Factory for selection fields. - * @param hash $attributes Element attributes. - * @return SimpleTag Tag object. - * @access protected - */ - protected function createSelectionTag($attributes) { - if (isset($attributes['multiple'])) { - return new MultipleSelectionTag($attributes); - } - return new SimpleSelectionTag($attributes); - } - - /** - * Factory for input tags. - * @param hash $attributes Element attributes. - * @return SimpleTag Tag object. - * @access protected - */ - protected function createInputTag($attributes) { - if (! isset($attributes['type'])) { - return new SimpleTextTag($attributes); - } - $type = strtolower(trim($attributes['type'])); - $map = array( - 'submit' => 'SimpleSubmitTag', - 'image' => 'SimpleImageSubmitTag', - 'checkbox' => 'SimpleCheckboxTag', - 'radio' => 'SimpleRadioButtonTag', - 'text' => 'SimpleTextTag', - 'hidden' => 'SimpleTextTag', - 'password' => 'SimpleTextTag', - 'file' => 'SimpleUploadTag'); - if (array_key_exists($type, $map)) { - $tag_class = $map[$type]; - return new $tag_class($attributes); - } - return false; - } - - /** - * Make the keys lower case for case insensitive look-ups. - * @param hash $map Hash to convert. - * @return hash Unchanged values, but keys lower case. - * @access private - */ - protected function keysToLowerCase($map) { - $lower = array(); - foreach ($map as $key => $value) { - $lower[strtolower($key)] = $value; - } - return $lower; - } -} - -/** - * HTML or XML tag. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleTag { - private $name; - private $attributes; - private $content; - - /** - * Starts with a named tag with attributes only. - * @param string $name Tag name. - * @param hash $attributes Attribute names and - * string values. Note that - * the keys must have been - * converted to lower case. - */ - function __construct($name, $attributes) { - $this->name = strtolower(trim($name)); - $this->attributes = $attributes; - $this->content = ''; - } - - /** - * Check to see if the tag can have both start and - * end tags with content in between. - * @return boolean True if content allowed. - * @access public - */ - function expectEndTag() { - return true; - } - - /** - * The current tag should not swallow all content for - * itself as it's searchable page content. Private - * content tags are usually widgets that contain default - * values. - * @return boolean False as content is available - * to other tags by default. - * @access public - */ - function isPrivateContent() { - return false; - } - - /** - * Appends string content to the current content. - * @param string $content Additional text. - * @access public - */ - function addContent($content) { - $this->content .= (string)$content; - return $this; - } - - /** - * Adds an enclosed tag to the content. - * @param SimpleTag $tag New tag. - * @access public - */ - function addTag($tag) { - } - - /** - * Adds multiple enclosed tags to the content. - * @param array List of SimpleTag objects to be added. - */ - function addTags($tags) { - foreach ($tags as $tag) { - $this->addTag($tag); - } - } - - /** - * Accessor for tag name. - * @return string Name of tag. - * @access public - */ - function getTagName() { - return $this->name; - } - - /** - * List of legal child elements. - * @return array List of element names. - * @access public - */ - function getChildElements() { - return array(); - } - - /** - * Accessor for an attribute. - * @param string $label Attribute name. - * @return string Attribute value. - * @access public - */ - function getAttribute($label) { - $label = strtolower($label); - if (! isset($this->attributes[$label])) { - return false; - } - return (string)$this->attributes[$label]; - } - - /** - * Sets an attribute. - * @param string $label Attribute name. - * @return string $value New attribute value. - * @access protected - */ - protected function setAttribute($label, $value) { - $this->attributes[strtolower($label)] = $value; - } - - /** - * Accessor for the whole content so far. - * @return string Content as big raw string. - * @access public - */ - function getContent() { - return $this->content; - } - - /** - * Accessor for content reduced to visible text. Acts - * like a text mode browser, normalising space and - * reducing images to their alt text. - * @return string Content as plain text. - * @access public - */ - function getText() { - return SimplePage::normalise($this->content); - } - - /** - * Test to see if id attribute matches. - * @param string $id ID to test against. - * @return boolean True on match. - * @access public - */ - function isId($id) { - return ($this->getAttribute('id') == $id); - } -} - -/** - * Base url. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleBaseTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('base', $attributes); - } - - /** - * Base tag is not a block tag. - * @return boolean false - * @access public - */ - function expectEndTag() { - return false; - } -} - -/** - * Page title. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleTitleTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('title', $attributes); - } -} - -/** - * Link. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleAnchorTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('a', $attributes); - } - - /** - * Accessor for URL as string. - * @return string Coerced as string. - * @access public - */ - function getHref() { - $url = $this->getAttribute('href'); - if (is_bool($url)) { - $url = ''; - } - return $url; - } -} - -/** - * Form element. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleWidget extends SimpleTag { - private $value; - private $label; - private $is_set; - - /** - * Starts with a named tag with attributes only. - * @param string $name Tag name. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($name, $attributes) { - parent::__construct($name, $attributes); - $this->value = false; - $this->label = false; - $this->is_set = false; - } - - /** - * Accessor for name submitted as the key in - * GET/POST privateiables hash. - * @return string Parsed value. - * @access public - */ - function getName() { - return $this->getAttribute('name'); - } - - /** - * Accessor for default value parsed with the tag. - * @return string Parsed value. - * @access public - */ - function getDefault() { - return $this->getAttribute('value'); - } - - /** - * Accessor for currently set value or default if - * none. - * @return string Value set by form or default - * if none. - * @access public - */ - function getValue() { - if (! $this->is_set) { - return $this->getDefault(); - } - return $this->value; - } - - /** - * Sets the current form element value. - * @param string $value New value. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - $this->value = $value; - $this->is_set = true; - return true; - } - - /** - * Resets the form element value back to the - * default. - * @access public - */ - function resetValue() { - $this->is_set = false; - } - - /** - * Allows setting of a label externally, say by a - * label tag. - * @param string $label Label to attach. - * @access public - */ - function setLabel($label) { - $this->label = trim($label); - return $this; - } - - /** - * Reads external or internal label. - * @param string $label Label to test. - * @return boolean True is match. - * @access public - */ - function isLabel($label) { - return $this->label == trim($label); - } - - /** - * Dispatches the value into the form encoded packet. - * @param SimpleEncoding $encoding Form packet. - * @access public - */ - function write($encoding) { - if ($this->getName()) { - $encoding->add($this->getName(), $this->getValue()); - } - } -} - -/** - * Text, password and hidden field. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleTextTag extends SimpleWidget { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('input', $attributes); - if ($this->getAttribute('value') === false) { - $this->setAttribute('value', ''); - } - } - - /** - * Tag contains no content. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * Sets the current form element value. Cannot - * change the value of a hidden field. - * @param string $value New value. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - if ($this->getAttribute('type') == 'hidden') { - return false; - } - return parent::setValue($value); - } -} - -/** - * Submit button as input tag. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleSubmitTag extends SimpleWidget { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('input', $attributes); - if ($this->getAttribute('value') === false) { - $this->setAttribute('value', 'Submit'); - } - } - - /** - * Tag contains no end element. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * Disables the setting of the button value. - * @param string $value Ignored. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - return false; - } - - /** - * Value of browser visible text. - * @return string Visible label. - * @access public - */ - function getLabel() { - return $this->getValue(); - } - - /** - * Test for a label match when searching. - * @param string $label Label to test. - * @return boolean True on match. - * @access public - */ - function isLabel($label) { - return trim($label) == trim($this->getLabel()); - } -} - -/** - * Image button as input tag. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleImageSubmitTag extends SimpleWidget { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('input', $attributes); - } - - /** - * Tag contains no end element. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * Disables the setting of the button value. - * @param string $value Ignored. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - return false; - } - - /** - * Value of browser visible text. - * @return string Visible label. - * @access public - */ - function getLabel() { - if ($this->getAttribute('title')) { - return $this->getAttribute('title'); - } - return $this->getAttribute('alt'); - } - - /** - * Test for a label match when searching. - * @param string $label Label to test. - * @return boolean True on match. - * @access public - */ - function isLabel($label) { - return trim($label) == trim($this->getLabel()); - } - - /** - * Dispatches the value into the form encoded packet. - * @param SimpleEncoding $encoding Form packet. - * @param integer $x X coordinate of click. - * @param integer $y Y coordinate of click. - * @access public - */ - function write($encoding, $x = 1, $y = 1) { - if ($this->getName()) { - $encoding->add($this->getName() . '.x', $x); - $encoding->add($this->getName() . '.y', $y); - } else { - $encoding->add('x', $x); - $encoding->add('y', $y); - } - } -} - -/** - * Submit button as button tag. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleButtonTag extends SimpleWidget { - - /** - * Starts with a named tag with attributes only. - * Defaults are very browser dependent. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('button', $attributes); - } - - /** - * Check to see if the tag can have both start and - * end tags with content in between. - * @return boolean True if content allowed. - * @access public - */ - function expectEndTag() { - return true; - } - - /** - * Disables the setting of the button value. - * @param string $value Ignored. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - return false; - } - - /** - * Value of browser visible text. - * @return string Visible label. - * @access public - */ - function getLabel() { - return $this->getContent(); - } - - /** - * Test for a label match when searching. - * @param string $label Label to test. - * @return boolean True on match. - * @access public - */ - function isLabel($label) { - return trim($label) == trim($this->getLabel()); - } -} - -/** - * Content tag for text area. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleTextAreaTag extends SimpleWidget { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('textarea', $attributes); - } - - /** - * Accessor for starting value. - * @return string Parsed value. - * @access public - */ - function getDefault() { - return $this->wrap(html_entity_decode($this->getContent(), ENT_QUOTES)); - } - - /** - * Applies word wrapping if needed. - * @param string $value New value. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - return parent::setValue($this->wrap($value)); - } - - /** - * Test to see if text should be wrapped. - * @return boolean True if wrapping on. - * @access private - */ - function wrapIsEnabled() { - if ($this->getAttribute('cols')) { - $wrap = $this->getAttribute('wrap'); - if (($wrap == 'physical') || ($wrap == 'hard')) { - return true; - } - } - return false; - } - - /** - * Performs the formatting that is peculiar to - * this tag. There is strange behaviour in this - * one, including stripping a leading new line. - * Go figure. I am using Firefox as a guide. - * @param string $text Text to wrap. - * @return string Text wrapped with carriage - * returns and line feeds - * @access private - */ - protected function wrap($text) { - $text = str_replace("\r\r\n", "\r\n", str_replace("\n", "\r\n", $text)); - $text = str_replace("\r\n\n", "\r\n", str_replace("\r", "\r\n", $text)); - if (strncmp($text, "\r\n", strlen("\r\n")) == 0) { - $text = substr($text, strlen("\r\n")); - } - if ($this->wrapIsEnabled()) { - return wordwrap( - $text, - (integer)$this->getAttribute('cols'), - "\r\n"); - } - return $text; - } - - /** - * The content of textarea is not part of the page. - * @return boolean True. - * @access public - */ - function isPrivateContent() { - return true; - } -} - -/** - * File upload widget. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleUploadTag extends SimpleWidget { - - /** - * Starts with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('input', $attributes); - } - - /** - * Tag contains no content. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * Dispatches the value into the form encoded packet. - * @param SimpleEncoding $encoding Form packet. - * @access public - */ - function write($encoding) { - if (! file_exists($this->getValue())) { - return; - } - $encoding->attach( - $this->getName(), - implode('', file($this->getValue())), - basename($this->getValue())); - } -} - -/** - * Drop down widget. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleSelectionTag extends SimpleWidget { - private $options; - private $choice; - - /** - * Starts with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('select', $attributes); - $this->options = array(); - $this->choice = false; - } - - /** - * Adds an option tag to a selection field. - * @param SimpleOptionTag $tag New option. - * @access public - */ - function addTag($tag) { - if ($tag->getTagName() == 'option') { - $this->options[] = $tag; - } - } - - /** - * Text within the selection element is ignored. - * @param string $content Ignored. - * @access public - */ - function addContent($content) { - return $this; - } - - /** - * Scans options for defaults. If none, then - * the first option is selected. - * @return string Selected field. - * @access public - */ - function getDefault() { - for ($i = 0, $count = count($this->options); $i < $count; $i++) { - if ($this->options[$i]->getAttribute('selected') !== false) { - return $this->options[$i]->getDefault(); - } - } - if ($count > 0) { - return $this->options[0]->getDefault(); - } - return ''; - } - - /** - * Can only set allowed values. - * @param string $value New choice. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - for ($i = 0, $count = count($this->options); $i < $count; $i++) { - if ($this->options[$i]->isValue($value)) { - $this->choice = $i; - return true; - } - } - return false; - } - - /** - * Accessor for current selection value. - * @return string Value attribute or - * content of opton. - * @access public - */ - function getValue() { - if ($this->choice === false) { - return $this->getDefault(); - } - return $this->options[$this->choice]->getValue(); - } -} - -/** - * Drop down widget. - * @package SimpleTest - * @subpackage WebTester - */ -class MultipleSelectionTag extends SimpleWidget { - private $options; - private $values; - - /** - * Starts with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('select', $attributes); - $this->options = array(); - $this->values = false; - } - - /** - * Adds an option tag to a selection field. - * @param SimpleOptionTag $tag New option. - * @access public - */ - function addTag($tag) { - if ($tag->getTagName() == 'option') { - $this->options[] = &$tag; - } - } - - /** - * Text within the selection element is ignored. - * @param string $content Ignored. - * @access public - */ - function addContent($content) { - return $this; - } - - /** - * Scans options for defaults to populate the - * value array(). - * @return array Selected fields. - * @access public - */ - function getDefault() { - $default = array(); - for ($i = 0, $count = count($this->options); $i < $count; $i++) { - if ($this->options[$i]->getAttribute('selected') !== false) { - $default[] = $this->options[$i]->getDefault(); - } - } - return $default; - } - - /** - * Can only set allowed values. Any illegal value - * will result in a failure, but all correct values - * will be set. - * @param array $desired New choices. - * @return boolean True if all allowed. - * @access public - */ - function setValue($desired) { - $achieved = array(); - foreach ($desired as $value) { - $success = false; - for ($i = 0, $count = count($this->options); $i < $count; $i++) { - if ($this->options[$i]->isValue($value)) { - $achieved[] = $this->options[$i]->getValue(); - $success = true; - break; - } - } - if (! $success) { - return false; - } - } - $this->values = $achieved; - return true; - } - - /** - * Accessor for current selection value. - * @return array List of currently set options. - * @access public - */ - function getValue() { - if ($this->values === false) { - return $this->getDefault(); - } - return $this->values; - } -} - -/** - * Option for selection field. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleOptionTag extends SimpleWidget { - - /** - * Stashes the attributes. - */ - function __construct($attributes) { - parent::__construct('option', $attributes); - } - - /** - * Does nothing. - * @param string $value Ignored. - * @return boolean Not allowed. - * @access public - */ - function setValue($value) { - return false; - } - - /** - * Test to see if a value matches the option. - * @param string $compare Value to compare with. - * @return boolean True if possible match. - * @access public - */ - function isValue($compare) { - $compare = trim($compare); - if (trim($this->getValue()) == $compare) { - return true; - } - return trim(strip_tags($this->getContent())) == $compare; - } - - /** - * Accessor for starting value. Will be set to - * the option label if no value exists. - * @return string Parsed value. - * @access public - */ - function getDefault() { - if ($this->getAttribute('value') === false) { - return strip_tags($this->getContent()); - } - return $this->getAttribute('value'); - } - - /** - * The content of options is not part of the page. - * @return boolean True. - * @access public - */ - function isPrivateContent() { - return true; - } -} - -/** - * Radio button. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleRadioButtonTag extends SimpleWidget { - - /** - * Stashes the attributes. - * @param array $attributes Hash of attributes. - */ - function __construct($attributes) { - parent::__construct('input', $attributes); - if ($this->getAttribute('value') === false) { - $this->setAttribute('value', 'on'); - } - } - - /** - * Tag contains no content. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * The only allowed value sn the one in the - * "value" attribute. - * @param string $value New value. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - if ($value === false) { - return parent::setValue($value); - } - if ($value != $this->getAttribute('value')) { - return false; - } - return parent::setValue($value); - } - - /** - * Accessor for starting value. - * @return string Parsed value. - * @access public - */ - function getDefault() { - if ($this->getAttribute('checked') !== false) { - return $this->getAttribute('value'); - } - return false; - } -} - -/** - * Checkbox widget. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleCheckboxTag extends SimpleWidget { - - /** - * Starts with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('input', $attributes); - if ($this->getAttribute('value') === false) { - $this->setAttribute('value', 'on'); - } - } - - /** - * Tag contains no content. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } - - /** - * The only allowed value in the one in the - * "value" attribute. The default for this - * attribute is "on". If this widget is set to - * true, then the usual value will be taken. - * @param string $value New value. - * @return boolean True if allowed. - * @access public - */ - function setValue($value) { - if ($value === false) { - return parent::setValue($value); - } - if ($value === true) { - return parent::setValue($this->getAttribute('value')); - } - if ($value != $this->getAttribute('value')) { - return false; - } - return parent::setValue($value); - } - - /** - * Accessor for starting value. The default - * value is "on". - * @return string Parsed value. - * @access public - */ - function getDefault() { - if ($this->getAttribute('checked') !== false) { - return $this->getAttribute('value'); - } - return false; - } -} - -/** - * A group of multiple widgets with some shared behaviour. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleTagGroup { - private $widgets = array(); - - /** - * Adds a tag to the group. - * @param SimpleWidget $widget - * @access public - */ - function addWidget($widget) { - $this->widgets[] = $widget; - } - - /** - * Accessor to widget set. - * @return array All widgets. - * @access protected - */ - protected function &getWidgets() { - return $this->widgets; - } - - /** - * Accessor for an attribute. - * @param string $label Attribute name. - * @return boolean Always false. - * @access public - */ - function getAttribute($label) { - return false; - } - - /** - * Fetches the name for the widget from the first - * member. - * @return string Name of widget. - * @access public - */ - function getName() { - if (count($this->widgets) > 0) { - return $this->widgets[0]->getName(); - } - } - - /** - * Scans the widgets for one with the appropriate - * ID field. - * @param string $id ID value to try. - * @return boolean True if matched. - * @access public - */ - function isId($id) { - for ($i = 0, $count = count($this->widgets); $i < $count; $i++) { - if ($this->widgets[$i]->isId($id)) { - return true; - } - } - return false; - } - - /** - * Scans the widgets for one with the appropriate - * attached label. - * @param string $label Attached label to try. - * @return boolean True if matched. - * @access public - */ - function isLabel($label) { - for ($i = 0, $count = count($this->widgets); $i < $count; $i++) { - if ($this->widgets[$i]->isLabel($label)) { - return true; - } - } - return false; - } - - /** - * Dispatches the value into the form encoded packet. - * @param SimpleEncoding $encoding Form packet. - * @access public - */ - function write($encoding) { - $encoding->add($this->getName(), $this->getValue()); - } -} - -/** - * A group of tags with the same name within a form. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleCheckboxGroup extends SimpleTagGroup { - - /** - * Accessor for current selected widget or false - * if none. - * @return string/array Widget values or false if none. - * @access public - */ - function getValue() { - $values = array(); - $widgets = $this->getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if ($widgets[$i]->getValue() !== false) { - $values[] = $widgets[$i]->getValue(); - } - } - return $this->coerceValues($values); - } - - /** - * Accessor for starting value that is active. - * @return string/array Widget values or false if none. - * @access public - */ - function getDefault() { - $values = array(); - $widgets = $this->getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if ($widgets[$i]->getDefault() !== false) { - $values[] = $widgets[$i]->getDefault(); - } - } - return $this->coerceValues($values); - } - - /** - * Accessor for current set values. - * @param string/array/boolean $values Either a single string, a - * hash or false for nothing set. - * @return boolean True if all values can be set. - * @access public - */ - function setValue($values) { - $values = $this->makeArray($values); - if (! $this->valuesArePossible($values)) { - return false; - } - $widgets = $this->getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - $possible = $widgets[$i]->getAttribute('value'); - if (in_array($widgets[$i]->getAttribute('value'), $values)) { - $widgets[$i]->setValue($possible); - } else { - $widgets[$i]->setValue(false); - } - } - return true; - } - - /** - * Tests to see if a possible value set is legal. - * @param string/array/boolean $values Either a single string, a - * hash or false for nothing set. - * @return boolean False if trying to set a - * missing value. - * @access private - */ - protected function valuesArePossible($values) { - $matches = array(); - $widgets = &$this->getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - $possible = $widgets[$i]->getAttribute('value'); - if (in_array($possible, $values)) { - $matches[] = $possible; - } - } - return ($values == $matches); - } - - /** - * Converts the output to an appropriate format. This means - * that no values is false, a single value is just that - * value and only two or more are contained in an array. - * @param array $values List of values of widgets. - * @return string/array/boolean Expected format for a tag. - * @access private - */ - protected function coerceValues($values) { - if (count($values) == 0) { - return false; - } elseif (count($values) == 1) { - return $values[0]; - } else { - return $values; - } - } - - /** - * Converts false or string into array. The opposite of - * the coercian method. - * @param string/array/boolean $value A single item is converted - * to a one item list. False - * gives an empty list. - * @return array List of values, possibly empty. - * @access private - */ - protected function makeArray($value) { - if ($value === false) { - return array(); - } - if (is_string($value)) { - return array($value); - } - return $value; - } -} - -/** - * A group of tags with the same name within a form. - * Used for radio buttons. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleRadioGroup extends SimpleTagGroup { - - /** - * Each tag is tried in turn until one is - * successfully set. The others will be - * unchecked if successful. - * @param string $value New value. - * @return boolean True if any allowed. - * @access public - */ - function setValue($value) { - if (! $this->valueIsPossible($value)) { - return false; - } - $index = false; - $widgets = $this->getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if (! $widgets[$i]->setValue($value)) { - $widgets[$i]->setValue(false); - } - } - return true; - } - - /** - * Tests to see if a value is allowed. - * @param string Attempted value. - * @return boolean True if a valid value. - * @access private - */ - protected function valueIsPossible($value) { - $widgets = $this->getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if ($widgets[$i]->getAttribute('value') == $value) { - return true; - } - } - return false; - } - - /** - * Accessor for current selected widget or false - * if none. - * @return string/boolean Value attribute or - * content of opton. - * @access public - */ - function getValue() { - $widgets = $this->getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if ($widgets[$i]->getValue() !== false) { - return $widgets[$i]->getValue(); - } - } - return false; - } - - /** - * Accessor for starting value that is active. - * @return string/boolean Value of first checked - * widget or false if none. - * @access public - */ - function getDefault() { - $widgets = $this->getWidgets(); - for ($i = 0, $count = count($widgets); $i < $count; $i++) { - if ($widgets[$i]->getDefault() !== false) { - return $widgets[$i]->getDefault(); - } - } - return false; - } -} - -/** - * Tag to keep track of labels. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleLabelTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('label', $attributes); - } - - /** - * Access for the ID to attach the label to. - * @return string For attribute. - * @access public - */ - function getFor() { - return $this->getAttribute('for'); - } -} - -/** - * Tag to aid parsing the form. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleFormTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('form', $attributes); - } -} - -/** - * Tag to aid parsing the frames in a page. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleFrameTag extends SimpleTag { - - /** - * Starts with a named tag with attributes only. - * @param hash $attributes Attribute names and - * string values. - */ - function __construct($attributes) { - parent::__construct('frame', $attributes); - } - - /** - * Tag contains no content. - * @return boolean False. - * @access public - */ - function expectEndTag() { - return false; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/acceptance_test.php b/3rdparty/simpletest/test/acceptance_test.php deleted file mode 100644 index e96fe737e5fcdae82a72762bbbf5b9979ef4df4b..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/acceptance_test.php +++ /dev/null @@ -1,1729 +0,0 @@ -<?php -// $Id: acceptance_test.php 2013 2011-04-29 09:29:45Z pp11 $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../compatibility.php'); -require_once(dirname(__FILE__) . '/../browser.php'); -require_once(dirname(__FILE__) . '/../web_tester.php'); -require_once(dirname(__FILE__) . '/../unit_tester.php'); - -class SimpleTestAcceptanceTest extends WebTestCase { - static function samples() { - return 'http://www.lastcraft.com/test/'; - } -} - -class TestOfLiveBrowser extends UnitTestCase { - function samples() { - return SimpleTestAcceptanceTest::samples(); - } - - function testGet() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $this->assertTrue($browser->get($this->samples() . 'network_confirm.php')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - $this->assertPattern('/Request method.*?<dd>GET<\/dd>/', $browser->getContent()); - $this->assertEqual($browser->getTitle(), 'Simple test target file'); - $this->assertEqual($browser->getResponseCode(), 200); - $this->assertEqual($browser->getMimeType(), 'text/html'); - } - - function testPost() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $this->assertTrue($browser->post($this->samples() . 'network_confirm.php')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/', $browser->getContent()); - } - - function testAbsoluteLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLink('Absolute')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testRelativeEncodedLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - // Warning: the below data is ISO 8859-1 encoded - $this->assertTrue($browser->clickLink("m\xE4rc\xEAl kiek'eboe")); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testRelativeLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLink('Relative')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testUnifiedClickLinkClicking() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->click('Relative')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testIdLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLinkById(1)); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testCookieReading() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'set_cookies.php'); - $this->assertEqual($browser->getCurrentCookieValue('session_cookie'), 'A'); - $this->assertEqual($browser->getCurrentCookieValue('short_cookie'), 'B'); - $this->assertEqual($browser->getCurrentCookieValue('day_cookie'), 'C'); - } - - function testSimpleSubmit() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'form.html'); - $this->assertTrue($browser->clickSubmit('Go!')); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/', $browser->getContent()); - $this->assertPattern('/go=\[Go!\]/', $browser->getContent()); - } - - function testUnifiedClickCanSubmit() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'form.html'); - $this->assertTrue($browser->click('Go!')); - $this->assertPattern('/go=\[Go!\]/', $browser->getContent()); - } -} - -class TestOfLocalFileBrowser extends UnitTestCase { - function samples() { - return 'file://'.dirname(__FILE__).'/site/'; - } - - function testGet() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $this->assertTrue($browser->get($this->samples() . 'file.html')); - $this->assertPattern('/Link to SimpleTest/', $browser->getContent()); - $this->assertEqual($browser->getTitle(), 'Link to SimpleTest'); - $this->assertFalse($browser->getResponseCode()); - $this->assertEqual($browser->getMimeType(), ''); - } -} - -class TestOfRequestMethods extends UnitTestCase { - function samples() { - return SimpleTestAcceptanceTest::samples(); - } - - function testHeadRequest() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->head($this->samples() . 'request_methods.php')); - $this->assertEqual($browser->getResponseCode(), 202); - } - - function testGetRequest() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->get($this->samples() . 'request_methods.php')); - $this->assertEqual($browser->getResponseCode(), 405); - } - - function testPostWithPlainEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->post($this->samples() . 'request_methods.php', 'A content message')); - $this->assertEqual($browser->getResponseCode(), 406); - $this->assertPattern('/Please ensure content type is an XML format/', $browser->getContent()); - } - - function testPostWithXmlEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->post($this->samples() . 'request_methods.php', '<a><b>c</b></a>', 'text/xml')); - $this->assertEqual($browser->getResponseCode(), 201); - $this->assertPattern('/c/', $browser->getContent()); - } - - function testPutWithPlainEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->put($this->samples() . 'request_methods.php', 'A content message')); - $this->assertEqual($browser->getResponseCode(), 406); - $this->assertPattern('/Please ensure content type is an XML format/', $browser->getContent()); - } - - function testPutWithXmlEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->put($this->samples() . 'request_methods.php', '<a><b>c</b></a>', 'application/xml')); - $this->assertEqual($browser->getResponseCode(), 201); - $this->assertPattern('/c/', $browser->getContent()); - } - - function testDeleteRequest() { - $browser = new SimpleBrowser(); - $browser->delete($this->samples() . 'request_methods.php'); - $this->assertEqual($browser->getResponseCode(), 202); - $this->assertPattern('/Your delete request was accepted/', $browser->getContent()); - } - -} - -class TestRadioFields extends SimpleTestAcceptanceTest { - function testSetFieldAsInteger() { - $this->get($this->samples() . 'form_with_radio_buttons.html'); - $this->assertTrue($this->setField('tested_field', 2)); - $this->clickSubmitByName('send'); - $this->assertEqual($this->getUrl(), $this->samples() . 'form_with_radio_buttons.html?tested_field=2&send=click+me'); - } - - function testSetFieldAsString() { - $this->get($this->samples() . 'form_with_radio_buttons.html'); - $this->assertTrue($this->setField('tested_field', '2')); - $this->clickSubmitByName('send'); - $this->assertEqual($this->getUrl(), $this->samples() . 'form_with_radio_buttons.html?tested_field=2&send=click+me'); - } -} - -class TestOfLiveFetching extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testFormWithArrayBasedInputs() { - $this->get($this->samples() . 'form_with_array_based_inputs.php'); - $this->setField('value[]', '3', '1'); - $this->setField('value[]', '4', '2'); - $this->clickSubmit('Go'); - $this->assertPattern('/QUERY_STRING : value%5B%5D=3&value%5B%5D=4&submit=Go/'); - } - - function testFormWithQuotedValues() { - $this->get($this->samples() . 'form_with_quoted_values.php'); - $this->assertField('a', 'default'); - $this->assertFieldById('text_field', 'default'); - $this->clickSubmit('Go'); - $this->assertPattern('/a=default&submit=Go/'); - } - - function testGet() { - $this->assertTrue($this->get($this->samples() . 'network_confirm.php')); - $this->assertEqual($this->getUrl(), $this->samples() . 'network_confirm.php'); - $this->assertText('target for the SimpleTest'); - $this->assertPattern('/Request method.*?<dd>GET<\/dd>/'); - $this->assertTitle('Simple test target file'); - $this->assertTitle(new PatternExpectation('/target file/')); - $this->assertResponse(200); - $this->assertMime('text/html'); - $this->assertHeader('connection', 'close'); - $this->assertHeader('connection', new PatternExpectation('/los/')); - } - - function testSlowGet() { - $this->assertTrue($this->get($this->samples() . 'slow_page.php')); - } - - function testTimedOutGet() { - $this->setConnectionTimeout(1); - $this->ignoreErrors(); - $this->assertFalse($this->get($this->samples() . 'slow_page.php')); - } - - function testPost() { - $this->assertTrue($this->post($this->samples() . 'network_confirm.php')); - $this->assertText('target for the SimpleTest'); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/'); - } - - function testGetWithData() { - $this->get($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?<dd>GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostWithData() { - $this->post($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostWithRecursiveData() { - $this->post($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/'); - $this->assertText('a=[aaa]'); - - $this->post($this->samples() . 'network_confirm.php', array("a[aa]" => "aaa")); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/'); - $this->assertText('a=[aa=[aaa]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a[aa][aaa]" => "aaaa")); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/'); - $this->assertText('a=[aa=[aaa=[aaaa]]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a" => array("aa" => "aaa"))); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/'); - $this->assertText('a=[aa=[aaa]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a" => array("aa" => array("aaa" => "aaaa")))); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/'); - $this->assertText('a=[aa=[aaa=[aaaa]]]'); - } - - function testRelativeGet() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->get('network_confirm.php')); - $this->assertText('target for the SimpleTest'); - } - - function testRelativePost() { - $this->post($this->samples() . 'link_confirm.php', array('a' => '123')); - $this->assertTrue($this->post('network_confirm.php')); - $this->assertText('target for the SimpleTest'); - } -} - -class TestOfLinkFollowing extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testLinkAssertions() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertLink('Absolute', $this->samples() . 'network_confirm.php'); - $this->assertLink('Absolute', new PatternExpectation('/confirm/')); - $this->assertClickable('Absolute'); - } - - function testAbsoluteLinkFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->clickLink('Absolute')); - $this->assertText('target for the SimpleTest'); - } - - function testRelativeLinkFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->clickLink('Relative')); - $this->assertText('target for the SimpleTest'); - } - - function testLinkIdFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertLinkById(1); - $this->assertTrue($this->clickLinkById(1)); - $this->assertText('target for the SimpleTest'); - } - - function testAbsoluteUrlBehavesAbsolutely() { - $this->get($this->samples() . 'link_confirm.php'); - $this->get('http://www.lastcraft.com'); - $this->assertText('No guarantee of quality is given or even intended'); - } - - function testRelativeUrlRespectsBaseTag() { - $this->get($this->samples() . 'base_tag/base_link.html'); - $this->click('Back to test pages'); - $this->assertTitle('Simple test target file'); - } -} - -class TestOfLivePageLinkingWithMinimalLinks extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testClickToExplicitelyNamedSelfReturns() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->assertEqual($this->getUrl(), $this->samples() . 'front_controller_style/a_page.php'); - $this->assertTitle('Simple test page with links'); - $this->assertLink('Self'); - $this->clickLink('Self'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToMissingPageReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('No page'); - $this->assertTitle('Simple test page with links'); - $this->assertText('[action=no_page]'); - } - - function testClickToBareActionReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Bare action'); - $this->assertTitle('Simple test page with links'); - $this->assertText('[action=]'); - } - - function testClickToSingleQuestionMarkReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Empty query'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToEmptyStringReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Empty link'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToSingleDotGoesToCurrentDirectory() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Current directory'); - $this->assertTitle( - 'Simple test front controller', - '%s -> index.php needs to be set as a default web server home page'); - } - - function testClickBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Down one'); - $this->assertPattern('|Index of .*?/test|i'); - } -} - -class TestOfLiveFrontControllerEmulation extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testJumpToNamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->assertText('Simple test front controller'); - $this->clickLink('Index'); - $this->assertResponse(200); - $this->assertText('[action=index]'); - } - - function testJumpToUnnamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('No page'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=no_page]'); - } - - function testJumpToUnnamedPageWithBareParameter() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Bare action'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=]'); - } - - function testJumpToUnnamedPageWithEmptyQuery() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Empty query'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - } - - function testJumpToUnnamedPageWithEmptyLink() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Empty link'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - } - - function testJumpBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Down one'); - $this->assertPattern('|Index of .*?/test|'); - } - - function testSubmitToNamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->assertText('Simple test front controller'); - $this->clickSubmit('Index'); - $this->assertResponse(200); - $this->assertText('[action=Index]'); - } - - function testSubmitToSameDirectory() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('Same directory'); - $this->assertResponse(200); - $this->assertText('[action=Same+directory]'); - } - - function testSubmitToEmptyAction() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('Empty action'); - $this->assertResponse(200); - $this->assertText('[action=Empty+action]'); - } - - function testSubmitToNoAction() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('No action'); - $this->assertResponse(200); - $this->assertText('[action=No+action]'); - } - - function testSubmitBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickSubmit('Down one'); - $this->assertPattern('|Index of .*?/test|'); - } - - function testSubmitToNamedPageWithMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/?a=A'); - $this->assertText('Simple test front controller'); - $this->clickSubmit('Index post'); - $this->assertText('action=[Index post]'); - $this->assertNoText('[a=A]'); - } - - function testSubmitToSameDirectoryMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('Same directory post'); - $this->assertText('action=[Same directory post]'); - $this->assertNoText('[a=A]'); - } - - function testSubmitToEmptyActionMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('Empty action post'); - $this->assertText('action=[Empty action post]'); - $this->assertText('[a=A]'); - } - - function testSubmitToNoActionMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('No action post'); - $this->assertText('action=[No action post]'); - $this->assertText('[a=A]'); - } -} - -class TestOfLiveHeaders extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testConfirmingHeaderExistence() { - $this->get('http://www.lastcraft.com/'); - $this->assertHeader('content-type'); - $this->assertHeader('content-type', 'text/html'); - $this->assertHeader('content-type', new PatternExpectation('/HTML/i')); - $this->assertNoHeader('WWW-Authenticate'); - } -} - -class TestOfLiveRedirects extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testNoRedirects() { - $this->setMaximumRedirects(0); - $this->get($this->samples() . 'redirect.php'); - $this->assertTitle('Redirection test'); - } - - function testRedirects() { - $this->setMaximumRedirects(1); - $this->get($this->samples() . 'redirect.php'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectLosesGetData() { - $this->get($this->samples() . 'redirect.php', array('a' => 'aaa')); - $this->assertNoText('a=[aaa]'); - } - - function testRedirectKeepsExtraRequestDataOfItsOwn() { - $this->get($this->samples() . 'redirect.php'); - $this->assertText('r=[rrr]'); - } - - function testRedirectLosesPostData() { - $this->post($this->samples() . 'redirect.php', array('a' => 'aaa')); - $this->assertTitle('Simple test target file'); - $this->assertNoText('a=[aaa]'); - } - - function testRedirectWithBaseUrlChange() { - $this->get($this->samples() . 'base_change_redirect.php'); - $this->assertTitle('Simple test target file in folder'); - $this->get($this->samples() . 'path/base_change_redirect.php'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectWithDoubleBaseUrlChange() { - $this->get($this->samples() . 'double_base_change_redirect.php'); - $this->assertTitle('Simple test target file'); - } -} - -class TestOfLiveCookies extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function here() { - return new SimpleUrl($this->samples()); - } - - function thisHost() { - $here = $this->here(); - return $here->getHost(); - } - - function thisPath() { - $here = $this->here(); - return $here->getPath(); - } - - function testCookieSettingAndAssertions() { - $this->setCookie('a', 'Test cookie a'); - $this->setCookie('b', 'Test cookie b', $this->thisHost()); - $this->setCookie('c', 'Test cookie c', $this->thisHost(), $this->thisPath()); - $this->get($this->samples() . 'network_confirm.php'); - $this->assertText('Test cookie a'); - $this->assertText('Test cookie b'); - $this->assertText('Test cookie c'); - $this->assertCookie('a'); - $this->assertCookie('b', 'Test cookie b'); - $this->assertTrue($this->getCookie('c') == 'Test cookie c'); - } - - function testNoCookieSetWhenCookiesDisabled() { - $this->setCookie('a', 'Test cookie a'); - $this->ignoreCookies(); - $this->get($this->samples() . 'network_confirm.php'); - $this->assertNoText('Test cookie a'); - } - - function testCookieReading() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertCookie('session_cookie', 'A'); - $this->assertCookie('short_cookie', 'B'); - $this->assertCookie('day_cookie', 'C'); - } - - function testNoCookie() { - $this->assertNoCookie('aRandomCookie'); - } - - function testNoCookieReadingWhenCookiesDisabled() { - $this->ignoreCookies(); - $this->get($this->samples() . 'set_cookies.php'); - $this->assertNoCookie('session_cookie'); - $this->assertNoCookie('short_cookie'); - $this->assertNoCookie('day_cookie'); - } - - function testCookiePatternAssertions() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertCookie('session_cookie', new PatternExpectation('/a/i')); - } - - function testTemporaryCookieExpiry() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(); - $this->assertNoCookie('session_cookie'); - $this->assertCookie('day_cookie', 'C'); - } - - function testTimedCookieExpiryWith100SecondMargin() { - $this->get($this->samples() . 'set_cookies.php'); - $this->ageCookies(3600); - $this->restart(time() + 100); - $this->assertNoCookie('session_cookie'); - $this->assertNoCookie('hour_cookie'); - $this->assertCookie('day_cookie', 'C'); - } - - function testNoClockOverDriftBy100Seconds() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(time() + 200); - $this->assertNoCookie( - 'short_cookie', - '%s -> Please check your computer clock setting if you are not using NTP'); - } - - function testNoClockUnderDriftBy100Seconds() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(time() + 0); - $this->assertCookie( - 'short_cookie', - 'B', - '%s -> Please check your computer clock setting if you are not using NTP'); - } - - function testCookiePath() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertNoCookie('path_cookie', 'D'); - $this->get('./path/show_cookies.php'); - $this->assertPattern('/path_cookie/'); - $this->assertCookie('path_cookie', 'D'); - } -} - -class LiveTestOfForms extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testSimpleSubmit() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/'); - $this->assertText('go=[Go!]'); - } - - function testDefaultFormValues() { - $this->get($this->samples() . 'form.html'); - $this->assertFieldByName('a', ''); - $this->assertFieldByName('b', 'Default text'); - $this->assertFieldByName('c', ''); - $this->assertFieldByName('d', 'd1'); - $this->assertFieldByName('e', false); - $this->assertFieldByName('f', 'on'); - $this->assertFieldByName('g', 'g3'); - $this->assertFieldByName('h', 2); - $this->assertFieldByName('go', 'Go!'); - $this->assertClickable('Go!'); - $this->assertSubmit('Go!'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('go=[Go!]'); - $this->assertText('a=[]'); - $this->assertText('b=[Default text]'); - $this->assertText('c=[]'); - $this->assertText('d=[d1]'); - $this->assertNoText('e=['); - $this->assertText('f=[on]'); - $this->assertText('g=[g3]'); - } - - function testFormSubmissionByButtonLabel() { - $this->get($this->samples() . 'form.html'); - $this->setFieldByName('a', 'aaa'); - $this->setFieldByName('b', 'bbb'); - $this->setFieldByName('c', 'ccc'); - $this->setFieldByName('d', 'D2'); - $this->setFieldByName('e', 'on'); - $this->setFieldByName('f', false); - $this->setFieldByName('g', 'g2'); - $this->setFieldByName('h', 1); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - } - - function testAdditionalFormValues() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Go!', array('add' => 'A'))); - $this->assertText('go=[Go!]'); - $this->assertText('add=[A]'); - } - - function testFormSubmissionByName() { - $this->get($this->samples() . 'form.html'); - $this->setFieldByName('a', 'A'); - $this->assertTrue($this->clickSubmitByName('go')); - $this->assertText('a=[A]'); - } - - function testFormSubmissionByNameAndAdditionalParameters() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmitByName('go', array('add' => 'A'))); - $this->assertText('go=[Go!]'); - $this->assertText('add=[A]'); - } - - function testFormSubmissionBySubmitButtonLabeledSubmit() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmitByName('test')); - $this->assertText('test=[Submit]'); - } - - function testFormSubmissionWithIds() { - $this->get($this->samples() . 'form.html'); - $this->assertFieldById(1, ''); - $this->assertFieldById(2, 'Default text'); - $this->assertFieldById(3, ''); - $this->assertFieldById(4, 'd1'); - $this->assertFieldById(5, false); - $this->assertFieldById(6, 'on'); - $this->assertFieldById(8, 'g3'); - $this->assertFieldById(11, 2); - $this->setFieldById(1, 'aaa'); - $this->setFieldById(2, 'bbb'); - $this->setFieldById(3, 'ccc'); - $this->setFieldById(4, 'D2'); - $this->setFieldById(5, 'on'); - $this->setFieldById(6, false); - $this->setFieldById(8, 'g2'); - $this->setFieldById(11, 'H1'); - $this->assertTrue($this->clickSubmitById(99)); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testFormSubmissionWithIdsAndAdditionnalData() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmitById(99, array('additionnal' => "data"))); - $this->assertText('additionnal=[data]'); - } - - function testFormSubmissionWithLabels() { - $this->get($this->samples() . 'form.html'); - $this->assertField('Text A', ''); - $this->assertField('Text B', 'Default text'); - $this->assertField('Text area C', ''); - $this->assertField('Selection D', 'd1'); - $this->assertField('Checkbox E', false); - $this->assertField('Checkbox F', 'on'); - $this->assertField('3', 'g3'); - $this->assertField('Selection H', 2); - $this->setField('Text A', 'aaa'); - $this->setField('Text B', 'bbb'); - $this->setField('Text area C', 'ccc'); - $this->setField('Selection D', 'D2'); - $this->setField('Checkbox E', 'on'); - $this->setField('Checkbox F', false); - $this->setField('2', 'g2'); - $this->setField('Selection H', 'H1'); - $this->clickSubmit('Go!'); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testSettingCheckboxWithBooleanTrueSetsUnderlyingValue() { - $this->get($this->samples() . 'form.html'); - $this->setField('Checkbox E', true); - $this->assertField('Checkbox E', 'on'); - $this->clickSubmit('Go!'); - $this->assertText('e=[on]'); - } - - function testFormSubmissionWithMixedPostAndGet() { - $this->get($this->samples() . 'form_with_mixed_post_and_get.html'); - $this->setField('Text A', 'Hello'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[Hello]'); - $this->assertText('x=[X]'); - $this->assertText('y=[Y]'); - } - - function testFormSubmissionWithMixedPostAndEncodedGet() { - $this->get($this->samples() . 'form_with_mixed_post_and_get.html'); - $this->setField('Text B', 'Hello'); - $this->assertTrue($this->clickSubmit('Go encoded!')); - $this->assertText('b=[Hello]'); - $this->assertText('x=[X]'); - $this->assertText('y=[Y]'); - } - - function testFormSubmissionWithoutAction() { - $this->get($this->samples() . 'form_without_action.php?test=test'); - $this->assertText('_GET : [test]'); - $this->assertTrue($this->clickSubmit('Submit Post With Empty Action')); - $this->assertText('_GET : [test]'); - $this->assertText('_POST : [test]'); - } - - function testImageSubmissionByLabel() { - $this->get($this->samples() . 'form.html'); - $this->assertImage('Image go!'); - $this->assertTrue($this->clickImage('Image go!', 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testImageSubmissionByLabelWithAdditionalParameters() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImage('Image go!', 10, 12, array('add' => 'A'))); - $this->assertText('add=[A]'); - } - - function testImageSubmissionByName() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImageByName('go', 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testImageSubmissionById() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImageById(97, 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testButtonSubmissionByLabel() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Button go!', 10, 12)); - $this->assertPattern('/go=\[ButtonGo\]/s'); - } - - function testNamelessSubmitSendsNoValue() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->click('Go!'); - $this->assertNoText('Go!'); - $this->assertNoText('submit'); - } - - function testNamelessImageSendsXAndYValues() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->clickImage('Image go!', 4, 5); - $this->assertNoText('ImageGo'); - $this->assertText('x=[4]'); - $this->assertText('y=[5]'); - } - - function testNamelessButtonSendsNoValue() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->click('Button Go!'); - $this->assertNoText('ButtonGo'); - } - - function testSelfSubmit() { - $this->get($this->samples() . 'self_form.php'); - $this->assertNoText('[Submitted]'); - $this->assertNoText('[Wrong form]'); - $this->assertTrue($this->clickSubmit()); - $this->assertText('[Submitted]'); - $this->assertNoText('[Wrong form]'); - $this->assertTitle('Test of form self submission'); - } - - function testSelfSubmitWithParameters() { - $this->get($this->samples() . 'self_form.php'); - $this->setFieldByName('visible', 'Resent'); - $this->assertTrue($this->clickSubmit()); - $this->assertText('[Resent]'); - } - - function testSettingOfBlankOption() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->setFieldByName('d', '')); - $this->clickSubmit('Go!'); - $this->assertText('d=[]'); - } - - function testAssertingFieldValueWithPattern() { - $this->get($this->samples() . 'form.html'); - $this->setField('c', 'A very long string'); - $this->assertField('c', new PatternExpectation('/very long/')); - } - - function testSendingMultipartFormDataEncodedForm() { - $this->get($this->samples() . 'form_data_encoded_form.html'); - $this->assertField('Text A', ''); - $this->assertField('Text B', 'Default text'); - $this->assertField('Text area C', ''); - $this->assertField('Selection D', 'd1'); - $this->assertField('Checkbox E', false); - $this->assertField('Checkbox F', 'on'); - $this->assertField('3', 'g3'); - $this->assertField('Selection H', 2); - $this->setField('Text A', 'aaa'); - $this->setField('Text B', 'bbb'); - $this->setField('Text area C', 'ccc'); - $this->setField('Selection D', 'D2'); - $this->setField('Checkbox E', 'on'); - $this->setField('Checkbox F', false); - $this->setField('2', 'g2'); - $this->setField('Selection H', 'H1'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testSettingVariousBlanksInFields() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->assertField('Text A', ''); - $this->setField('Text A', '0'); - $this->assertField('Text A', '0'); - $this->assertField('Text area B', ''); - $this->setField('Text area B', '0'); - $this->assertField('Text area B', '0'); - $this->assertField('Selection D', ''); - $this->setField('Selection D', 'D2'); - $this->assertField('Selection D', 'D2'); - $this->setField('Selection D', 'D3'); - $this->assertField('Selection D', '0'); - $this->setField('Selection D', 'D4'); - $this->assertField('Selection D', '?'); - $this->assertField('Checkbox E', ''); - $this->assertField('Checkbox F', 'on'); - $this->assertField('Checkbox G', '0'); - $this->assertField('Checkbox H', '?'); - $this->assertFieldByName('i', 'on'); - $this->setFieldByName('i', ''); - $this->assertFieldByName('i', ''); - $this->setFieldByName('i', '0'); - $this->assertFieldByName('i', '0'); - $this->setFieldByName('i', '?'); - $this->assertFieldByName('i', '?'); - } - - function testDefaultValueOfTextareaHasNewlinesAndWhitespacePreserved() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->assertField('Text area C', ' '); - } - - function chars($t) { - for ($i = 0; $i < strlen($t); $i++) { - print "[$t[$i]]"; - } - } - - function testSubmissionOfBlankFields() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', ''); - $this->setField('Text area B', ''); - $this->setFieldByName('i', ''); - $this->click('Go!'); - $this->assertText('a=[]'); - $this->assertText('b=[]'); - $this->assertText('d=[]'); - $this->assertText('e=[]'); - $this->assertText('i=[]'); - } - - function testDefaultValueOfTextareaHasNewlinesAndWhitespacePreservedOnSubmission() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->click('Go!'); - $this->assertPattern('/c=\[ \]/'); - } - - function testSubmissionOfEmptyValues() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Selection D', 'D2'); - $this->click('Go!'); - $this->assertText('a=[]'); - $this->assertText('b=[]'); - $this->assertText('d=[D2]'); - $this->assertText('f=[on]'); - $this->assertText('i=[on]'); - } - - function testSubmissionOfZeroes() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', '0'); - $this->setField('Text area B', '0'); - $this->setField('Selection D', 'D3'); - $this->setFieldByName('i', '0'); - $this->click('Go!'); - $this->assertText('a=[0]'); - $this->assertText('b=[0]'); - $this->assertText('d=[0]'); - $this->assertText('g=[0]'); - $this->assertText('i=[0]'); - } - - function testSubmissionOfQuestionMarks() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', '?'); - $this->setField('Text area B', '?'); - $this->setField('Selection D', 'D4'); - $this->setFieldByName('i', '?'); - $this->click('Go!'); - $this->assertText('a=[?]'); - $this->assertText('b=[?]'); - $this->assertText('d=[?]'); - $this->assertText('h=[?]'); - $this->assertText('i=[?]'); - } - - function testSubmissionOfHtmlEncodedValues() { - $this->get($this->samples() . 'form_with_tricky_defaults.html'); - $this->assertField('Text A', '&\'"<>'); - $this->assertField('Text B', '"'); - $this->assertField('Text area C', '&\'"<>'); - $this->assertField('Selection D', "'"); - $this->assertField('Checkbox E', '&\'"<>'); - $this->assertField('Checkbox F', false); - $this->assertFieldByname('i', "'"); - $this->click('Go!'); - $this->assertText('a=[&\'"<>, "]'); - $this->assertText('c=[&\'"<>]'); - $this->assertText("d=[']"); - $this->assertText('e=[&\'"<>]'); - $this->assertText("i=[']"); - } - - function testFormActionRespectsBaseTag() { - $this->get($this->samples() . 'base_tag/form.html'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('go=[Go!]'); - $this->assertText('a=[]'); - } -} - -class TestOfLiveMultiValueWidgets extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testDefaultFormValueSubmission() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->assertFieldByName('a', array('a2', 'a3')); - $this->assertFieldByName('b', array('b2', 'b3')); - $this->assertFieldByName('c[]', array('c2', 'c3')); - $this->assertFieldByName('d', array('2', '3')); - $this->assertFieldByName('e', array('2', '3')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a2, a3]'); - $this->assertText('b=[b2, b3]'); - $this->assertText('c=[c2, c3]'); - $this->assertText('d=[2, 3]'); - $this->assertText('e=[2, 3]'); - } - - function testSubmittingMultipleValues() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setFieldByName('a', array('a1', 'a4')); - $this->assertFieldByName('a', array('a1', 'a4')); - $this->assertFieldByName('a', array('a4', 'a1')); - $this->setFieldByName('b', array('b1', 'b4')); - $this->assertFieldByName('b', array('b1', 'b4')); - $this->setFieldByName('c[]', array('c1', 'c4')); - $this->assertField('c[]', array('c1', 'c4')); - $this->setFieldByName('d', array('1', '4')); - $this->assertField('d', array('1', '4')); - $this->setFieldByName('e', array('e1', 'e4')); - $this->assertField('e', array('1', '4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1, a4]'); - $this->assertText('b=[b1, b4]'); - $this->assertText('c=[c1, c4]'); - $this->assertText('d=[1, 4]'); - $this->assertText('e=[1, 4]'); - } - - function testSettingByOptionValue() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setFieldByName('d', array('1', '4')); - $this->assertField('d', array('1', '4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('d=[1, 4]'); - } - - function testSubmittingMultipleValuesByLabel() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setField('Multiple selection A', array('a1', 'a4')); - $this->assertField('Multiple selection A', array('a1', 'a4')); - $this->assertField('Multiple selection A', array('a4', 'a1')); - $this->setField('multiple selection C', array('c1', 'c4')); - $this->assertField('multiple selection C', array('c1', 'c4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1, a4]'); - $this->assertText('c=[c1, c4]'); - } - - function testSavantStyleHiddenFieldDefaults() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertFieldByName('a', array('a0')); - $this->assertFieldByName('b', array('b0')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a0]'); - $this->assertText('b=[b0]'); - } - - function testSavantStyleHiddenDefaultsAreOverridden() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertTrue($this->setFieldByName('a', array('a1'))); - $this->assertTrue($this->setFieldByName('b', 'b1')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1]'); - $this->assertText('b=[b1]'); - } - - function testSavantStyleFormSettingById() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertFieldById(1, array('a0')); - $this->assertFieldById(4, array('b0')); - $this->assertTrue($this->setFieldById(2, 'a1')); - $this->assertTrue($this->setFieldById(5, 'b1')); - $this->assertTrue($this->clickSubmitById(99)); - $this->assertText('a=[a1]'); - $this->assertText('b=[b1]'); - } -} - -class TestOfFileUploads extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testSingleFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/upload_sample.txt')); - $this->assertField('Content:', dirname(__FILE__) . '/support/upload_sample.txt'); - $this->click('Go!'); - $this->assertText('Sample for testing file upload'); - } - - function testMultipleFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/upload_sample.txt')); - $this->assertTrue($this->setField('Supplemental:', - dirname(__FILE__) . '/support/supplementary_upload_sample.txt')); - $this->assertField('Supplemental:', - dirname(__FILE__) . '/support/supplementary_upload_sample.txt'); - $this->click('Go!'); - $this->assertText('Sample for testing file upload'); - $this->assertText('Some more text content'); - } - - function testBinaryFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/latin1_sample')); - $this->click('Go!'); - $this->assertText( - implode('', file(dirname(__FILE__) . '/support/latin1_sample'))); - } -} - -class TestOfLiveHistoryNavigation extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testRetry() { - $this->get($this->samples() . 'cookie_based_counter.php'); - $this->assertPattern('/count: 1/i'); - $this->retry(); - $this->assertPattern('/count: 2/i'); - $this->retry(); - $this->assertPattern('/count: 3/i'); - } - - function testOfBackButton() { - $this->get($this->samples() . '1.html'); - $this->clickLink('2'); - $this->assertTitle('2'); - $this->assertTrue($this->back()); - $this->assertTitle('1'); - $this->assertTrue($this->forward()); - $this->assertTitle('2'); - $this->assertFalse($this->forward()); - } - - function testGetRetryResubmitsData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php?a=aaa')); - $this->assertPattern('/Request method.*?<dd>GET<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?<dd>GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testGetRetryResubmitsExtraData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php', - array('a' => 'aaa'))); - $this->assertPattern('/Request method.*?<dd>GET<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?<dd>GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostRetryResubmitsData() { - $this->assertTrue($this->post( - $this->samples() . 'network_confirm.php', - array('a' => 'aaa'))); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?<dd>POST<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testGetRetryResubmitsRepeatedData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php?a=1&a=2')); - $this->assertPattern('/Request method.*?<dd>GET<\/dd>/'); - $this->assertText('a=[1, 2]'); - $this->retry(); - $this->assertPattern('/Request method.*?<dd>GET<\/dd>/'); - $this->assertText('a=[1, 2]'); - } -} - -class TestOfLiveAuthentication extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testChallengeFromProtectedPage() { - $this->get($this->samples() . 'protected/'); - $this->assertResponse(401); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertRealm(new PatternExpectation('/simpletest/i')); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->retry(); - $this->assertResponse(200); - } - - function testTrailingSlashImpliedWithinRealm() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->get($this->samples() . 'protected'); - $this->assertResponse(200); - } - - function testTrailingSlashImpliedSettingRealm() { - $this->get($this->samples() . 'protected'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->get($this->samples() . 'protected/'); - $this->assertResponse(200); - } - - function testEncodedAuthenticationFetchesPage() { - $this->get('http://test:secret@www.lastcraft.com/test/protected/'); - $this->assertResponse(200); - } - - function testEncodedAuthenticationFetchesPageAfterTrailingSlashRedirect() { - $this->get('http://test:secret@www.lastcraft.com/test/protected'); - $this->assertResponse(200); - } - - function testRealmExtendsToWholeDirectory() { - $this->get($this->samples() . 'protected/1.html'); - $this->authenticate('test', 'secret'); - $this->clickLink('2'); - $this->assertResponse(200); - $this->clickLink('3'); - $this->assertResponse(200); - } - - function testRedirectKeepsAuthentication() { - $this->get($this->samples() . 'protected/local_redirect.php'); - $this->authenticate('test', 'secret'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectKeepsEncodedAuthentication() { - $this->get('http://test:secret@www.lastcraft.com/test/protected/local_redirect.php'); - $this->assertResponse(200); - $this->assertTitle('Simple test target file'); - } - - function testSessionRestartLosesAuthentication() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->restart(); - $this->get($this->samples() . 'protected/'); - $this->assertResponse(401); - } -} - -class TestOfLoadingFrames extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testNoFramesContentWhenFramesDisabled() { - $this->ignoreFrames(); - $this->get($this->samples() . 'one_page_frameset.html'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('This content is for no frames only'); - } - - function testPatternMatchCanReadTheOnlyFrame() { - $this->get($this->samples() . 'one_page_frameset.html'); - $this->assertText('A target for the SimpleTest test suite'); - $this->assertNoText('This content is for no frames only'); - } - - function testMessyFramesetResponsesByName() { - $this->assertTrue($this->get( - $this->samples() . 'messy_frameset.html')); - $this->assertTitle('Frameset for testing of SimpleTest'); - - $this->assertTrue($this->setFrameFocus('Front controller')); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - - $this->assertTrue($this->setFrameFocus('One')); - $this->assertResponse(200); - $this->assertLink('2'); - - $this->assertTrue($this->setFrameFocus('Frame links')); - $this->assertResponse(200); - $this->assertLink('Set one to 2'); - - $this->assertTrue($this->setFrameFocus('Counter')); - $this->assertResponse(200); - $this->assertText('Count: 1'); - - $this->assertTrue($this->setFrameFocus('Redirected')); - $this->assertResponse(200); - $this->assertText('r=rrr'); - - $this->assertTrue($this->setFrameFocus('Protected')); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocus('Protected redirect')); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocusByIndex(1)); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - - $this->assertTrue($this->setFrameFocusByIndex(2)); - $this->assertResponse(200); - $this->assertLink('2'); - - $this->assertTrue($this->setFrameFocusByIndex(3)); - $this->assertResponse(200); - $this->assertLink('Set one to 2'); - - $this->assertTrue($this->setFrameFocusByIndex(4)); - $this->assertResponse(200); - $this->assertText('Count: 1'); - - $this->assertTrue($this->setFrameFocusByIndex(5)); - $this->assertResponse(200); - $this->assertText('r=rrr'); - - $this->assertTrue($this->setFrameFocusByIndex(6)); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocusByIndex(7)); - } - - function testReloadingFramesetPage() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertText('Count: 1'); - $this->retry(); - $this->assertText('Count: 2'); - $this->retry(); - $this->assertText('Count: 3'); - } - - function testReloadingSingleFrameWithCookieCounter() { - $this->get($this->samples() . 'counting_frameset.html'); - $this->setFrameFocus('a'); - $this->assertText('Count: 1'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - - $this->setFrameFocus('a'); - $this->retry(); - $this->assertText('Count: 3'); - $this->retry(); - $this->assertText('Count: 4'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - } - - function testReloadingFrameWhenUnfocusedReloadsWholeFrameset() { - $this->get($this->samples() . 'counting_frameset.html'); - $this->setFrameFocus('a'); - $this->assertText('Count: 1'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - - $this->clearFrameFocus('a'); - $this->retry(); - - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->setFrameFocus('a'); - $this->assertText('Count: 3'); - $this->setFrameFocus('b'); - $this->assertText('Count: 4'); - } - - function testClickingNormalLinkReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('2'); - $this->assertLink('3'); - $this->assertText('Simple test front controller'); - } - - function testJumpToNamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertPattern('/Simple test front controller/'); - $this->clickLink('Index'); - $this->assertResponse(200); - $this->assertText('[action=index]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('No page'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=no_page]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageWithBareParameterReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Bare action'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageWithEmptyQueryReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Empty query'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - $this->assertPattern('/Count: 1/'); - } - - function testJumpToUnnamedPageWithEmptyLinkReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Empty link'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - $this->assertPattern('/Count: 1/'); - } - - function testJumpBackADirectoryLevelReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Down one'); - $this->assertPattern('/index of .*\/test/i'); - $this->assertPattern('/Count: 1/'); - } - - function testSubmitToNamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertPattern('/Simple test front controller/'); - $this->clickSubmit('Index'); - $this->assertResponse(200); - $this->assertText('[action=Index]'); - $this->assertText('Count: 1'); - } - - function testSubmitToSameDirectoryReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Same directory'); - $this->assertResponse(200); - $this->assertText('[action=Same+directory]'); - $this->assertText('Count: 1'); - } - - function testSubmitToEmptyActionReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Empty action'); - $this->assertResponse(200); - $this->assertText('[action=Empty+action]'); - $this->assertText('Count: 1'); - } - - function testSubmitToNoActionReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('No action'); - $this->assertResponse(200); - $this->assertText('[action=No+action]'); - $this->assertText('Count: 1'); - } - - function testSubmitBackADirectoryLevelReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Down one'); - $this->assertPattern('/index of .*\/test/i'); - $this->assertPattern('/Count: 1/'); - } - - function testTopLinkExitsFrameset() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Exit the frameset'); - $this->assertTitle('Simple test target file'); - } - - function testLinkInOnePageCanLoadAnother() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertNoLink('3'); - $this->clickLink('Set one to 2'); - $this->assertLink('3'); - $this->assertNoLink('2'); - $this->assertTitle('Frameset for testing of SimpleTest'); - } - - function testFrameWithRelativeLinksRespectsBaseTagForThatPage() { - $this->get($this->samples() . 'base_tag/frameset.html'); - $this->click('Back to test pages'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('A target for the SimpleTest test suite'); - } - - function testRelativeLinkInFrameIsNotAffectedByFramesetBaseTag() { - $this->get($this->samples() . 'base_tag/frameset_with_base_tag.html'); - $this->assertText('This is page 1'); - $this->click('To page 2'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('This is page 2'); - } -} - -class TestOfFrameAuthentication extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testUnauthenticatedFrameSendsChallenge() { - $this->get($this->samples() . 'protected/'); - $this->setFrameFocus('Protected'); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertResponse(401); - } - - function testCanReadFrameFromAlreadyAuthenticatedRealm() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - } - - function testCanAuthenticateFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - $this->clearFrameFocus(); - $this->assertText('Count: 1'); - } - - function testCanAuthenticateRedirectedFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected redirect'); - $this->assertResponse(401); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - $this->clearFrameFocus(); - $this->assertText('Count: 1'); - } -} - -class TestOfNestedFrames extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testCanNavigateToSpecificContent() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertTitle('Nested frameset for testing of SimpleTest'); - - $this->assertPattern('/This is frame A/'); - $this->assertPattern('/This is frame B/'); - $this->assertPattern('/Simple test front controller/'); - $this->assertLink('2'); - $this->assertLink('Set one to 2'); - $this->assertPattern('/Count: 1/'); - $this->assertPattern('/r=rrr/'); - - $this->setFrameFocus('pair'); - $this->assertPattern('/This is frame A/'); - $this->assertPattern('/This is frame B/'); - $this->assertNoPattern('/Simple test front controller/'); - $this->assertNoLink('2'); - - $this->setFrameFocus('aaa'); - $this->assertPattern('/This is frame A/'); - $this->assertNoPattern('/This is frame B/'); - - $this->clearFrameFocus(); - $this->assertResponse(200); - $this->setFrameFocus('messy'); - $this->assertResponse(200); - $this->setFrameFocus('Front controller'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertNoLink('2'); - } - - function testReloadingFramesetPage() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertPattern('/Count: 1/'); - $this->retry(); - $this->assertPattern('/Count: 2/'); - $this->retry(); - $this->assertPattern('/Count: 3/'); - } - - function testRetryingNestedPageOnlyRetriesThatSet() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertPattern('/Count: 1/'); - $this->setFrameFocus('messy'); - $this->retry(); - $this->assertPattern('/Count: 2/'); - $this->setFrameFocus('Counter'); - $this->retry(); - $this->assertPattern('/Count: 3/'); - - $this->clearFrameFocus(); - $this->setFrameFocus('messy'); - $this->setFrameFocus('Front controller'); - $this->retry(); - - $this->clearFrameFocus(); - $this->assertPattern('/Count: 3/'); - } - - function testAuthenticatingNestedPage() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->setFrameFocus('messy'); - $this->setFrameFocus('Protected'); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertResponse(401); - - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertPattern('/A target for the SimpleTest test suite/'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/adapter_test.php b/3rdparty/simpletest/test/adapter_test.php deleted file mode 100755 index c1a06a2f6534b60f6f20e69864fa8fac6c738438..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/adapter_test.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php -// $Id: adapter_test.php 1748 2008-04-14 01:50:41Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../extensions/pear_test_case.php'); - -class SameTestClass { -} - -class TestOfPearAdapter extends PHPUnit_TestCase { - - function testBoolean() { - $this->assertTrue(true, "PEAR true"); - $this->assertFalse(false, "PEAR false"); - } - - function testName() { - $this->assertTrue($this->getName() == get_class($this)); - } - - function testPass() { - $this->pass("PEAR pass"); - } - - function testNulls() { - $value = null; - $this->assertNull($value, "PEAR null"); - $value = 0; - $this->assertNotNull($value, "PEAR not null"); - } - - function testType() { - $this->assertType("Hello", "string", "PEAR type"); - } - - function testEquals() { - $this->assertEquals(12, 12, "PEAR identity"); - $this->setLooselyTyped(true); - $this->assertEquals("12", 12, "PEAR equality"); - } - - function testSame() { - $same = new SameTestClass(); - $this->assertSame($same, $same, "PEAR same"); - } - - function testRegExp() { - $this->assertRegExp('/hello/', "A big hello from me", "PEAR regex"); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/all_tests.php b/3rdparty/simpletest/test/all_tests.php deleted file mode 100755 index 99ce9451e32b8d62edc5e29efadab38ea43bbac8..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/all_tests.php +++ /dev/null @@ -1,13 +0,0 @@ -<?php -require_once(dirname(__FILE__) . '/../autorun.php'); - -class AllTests extends TestSuite { - function AllTests() { - $this->TestSuite('All tests for SimpleTest ' . SimpleTest::getVersion()); - $this->addFile(dirname(__FILE__) . '/unit_tests.php'); - $this->addFile(dirname(__FILE__) . '/shell_test.php'); - $this->addFile(dirname(__FILE__) . '/live_test.php'); - $this->addFile(dirname(__FILE__) . '/acceptance_test.php'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/arguments_test.php b/3rdparty/simpletest/test/arguments_test.php deleted file mode 100755 index 0cca4e99b244436869243a65b09cdfe8816cfcce..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/arguments_test.php +++ /dev/null @@ -1,82 +0,0 @@ -<?php -// $Id: cookies_test.php 1506 2007-05-07 00:58:03Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../arguments.php'); - -class TestOfCommandLineArgumentParsing extends UnitTestCase { - function testArgumentListWithJustProgramNameGivesFalseToEveryName() { - $arguments = new SimpleArguments(array('me')); - $this->assertIdentical($arguments->a, false); - $this->assertIdentical($arguments->all(), array()); - } - - function testSingleArgumentNameRecordedAsTrue() { - $arguments = new SimpleArguments(array('me', '-a')); - $this->assertIdentical($arguments->a, true); - } - - function testSingleArgumentCanBeGivenAValue() { - $arguments = new SimpleArguments(array('me', '-a=AAA')); - $this->assertIdentical($arguments->a, 'AAA'); - } - - function testSingleArgumentCanBeGivenSpaceSeparatedValue() { - $arguments = new SimpleArguments(array('me', '-a', 'AAA')); - $this->assertIdentical($arguments->a, 'AAA'); - } - - function testWillBuildArrayFromRepeatedValue() { - $arguments = new SimpleArguments(array('me', '-a', 'A', '-a', 'AA')); - $this->assertIdentical($arguments->a, array('A', 'AA')); - } - - function testWillBuildArrayFromMultiplyRepeatedValues() { - $arguments = new SimpleArguments(array('me', '-a', 'A', '-a', 'AA', '-a', 'AAA')); - $this->assertIdentical($arguments->a, array('A', 'AA', 'AAA')); - } - - function testCanParseLongFormArguments() { - $arguments = new SimpleArguments(array('me', '--aa=AA', '--bb', 'BB')); - $this->assertIdentical($arguments->aa, 'AA'); - $this->assertIdentical($arguments->bb, 'BB'); - } - - function testGetsFullSetOfResultsAsHash() { - $arguments = new SimpleArguments(array('me', '-a', '-b=1', '-b', '2', '--aa=AA', '--bb', 'BB', '-c')); - $this->assertEqual($arguments->all(), - array('a' => true, 'b' => array('1', '2'), 'aa' => 'AA', 'bb' => 'BB', 'c' => true)); - } -} - -class TestOfHelpOutput extends UnitTestCase { - function testDisplaysGeneralHelpBanner() { - $help = new SimpleHelp('Cool program'); - $this->assertEqual($help->render(), "Cool program\n"); - } - - function testDisplaysOnlySingleLineEndings() { - $help = new SimpleHelp("Cool program\n"); - $this->assertEqual($help->render(), "Cool program\n"); - } - - function testDisplaysHelpOnShortFlag() { - $help = new SimpleHelp('Cool program'); - $help->explainFlag('a', 'Enables A'); - $this->assertEqual($help->render(), "Cool program\n-a Enables A\n"); - } - - function testHasAtleastFourSpacesAfterLongestFlag() { - $help = new SimpleHelp('Cool program'); - $help->explainFlag('a', 'Enables A'); - $help->explainFlag('long', 'Enables Long'); - $this->assertEqual($help->render(), - "Cool program\n-a Enables A\n--long Enables Long\n"); - } - - function testCanDisplaysMultipleFlagsForEachOption() { - $help = new SimpleHelp('Cool program'); - $help->explainFlag(array('a', 'aa'), 'Enables A'); - $this->assertEqual($help->render(), "Cool program\n-a Enables A\n --aa\n"); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/authentication_test.php b/3rdparty/simpletest/test/authentication_test.php deleted file mode 100755 index 081cccddfaedb74c38ce2fcc611cbbaa2f15a687..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/authentication_test.php +++ /dev/null @@ -1,145 +0,0 @@ -<?php -// $Id: authentication_test.php 1748 2008-04-14 01:50:41Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../authentication.php'); -require_once(dirname(__FILE__) . '/../http.php'); -Mock::generate('SimpleHttpRequest'); - -class TestOfRealm extends UnitTestCase { - - function testWithinSameUrl() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/hello.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/hello.html'))); - } - - function testInsideWithLongerUrl() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/hello.html'))); - } - - function testBelowRootIsOutside() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/more/hello.html'))); - } - - function testOldNetscapeDefinitionIsOutside() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/pathmore/hello.html'))); - } - - function testInsideWithMissingTrailingSlash() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path'))); - } - - function testDifferentPageNameStillInside() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/hello.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/goodbye.html'))); - } - - function testNewUrlInSameDirectoryDoesNotChangeRealm() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/hello.html')); - $realm->stretch(new SimpleUrl('http://www.here.com/path/goodbye.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/index.html'))); - } - - function testNewUrlMakesRealmTheCommonPath() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/here/hello.html')); - $realm->stretch(new SimpleUrl('http://www.here.com/path/there/goodbye.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/here/index.html'))); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/there/index.html'))); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/paths/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/pathindex.html'))); - } -} - -class TestOfAuthenticator extends UnitTestCase { - - function testNoRealms() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = new SimpleAuthenticator(); - $authenticator->addHeaders($request, new SimpleUrl('http://here.com/')); - } - - function &createSingleRealm() { - $authenticator = new SimpleAuthenticator(); - $authenticator->addRealm( - new SimpleUrl('http://www.here.com/path/hello.html'), - 'Basic', - 'Sanctuary'); - $authenticator->setIdentityForRealm('www.here.com', 'Sanctuary', 'test', 'secret'); - return $authenticator; - } - - function testOutsideRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/hello.html')); - } - - function testWithinRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectOnce('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/path/more/hello.html')); - } - - function testRestartingClearsRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->restartSession(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/hello.html')); - } - - function testDifferentHostIsOutsideRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://here.com/path/hello.html')); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/autorun_test.php b/3rdparty/simpletest/test/autorun_test.php deleted file mode 100755 index d85ea19897ce7150f690fb4a4d996e4f2c045491..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/autorun_test.php +++ /dev/null @@ -1,23 +0,0 @@ -<?php -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/support/test1.php'); - -class TestOfAutorun extends UnitTestCase { - function testLoadIfIncluded() { - $tests = new TestSuite(); - $tests->addFile(dirname(__FILE__) . '/support/test1.php'); - $this->assertEqual($tests->getSize(), 1); - } - - function testExitStatusOneIfTestsFail() { - exec('php ' . dirname(__FILE__) . '/support/failing_test.php', $output, $exit_status); - $this->assertEqual($exit_status, 1); - } - - function testExitStatusZeroIfTestsPass() { - exec('php ' . dirname(__FILE__) . '/support/passing_test.php', $output, $exit_status); - $this->assertEqual($exit_status, 0); - } -} - -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/bad_test_suite.php b/3rdparty/simpletest/test/bad_test_suite.php deleted file mode 100755 index b426013be40f19a9d7634e1084394b45fbe182b9..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/bad_test_suite.php +++ /dev/null @@ -1,10 +0,0 @@ -<?php -require_once(dirname(__FILE__) . '/../autorun.php'); - -class BadTestCases extends TestSuite { - function BadTestCases() { - $this->TestSuite('Two bad test cases'); - $this->addFile(dirname(__FILE__) . '/support/empty_test_file.php'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/browser_test.php b/3rdparty/simpletest/test/browser_test.php deleted file mode 100755 index 3a52aaa8ff4a1c8b5ba9eae486fdbad0231eeaef..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/browser_test.php +++ /dev/null @@ -1,802 +0,0 @@ -<?php -// $Id: browser_test.php 1964 2009-10-13 15:27:31Z maetl_ $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../browser.php'); -require_once(dirname(__FILE__) . '/../user_agent.php'); -require_once(dirname(__FILE__) . '/../http.php'); -require_once(dirname(__FILE__) . '/../page.php'); -require_once(dirname(__FILE__) . '/../encoding.php'); - -Mock::generate('SimpleHttpResponse'); -Mock::generate('SimplePage'); -Mock::generate('SimpleForm'); -Mock::generate('SimpleUserAgent'); -Mock::generatePartial( - 'SimpleBrowser', - 'MockParseSimpleBrowser', - array('createUserAgent', 'parse')); -Mock::generatePartial( - 'SimpleBrowser', - 'MockUserAgentSimpleBrowser', - array('createUserAgent')); - -class TestOfHistory extends UnitTestCase { - - function testEmptyHistoryHasFalseContents() { - $history = new SimpleBrowserHistory(); - $this->assertIdentical($history->getUrl(), false); - $this->assertIdentical($history->getParameters(), false); - } - - function testCannotMoveInEmptyHistory() { - $history = new SimpleBrowserHistory(); - $this->assertFalse($history->back()); - $this->assertFalse($history->forward()); - } - - function testCurrentTargetAccessors() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.here.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.here.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testSecondEntryAccessors() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); - $this->assertIdentical( - $history->getParameters(), - new SimplePostEncoding(array('a' => 1))); - } - - function testGoingBackwards() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertTrue($history->back()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingBackwardsOffBeginning() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $this->assertFalse($history->back()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingForwardsOffEnd() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $this->assertFalse($history->forward()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingBackwardsAndForwards() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertTrue($history->back()); - $this->assertTrue($history->forward()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); - $this->assertIdentical( - $history->getParameters(), - new SimplePostEncoding(array('a' => 1))); - } - - function testNewEntryReplacesNextOne() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $history->back(); - $history->recordEntry( - new SimpleUrl('http://www.third.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.third.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testNewEntryDropsFutureEntries() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.third.com/'), - new SimpleGetEncoding()); - $history->back(); - $history->back(); - $history->recordEntry( - new SimpleUrl('http://www.fourth.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.fourth.com/')); - $this->assertFalse($history->forward()); - $history->back(); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertFalse($history->back()); - } -} - -class TestOfParsedPageAccess extends UnitTestCase { - - function loadPage(&$page) { - $response = new MockSimpleHttpResponse($this); - $agent = new MockSimpleUserAgent($this); - $agent->returns('fetchResponse', $response); - - $browser = new MockParseSimpleBrowser($this); - $browser->returns('createUserAgent', $agent); - $browser->returns('parse', $page); - $browser->__construct(); - - $browser->get('http://this.com/page.html'); - return $browser; - } - - function testAccessorsWhenNoPage() { - $agent = new MockSimpleUserAgent($this); - $browser = new MockParseSimpleBrowser($this); - $browser->returns('createUserAgent', $agent); - $browser->__construct(); - $this->assertEqual($browser->getContent(), ''); - } - - function testParse() { - $page = new MockSimplePage(); - $page->setReturnValue('getRequest', "GET here.html\r\n\r\n"); - $page->setReturnValue('getRaw', 'Raw HTML'); - $page->setReturnValue('getTitle', 'Here'); - $page->setReturnValue('getFrameFocus', 'Frame'); - $page->setReturnValue('getMimeType', 'text/html'); - $page->setReturnValue('getResponseCode', 200); - $page->setReturnValue('getAuthentication', 'Basic'); - $page->setReturnValue('getRealm', 'Somewhere'); - $page->setReturnValue('getTransportError', 'Ouch!'); - - $browser = $this->loadPage($page); - $this->assertEqual($browser->getRequest(), "GET here.html\r\n\r\n"); - $this->assertEqual($browser->getContent(), 'Raw HTML'); - $this->assertEqual($browser->getTitle(), 'Here'); - $this->assertEqual($browser->getFrameFocus(), 'Frame'); - $this->assertIdentical($browser->getResponseCode(), 200); - $this->assertEqual($browser->getMimeType(), 'text/html'); - $this->assertEqual($browser->getAuthentication(), 'Basic'); - $this->assertEqual($browser->getRealm(), 'Somewhere'); - $this->assertEqual($browser->getTransportError(), 'Ouch!'); - } - - function testLinkAffirmationWhenPresent() { - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array('http://www.nowhere.com')); - $page->expectOnce('getUrlsByLabel', array('a link label')); - $browser = $this->loadPage($page); - $this->assertIdentical($browser->getLink('a link label'), 'http://www.nowhere.com'); - } - - function testLinkAffirmationByIdWhenPresent() { - $page = new MockSimplePage(); - $page->setReturnValue('getUrlById', 'a_page.com', array(99)); - $page->setReturnValue('getUrlById', false, array('*')); - $browser = $this->loadPage($page); - $this->assertIdentical($browser->getLinkById(99), 'a_page.com'); - $this->assertFalse($browser->getLinkById(98)); - } - - function testSettingFieldIsPassedToPage() { - $page = new MockSimplePage(); - $page->expectOnce('setField', array(new SimpleByLabelOrName('key'), 'Value', false)); - $page->setReturnValue('getField', 'Value'); - $browser = $this->loadPage($page); - $this->assertEqual($browser->getField('key'), 'Value'); - $browser->setField('key', 'Value'); - } -} - -class TestOfBrowserNavigation extends UnitTestCase { - function createBrowser($agent, $page) { - $browser = new MockParseSimpleBrowser(); - $browser->returns('createUserAgent', $agent); - $browser->returns('parse', $page); - $browser->__construct(); - return $browser; - } - - function testBrowserRequestMethods() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 0, - 'fetchResponse', - array(new SimpleUrl('http://this.com/get.req'), new SimpleGetEncoding())); - $agent->expectAt( - 1, - 'fetchResponse', - array(new SimpleUrl('http://this.com/post.req'), new SimplePostEncoding())); - $agent->expectAt( - 2, - 'fetchResponse', - array(new SimpleUrl('http://this.com/put.req'), new SimplePutEncoding())); - $agent->expectAt( - 3, - 'fetchResponse', - array(new SimpleUrl('http://this.com/delete.req'), new SimpleDeleteEncoding())); - $agent->expectAt( - 4, - 'fetchResponse', - array(new SimpleUrl('http://this.com/head.req'), new SimpleHeadEncoding())); - $agent->expectCallCount('fetchResponse', 5); - - $page = new MockSimplePage(); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/get.req'); - $browser->post('http://this.com/post.req'); - $browser->put('http://this.com/put.req'); - $browser->delete('http://this.com/delete.req'); - $browser->head('http://this.com/head.req'); - } - - function testClickLinkRequestsPage() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 0, - 'fetchResponse', - array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding())); - $agent->expectAt( - 1, - 'fetchResponse', - array(new SimpleUrl('http://this.com/new.html'), new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array(new SimpleUrl('http://this.com/new.html'))); - $page->expectOnce('getUrlsByLabel', array('New')); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New')); - } - - function testClickLinkWithUnknownFrameStillRequestsWholePage() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 0, - 'fetchResponse', - array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding())); - $target = new SimpleUrl('http://this.com/new.html'); - $target->setTarget('missing'); - $agent->expectAt( - 1, - 'fetchResponse', - array($target, new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $parsed_url = new SimpleUrl('http://this.com/new.html'); - $parsed_url->setTarget('missing'); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array($parsed_url)); - $page->setReturnValue('hasFrames', false); - $page->expectOnce('getUrlsByLabel', array('New')); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New')); - } - - function testClickingMissingLinkFails() { - $agent = new MockSimpleUserAgent($this); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array()); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $this->assertTrue($browser->get('http://this.com/page.html')); - $this->assertFalse($browser->clickLink('New')); - } - - function testClickIndexedLink() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 1, - 'fetchResponse', - array(new SimpleUrl('1.html'), new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = new MockSimplePage(); - $page->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('0.html'), new SimpleUrl('1.html'))); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New', 1)); - } - - function testClinkLinkById() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/link.html'), - new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlById', new SimpleUrl('http://this.com/link.html')); - $page->expectOnce('getUrlById', array(2)); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLinkById(2)); - } - - function testClickingMissingLinkIdFails() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlById', false); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertFalse($browser->clickLink(0)); - } - - function testSubmitFormByLabel() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/handler.html'), - new SimplePostEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitButton', array(new SimpleByLabel('Go'), false)); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Go'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmit('Go')); - } - - function testDefaultSubmitFormByLabel() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/page.html'), - new SimpleGetEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/page.html')); - $form->setReturnValue('getMethod', 'get'); - $form->setReturnValue('submitButton', new SimpleGetEncoding(array('a' => 'A'))); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Submit'))); - $page->setReturnValue('getRaw', 'stuff'); - $page->setReturnValue('getUrl', new SimpleUrl('http://this.com/page.html')); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmit()); - } - - function testSubmitFormByName() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByName('me'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmitByName('me')); - } - - function testSubmitFormById() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitButton', array(new SimpleById(99), false)); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleById(99))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmitById(99)); - } - - function testSubmitFormByImageLabel() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleByLabel('Go!'), 10, 11, false)); - - $page = new MockSimplePage(); - $page->returns('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleByLabel('Go!'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImage('Go!', 10, 11)); - } - - function testSubmitFormByImageName() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleByName('a'), 10, 11, false)); - - $page = new MockSimplePage(); - $page->returns('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleByName('a'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImageByName('a', 10, 11)); - } - - function testSubmitFormByImageId() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleById(99), 10, 11, false)); - - $page = new MockSimplePage(); - $page->returns('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleById(99))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImageById(99, 10, 11)); - } - - function testSubmitFormByFormId() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/handler.html'), - new SimplePostEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submit', new SimplePostEncoding(array('a' => 'A'))); - - $page = new MockSimplePage(); - $page->returns('getFormById', $form); - $page->expectOnce('getFormById', array(33)); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->submitFormById(33)); - } -} - -class TestOfBrowserFrames extends UnitTestCase { - - function createBrowser($agent) { - $browser = new MockUserAgentSimpleBrowser(); - $browser->returns('createUserAgent', $agent); - $browser->__construct(); - return $browser; - } - - function createUserAgent($pages) { - $agent = new MockSimpleUserAgent(); - foreach ($pages as $url => $raw) { - $url = new SimpleUrl($url); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', $url); - $response->setReturnValue('getContent', $raw); - $agent->returns('fetchResponse', $response, array($url, '*')); - } - return $agent; - } - - function testSimplePageHasNoFrames() { - $browser = $this->createBrowser($this->createUserAgent( - array('http://site.with.no.frames/' => 'A non-framed page'))); - $this->assertEqual( - $browser->get('http://site.with.no.frames/'), - 'A non-framed page'); - $this->assertIdentical($browser->getFrames(), 'http://site.with.no.frames/'); - } - - function testFramesetWithSingleFrame() { - $frameset = '<frameset><frame name="a" src="frame.html"></frameset>'; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => 'A frame'))); - $this->assertEqual($browser->get('http://site.with.one.frame/'), 'A frame'); - $this->assertIdentical( - $browser->getFrames(), - array('a' => 'http://site.with.one.frame/frame.html')); - } - - function testTitleTakenFromFramesetPage() { - $frameset = '<title>Frameset title</title>' . - '<frameset><frame name="a" src="frame.html"></frameset>'; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => '<title>Page title</title>'))); - $browser->get('http://site.with.one.frame/'); - $this->assertEqual($browser->getTitle(), 'Frameset title'); - } - - function testFramesetWithSingleUnnamedFrame() { - $frameset = '<frameset><frame src="frame.html"></frameset>'; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => 'One frame'))); - $this->assertEqual( - $browser->get('http://site.with.one.frame/'), - 'One frame'); - $this->assertIdentical( - $browser->getFrames(), - array(1 => 'http://site.with.one.frame/frame.html')); - } - - function testFramesetWithMultipleFrames() { - $frameset = '<frameset>' . - '<frame name="a" src="frame_a.html">' . - '<frame name="b" src="frame_b.html">' . - '<frame name="c" src="frame_c.html">' . - '</frameset>'; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame'))); - $this->assertEqual( - $browser->get('http://site.with.frames/'), - 'A frameB frameC frame'); - $this->assertIdentical($browser->getFrames(), array( - 'a' => 'http://site.with.frames/frame_a.html', - 'b' => 'http://site.with.frames/frame_b.html', - 'c' => 'http://site.with.frames/frame_c.html')); - } - - function testFrameFocusByName() { - $frameset = '<frameset>' . - '<frame name="a" src="frame_a.html">' . - '<frame name="b" src="frame_b.html">' . - '<frame name="c" src="frame_c.html">' . - '</frameset>'; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame'))); - $browser->get('http://site.with.frames/'); - $browser->setFrameFocus('a'); - $this->assertEqual($browser->getContent(), 'A frame'); - $browser->setFrameFocus('b'); - $this->assertEqual($browser->getContent(), 'B frame'); - $browser->setFrameFocus('c'); - $this->assertEqual($browser->getContent(), 'C frame'); - } - - function testFramesetWithSomeNamedFrames() { - $frameset = '<frameset>' . - '<frame name="a" src="frame_a.html">' . - '<frame src="frame_b.html">' . - '<frame name="c" src="frame_c.html">' . - '<frame src="frame_d.html">' . - '</frameset>'; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame', - 'http://site.with.frames/frame_d.html' => 'D frame'))); - $this->assertEqual( - $browser->get('http://site.with.frames/'), - 'A frameB frameC frameD frame'); - $this->assertIdentical($browser->getFrames(), array( - 'a' => 'http://site.with.frames/frame_a.html', - 2 => 'http://site.with.frames/frame_b.html', - 'c' => 'http://site.with.frames/frame_c.html', - 4 => 'http://site.with.frames/frame_d.html')); - } - - function testFrameFocusWithMixedNamesAndIndexes() { - $frameset = '<frameset>' . - '<frame name="a" src="frame_a.html">' . - '<frame src="frame_b.html">' . - '<frame name="c" src="frame_c.html">' . - '<frame src="frame_d.html">' . - '</frameset>'; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame', - 'http://site.with.frames/frame_d.html' => 'D frame'))); - $browser->get('http://site.with.frames/'); - $browser->setFrameFocus('a'); - $this->assertEqual($browser->getContent(), 'A frame'); - $browser->setFrameFocus(2); - $this->assertEqual($browser->getContent(), 'B frame'); - $browser->setFrameFocus('c'); - $this->assertEqual($browser->getContent(), 'C frame'); - $browser->setFrameFocus(4); - $this->assertEqual($browser->getContent(), 'D frame'); - $browser->clearFrameFocus(); - $this->assertEqual($browser->getContent(), 'A frameB frameC frameD frame'); - } - - function testNestedFrameset() { - $inner = '<frameset>' . - '<frame name="page" src="page.html">' . - '</frameset>'; - $outer = '<frameset>' . - '<frame name="inner" src="inner.html">' . - '</frameset>'; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frame/' => $outer, - 'http://site.with.nested.frame/inner.html' => $inner, - 'http://site.with.nested.frame/page.html' => 'The page'))); - $this->assertEqual( - $browser->get('http://site.with.nested.frame/'), - 'The page'); - $this->assertIdentical($browser->getFrames(), array( - 'inner' => array( - 'page' => 'http://site.with.nested.frame/page.html'))); - } - - function testCanNavigateToNestedFrame() { - $inner = '<frameset>' . - '<frame name="one" src="one.html">' . - '<frame name="two" src="two.html">' . - '</frameset>'; - $outer = '<frameset>' . - '<frame name="inner" src="inner.html">' . - '<frame name="three" src="three.html">' . - '</frameset>'; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frames/' => $outer, - 'http://site.with.nested.frames/inner.html' => $inner, - 'http://site.with.nested.frames/one.html' => 'Page one', - 'http://site.with.nested.frames/two.html' => 'Page two', - 'http://site.with.nested.frames/three.html' => 'Page three'))); - - $browser->get('http://site.with.nested.frames/'); - $this->assertEqual($browser->getContent(), 'Page onePage twoPage three'); - - $this->assertTrue($browser->setFrameFocus('inner')); - $this->assertEqual($browser->getFrameFocus(), array('inner')); - $this->assertTrue($browser->setFrameFocus('one')); - $this->assertEqual($browser->getFrameFocus(), array('inner', 'one')); - $this->assertEqual($browser->getContent(), 'Page one'); - - $this->assertTrue($browser->setFrameFocus('two')); - $this->assertEqual($browser->getFrameFocus(), array('inner', 'two')); - $this->assertEqual($browser->getContent(), 'Page two'); - - $browser->clearFrameFocus(); - $this->assertTrue($browser->setFrameFocus('three')); - $this->assertEqual($browser->getFrameFocus(), array('three')); - $this->assertEqual($browser->getContent(), 'Page three'); - - $this->assertTrue($browser->setFrameFocus('inner')); - $this->assertEqual($browser->getContent(), 'Page onePage two'); - } - - function testCanNavigateToNestedFrameByIndex() { - $inner = '<frameset>' . - '<frame src="one.html">' . - '<frame src="two.html">' . - '</frameset>'; - $outer = '<frameset>' . - '<frame src="inner.html">' . - '<frame src="three.html">' . - '</frameset>'; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frames/' => $outer, - 'http://site.with.nested.frames/inner.html' => $inner, - 'http://site.with.nested.frames/one.html' => 'Page one', - 'http://site.with.nested.frames/two.html' => 'Page two', - 'http://site.with.nested.frames/three.html' => 'Page three'))); - - $browser->get('http://site.with.nested.frames/'); - $this->assertEqual($browser->getContent(), 'Page onePage twoPage three'); - - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getFrameFocus(), array(1)); - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getFrameFocus(), array(1, 1)); - $this->assertEqual($browser->getContent(), 'Page one'); - - $this->assertTrue($browser->setFrameFocusByIndex(2)); - $this->assertEqual($browser->getFrameFocus(), array(1, 2)); - $this->assertEqual($browser->getContent(), 'Page two'); - - $browser->clearFrameFocus(); - $this->assertTrue($browser->setFrameFocusByIndex(2)); - $this->assertEqual($browser->getFrameFocus(), array(2)); - $this->assertEqual($browser->getContent(), 'Page three'); - - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getContent(), 'Page onePage two'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/collector_test.php b/3rdparty/simpletest/test/collector_test.php deleted file mode 100755 index efdbf377ece41ed96968d28f65ac82ac78d12543..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/collector_test.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php -// $Id: collector_test.php 1769 2008-04-19 14:39:00Z pp11 $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../collector.php'); -SimpleTest::ignore('MockTestSuite'); -Mock::generate('TestSuite'); - -class PathEqualExpectation extends EqualExpectation { - function __construct($value, $message = '%s') { - parent::__construct(str_replace("\\", '/', $value), $message); - } - - function test($compare) { - return parent::test(str_replace("\\", '/', $compare)); - } -} - -class TestOfCollector extends UnitTestCase { - function testCollectionIsAddedToGroup() { - $suite = new MockTestSuite(); - $suite->expectMinimumCallCount('addFile', 2); - $suite->expect( - 'addFile', - array(new PatternExpectation('/collectable\\.(1|2)$/'))); - $collector = new SimpleCollector(); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } -} - -class TestOfPatternCollector extends UnitTestCase { - - function testAddingEverythingToGroup() { - $suite = new MockTestSuite(); - $suite->expectCallCount('addFile', 2); - $suite->expect( - 'addFile', - array(new PatternExpectation('/collectable\\.(1|2)$/'))); - $collector = new SimplePatternCollector('/.*/'); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } - - function testOnlyMatchedFilesAreAddedToGroup() { - $suite = new MockTestSuite(); - $suite->expectOnce('addFile', array(new PathEqualExpectation( - dirname(__FILE__) . '/support/collector/collectable.1'))); - $collector = new SimplePatternCollector('/1$/'); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/command_line_test.php b/3rdparty/simpletest/test/command_line_test.php deleted file mode 100755 index 5baabff33c6794916815ed8ade8265677e1aa76b..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/command_line_test.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../default_reporter.php'); - -class TestOfCommandLineParsing extends UnitTestCase { - - function testDefaultsToEmptyStringToMeanNullToTheSelectiveReporter() { - $parser = new SimpleCommandLineParser(array()); - $this->assertIdentical($parser->getTest(), ''); - $this->assertIdentical($parser->getTestCase(), ''); - } - - function testNotXmlByDefault() { - $parser = new SimpleCommandLineParser(array()); - $this->assertFalse($parser->isXml()); - } - - function testCanDetectRequestForXml() { - $parser = new SimpleCommandLineParser(array('--xml')); - $this->assertTrue($parser->isXml()); - } - - function testCanReadAssignmentSyntax() { - $parser = new SimpleCommandLineParser(array('--test=myTest')); - $this->assertEqual($parser->getTest(), 'myTest'); - } - - function testCanReadFollowOnSyntax() { - $parser = new SimpleCommandLineParser(array('--test', 'myTest')); - $this->assertEqual($parser->getTest(), 'myTest'); - } - - function testCanReadShortForms() { - $parser = new SimpleCommandLineParser(array('-t', 'myTest', '-c', 'MyClass', '-x')); - $this->assertEqual($parser->getTest(), 'myTest'); - $this->assertEqual($parser->getTestCase(), 'MyClass'); - $this->assertTrue($parser->isXml()); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/compatibility_test.php b/3rdparty/simpletest/test/compatibility_test.php deleted file mode 100755 index b8635e5bb8370fa46c6d4ac2a97d23fa58188c3b..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/compatibility_test.php +++ /dev/null @@ -1,87 +0,0 @@ -<?php -// $Id: compatibility_test.php 1748 2008-04-14 01:50:41Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../compatibility.php'); - -class ComparisonClass { } -class ComparisonSubclass extends ComparisonClass { } -interface ComparisonInterface { } -class ComparisonClassWithInterface implements ComparisonInterface { } - -class TestOfCompatibility extends UnitTestCase { - - function testIsA() { - $this->assertTrue(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonClass')); - $this->assertFalse(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonSubclass')); - $this->assertTrue(SimpleTestCompatibility::isA( - new ComparisonSubclass(), - 'ComparisonClass')); - } - - function testIdentityOfNumericStrings() { - $numericString1 = "123"; - $numericString2 = "00123"; - $this->assertNotIdentical($numericString1, $numericString2); - } - - function testIdentityOfObjects() { - $object1 = new ComparisonClass(); - $object2 = new ComparisonClass(); - $this->assertIdentical($object1, $object2); - } - - function testReferences () { - $thing = "Hello"; - $thing_reference = &$thing; - $thing_copy = $thing; - $this->assertTrue(SimpleTestCompatibility::isReference( - $thing, - $thing)); - $this->assertTrue(SimpleTestCompatibility::isReference( - $thing, - $thing_reference)); - $this->assertFalse(SimpleTestCompatibility::isReference( - $thing, - $thing_copy)); - } - - function testObjectReferences () { - $object = new ComparisonClass(); - $object_reference = $object; - $object_copy = new ComparisonClass(); - $object_assignment = $object; - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object)); - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object_reference)); - $this->assertFalse(SimpleTestCompatibility::isReference( - $object, - $object_copy)); - if (version_compare(phpversion(), '5', '>=')) { - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object_assignment)); - } else { - $this->assertFalse(SimpleTestCompatibility::isReference( - $object, - $object_assignment)); - } - } - - function testInteraceComparison() { - $object = new ComparisonClassWithInterface(); - $this->assertFalse(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonInterface')); - $this->assertTrue(SimpleTestCompatibility::isA( - new ComparisonClassWithInterface(), - 'ComparisonInterface')); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/cookies_test.php b/3rdparty/simpletest/test/cookies_test.php deleted file mode 100755 index 0b49e43bf9f809805499d56d1c8ef2fc27e9662e..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/cookies_test.php +++ /dev/null @@ -1,227 +0,0 @@ -<?php -// $Id: cookies_test.php 1506 2007-05-07 00:58:03Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../cookies.php'); - -class TestOfCookie extends UnitTestCase { - - function testCookieDefaults() { - $cookie = new SimpleCookie("name"); - $this->assertFalse($cookie->getValue()); - $this->assertEqual($cookie->getPath(), "/"); - $this->assertIdentical($cookie->getHost(), false); - $this->assertFalse($cookie->getExpiry()); - $this->assertFalse($cookie->isSecure()); - } - - function testCookieAccessors() { - $cookie = new SimpleCookie( - "name", - "value", - "/path", - "Mon, 18 Nov 2002 15:50:29 GMT", - true); - $this->assertEqual($cookie->getName(), "name"); - $this->assertEqual($cookie->getValue(), "value"); - $this->assertEqual($cookie->getPath(), "/path/"); - $this->assertEqual($cookie->getExpiry(), "Mon, 18 Nov 2002 15:50:29 GMT"); - $this->assertTrue($cookie->isSecure()); - } - - function testFullHostname() { - $cookie = new SimpleCookie("name"); - $this->assertTrue($cookie->setHost("host.name.here")); - $this->assertEqual($cookie->getHost(), "host.name.here"); - $this->assertTrue($cookie->setHost("host.com")); - $this->assertEqual($cookie->getHost(), "host.com"); - } - - function testHostTruncation() { - $cookie = new SimpleCookie("name"); - $cookie->setHost("this.host.name.here"); - $this->assertEqual($cookie->getHost(), "host.name.here"); - $cookie->setHost("this.host.com"); - $this->assertEqual($cookie->getHost(), "host.com"); - $this->assertTrue($cookie->setHost("dashes.in-host.com")); - $this->assertEqual($cookie->getHost(), "in-host.com"); - } - - function testBadHosts() { - $cookie = new SimpleCookie("name"); - $this->assertFalse($cookie->setHost("gibberish")); - $this->assertFalse($cookie->setHost("host.here")); - $this->assertFalse($cookie->setHost("host..com")); - $this->assertFalse($cookie->setHost("...")); - $this->assertFalse($cookie->setHost("host.com.")); - } - - function testHostValidity() { - $cookie = new SimpleCookie("name"); - $cookie->setHost("this.host.name.here"); - $this->assertTrue($cookie->isValidHost("host.name.here")); - $this->assertTrue($cookie->isValidHost("that.host.name.here")); - $this->assertFalse($cookie->isValidHost("bad.host")); - $this->assertFalse($cookie->isValidHost("nearly.name.here")); - } - - function testPathValidity() { - $cookie = new SimpleCookie("name", "value", "/path"); - $this->assertFalse($cookie->isValidPath("/")); - $this->assertTrue($cookie->isValidPath("/path/")); - $this->assertTrue($cookie->isValidPath("/path/more")); - } - - function testSessionExpiring() { - $cookie = new SimpleCookie("name", "value", "/path"); - $this->assertTrue($cookie->isExpired(0)); - } - - function testTimestampExpiry() { - $cookie = new SimpleCookie("name", "value", "/path", 456); - $this->assertFalse($cookie->isExpired(0)); - $this->assertTrue($cookie->isExpired(457)); - $this->assertFalse($cookie->isExpired(455)); - } - - function testDateExpiry() { - $cookie = new SimpleCookie( - "name", - "value", - "/path", - "Mon, 18 Nov 2002 15:50:29 GMT"); - $this->assertTrue($cookie->isExpired("Mon, 18 Nov 2002 15:50:30 GMT")); - $this->assertFalse($cookie->isExpired("Mon, 18 Nov 2002 15:50:28 GMT")); - } - - function testAging() { - $cookie = new SimpleCookie("name", "value", "/path", 200); - $cookie->agePrematurely(199); - $this->assertFalse($cookie->isExpired(0)); - $cookie->agePrematurely(2); - $this->assertTrue($cookie->isExpired(0)); - } -} - -class TestOfCookieJar extends UnitTestCase { - - function testAddCookie() { - $jar = new SimpleCookieJar(); - $jar->setCookie("a", "A"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - } - - function testHostFilter() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', 'my-host.com'); - $jar->setCookie('b', 'B', 'another-host.com'); - $jar->setCookie('c', 'C'); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com')), - array('a=A', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('another-host.com')), - array('b=B', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('www.another-host.com')), - array('b=B', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('new-host.org')), - array('c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('/')), - array('a=A', 'b=B', 'c=C')); - } - - function testPathFilter() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/path/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/elsewhere')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/here')), array('a=A')); - } - - function testPathFilterDeeply() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/path/more_path/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/and_more')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/not_here/')), array()); - } - - function testMultipleCookieWithDifferentPathsButSameName() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', '123', false, '/path/here/'); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here')), - array('a=abc', 'a=123')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here/there')), - array('a=abc', 'a=123')); - } - - function testOverwrite() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', 'cde', false, '/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=cde')); - } - - function testClearSessionCookies() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/'); - $jar->restartSession(); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testExpiryFilterByDate() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT'); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - $jar->restartSession("Wed, 25-Dec-02 04:24:21 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testExpiryFilterByAgeing() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT'); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - $jar->agePrematurely(2); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testCookieClearing() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', '', false, '/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=')); - } - - function testCookieClearByLoweringDate() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/', 'Wed, 25-Dec-02 04:24:21 GMT'); - $jar->setCookie('a', 'def', false, '/', 'Wed, 25-Dec-02 04:24:19 GMT'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=def')); - $jar->restartSession('Wed, 25-Dec-02 04:24:20 GMT'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/detached_test.php b/3rdparty/simpletest/test/detached_test.php deleted file mode 100755 index f651d97eb61404bf57c31f47760f4b434299976c..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/detached_test.php +++ /dev/null @@ -1,15 +0,0 @@ -<?php -// $Id: detached_test.php 1884 2009-07-01 16:30:40Z lastcraft $ -require_once('../detached.php'); -require_once('../reporter.php'); - -// The following URL will depend on your own installation. -$command = 'php ' . dirname(__FILE__) . '/visual_test.php xml'; - -$test = new TestSuite('Remote tests'); -$test->add(new DetachedTestCase($command)); -if (SimpleReporter::inCli()) { - exit ($test->run(new TextReporter()) ? 0 : 1); -} -$test->run(new HtmlReporter()); -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/dumper_test.php b/3rdparty/simpletest/test/dumper_test.php deleted file mode 100755 index 789047de92467d02abc1a75bf8847335df24d615..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/dumper_test.php +++ /dev/null @@ -1,88 +0,0 @@ -<?php -// $Id: dumper_test.php 1505 2007-04-30 23:39:59Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); - -class DumperDummy { -} - -class TestOfTextFormatting extends UnitTestCase { - - function testClipping() { - $dumper = new SimpleDumper(); - $this->assertEqual( - $dumper->clipString("Hello", 6), - "Hello", - "Hello, 6->%s"); - $this->assertEqual( - $dumper->clipString("Hello", 5), - "Hello", - "Hello, 5->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 3), - "Hel...", - "Hello world, 3->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 6, 3), - "Hello ...", - "Hello world, 6, 3->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 3, 6), - "...o w...", - "Hello world, 3, 6->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 4, 11), - "...orld", - "Hello world, 4, 11->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 4, 12), - "...orld", - "Hello world, 4, 12->%s"); - } - - function testDescribeNull() { - $dumper = new SimpleDumper(); - $this->assertPattern('/null/i', $dumper->describeValue(null)); - } - - function testDescribeBoolean() { - $dumper = new SimpleDumper(); - $this->assertPattern('/boolean/i', $dumper->describeValue(true)); - $this->assertPattern('/true/i', $dumper->describeValue(true)); - $this->assertPattern('/false/i', $dumper->describeValue(false)); - } - - function testDescribeString() { - $dumper = new SimpleDumper(); - $this->assertPattern('/string/i', $dumper->describeValue('Hello')); - $this->assertPattern('/Hello/', $dumper->describeValue('Hello')); - } - - function testDescribeInteger() { - $dumper = new SimpleDumper(); - $this->assertPattern('/integer/i', $dumper->describeValue(35)); - $this->assertPattern('/35/', $dumper->describeValue(35)); - } - - function testDescribeFloat() { - $dumper = new SimpleDumper(); - $this->assertPattern('/float/i', $dumper->describeValue(0.99)); - $this->assertPattern('/0\.99/', $dumper->describeValue(0.99)); - } - - function testDescribeArray() { - $dumper = new SimpleDumper(); - $this->assertPattern('/array/i', $dumper->describeValue(array(1, 4))); - $this->assertPattern('/2/i', $dumper->describeValue(array(1, 4))); - } - - function testDescribeObject() { - $dumper = new SimpleDumper(); - $this->assertPattern( - '/object/i', - $dumper->describeValue(new DumperDummy())); - $this->assertPattern( - '/DumperDummy/i', - $dumper->describeValue(new DumperDummy())); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/eclipse_test.php b/3rdparty/simpletest/test/eclipse_test.php deleted file mode 100755 index c90cbc918fd614e6d45f526f33665199deaed9ea..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/eclipse_test.php +++ /dev/null @@ -1,32 +0,0 @@ -<?php -// $Id: eclipse_test.php 1739 2008-04-09 20:48:37Z edwardzyang $ - -//To run this from the eclipse plugin...you need to make sure that the -//SimpleTest path in the preferences is the same as the location of the -//eclipse.php file below otherwise you end up with two "different" eclipse.php -//files included and that does not work... - -include_once(dirname(__FILE__) . '/../eclipse.php'); -Mock::generate('SimpleSocket'); - -class TestOfEclipse extends UnitTestCase { - - function testPass() { - $listener = &new MockSimpleSocket(); - - $fullpath = realpath(dirname(__FILE__).'/support/test1.php'); - $testpath = EclipseReporter::escapeVal($fullpath); - $expected = "{status:\"pass\",message:\"pass1 at [$testpath line 4]\",group:\"$testpath\",case:\"test1\",method:\"test_pass\"}"; - //this should work...but it doesn't so the next line and the last line are the hacks - //$listener->expectOnce('write',array($expected)); - $listener->setReturnValue('write',-1); - - $pathparts = pathinfo($fullpath); - $filename = $pathparts['basename']; - $test= &new TestSuite($filename); - $test->addTestFile($fullpath); - $test->run(new EclipseReporter($listener)); - $this->assertEqual($expected,$listener->output); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/encoding_test.php b/3rdparty/simpletest/test/encoding_test.php deleted file mode 100755 index a09236e057cc4df97cb7b5603c36e2e328de8b5d..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/encoding_test.php +++ /dev/null @@ -1,240 +0,0 @@ -<?php -// $Id: encoding_test.php 1963 2009-10-07 11:57:52Z maetl_ $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../url.php'); -require_once(dirname(__FILE__) . '/../socket.php'); - -Mock::generate('SimpleSocket'); - -class TestOfEncodedParts extends UnitTestCase { - - function testFormEncodedAsKeyEqualsValue() { - $pair = new SimpleEncodedPair('a', 'A'); - $this->assertEqual($pair->asRequest(), 'a=A'); - } - - function testMimeEncodedAsHeadersAndContent() { - $pair = new SimpleEncodedPair('a', 'A'); - $this->assertEqual( - $pair->asMime(), - "Content-Disposition: form-data; name=\"a\"\r\n\r\nA"); - } - - function testAttachmentEncodedAsHeadersWithDispositionAndContent() { - $part = new SimpleAttachment('a', 'A', 'aaa.txt'); - $this->assertEqual( - $part->asMime(), - "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . - "Content-Type: text/plain\r\n\r\nA"); - } -} - -class TestOfEncoding extends UnitTestCase { - private $content_so_far; - - function write($content) { - $this->content_so_far .= $content; - } - - function clear() { - $this->content_so_far = ''; - } - - function assertWritten($encoding, $content, $message = '%s') { - $this->clear(); - $encoding->writeTo($this); - $this->assertIdentical($this->content_so_far, $content, $message); - } - - function testGetEmpty() { - $encoding = new SimpleGetEncoding(); - $this->assertIdentical($encoding->getValue('a'), false); - $this->assertIdentical($encoding->asUrlRequest(), ''); - } - - function testPostEmpty() { - $encoding = new SimplePostEncoding(); - $this->assertIdentical($encoding->getValue('a'), false); - $this->assertWritten($encoding, ''); - } - - function testPrefilled() { - $encoding = new SimplePostEncoding(array('a' => 'aaa')); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertWritten($encoding, 'a=aaa'); - } - - function testPrefilledWithTwoLevels() { - $query = array('a' => array('aa' => 'aaa')); - $encoding = new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa]' => 'aaa')); - $this->assertIdentical($encoding->getValue('a[aa]'), 'aaa'); - $this->assertWritten($encoding, 'a%5Baa%5D=aaa'); - } - - function testPrefilledWithThreeLevels() { - $query = array('a' => array('aa' => array('aaa' => 'aaaa'))); - $encoding = new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa][aaa]' => 'aaaa')); - $this->assertIdentical($encoding->getValue('a[aa][aaa]'), 'aaaa'); - $this->assertWritten($encoding, 'a%5Baa%5D%5Baaa%5D=aaaa'); - } - - function testPrefilledWithObject() { - $encoding = new SimplePostEncoding(new SimpleEncoding(array('a' => 'aaa'))); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertWritten($encoding, 'a=aaa'); - } - - function testMultiplePrefilled() { - $query = array('a' => array('a1', 'a2')); - $encoding = new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[0]' => 'a1', 'a[1]' => 'a2')); - $this->assertIdentical($encoding->getValue('a[0]'), 'a1'); - $this->assertIdentical($encoding->getValue('a[1]'), 'a2'); - $this->assertWritten($encoding, 'a%5B0%5D=a1&a%5B1%5D=a2'); - } - - function testSingleParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $this->assertEqual($encoding->getValue('a'), 'Hello'); - $this->assertWritten($encoding, 'a=Hello'); - } - - function testFalseParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', false); - $this->assertEqual($encoding->getValue('a'), false); - $this->assertWritten($encoding, ''); - } - - function testUrlEncoding() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello there!'); - $this->assertWritten($encoding, 'a=Hello+there%21'); - } - - function testUrlEncodingOfKey() { - $encoding = new SimplePostEncoding(); - $encoding->add('a!', 'Hello'); - $this->assertWritten($encoding, 'a%21=Hello'); - } - - function testMultipleParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $encoding->add('b', 'Goodbye'); - $this->assertWritten($encoding, 'a=Hello&b=Goodbye'); - } - - function testEmptyParameters() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', ''); - $encoding->add('b', ''); - $this->assertWritten($encoding, 'a=&b='); - } - - function testRepeatedParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $encoding->add('a', 'Goodbye'); - $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); - $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); - } - - function testAddingLists() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', array('Hello', 'Goodbye')); - $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); - $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); - } - - function testMergeInHash() { - $encoding = new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); - $encoding->merge(array('a' => 'A2')); - $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); - $this->assertIdentical($encoding->getValue('b'), 'B'); - } - - function testMergeInObject() { - $encoding = new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); - $encoding->merge(new SimpleEncoding(array('a' => 'A2'))); - $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); - $this->assertIdentical($encoding->getValue('b'), 'B'); - } - - function testPrefilledMultipart() { - $encoding = new SimpleMultipartEncoding(array('a' => 'aaa'), 'boundary'); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertwritten($encoding, - "--boundary\r\n" . - "Content-Disposition: form-data; name=\"a\"\r\n" . - "\r\n" . - "aaa\r\n" . - "--boundary--\r\n"); - } - - function testAttachment() { - $encoding = new SimpleMultipartEncoding(array(), 'boundary'); - $encoding->attach('a', 'aaa', 'aaa.txt'); - $this->assertIdentical($encoding->getValue('a'), 'aaa.txt'); - $this->assertwritten($encoding, - "--boundary\r\n" . - "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . - "Content-Type: text/plain\r\n" . - "\r\n" . - "aaa\r\n" . - "--boundary--\r\n"); - } - - function testEntityEncodingDefaultContentType() { - $encoding = new SimpleEntityEncoding(); - $this->assertIdentical($encoding->getContentType(), 'application/x-www-form-urlencoded'); - $this->assertWritten($encoding, ''); - } - - function testEntityEncodingTextBody() { - $encoding = new SimpleEntityEncoding('plain text'); - $this->assertIdentical($encoding->getContentType(), 'text/plain'); - $this->assertWritten($encoding, 'plain text'); - } - - function testEntityEncodingXmlBody() { - $encoding = new SimpleEntityEncoding('<p><a>xml</b><b>text</b></p>', 'text/xml'); - $this->assertIdentical($encoding->getContentType(), 'text/xml'); - $this->assertWritten($encoding, '<p><a>xml</b><b>text</b></p>'); - } -} - -class TestOfEncodingHeaders extends UnitTestCase { - - function testEmptyEncodingWritesZeroContentLength() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 0\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $encoding = new SimpleEntityEncoding(); - $encoding->writeHeadersTo($socket); - } - - function testTextEncodingWritesDefaultContentType() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 18\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: text/plain\r\n")); - $encoding = new SimpleEntityEncoding('one two three four'); - $encoding->writeHeadersTo($socket); - } - - function testEmptyMultipartEncodingWritesEndBoundaryContentLength() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 14\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: multipart/form-data; boundary=boundary\r\n")); - $encoding = new SimpleMultipartEncoding(array(), 'boundary'); - $encoding->writeHeadersTo($socket); - } - -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/errors_test.php b/3rdparty/simpletest/test/errors_test.php deleted file mode 100755 index ebb9e05891f25d15279f986d58732edd096ae984..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/errors_test.php +++ /dev/null @@ -1,229 +0,0 @@ -<?php -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../errors.php'); -require_once(dirname(__FILE__) . '/../expectation.php'); -require_once(dirname(__FILE__) . '/../test_case.php'); -Mock::generate('SimpleTestCase'); -Mock::generate('SimpleExpectation'); -SimpleTest::ignore('MockSimpleTestCase'); - -class TestOfErrorQueue extends UnitTestCase { - - function setUp() { - $context = SimpleTest::getContext(); - $queue = $context->get('SimpleErrorQueue'); - $queue->clear(); - } - - function tearDown() { - $context = SimpleTest::getContext(); - $queue = $context->get('SimpleErrorQueue'); - $queue->clear(); - } - - function testExpectationMatchCancelsIncomingError() { - $test = new MockSimpleTestCase(); - $test->expectOnce('assert', array( - new IdenticalExpectation(new AnythingExpectation()), - 'B', - 'a message')); - $test->setReturnValue('assert', true); - $test->expectNever('error'); - $queue = new SimpleErrorQueue(); - $queue->setTestCase($test); - $queue->expectError(new AnythingExpectation(), 'a message'); - $queue->add(1024, 'B', 'b.php', 100); - } -} - -class TestOfErrorTrap extends UnitTestCase { - private $old; - - function setUp() { - $this->old = error_reporting(E_ALL); - set_error_handler('SimpleTestErrorHandler'); - } - - function tearDown() { - restore_error_handler(); - error_reporting($this->old); - } - - function testQueueStartsEmpty() { - $context = SimpleTest::getContext(); - $queue = $context->get('SimpleErrorQueue'); - $this->assertFalse($queue->extract()); - } - - function testErrorsAreSwallowedByMatchingExpectation() { - $this->expectError('Ouch!'); - trigger_error('Ouch!'); - } - - function testErrorsAreSwallowedInOrder() { - $this->expectError('a'); - $this->expectError('b'); - trigger_error('a'); - trigger_error('b'); - } - - function testAnyErrorCanBeSwallowed() { - $this->expectError(); - trigger_error('Ouch!'); - } - - function testErrorCanBeSwallowedByPatternMatching() { - $this->expectError(new PatternExpectation('/ouch/i')); - trigger_error('Ouch!'); - } - - function testErrorWithPercentsPassesWithNoSprintfError() { - $this->expectError("%"); - trigger_error('%'); - } -} - -class TestOfErrors extends UnitTestCase { - private $old; - - function setUp() { - $this->old = error_reporting(E_ALL); - } - - function tearDown() { - error_reporting($this->old); - } - - function testDefaultWhenAllReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!'); - } - - function testNoticeWhenReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!', E_USER_NOTICE); - } - - function testWarningWhenReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!', E_USER_WARNING); - } - - function testErrorWhenReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!', E_USER_ERROR); - } - - function testNoNoticeWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_NOTICE); - } - - function testNoWarningWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_WARNING); - } - - function testNoticeSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_NOTICE); - } - - function testWarningSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_WARNING); - } - - function testErrorWithPercentsReportedWithNoSprintfError() { - $this->expectError('%'); - trigger_error('%'); - } -} - -class TestOfPHP52RecoverableErrors extends UnitTestCase { - function skip() { - $this->skipIf( - version_compare(phpversion(), '5.2', '<'), - 'E_RECOVERABLE_ERROR not tested for PHP below 5.2'); - } - - function testError() { - eval(' - class RecoverableErrorTestingStub { - function ouch(RecoverableErrorTestingStub $obj) { - } - } - '); - - $stub = new RecoverableErrorTestingStub(); - $this->expectError(new PatternExpectation('/must be an instance of RecoverableErrorTestingStub/i')); - $stub->ouch(new stdClass()); - } -} - -class TestOfErrorsExcludingPHP52AndAbove extends UnitTestCase { - function skip() { - $this->skipIf( - version_compare(phpversion(), '5.2', '>='), - 'E_USER_ERROR not tested for PHP 5.2 and above'); - } - - function testNoErrorWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_ERROR); - } - - function testErrorSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_ERROR); - } -} - -SimpleTest::ignore('TestOfNotEnoughErrors'); -/** - * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors} - * to verify that it fails as expected. - * - * @ignore - */ -class TestOfNotEnoughErrors extends UnitTestCase { - function testExpectTwoErrorsThrowOne() { - $this->expectError('Error 1'); - trigger_error('Error 1'); - $this->expectError('Error 2'); - } -} - -SimpleTest::ignore('TestOfLeftOverErrors'); -/** - * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors} - * to verify that it fails as expected. - * - * @ignore - */ -class TestOfLeftOverErrors extends UnitTestCase { - function testExpectOneErrorGetTwo() { - $this->expectError('Error 1'); - trigger_error('Error 1'); - trigger_error('Error 2'); - } -} - -class TestRunnerForLeftOverAndNotEnoughErrors extends UnitTestCase { - function testRunLeftOverErrorsTestCase() { - $test = new TestOfLeftOverErrors(); - $this->assertFalse($test->run(new SimpleReporter())); - } - - function testRunNotEnoughErrors() { - $test = new TestOfNotEnoughErrors(); - $this->assertFalse($test->run(new SimpleReporter())); - } -} - -// TODO: Add stacked error handler test -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/exceptions_test.php b/3rdparty/simpletest/test/exceptions_test.php deleted file mode 100755 index 1011543d4fa8c9443a76377272c7b20513d85379..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/exceptions_test.php +++ /dev/null @@ -1,183 +0,0 @@ -<?php -// $Id: exceptions_test.php 1882 2009-07-01 14:30:05Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../exceptions.php'); -require_once(dirname(__FILE__) . '/../expectation.php'); -require_once(dirname(__FILE__) . '/../test_case.php'); -Mock::generate('SimpleTestCase'); -Mock::generate('SimpleExpectation'); - -class MyTestException extends Exception {} -class HigherTestException extends MyTestException {} -class OtherTestException extends Exception {} - -class TestOfExceptionExpectation extends UnitTestCase { - - function testExceptionClassAsStringWillMatchExceptionsRootedOnThatClass() { - $expectation = new ExceptionExpectation('MyTestException'); - $this->assertTrue($expectation->test(new MyTestException())); - $this->assertTrue($expectation->test(new HigherTestException())); - $this->assertFalse($expectation->test(new OtherTestException())); - } - - function testMatchesClassAndMessageWhenExceptionExpected() { - $expectation = new ExceptionExpectation(new MyTestException('Hello')); - $this->assertTrue($expectation->test(new MyTestException('Hello'))); - $this->assertFalse($expectation->test(new HigherTestException('Hello'))); - $this->assertFalse($expectation->test(new OtherTestException('Hello'))); - $this->assertFalse($expectation->test(new MyTestException('Goodbye'))); - $this->assertFalse($expectation->test(new MyTestException())); - } - - function testMessagelessExceptionMatchesOnlyOnClass() { - $expectation = new ExceptionExpectation(new MyTestException()); - $this->assertTrue($expectation->test(new MyTestException())); - $this->assertFalse($expectation->test(new HigherTestException())); - } -} - -class TestOfExceptionTrap extends UnitTestCase { - - function testNoExceptionsInQueueMeansNoTestMessages() { - $test = new MockSimpleTestCase(); - $test->expectNever('assert'); - $queue = new SimpleExceptionTrap(); - $this->assertFalse($queue->isExpected($test, new Exception())); - } - - function testMatchingExceptionGivesTrue() { - $expectation = new MockSimpleExpectation(); - $expectation->setReturnValue('test', true); - $test = new MockSimpleTestCase(); - $test->setReturnValue('assert', true); - $queue = new SimpleExceptionTrap(); - $queue->expectException($expectation, 'message'); - $this->assertTrue($queue->isExpected($test, new Exception())); - } - - function testMatchingExceptionTriggersAssertion() { - $test = new MockSimpleTestCase(); - $test->expectOnce('assert', array( - '*', - new ExceptionExpectation(new Exception()), - 'message')); - $queue = new SimpleExceptionTrap(); - $queue->expectException(new ExceptionExpectation(new Exception()), 'message'); - $queue->isExpected($test, new Exception()); - } -} - -class TestOfCatchingExceptions extends UnitTestCase { - - function testCanCatchAnyExpectedException() { - $this->expectException(); - throw new Exception(); - } - - function testCanMatchExceptionByClass() { - $this->expectException('MyTestException'); - throw new HigherTestException(); - } - - function testCanMatchExceptionExactly() { - $this->expectException(new Exception('Ouch')); - throw new Exception('Ouch'); - } - - function testLastListedExceptionIsTheOneThatCounts() { - $this->expectException('OtherTestException'); - $this->expectException('MyTestException'); - throw new HigherTestException(); - } -} - -class TestOfIgnoringExceptions extends UnitTestCase { - - function testCanIgnoreAnyException() { - $this->ignoreException(); - throw new Exception(); - } - - function testCanIgnoreSpecificException() { - $this->ignoreException('MyTestException'); - throw new MyTestException(); - } - - function testCanIgnoreExceptionExactly() { - $this->ignoreException(new Exception('Ouch')); - throw new Exception('Ouch'); - } - - function testIgnoredExceptionsDoNotMaskExpectedExceptions() { - $this->ignoreException('Exception'); - $this->expectException('MyTestException'); - throw new MyTestException(); - } - - function testCanIgnoreMultipleExceptions() { - $this->ignoreException('MyTestException'); - $this->ignoreException('OtherTestException'); - throw new OtherTestException(); - } -} - -class TestOfCallingTearDownAfterExceptions extends UnitTestCase { - private $debri = 0; - - function tearDown() { - $this->debri--; - } - - function testLeaveSomeDebri() { - $this->debri++; - $this->expectException(); - throw new Exception(__FUNCTION__); - } - - function testDebriWasRemovedOnce() { - $this->assertEqual($this->debri, 0); - } -} - -class TestOfExceptionThrownInSetUpDoesNotRunTestBody extends UnitTestCase { - - function setUp() { - $this->expectException(); - throw new Exception(); - } - - function testShouldNotBeRun() { - $this->fail('This test body should not be run'); - } - - function testShouldNotBeRunEither() { - $this->fail('This test body should not be run either'); - } -} - -class TestOfExpectExceptionWithSetUp extends UnitTestCase { - - function setUp() { - $this->expectException(); - } - - function testThisExceptionShouldBeCaught() { - throw new Exception(); - } - - function testJustThrowingMyTestException() { - throw new MyTestException(); - } -} - -class TestOfThrowingExceptionsInTearDown extends UnitTestCase { - - function tearDown() { - throw new Exception(); - } - - function testDoesntFatal() { - $this->expectException(); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/expectation_test.php b/3rdparty/simpletest/test/expectation_test.php deleted file mode 100755 index 31fbe65e683289b907c14b9bec36e7174cb378db..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/expectation_test.php +++ /dev/null @@ -1,317 +0,0 @@ -<?php -// $Id: expectation_test.php 2009 2011-04-28 08:57:25Z pp11 $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../expectation.php'); - -class TestOfEquality extends UnitTestCase { - - function testBoolean() { - $is_true = new EqualExpectation(true); - $this->assertTrue($is_true->test(true)); - $this->assertFalse($is_true->test(false)); - } - - function testStringMatch() { - $hello = new EqualExpectation("Hello"); - $this->assertTrue($hello->test("Hello")); - $this->assertFalse($hello->test("Goodbye")); - } - - function testInteger() { - $fifteen = new EqualExpectation(15); - $this->assertTrue($fifteen->test(15)); - $this->assertFalse($fifteen->test(14)); - } - - function testFloat() { - $pi = new EqualExpectation(3.14); - $this->assertTrue($pi->test(3.14)); - $this->assertFalse($pi->test(3.15)); - } - - function testArray() { - $colours = new EqualExpectation(array("r", "g", "b")); - $this->assertTrue($colours->test(array("r", "g", "b"))); - $this->assertFalse($colours->test(array("g", "b", "r"))); - } - - function testHash() { - $is_blue = new EqualExpectation(array("r" => 0, "g" => 0, "b" => 255)); - $this->assertTrue($is_blue->test(array("r" => 0, "g" => 0, "b" => 255))); - $this->assertFalse($is_blue->test(array("r" => 0, "g" => 255, "b" => 0))); - } - - function testHashWithOutOfOrderKeysShouldStillMatch() { - $any_order = new EqualExpectation(array('a' => 1, 'b' => 2)); - $this->assertTrue($any_order->test(array('b' => 2, 'a' => 1))); - } -} - -class TestOfWithin extends UnitTestCase { - - function testWithinFloatingPointMargin() { - $within = new WithinMarginExpectation(1.0, 0.2); - $this->assertFalse($within->test(0.7)); - $this->assertTrue($within->test(0.8)); - $this->assertTrue($within->test(0.9)); - $this->assertTrue($within->test(1.1)); - $this->assertTrue($within->test(1.2)); - $this->assertFalse($within->test(1.3)); - } - - function testOutsideFloatingPointMargin() { - $within = new OutsideMarginExpectation(1.0, 0.2); - $this->assertTrue($within->test(0.7)); - $this->assertFalse($within->test(0.8)); - $this->assertFalse($within->test(1.2)); - $this->assertTrue($within->test(1.3)); - } -} - -class TestOfInequality extends UnitTestCase { - - function testStringMismatch() { - $not_hello = new NotEqualExpectation("Hello"); - $this->assertTrue($not_hello->test("Goodbye")); - $this->assertFalse($not_hello->test("Hello")); - } -} - -class RecursiveNasty { - private $me; - - function RecursiveNasty() { - $this->me = $this; - } -} - -class OpaqueContainer { - private $stuff; - private $value; - - public function __construct($value) { - $this->value = $value; - } -} - -class DerivedOpaqueContainer extends OpaqueContainer { - // Deliberately have a variable whose name with the same suffix as a later - // variable - private $new_value = 1; - - // Deliberately obscures the variable of the same name in the base - // class. - private $value; - - public function __construct($value, $base_value) { - parent::__construct($base_value); - $this->value = $value; - } -} - -class TestOfIdentity extends UnitTestCase { - - function testType() { - $string = new IdenticalExpectation("37"); - $this->assertTrue($string->test("37")); - $this->assertFalse($string->test(37)); - $this->assertFalse($string->test("38")); - } - - function _testNastyPhp5Bug() { - $this->assertFalse(new RecursiveNasty() != new RecursiveNasty()); - } - - function _testReallyHorribleRecursiveStructure() { - $hopeful = new IdenticalExpectation(new RecursiveNasty()); - $this->assertTrue($hopeful->test(new RecursiveNasty())); - } - - function testCanComparePrivateMembers() { - $expectFive = new IdenticalExpectation(new OpaqueContainer(5)); - $this->assertTrue($expectFive->test(new OpaqueContainer(5))); - $this->assertFalse($expectFive->test(new OpaqueContainer(6))); - } - - function testCanComparePrivateMembersOfObjectsInArrays() { - $expectFive = new IdenticalExpectation(array(new OpaqueContainer(5))); - $this->assertTrue($expectFive->test(array(new OpaqueContainer(5)))); - $this->assertFalse($expectFive->test(array(new OpaqueContainer(6)))); - } - - function testCanComparePrivateMembersOfObjectsWherePrivateMemberOfBaseClassIsObscured() { - $expectFive = new IdenticalExpectation(array(new DerivedOpaqueContainer(1,2))); - $this->assertTrue($expectFive->test(array(new DerivedOpaqueContainer(1,2)))); - $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(0,2)))); - $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(0,9)))); - $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(1,0)))); - } -} - -class TransparentContainer { - public $value; - - public function __construct($value) { - $this->value = $value; - } -} - -class TestOfMemberComparison extends UnitTestCase { - - function testMemberExpectationCanMatchPublicMember() { - $expect_five = new MemberExpectation('value', 5); - $this->assertTrue($expect_five->test(new TransparentContainer(5))); - $this->assertFalse($expect_five->test(new TransparentContainer(8))); - } - - function testMemberExpectationCanMatchPrivateMember() { - $expect_five = new MemberExpectation('value', 5); - $this->assertTrue($expect_five->test(new OpaqueContainer(5))); - $this->assertFalse($expect_five->test(new OpaqueContainer(8))); - } - - function testMemberExpectationCanMatchPrivateMemberObscuredByDerivedClass() { - $expect_five = new MemberExpectation('value', 5); - $this->assertTrue($expect_five->test(new DerivedOpaqueContainer(5,8))); - $this->assertTrue($expect_five->test(new DerivedOpaqueContainer(5,5))); - $this->assertFalse($expect_five->test(new DerivedOpaqueContainer(8,8))); - $this->assertFalse($expect_five->test(new DerivedOpaqueContainer(8,5))); - } - -} - -class DummyReferencedObject{} - -class TestOfReference extends UnitTestCase { - - function testReference() { - $foo = "foo"; - $ref = &$foo; - $not_ref = $foo; - $bar = "bar"; - - $expect = new ReferenceExpectation($foo); - $this->assertTrue($expect->test($ref)); - $this->assertFalse($expect->test($not_ref)); - $this->assertFalse($expect->test($bar)); - } -} - -class TestOfNonIdentity extends UnitTestCase { - - function testType() { - $string = new NotIdenticalExpectation("37"); - $this->assertTrue($string->test("38")); - $this->assertTrue($string->test(37)); - $this->assertFalse($string->test("37")); - } -} - -class TestOfPatterns extends UnitTestCase { - - function testWanted() { - $pattern = new PatternExpectation('/hello/i'); - $this->assertTrue($pattern->test("Hello world")); - $this->assertFalse($pattern->test("Goodbye world")); - } - - function testUnwanted() { - $pattern = new NoPatternExpectation('/hello/i'); - $this->assertFalse($pattern->test("Hello world")); - $this->assertTrue($pattern->test("Goodbye world")); - } -} - -class ExpectedMethodTarget { - function hasThisMethod() {} -} - -class TestOfMethodExistence extends UnitTestCase { - - function testHasMethod() { - $instance = new ExpectedMethodTarget(); - $expectation = new MethodExistsExpectation('hasThisMethod'); - $this->assertTrue($expectation->test($instance)); - $expectation = new MethodExistsExpectation('doesNotHaveThisMethod'); - $this->assertFalse($expectation->test($instance)); - } -} - -class TestOfIsA extends UnitTestCase { - - function testString() { - $expectation = new IsAExpectation('string'); - $this->assertTrue($expectation->test('Hello')); - $this->assertFalse($expectation->test(5)); - } - - function testBoolean() { - $expectation = new IsAExpectation('boolean'); - $this->assertTrue($expectation->test(true)); - $this->assertFalse($expectation->test(1)); - } - - function testBool() { - $expectation = new IsAExpectation('bool'); - $this->assertTrue($expectation->test(true)); - $this->assertFalse($expectation->test(1)); - } - - function testDouble() { - $expectation = new IsAExpectation('double'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testFloat() { - $expectation = new IsAExpectation('float'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testReal() { - $expectation = new IsAExpectation('real'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testInteger() { - $expectation = new IsAExpectation('integer'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test(5.0)); - } - - function testInt() { - $expectation = new IsAExpectation('int'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test(5.0)); - } - - function testScalar() { - $expectation = new IsAExpectation('scalar'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test(array(5))); - } - - function testNumeric() { - $expectation = new IsAExpectation('numeric'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test('string')); - } - - function testNull() { - $expectation = new IsAExpectation('null'); - $this->assertTrue($expectation->test(null)); - $this->assertFalse($expectation->test('string')); - } -} - -class TestOfNotA extends UnitTestCase { - - function testString() { - $expectation = new NotAExpectation('string'); - $this->assertFalse($expectation->test('Hello')); - $this->assertTrue($expectation->test(5)); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/form_test.php b/3rdparty/simpletest/test/form_test.php deleted file mode 100755 index 70a18f2b3a0a3abe7cfccb6c4475f0bc6fbb3b08..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/form_test.php +++ /dev/null @@ -1,344 +0,0 @@ -<?php -// $Id: form_test.php 1996 2010-07-27 09:11:59Z pp11 $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../url.php'); -require_once(dirname(__FILE__) . '/../form.php'); -require_once(dirname(__FILE__) . '/../page.php'); -require_once(dirname(__FILE__) . '/../encoding.php'); -Mock::generate('SimplePage'); - -class TestOfForm extends UnitTestCase { - - function page($url, $action = false) { - $page = new MockSimplePage(); - $page->returns('getUrl', new SimpleUrl($url)); - $page->returns('expandUrl', new SimpleUrl($url)); - return $page; - } - - function testFormAttributes() { - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php', 'id' => '33')); - $form = new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual($form->getMethod(), 'get'); - $this->assertIdentical($form->getId(), '33'); - $this->assertNull($form->getValue(new SimpleByName('a'))); - } - - function testAction() { - $page = new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('here.php'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/here.php')); - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php')); - $form = new SimpleForm($tag, $page); - $this->assertEqual($form->getAction(), new SimpleUrl('http://host/here.php')); - } - - function testEmptyAction() { - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => '', 'id' => '33')); - $form = new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/a/index.html')); - } - - function testMissingAction() { - $tag = new SimpleFormTag(array('method' => 'GET')); - $form = new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/a/index.html')); - } - - function testRootAction() { - $page = new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('/'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/')); - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => '/')); - $form = new SimpleForm($tag, $page); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/')); - } - - function testDefaultFrameTargetOnForm() { - $page = new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('here.php'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/here.php')); - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php')); - $form = new SimpleForm($tag, $page); - $form->setDefaultTarget('frame'); - $expected = new SimpleUrl('http://host/here.php'); - $expected->setTarget('frame'); - $this->assertEqual($form->getAction(), $expected); - } - - function testTextWidget() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleTextTag( - array('name' => 'me', 'type' => 'text', 'value' => 'Myself'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Myself'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'Not me')); - $this->assertFalse($form->setField(new SimpleByName('not_present'), 'Not me')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Not me'); - $this->assertNull($form->getValue(new SimpleByName('not_present'))); - } - - function testTextWidgetById() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleTextTag( - array('name' => 'me', 'type' => 'text', 'value' => 'Myself', 'id' => 50))); - $this->assertIdentical($form->getValue(new SimpleById(50)), 'Myself'); - $this->assertTrue($form->setField(new SimpleById(50), 'Not me')); - $this->assertIdentical($form->getValue(new SimpleById(50)), 'Not me'); - } - - function testTextWidgetByLabel() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $widget = new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a')); - $form->addWidget($widget); - $widget->setLabel('thing'); - $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'a'); - $this->assertTrue($form->setField(new SimpleByLabel('thing'), 'b')); - $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'b'); - } - - function testSubmitEmpty() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $this->assertIdentical($form->submit(), new SimpleGetEncoding()); - } - - function testSubmitButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go!', 'id' => '9'))); - $this->assertTrue($form->hasSubmit(new SimpleByName('go'))); - $this->assertEqual($form->getValue(new SimpleByName('go')), 'Go!'); - $this->assertEqual($form->getValue(new SimpleById(9)), 'Go!'); - $this->assertEqual( - $form->submitButton(new SimpleByName('go')), - new SimpleGetEncoding(array('go' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!')), - new SimpleGetEncoding(array('go' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleById(9)), - new SimpleGetEncoding(array('go' => 'Go!'))); - } - - function testSubmitWithAdditionalParameters() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!'), array('a' => 'A')), - new SimpleGetEncoding(array('go' => 'Go!', 'a' => 'A'))); - } - - function testSubmitButtonWithLabelOfSubmit() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'test', 'value' => 'Submit'))); - $this->assertEqual( - $form->submitButton(new SimpleByName('test')), - new SimpleGetEncoding(array('test' => 'Submit'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('test' => 'Submit'))); - } - - function testSubmitButtonWithWhitespacePaddedLabelOfSubmit() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'test', 'value' => ' Submit '))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('test' => ' Submit '))); - } - - function testImageSubmitButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleImageSubmitTag(array( - 'type' => 'image', - 'src' => 'source.jpg', - 'name' => 'go', - 'alt' => 'Go!', - 'id' => '9'))); - $this->assertTrue($form->hasImage(new SimpleByLabel('Go!'))); - $this->assertEqual( - $form->submitImage(new SimpleByLabel('Go!'), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - $this->assertTrue($form->hasImage(new SimpleByName('go'))); - $this->assertEqual( - $form->submitImage(new SimpleByName('go'), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - $this->assertTrue($form->hasImage(new SimpleById(9))); - $this->assertEqual( - $form->submitImage(new SimpleById(9), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - } - - function testImageSubmitButtonWithAdditionalData() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleImageSubmitTag(array( - 'type' => 'image', - 'src' => 'source.jpg', - 'name' => 'go', - 'alt' => 'Go!'))); - $this->assertEqual( - $form->submitImage(new SimpleByLabel('Go!'), 100, 101, array('a' => 'A')), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A'))); - } - - function testButtonTag() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $widget = new SimpleButtonTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go', 'id' => '9')); - $widget->addContent('Go!'); - $form->addWidget($widget); - $this->assertTrue($form->hasSubmit(new SimpleByName('go'))); - $this->assertTrue($form->hasSubmit(new SimpleByLabel('Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByName('go')), - new SimpleGetEncoding(array('go' => 'Go'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!')), - new SimpleGetEncoding(array('go' => 'Go'))); - $this->assertEqual( - $form->submitButton(new SimpleById(9)), - new SimpleGetEncoding(array('go' => 'Go'))); - } - - function testMultipleFieldsWithSameNameSubmitted() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $input = new SimpleTextTag(array('name' => 'elements[]', 'value' => '1')); - $form->addWidget($input); - $input = new SimpleTextTag(array('name' => 'elements[]', 'value' => '2')); - $form->addWidget($input); - $form->setField(new SimpleByLabelOrName('elements[]'), '3', 1); - $form->setField(new SimpleByLabelOrName('elements[]'), '4', 2); - $submit = $form->submit(); - $requests = $submit->getAll(); - $this->assertEqual(count($requests), 2); - $this->assertIdentical($requests[0], new SimpleEncodedPair('elements[]', '3')); - $this->assertIdentical($requests[1], new SimpleEncodedPair('elements[]', '4')); - } - - function testSingleSelectFieldSubmitted() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $select = new SimpleSelectionTag(array('name' => 'a')); - $select->addTag(new SimpleOptionTag( - array('value' => 'aaa', 'selected' => ''))); - $form->addWidget($select); - $this->assertIdentical( - $form->submit(), - new SimpleGetEncoding(array('a' => 'aaa'))); - } - - function testSingleSelectFieldSubmittedWithPost() { - $form = new SimpleForm(new SimpleFormTag(array('method' => 'post')), $this->page('htp://host')); - $select = new SimpleSelectionTag(array('name' => 'a')); - $select->addTag(new SimpleOptionTag( - array('value' => 'aaa', 'selected' => ''))); - $form->addWidget($select); - $this->assertIdentical( - $form->submit(), - new SimplePostEncoding(array('a' => 'aaa'))); - } - - function testUnchecked() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'me', 'type' => 'checkbox'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'on')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'on'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'other')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'on'); - } - - function testChecked() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'me', 'value' => 'a', 'type' => 'checkbox', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), false)); - $this->assertEqual($form->getValue(new SimpleByName('me')), false); - } - - function testSingleUncheckedRadioButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'a'); - } - - function testSingleCheckedRadioButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'other')); - } - - function testUncheckedRadioButtons() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'b', 'type' => 'radio'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'b')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'c')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - } - - function testCheckedRadioButtons() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'b', 'type' => 'radio', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - } - - function testMultipleFieldsWithSameKey() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'a', 'type' => 'checkbox', 'value' => 'me'))); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'a', 'type' => 'checkbox', 'value' => 'you'))); - $this->assertIdentical($form->getValue(new SimpleByName('a')), false); - $this->assertTrue($form->setField(new SimpleByName('a'), 'me')); - $this->assertIdentical($form->getValue(new SimpleByName('a')), 'me'); - } - - function testRemoveGetParamsFromAction() { - Mock::generatePartial('SimplePage', 'MockPartialSimplePage', array('getUrl')); - $page = new MockPartialSimplePage(); - $page->returns('getUrl', new SimpleUrl('htp://host/')); - - # Keep GET params in "action", if the form has no widgets - $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1')), $page); - $this->assertEqual($form->getAction()->asString(), 'htp://host/'); - - $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1')), $page); - $form->addWidget(new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a'))); - $this->assertEqual($form->getAction()->asString(), 'htp://host/'); - - $form = new SimpleForm(new SimpleFormTag(array('action'=>'')), $page); - $this->assertEqual($form->getAction()->asString(), 'htp://host/'); - - $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1', 'method'=>'post')), $page); - $this->assertEqual($form->getAction()->asString(), 'htp://host/?test=1'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/frames_test.php b/3rdparty/simpletest/test/frames_test.php deleted file mode 100755 index 29309700e3115ff1b30ac08ec9f522466f9c96ee..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/frames_test.php +++ /dev/null @@ -1,549 +0,0 @@ -<?php -// $Id: frames_test.php 1899 2009-07-28 19:33:42Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../tag.php'); -require_once(dirname(__FILE__) . '/../page.php'); -require_once(dirname(__FILE__) . '/../frames.php'); -Mock::generate('SimplePage'); -Mock::generate('SimpleForm'); - -class TestOfFrameset extends UnitTestCase { - - function testTitleReadFromFramesetPage() { - $page = new MockSimplePage(); - $page->setReturnValue('getTitle', 'This page'); - $frameset = new SimpleFrameset($page); - $this->assertEqual($frameset->getTitle(), 'This page'); - } - - function TestHeadersReadFromFramesetByDefault() { - $page = new MockSimplePage(); - $page->setReturnValue('getHeaders', 'Header: content'); - $page->setReturnValue('getMimeType', 'text/xml'); - $page->setReturnValue('getResponseCode', 401); - $page->setReturnValue('getTransportError', 'Could not parse headers'); - $page->setReturnValue('getAuthentication', 'Basic'); - $page->setReturnValue('getRealm', 'Safe place'); - - $frameset = new SimpleFrameset($page); - - $this->assertIdentical($frameset->getHeaders(), 'Header: content'); - $this->assertIdentical($frameset->getMimeType(), 'text/xml'); - $this->assertIdentical($frameset->getResponseCode(), 401); - $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers'); - $this->assertIdentical($frameset->getAuthentication(), 'Basic'); - $this->assertIdentical($frameset->getRealm(), 'Safe place'); - } - - function testEmptyFramesetHasNoContent() { - $page = new MockSimplePage(); - $page->setReturnValue('getRaw', 'This content'); - $frameset = new SimpleFrameset($page); - $this->assertEqual($frameset->getRaw(), ''); - } - - function testRawContentIsFromOnlyFrame() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame = new MockSimplePage(); - $frame->setReturnValue('getRaw', 'Stuff'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame); - $this->assertEqual($frameset->getRaw(), 'Stuff'); - } - - function testRawContentIsFromAllFrames() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } - - function testTextContentIsFromOnlyFrame() { - $page = new MockSimplePage(); - $page->expectNever('getText'); - - $frame = new MockSimplePage(); - $frame->setReturnValue('getText', 'Stuff'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame); - $this->assertEqual($frameset->getText(), 'Stuff'); - } - - function testTextContentIsFromAllFrames() { - $page = new MockSimplePage(); - $page->expectNever('getText'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getText', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getText', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertEqual($frameset->getText(), 'Stuff1 Stuff2'); - } - - function testFieldFoundIsFirstInFramelist() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getField', null); - $frame1->expectOnce('getField', array(new SimpleByName('a'))); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getField', 'A'); - $frame2->expectOnce('getField', array(new SimpleByName('a'))); - - $frame3 = new MockSimplePage(); - $frame3->expectNever('getField'); - - $page = new MockSimplePage(); - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $frameset->addFrame($frame3); - $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'A'); - } - - function testFrameReplacementByIndex() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->setFrame(array(1), $frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - } - - function testFrameReplacementByName() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1, 'a'); - $frameset->setFrame(array('a'), $frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - } -} - -class TestOfFrameNavigation extends UnitTestCase { - - function testStartsWithoutFrameFocus() { - $page = new MockSimplePage(); - $frameset = new SimpleFrameset($page); - $frameset->addFrame(new MockSimplePage()); - $this->assertFalse($frameset->getFrameFocus()); - } - - function testCanFocusOnSingleFrame() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame = new MockSimplePage(); - $frame->setReturnValue('getFrameFocus', array()); - $frame->setReturnValue('getRaw', 'Stuff'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame); - - $this->assertFalse($frameset->setFrameFocusByIndex(0)); - $this->assertTrue($frameset->setFrameFocusByIndex(1)); - $this->assertEqual($frameset->getRaw(), 'Stuff'); - $this->assertFalse($frameset->setFrameFocusByIndex(2)); - $this->assertIdentical($frameset->getFrameFocus(), array(1)); - } - - function testContentComesFromFrameInFocus() { - $page = new MockSimplePage(); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - $frame1->setReturnValue('getFrameFocus', array()); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - $frame2->setReturnValue('getFrameFocus', array()); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - - $this->assertTrue($frameset->setFrameFocusByIndex(1)); - $this->assertEqual($frameset->getFrameFocus(), array(1)); - $this->assertEqual($frameset->getRaw(), 'Stuff1'); - - $this->assertTrue($frameset->setFrameFocusByIndex(2)); - $this->assertEqual($frameset->getFrameFocus(), array(2)); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - - $this->assertFalse($frameset->setFrameFocusByIndex(3)); - $this->assertEqual($frameset->getFrameFocus(), array(2)); - - $frameset->clearFrameFocus(); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } - - function testCanFocusByName() { - $page = new MockSimplePage(); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - $frame1->setReturnValue('getFrameFocus', array()); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - $frame2->setReturnValue('getFrameFocus', array()); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - - $this->assertTrue($frameset->setFrameFocus('A')); - $this->assertEqual($frameset->getFrameFocus(), array('A')); - $this->assertEqual($frameset->getRaw(), 'Stuff1'); - - $this->assertTrue($frameset->setFrameFocusByIndex(2)); - $this->assertEqual($frameset->getFrameFocus(), array('B')); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - - $this->assertFalse($frameset->setFrameFocus('z')); - - $frameset->clearFrameFocus(); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } -} - -class TestOfFramesetPageInterface extends UnitTestCase { - private $page_interface; - private $frameset_interface; - - function __construct() { - parent::__construct(); - $this->page_interface = $this->getPageMethods(); - $this->frameset_interface = $this->getFramesetMethods(); - } - - function assertListInAnyOrder($list, $expected) { - sort($list); - sort($expected); - $this->assertEqual($list, $expected); - } - - private function getPageMethods() { - $methods = array(); - foreach (get_class_methods('SimplePage') as $method) { - if (strtolower($method) == strtolower('SimplePage')) { - continue; - } - if (strtolower($method) == strtolower('getFrameset')) { - continue; - } - if (strncmp($method, '_', 1) == 0) { - continue; - } - if (in_array($method, array('setTitle', 'setBase', 'setForms', 'normalise', 'setFrames', 'addLink'))) { - continue; - } - $methods[] = $method; - } - return $methods; - } - - private function getFramesetMethods() { - $methods = array(); - foreach (get_class_methods('SimpleFrameset') as $method) { - if (strtolower($method) == strtolower('SimpleFrameset')) { - continue; - } - if (strncmp($method, '_', 1) == 0) { - continue; - } - if (strncmp($method, 'add', 3) == 0) { - continue; - } - $methods[] = $method; - } - return $methods; - } - - function testFramsetHasPageInterface() { - $difference = array(); - foreach ($this->page_interface as $method) { - if (! in_array($method, $this->frameset_interface)) { - $this->fail("No [$method] in Frameset class"); - return; - } - } - $this->pass('Frameset covers Page interface'); - } - - function testHeadersReadFromFrameIfInFocus() { - $frame = new MockSimplePage(); - $frame->setReturnValue('getUrl', new SimpleUrl('http://localhost/stuff')); - - $frame->setReturnValue('getRequest', 'POST stuff'); - $frame->setReturnValue('getMethod', 'POST'); - $frame->setReturnValue('getRequestData', array('a' => 'A')); - $frame->setReturnValue('getHeaders', 'Header: content'); - $frame->setReturnValue('getMimeType', 'text/xml'); - $frame->setReturnValue('getResponseCode', 401); - $frame->setReturnValue('getTransportError', 'Could not parse headers'); - $frame->setReturnValue('getAuthentication', 'Basic'); - $frame->setReturnValue('getRealm', 'Safe place'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame); - $frameset->setFrameFocusByIndex(1); - - $url = new SimpleUrl('http://localhost/stuff'); - $url->setTarget(1); - $this->assertIdentical($frameset->getUrl(), $url); - - $this->assertIdentical($frameset->getRequest(), 'POST stuff'); - $this->assertIdentical($frameset->getMethod(), 'POST'); - $this->assertIdentical($frameset->getRequestData(), array('a' => 'A')); - $this->assertIdentical($frameset->getHeaders(), 'Header: content'); - $this->assertIdentical($frameset->getMimeType(), 'text/xml'); - $this->assertIdentical($frameset->getResponseCode(), 401); - $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers'); - $this->assertIdentical($frameset->getAuthentication(), 'Basic'); - $this->assertIdentical($frameset->getRealm(), 'Safe place'); - } - - function testUrlsComeFromBothFrames() { - $page = new MockSimplePage(); - $page->expectNever('getUrls'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue( - 'getUrls', - array('http://www.lastcraft.com/', 'http://myserver/')); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue( - 'getUrls', - array('http://www.lastcraft.com/', 'http://test/')); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertListInAnyOrder( - $frameset->getUrls(), - array('http://www.lastcraft.com/', 'http://myserver/', 'http://test/')); - } - - function testLabelledUrlsComeFromBothFrames() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('goodbye.php')), - array('a')); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('hello.php')), - array('a')); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2, 'Two'); - - $expected1 = new SimpleUrl('goodbye.php'); - $expected1->setTarget(1); - $expected2 = new SimpleUrl('hello.php'); - $expected2->setTarget('Two'); - $this->assertEqual( - $frameset->getUrlsByLabel('a'), - array($expected1, $expected2)); - } - - function testUrlByIdComesFromFirstFrameToRespond() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getUrlById', new SimpleUrl('four.php'), array(4)); - $frame1->setReturnValue('getUrlById', false, array(5)); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getUrlById', false, array(4)); - $frame2->setReturnValue('getUrlById', new SimpleUrl('five.php'), array(5)); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - - $four = new SimpleUrl('four.php'); - $four->setTarget(1); - $this->assertEqual($frameset->getUrlById(4), $four); - $five = new SimpleUrl('five.php'); - $five->setTarget(2); - $this->assertEqual($frameset->getUrlById(5), $five); - } - - function testReadUrlsFromFrameInFocus() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getUrls', array('a')); - $frame1->setReturnValue('getUrlsByLabel', array(new SimpleUrl('l'))); - $frame1->setReturnValue('getUrlById', new SimpleUrl('i')); - - $frame2 = new MockSimplePage(); - $frame2->expectNever('getUrls'); - $frame2->expectNever('getUrlsByLabel'); - $frame2->expectNever('getUrlById'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - - $this->assertIdentical($frameset->getUrls(), array('a')); - $expected = new SimpleUrl('l'); - $expected->setTarget('A'); - $this->assertIdentical($frameset->getUrlsByLabel('label'), array($expected)); - $expected = new SimpleUrl('i'); - $expected->setTarget('A'); - $this->assertIdentical($frameset->getUrlById(99), $expected); - } - - function testReadFrameTaggedUrlsFromFrameInFocus() { - $frame = new MockSimplePage(); - - $by_label = new SimpleUrl('l'); - $by_label->setTarget('L'); - $frame->setReturnValue('getUrlsByLabel', array($by_label)); - - $by_id = new SimpleUrl('i'); - $by_id->setTarget('I'); - $frame->setReturnValue('getUrlById', $by_id); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame, 'A'); - $frameset->setFrameFocus('A'); - - $this->assertIdentical($frameset->getUrlsByLabel('label'), array($by_label)); - $this->assertIdentical($frameset->getUrlById(99), $by_id); - } - - function testFindingFormsById() { - $frame = new MockSimplePage(); - $form = new MockSimpleForm(); - $frame->returns('getFormById', $form, array('a')); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertSame($frameset->getFormById('a'), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormById('a')); - - $frameset->setFrameFocus('B'); - $this->assertSame($frameset->getFormById('a'), $form); - } - - function testFindingFormsBySubmit() { - $frame = new MockSimplePage(); - $form = new MockSimpleForm(); - $frame->returns( - 'getFormBySubmit', - $form, - array(new SimpleByLabel('a'))); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertSame($frameset->getFormBySubmit(new SimpleByLabel('a')), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormBySubmit(new SimpleByLabel('a'))); - - $frameset->setFrameFocus('B'); - $this->assertSame($frameset->getFormBySubmit(new SimpleByLabel('a')), $form); - } - - function testFindingFormsByImage() { - $frame = new MockSimplePage(); - $form = new MockSimpleForm(); - $frame->returns( - 'getFormByImage', - $form, - array(new SimpleByLabel('a'))); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertSame($frameset->getFormByImage(new SimpleByLabel('a')), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormByImage(new SimpleByLabel('a'))); - - $frameset->setFrameFocus('B'); - $this->assertSame($frameset->getFormByImage(new SimpleByLabel('a')), $form); - } - - function testSettingAllFrameFieldsWhenNoFrameFocus() { - $frame1 = new MockSimplePage(); - $frame1->expectOnce('setField', array(new SimpleById(22), 'A')); - - $frame2 = new MockSimplePage(); - $frame2->expectOnce('setField', array(new SimpleById(22), 'A')); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setField(new SimpleById(22), 'A'); - } - - function testOnlySettingFieldFromFocusedFrame() { - $frame1 = new MockSimplePage(); - $frame1->expectOnce('setField', array(new SimpleByLabelOrName('a'), 'A')); - - $frame2 = new MockSimplePage(); - $frame2->expectNever('setField'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - $frameset->setField(new SimpleByLabelOrName('a'), 'A'); - } - - function testOnlyGettingFieldFromFocusedFrame() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getField', 'f', array(new SimpleByName('a'))); - - $frame2 = new MockSimplePage(); - $frame2->expectNever('getField'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'f'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/http_test.php b/3rdparty/simpletest/test/http_test.php deleted file mode 100755 index bd3fdd0d02841897f06473957802e2212637ddc0..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/http_test.php +++ /dev/null @@ -1,492 +0,0 @@ -<?php -// $Id: http_test.php 1964 2009-10-13 15:27:31Z maetl_ $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../encoding.php'); -require_once(dirname(__FILE__) . '/../http.php'); -require_once(dirname(__FILE__) . '/../socket.php'); -require_once(dirname(__FILE__) . '/../cookies.php'); -Mock::generate('SimpleSocket'); -Mock::generate('SimpleCookieJar'); -Mock::generate('SimpleRoute'); -Mock::generatePartial( - 'SimpleRoute', - 'PartialSimpleRoute', -array('createSocket')); -Mock::generatePartial( - 'SimpleProxyRoute', - 'PartialSimpleProxyRoute', -array('createSocket')); - -class TestOfDirectRoute extends UnitTestCase { - - function testDefaultGetRequest() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - $this->assertSame($route->createConnection('GET', 15), $socket); - } - - function testDefaultPostRequest() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("POST /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - - $route->createConnection('POST', 15); - } - - function testDefaultDeleteRequest() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("DELETE /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - $this->assertSame($route->createConnection('DELETE', 15), $socket); - } - - function testDefaultHeadRequest() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("HEAD /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - $this->assertSame($route->createConnection('HEAD', 15), $socket); - } - - function testGetWithPort() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host:81\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host:81/here.html')); - - $route->createConnection('GET', 15); - } - - function testGetWithParameters() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET /here.html?a=1&b=2 HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html?a=1&b=2')); - - $route->createConnection('GET', 15); - } -} - -class TestOfProxyRoute extends UnitTestCase { - - function testDefaultGet() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('GET', 15); - } - - function testDefaultPost() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("POST http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('POST', 15); - } - - function testGetWithPort() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host:81/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8081\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host:81/here.html'), - new SimpleUrl('http://my-proxy:8081')); - $route->createConnection('GET', 15); - } - - function testGetWithParameters() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html?a=1&b=2 HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html?a=1&b=2'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('GET', 15); - } - - function testGetWithAuthentication() { - $encoded = base64_encode('Me:Secret'); - - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Proxy-Authorization: Basic $encoded\r\n")); - $socket->expectAt(3, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 4); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy'), - 'Me', - 'Secret'); - $route->createConnection('GET', 15); - } -} - -class TestOfHttpRequest extends UnitTestCase { - - function testReadingBadConnection() { - $socket = new MockSimpleSocket(); - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $reponse = $request->fetch(15); - $this->assertTrue($reponse->isError()); - } - - function testReadingGoodConnection() { - $socket = new MockSimpleSocket(); - $socket->expectOnce('write', array("\r\n")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('GET', 15)); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testWritingAdditionalHeaders() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("My: stuff\r\n")); - $socket->expectAt(1, 'write', array("\r\n")); - $socket->expectCallCount('write', 2); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->addHeaderLine('My: stuff'); - $request->fetch(15); - } - - function testCookieWriting() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Cookie: a=A\r\n")); - $socket->expectAt(1, 'write', array("\r\n")); - $socket->expectCallCount('write', 2); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->readCookiesFromJar($jar, new SimpleUrl('/')); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testMultipleCookieWriting() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Cookie: a=A;b=B\r\n")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - $jar->setCookie('b', 'B'); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->readCookiesFromJar($jar, new SimpleUrl('/')); - $request->fetch(15); - } - - function testReadingDeleteConnection() { - $socket = new MockSimpleSocket(); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('DELETE', 15)); - - $request = new SimpleHttpRequest($route, new SimpleDeleteEncoding()); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } -} - -class TestOfHttpPostRequest extends UnitTestCase { - - function testReadingBadConnectionCausesErrorBecauseOfDeadSocket() { - $socket = new MockSimpleSocket(); - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $request = new SimpleHttpRequest($route, new SimplePostEncoding()); - $reponse = $request->fetch(15); - $this->assertTrue($reponse->isError()); - } - - function testReadingGoodConnection() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 0\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest($route, new SimplePostEncoding()); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testContentHeadersCalculatedWithUrlEncodedParams() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 3\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("a=A")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest( - $route, - new SimplePostEncoding(array('a' => 'A'))); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testContentHeadersCalculatedWithRawEntityBody() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 8\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: text/plain\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("raw body")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest( - $route, - new SimplePostEncoding('raw body')); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testContentHeadersCalculatedWithXmlEntityBody() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 27\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: text/xml\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("<a><b>one</b><c>two</c></a>")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest( - $route, - new SimplePostEncoding('<a><b>one</b><c>two</c></a>', 'text/xml')); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } -} - -class TestOfHttpHeaders extends UnitTestCase { - - function testParseBasicHeaders() { - $headers = new SimpleHttpHeaders( - "HTTP/1.1 200 OK\r\n" . - "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" . - "Content-Type: text/plain\r\n" . - "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getHttpVersion(), "1.1"); - $this->assertIdentical($headers->getResponseCode(), 200); - $this->assertEqual($headers->getMimeType(), "text/plain"); - } - - function testNonStandardResponseHeader() { - $headers = new SimpleHttpHeaders( - "HTTP/1.1 302 (HTTP-Version SP Status-Code CRLF)\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getResponseCode(), 302); - } - - function testCanParseMultipleCookies() { - $jar = new MockSimpleCookieJar(); - $jar->expectAt(0, 'setCookie', array('a', 'aaa', 'host', '/here/', 'Wed, 25 Dec 2002 04:24:20 GMT')); - $jar->expectAt(1, 'setCookie', array('b', 'bbb', 'host', '/', false)); - - $headers = new SimpleHttpHeaders( - "HTTP/1.1 200 OK\r\n" . - "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" . - "Content-Type: text/plain\r\n" . - "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" . - "Set-Cookie: a=aaa; expires=Wed, 25-Dec-02 04:24:20 GMT; path=/here/\r\n" . - "Set-Cookie: b=bbb\r\n" . - "Connection: close"); - $headers->writeCookiesToJar($jar, new SimpleUrl('http://host')); - } - - function testCanRecogniseRedirect() { - $headers = new SimpleHttpHeaders("HTTP/1.1 301 OK\r\n" . - "Content-Type: text/plain\r\n" . - "Content-Length: 0\r\n" . - "Location: http://www.somewhere-else.com/\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getResponseCode(), 301); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/"); - $this->assertTrue($headers->isRedirect()); - } - - function testCanParseChallenge() { - $headers = new SimpleHttpHeaders("HTTP/1.1 401 Authorization required\r\n" . - "Content-Type: text/plain\r\n" . - "Connection: close\r\n" . - "WWW-Authenticate: Basic realm=\"Somewhere\""); - $this->assertEqual($headers->getAuthentication(), 'Basic'); - $this->assertEqual($headers->getRealm(), 'Somewhere'); - $this->assertTrue($headers->isChallenge()); - } -} - -class TestOfHttpResponse extends UnitTestCase { - - function testBadRequest() { - $socket = new MockSimpleSocket(); - $socket->setReturnValue('getSent', ''); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertPattern('/Nothing fetched/', $response->getError()); - $this->assertIdentical($response->getContent(), false); - $this->assertIdentical($response->getSent(), ''); - } - - function testBadSocketDuringResponse() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValue("read", ""); - $socket->setReturnValue('getSent', 'HTTP/1.1 ...'); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertEqual($response->getContent(), ''); - $this->assertEqual($response->getSent(), 'HTTP/1.1 ...'); - } - - function testIncompleteHeader() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValueAt(2, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertEqual($response->getContent(), ""); - } - - function testParseOfResponseHeadersWhenChunked() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\nDate: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\nConne"); - $socket->setReturnValueAt(3, "read", "ction: close\r\n\r\nthis is a test file\n"); - $socket->setReturnValueAt(4, "read", "with two lines in it\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertFalse($response->isError()); - $this->assertEqual( - $response->getContent(), - "this is a test file\nwith two lines in it\n"); - $headers = $response->getHeaders(); - $this->assertIdentical($headers->getHttpVersion(), "1.1"); - $this->assertIdentical($headers->getResponseCode(), 200); - $this->assertEqual($headers->getMimeType(), "text/plain"); - $this->assertFalse($headers->isRedirect()); - $this->assertFalse($headers->getLocation()); - } - - function testRedirect() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com/\r\n"); - $socket->setReturnValueAt(3, "read", "Connection: close\r\n"); - $socket->setReturnValueAt(4, "read", "\r\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $headers = $response->getHeaders(); - $this->assertTrue($headers->isRedirect()); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/"); - } - - function testRedirectWithPort() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com:80/\r\n"); - $socket->setReturnValueAt(3, "read", "Connection: close\r\n"); - $socket->setReturnValueAt(4, "read", "\r\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $headers = $response->getHeaders(); - $this->assertTrue($headers->isRedirect()); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com:80/"); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/interfaces_test.php b/3rdparty/simpletest/test/interfaces_test.php deleted file mode 100755 index ab30fe47ff8ef8f674052686fd02e9f7a48fc644..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/interfaces_test.php +++ /dev/null @@ -1,137 +0,0 @@ -<?php -// $Id: interfaces_test.php 1981 2010-03-23 23:29:56Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -if (function_exists('spl_classes')) { - include(dirname(__FILE__) . '/support/spl_examples.php'); -} -if (version_compare(PHP_VERSION, '5.1', '>=')) { - include(dirname(__FILE__) . '/interfaces_test_php5_1.php'); -} - -interface DummyInterface { - function aMethod(); - function anotherMethod($a); - function &referenceMethod(&$a); -} - -Mock::generate('DummyInterface'); -Mock::generatePartial('DummyInterface', 'PartialDummyInterface', array()); - -class TestOfMockInterfaces extends UnitTestCase { - - function testCanMockAnInterface() { - $mock = new MockDummyInterface(); - $this->assertIsA($mock, 'SimpleMock'); - $this->assertIsA($mock, 'MockDummyInterface'); - $this->assertTrue(method_exists($mock, 'aMethod')); - $this->assertTrue(method_exists($mock, 'anotherMethod')); - $this->assertNull($mock->aMethod()); - } - - function testMockedInterfaceExpectsParameters() { - $mock = new MockDummyInterface(); - $this->expectError(); - $mock->anotherMethod(); - } - - function testCannotPartiallyMockAnInterface() { - $this->assertFalse(class_exists('PartialDummyInterface')); - } -} - -class TestOfSpl extends UnitTestCase { - - function skip() { - $this->skipUnless(function_exists('spl_classes'), 'No SPL module loaded'); - } - - function testCanMockAllSplClasses() { - if (! function_exists('spl_classes')) { - return; - } - foreach(spl_classes() as $class) { - if ($class == 'SplHeap' or $class = 'SplFileObject') { - continue; - } - if (version_compare(PHP_VERSION, '5.1', '<') && - $class == 'CachingIterator' || - $class == 'CachingRecursiveIterator' || - $class == 'FilterIterator' || - $class == 'LimitIterator' || - $class == 'ParentIterator') { - // These iterators require an iterator be passed to them during - // construction in PHP 5.0; there is no way for SimpleTest - // to supply such an iterator, however, so support for it is - // disabled. - continue; - } - $mock_class = "Mock$class"; - Mock::generate($class); - $this->assertIsA(new $mock_class(), $mock_class); - } - } - - function testExtensionOfCommonSplClasses() { - Mock::generate('IteratorImplementation'); - $this->assertIsA( - new IteratorImplementation(), - 'IteratorImplementation'); - Mock::generate('IteratorAggregateImplementation'); - $this->assertIsA( - new IteratorAggregateImplementation(), - 'IteratorAggregateImplementation'); - } -} - -class WithHint { - function hinted(DummyInterface $object) { } -} - -class ImplementsDummy implements DummyInterface { - function aMethod() { } - function anotherMethod($a) { } - function &referenceMethod(&$a) { } - function extraMethod($a = false) { } -} -Mock::generate('ImplementsDummy'); - -class TestOfImplementations extends UnitTestCase { - - function testMockedInterfaceCanPassThroughTypeHint() { - $mock = new MockDummyInterface(); - $hinter = new WithHint(); - $hinter->hinted($mock); - } - - function testImplementedInterfacesAreCarried() { - $mock = new MockImplementsDummy(); - $hinter = new WithHint(); - $hinter->hinted($mock); - } - - function testNoSpuriousWarningsWhenSkippingDefaultedParameter() { - $mock = new MockImplementsDummy(); - $mock->extraMethod(); - } -} - -interface SampleInterfaceWithConstruct { - function __construct($something); -} - -class TestOfInterfaceMocksWithConstruct extends UnitTestCase { - function TODO_testBasicConstructOfAnInterface() { // Fails in PHP 5.3dev - Mock::generate('SampleInterfaceWithConstruct'); - } -} - -interface SampleInterfaceWithClone { - function __clone(); -} - -class TestOfSampleInterfaceWithClone extends UnitTestCase { - function testCanMockWithoutErrors() { - Mock::generate('SampleInterfaceWithClone'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/interfaces_test_php5_1.php b/3rdparty/simpletest/test/interfaces_test_php5_1.php deleted file mode 100755 index 3d154f9953972d2fc1b10cd3b59efb322d8678a4..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/interfaces_test_php5_1.php +++ /dev/null @@ -1,14 +0,0 @@ -<?php - -interface SampleInterfaceWithHintInSignature { - function method(array $hinted); -} - -class TestOfInterfaceMocksWithHintInSignature extends UnitTestCase { - function testBasicConstructOfAnInterfaceWithHintInSignature() { - Mock::generate('SampleInterfaceWithHintInSignature'); - $mock = new MockSampleInterfaceWithHintInSignature(); - $this->assertIsA($mock, 'SampleInterfaceWithHintInSignature'); - } -} - diff --git a/3rdparty/simpletest/test/live_test.php b/3rdparty/simpletest/test/live_test.php deleted file mode 100755 index 3fbb54499d3e5de230696580a82cb049bc3a9ee2..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/live_test.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -// $Id: live_test.php 1748 2008-04-14 01:50:41Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../socket.php'); -require_once(dirname(__FILE__) . '/../http.php'); -require_once(dirname(__FILE__) . '/../compatibility.php'); - -if (SimpleTest::getDefaultProxy()) { - SimpleTest::ignore('LiveHttpTestCase'); -} - -class LiveHttpTestCase extends UnitTestCase { - - function testBadSocket() { - $socket = new SimpleSocket('bad_url', 111, 5); - $this->assertTrue($socket->isError()); - $this->assertPattern( - '/Cannot open \\[bad_url:111\\] with \\[/', - $socket->getError()); - $this->assertFalse($socket->isOpen()); - $this->assertFalse($socket->write('A message')); - } - - function testSocketClosure() { - $socket = new SimpleSocket('www.lastcraft.com', 80, 15, 8); - $this->assertTrue($socket->isOpen()); - $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); - $socket->write("Host: www.lastcraft.com\r\n"); - $socket->write("Connection: close\r\n\r\n"); - $this->assertEqual($socket->read(), "HTTP/1.1"); - $socket->close(); - $this->assertIdentical($socket->read(), false); - } - - function testRecordOfSentCharacters() { - $socket = new SimpleSocket('www.lastcraft.com', 80, 15); - $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); - $socket->write("Host: www.lastcraft.com\r\n"); - $socket->write("Connection: close\r\n\r\n"); - $socket->close(); - $this->assertEqual($socket->getSent(), - "GET /test/network_confirm.php HTTP/1.0\r\n" . - "Host: www.lastcraft.com\r\n" . - "Connection: close\r\n\r\n"); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/mock_objects_test.php b/3rdparty/simpletest/test/mock_objects_test.php deleted file mode 100755 index 7f3178995a743dc99340aba201cd27a8cfe148b1..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/mock_objects_test.php +++ /dev/null @@ -1,985 +0,0 @@ -<?php -// $Id: mock_objects_test.php 1900 2009-07-29 11:44:37Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../expectation.php'); -require_once(dirname(__FILE__) . '/../mock_objects.php'); - -class TestOfAnythingExpectation extends UnitTestCase { - function testSimpleInteger() { - $expectation = new AnythingExpectation(); - $this->assertTrue($expectation->test(33)); - $this->assertTrue($expectation->test(false)); - $this->assertTrue($expectation->test(null)); - } -} - -class TestOfParametersExpectation extends UnitTestCase { - - function testEmptyMatch() { - $expectation = new ParametersExpectation(array()); - $this->assertTrue($expectation->test(array())); - $this->assertFalse($expectation->test(array(33))); - } - - function testSingleMatch() { - $expectation = new ParametersExpectation(array(0)); - $this->assertFalse($expectation->test(array(1))); - $this->assertTrue($expectation->test(array(0))); - } - - function testAnyMatch() { - $expectation = new ParametersExpectation(false); - $this->assertTrue($expectation->test(array())); - $this->assertTrue($expectation->test(array(1, 2))); - } - - function testMissingParameter() { - $expectation = new ParametersExpectation(array(0)); - $this->assertFalse($expectation->test(array())); - } - - function testNullParameter() { - $expectation = new ParametersExpectation(array(null)); - $this->assertTrue($expectation->test(array(null))); - $this->assertFalse($expectation->test(array())); - } - - function testAnythingExpectations() { - $expectation = new ParametersExpectation(array(new AnythingExpectation())); - $this->assertFalse($expectation->test(array())); - $this->assertIdentical($expectation->test(array(null)), true); - $this->assertIdentical($expectation->test(array(13)), true); - } - - function testOtherExpectations() { - $expectation = new ParametersExpectation( - array(new PatternExpectation('/hello/i'))); - $this->assertFalse($expectation->test(array('Goodbye'))); - $this->assertTrue($expectation->test(array('hello'))); - $this->assertTrue($expectation->test(array('Hello'))); - } - - function testIdentityOnly() { - $expectation = new ParametersExpectation(array("0")); - $this->assertFalse($expectation->test(array(0))); - $this->assertTrue($expectation->test(array("0"))); - } - - function testLongList() { - $expectation = new ParametersExpectation( - array("0", 0, new AnythingExpectation(), false)); - $this->assertTrue($expectation->test(array("0", 0, 37, false))); - $this->assertFalse($expectation->test(array("0", 0, 37, true))); - $this->assertFalse($expectation->test(array("0", 0, 37))); - } -} - -class TestOfSimpleSignatureMap extends UnitTestCase { - - function testEmpty() { - $map = new SimpleSignatureMap(); - $this->assertFalse($map->isMatch("any", array())); - $this->assertNull($map->findFirstAction("any", array())); - } - - function testDifferentCallSignaturesCanHaveDifferentReferences() { - $map = new SimpleSignatureMap(); - $fred = 'Fred'; - $jim = 'jim'; - $map->add(array(0), $fred); - $map->add(array('0'), $jim); - $this->assertSame($fred, $map->findFirstAction(array(0))); - $this->assertSame($jim, $map->findFirstAction(array('0'))); - } - - function testWildcard() { - $fred = 'Fred'; - $map = new SimpleSignatureMap(); - $map->add(array(new AnythingExpectation(), 1, 3), $fred); - $this->assertTrue($map->isMatch(array(2, 1, 3))); - $this->assertSame($map->findFirstAction(array(2, 1, 3)), $fred); - } - - function testAllWildcard() { - $fred = 'Fred'; - $map = new SimpleSignatureMap(); - $this->assertFalse($map->isMatch(array(2, 1, 3))); - $map->add('', $fred); - $this->assertTrue($map->isMatch(array(2, 1, 3))); - $this->assertSame($map->findFirstAction(array(2, 1, 3)), $fred); - } - - function testOrdering() { - $map = new SimpleSignatureMap(); - $map->add(array(1, 2), new SimpleByValue("1, 2")); - $map->add(array(1, 3), new SimpleByValue("1, 3")); - $map->add(array(1), new SimpleByValue("1")); - $map->add(array(1, 4), new SimpleByValue("1, 4")); - $map->add(array(new AnythingExpectation()), new SimpleByValue("Any")); - $map->add(array(2), new SimpleByValue("2")); - $map->add("", new SimpleByValue("Default")); - $map->add(array(), new SimpleByValue("None")); - $this->assertEqual($map->findFirstAction(array(1, 2)), new SimpleByValue("1, 2")); - $this->assertEqual($map->findFirstAction(array(1, 3)), new SimpleByValue("1, 3")); - $this->assertEqual($map->findFirstAction(array(1, 4)), new SimpleByValue("1, 4")); - $this->assertEqual($map->findFirstAction(array(1)), new SimpleByValue("1")); - $this->assertEqual($map->findFirstAction(array(2)), new SimpleByValue("Any")); - $this->assertEqual($map->findFirstAction(array(3)), new SimpleByValue("Any")); - $this->assertEqual($map->findFirstAction(array()), new SimpleByValue("Default")); - } -} - -class TestOfCallSchedule extends UnitTestCase { - function testCanBeSetToAlwaysReturnTheSameReference() { - $a = 5; - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleByReference($a)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $a); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $a); - } - - function testSpecificSignaturesOverrideTheAlwaysCase() { - $any = 'any'; - $one = 'two'; - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', array(1), new SimpleByReference($one)); - $schedule->register('aMethod', false, new SimpleByReference($any)); - $this->assertReference($schedule->respond(0, 'aMethod', array(2)), $any); - $this->assertReference($schedule->respond(0, 'aMethod', array(1)), $one); - } - - function testReturnsCanBeSetOverTime() { - $one = 'one'; - $two = 'two'; - $schedule = new SimpleCallSchedule(); - $schedule->registerAt(0, 'aMethod', false, new SimpleByReference($one)); - $schedule->registerAt(1, 'aMethod', false, new SimpleByReference($two)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $one); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $two); - } - - function testReturnsOverTimecanBeAlteredByTheArguments() { - $one = '1'; - $two = '2'; - $two_a = '2a'; - $schedule = new SimpleCallSchedule(); - $schedule->registerAt(0, 'aMethod', false, new SimpleByReference($one)); - $schedule->registerAt(1, 'aMethod', array('a'), new SimpleByReference($two_a)); - $schedule->registerAt(1, 'aMethod', false, new SimpleByReference($two)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $one); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $two); - $this->assertReference($schedule->respond(1, 'aMethod', array('a')), $two_a); - } - - function testCanReturnByValue() { - $a = 5; - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleByValue($a)); - $this->assertCopy($schedule->respond(0, 'aMethod', array()), $a); - } - - function testCanThrowException() { - if (version_compare(phpversion(), '5', '>=')) { - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleThrower(new Exception('Ouch'))); - $this->expectException(new Exception('Ouch')); - $schedule->respond(0, 'aMethod', array()); - } - } - - function testCanEmitError() { - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleErrorThrower('Ouch', E_USER_WARNING)); - $this->expectError('Ouch'); - $schedule->respond(0, 'aMethod', array()); - } -} - -class Dummy { - function Dummy() { - } - - function aMethod() { - return true; - } - - function &aReferenceMethod() { - return true; - } - - function anotherMethod() { - return true; - } -} -Mock::generate('Dummy'); -Mock::generate('Dummy', 'AnotherMockDummy'); -Mock::generate('Dummy', 'MockDummyWithExtraMethods', array('extraMethod')); - -class TestOfMockGeneration extends UnitTestCase { - - function testCloning() { - $mock = new MockDummy(); - $this->assertTrue(method_exists($mock, "aMethod")); - $this->assertNull($mock->aMethod()); - } - - function testCloningWithExtraMethod() { - $mock = new MockDummyWithExtraMethods(); - $this->assertTrue(method_exists($mock, "extraMethod")); - } - - function testCloningWithChosenClassName() { - $mock = new AnotherMockDummy(); - $this->assertTrue(method_exists($mock, "aMethod")); - } -} - -class TestOfMockReturns extends UnitTestCase { - - function testDefaultReturn() { - $mock = new MockDummy(); - $mock->returnsByValue("aMethod", "aaa"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->aMethod(), "aaa"); - } - - function testParameteredReturn() { - $mock = new MockDummy(); - $mock->returnsByValue('aMethod', 'aaa', array(1, 2, 3)); - $this->assertNull($mock->aMethod()); - $this->assertIdentical($mock->aMethod(1, 2, 3), 'aaa'); - } - - function testSetReturnGivesObjectReference() { - $mock = new MockDummy(); - $object = new Dummy(); - $mock->returns('aMethod', $object, array(1, 2, 3)); - $this->assertSame($mock->aMethod(1, 2, 3), $object); - } - - function testSetReturnReferenceGivesOriginalReference() { - $mock = new MockDummy(); - $object = 1; - $mock->returnsByReference('aReferenceMethod', $object, array(1, 2, 3)); - $this->assertReference($mock->aReferenceMethod(1, 2, 3), $object); - } - - function testReturnValueCanBeChosenJustByPatternMatchingArguments() { - $mock = new MockDummy(); - $mock->returnsByValue( - "aMethod", - "aaa", - array(new PatternExpectation('/hello/i'))); - $this->assertIdentical($mock->aMethod('Hello'), 'aaa'); - $this->assertNull($mock->aMethod('Goodbye')); - } - - function testMultipleMethods() { - $mock = new MockDummy(); - $mock->returnsByValue("aMethod", 100, array(1)); - $mock->returnsByValue("aMethod", 200, array(2)); - $mock->returnsByValue("anotherMethod", 10, array(1)); - $mock->returnsByValue("anotherMethod", 20, array(2)); - $this->assertIdentical($mock->aMethod(1), 100); - $this->assertIdentical($mock->anotherMethod(1), 10); - $this->assertIdentical($mock->aMethod(2), 200); - $this->assertIdentical($mock->anotherMethod(2), 20); - } - - function testReturnSequence() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "aMethod", "aaa"); - $mock->returnsByValueAt(1, "aMethod", "bbb"); - $mock->returnsByValueAt(3, "aMethod", "ddd"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->aMethod(), "bbb"); - $this->assertNull($mock->aMethod()); - $this->assertIdentical($mock->aMethod(), "ddd"); - } - - function testSetReturnReferenceAtGivesOriginal() { - $mock = new MockDummy(); - $object = 100; - $mock->returnsByReferenceAt(1, "aReferenceMethod", $object); - $this->assertNull($mock->aReferenceMethod()); - $this->assertReference($mock->aReferenceMethod(), $object); - $this->assertNull($mock->aReferenceMethod()); - } - - function testReturnsAtGivesOriginalObjectHandle() { - $mock = new MockDummy(); - $object = new Dummy(); - $mock->returnsAt(1, "aMethod", $object); - $this->assertNull($mock->aMethod()); - $this->assertSame($mock->aMethod(), $object); - $this->assertNull($mock->aMethod()); - } - - function testComplicatedReturnSequence() { - $mock = new MockDummy(); - $object = new Dummy(); - $mock->returnsAt(1, "aMethod", "aaa", array("a")); - $mock->returnsAt(1, "aMethod", "bbb"); - $mock->returnsAt(2, "aMethod", $object, array('*', 2)); - $mock->returnsAt(2, "aMethod", "value", array('*', 3)); - $mock->returns("aMethod", 3, array(3)); - $this->assertNull($mock->aMethod()); - $this->assertEqual($mock->aMethod("a"), "aaa"); - $this->assertSame($mock->aMethod(1, 2), $object); - $this->assertEqual($mock->aMethod(3), 3); - $this->assertNull($mock->aMethod()); - } - - function testMultipleMethodSequences() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "aMethod", "aaa"); - $mock->returnsByValueAt(1, "aMethod", "bbb"); - $mock->returnsByValueAt(0, "anotherMethod", "ccc"); - $mock->returnsByValueAt(1, "anotherMethod", "ddd"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->anotherMethod(), "ccc"); - $this->assertIdentical($mock->aMethod(), "bbb"); - $this->assertIdentical($mock->anotherMethod(), "ddd"); - } - - function testSequenceFallback() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "aMethod", "aaa", array('a')); - $mock->returnsByValueAt(1, "aMethod", "bbb", array('a')); - $mock->returnsByValue("aMethod", "AAA"); - $this->assertIdentical($mock->aMethod('a'), "aaa"); - $this->assertIdentical($mock->aMethod('b'), "AAA"); - } - - function testMethodInterference() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "anotherMethod", "aaa"); - $mock->returnsByValue("aMethod", "AAA"); - $this->assertIdentical($mock->aMethod(), "AAA"); - $this->assertIdentical($mock->anotherMethod(), "aaa"); - } -} - -class TestOfMockExpectationsThatPass extends UnitTestCase { - - function testAnyArgument() { - $mock = new MockDummy(); - $mock->expect('aMethod', array('*')); - $mock->aMethod(1); - $mock->aMethod('hello'); - } - - function testAnyTwoArguments() { - $mock = new MockDummy(); - $mock->expect('aMethod', array('*', '*')); - $mock->aMethod(1, 2); - } - - function testSpecificArgument() { - $mock = new MockDummy(); - $mock->expect('aMethod', array(1)); - $mock->aMethod(1); - } - - function testExpectation() { - $mock = new MockDummy(); - $mock->expect('aMethod', array(new IsAExpectation('Dummy'))); - $mock->aMethod(new Dummy()); - } - - function testArgumentsInSequence() { - $mock = new MockDummy(); - $mock->expectAt(0, 'aMethod', array(1, 2)); - $mock->expectAt(1, 'aMethod', array(3, 4)); - $mock->aMethod(1, 2); - $mock->aMethod(3, 4); - } - - function testAtLeastOnceSatisfiedByOneCall() { - $mock = new MockDummy(); - $mock->expectAtLeastOnce('aMethod'); - $mock->aMethod(); - } - - function testAtLeastOnceSatisfiedByTwoCalls() { - $mock = new MockDummy(); - $mock->expectAtLeastOnce('aMethod'); - $mock->aMethod(); - $mock->aMethod(); - } - - function testOnceSatisfiedByOneCall() { - $mock = new MockDummy(); - $mock->expectOnce('aMethod'); - $mock->aMethod(); - } - - function testMinimumCallsSatisfiedByEnoughCalls() { - $mock = new MockDummy(); - $mock->expectMinimumCallCount('aMethod', 1); - $mock->aMethod(); - } - - function testMinimumCallsSatisfiedByTooManyCalls() { - $mock = new MockDummy(); - $mock->expectMinimumCallCount('aMethod', 3); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - } - - function testMaximumCallsSatisfiedByEnoughCalls() { - $mock = new MockDummy(); - $mock->expectMaximumCallCount('aMethod', 1); - $mock->aMethod(); - } - - function testMaximumCallsSatisfiedByNoCalls() { - $mock = new MockDummy(); - $mock->expectMaximumCallCount('aMethod', 1); - } -} - -class MockWithInjectedTestCase extends SimpleMock { - protected function getCurrentTestCase() { - return SimpleTest::getContext()->getTest()->getMockedTest(); - } -} -SimpleTest::setMockBaseClass('MockWithInjectedTestCase'); -Mock::generate('Dummy', 'MockDummyWithInjectedTestCase'); -SimpleTest::setMockBaseClass('SimpleMock'); -Mock::generate('SimpleTestCase'); - -class LikeExpectation extends IdenticalExpectation { - function __construct($expectation) { - $expectation->message = ''; - parent::__construct($expectation); - } - - function test($compare) { - $compare->message = ''; - return parent::test($compare); - } - - function testMessage($compare) { - $compare->message = ''; - return parent::testMessage($compare); - } -} - -class TestOfMockExpectations extends UnitTestCase { - private $test; - - function setUp() { - $this->test = new MockSimpleTestCase(); - } - - function getMockedTest() { - return $this->test; - } - - function testSettingExpectationOnNonMethodThrowsError() { - $mock = new MockDummyWithInjectedTestCase(); - $this->expectError(); - $mock->expectMaximumCallCount('aMissingMethod', 2); - } - - function testMaxCallsDetectsOverrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 3)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectMaximumCallCount('aMethod', 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testTallyOnMaxCallsSendsPassOnUnderrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 2)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectMaximumCallCount("aMethod", 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testExpectNeverDetectsOverrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 1)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testTallyOnExpectNeverStillSendsPassOnUnderrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 0)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testMinCalls() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 2)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectMinimumCallCount('aMethod', 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testFailedNever() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 1)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testUnderOnce() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 0)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectOnce('aMethod'); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testOverOnce() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 2)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectOnce('aMethod'); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testUnderAtLeastOnce() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 0)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectAtLeastOnce("aMethod"); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testZeroArguments() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', array()), array(), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expect('aMethod', array()); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testExpectedArguments() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', array(1, 2, 3)), array(1, 2, 3), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expect('aMethod', array(1, 2, 3)); - $mock->aMethod(1, 2, 3); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testFailedArguments() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', array('this')), array('that'), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expect('aMethod', array('this')); - $mock->aMethod('that'); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testWildcardsAreTranslatedToAnythingExpectations() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', - array(new AnythingExpectation(), - 123, - new AnythingExpectation())), - array(100, 123, 101), '*')); - $mock = new MockDummyWithInjectedTestCase($this); - $mock->expect("aMethod", array('*', 123, '*')); - $mock->aMethod(100, 123, 101); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testSpecificPassingSequence() { - $this->test->expectAt(0, 'assert', - array(new MemberExpectation('expected', array(1, 2, 3)), array(1, 2, 3), '*')); - $this->test->expectAt(1, 'assert', - array(new MemberExpectation('expected', array('Hello')), array('Hello'), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectAt(1, 'aMethod', array(1, 2, 3)); - $mock->expectAt(2, 'aMethod', array('Hello')); - $mock->aMethod(); - $mock->aMethod(1, 2, 3); - $mock->aMethod('Hello'); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testNonArrayForExpectedParametersGivesError() { - $mock = new MockDummyWithInjectedTestCase(); - $this->expectError(new PatternExpectation('/\$args.*not an array/i')); - $mock->expect("aMethod", "foo"); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } -} - -class TestOfMockComparisons extends UnitTestCase { - - function testEqualComparisonOfMocksDoesNotCrash() { - $expectation = new EqualExpectation(new MockDummy()); - $this->assertTrue($expectation->test(new MockDummy(), true)); - } - - function testIdenticalComparisonOfMocksDoesNotCrash() { - $expectation = new IdenticalExpectation(new MockDummy()); - $this->assertTrue($expectation->test(new MockDummy())); - } -} - -class ClassWithSpecialMethods { - function __get($name) { } - function __set($name, $value) { } - function __isset($name) { } - function __unset($name) { } - function __call($method, $arguments) { } - function __toString() { } -} -Mock::generate('ClassWithSpecialMethods'); - -class TestOfSpecialMethodsAfterPHP51 extends UnitTestCase { - - function skip() { - $this->skipIf(version_compare(phpversion(), '5.1', '<'), '__isset and __unset overloading not tested unless PHP 5.1+'); - } - - function testCanEmulateIsset() { - $mock = new MockClassWithSpecialMethods(); - $mock->returnsByValue('__isset', true); - $this->assertIdentical(isset($mock->a), true); - } - - function testCanExpectUnset() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__unset', array('a')); - unset($mock->a); - } - -} - -class TestOfSpecialMethods extends UnitTestCase { - function skip() { - $this->skipIf(version_compare(phpversion(), '5', '<'), 'Overloading not tested unless PHP 5+'); - } - - function testCanMockTheThingAtAll() { - $mock = new MockClassWithSpecialMethods(); - } - - function testReturnFromSpecialAccessor() { - $mock = new MockClassWithSpecialMethods(); - $mock->returnsByValue('__get', '1st Return', array('first')); - $mock->returnsByValue('__get', '2nd Return', array('second')); - $this->assertEqual($mock->first, '1st Return'); - $this->assertEqual($mock->second, '2nd Return'); - } - - function testcanExpectTheSettingOfValue() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__set', array('a', 'A')); - $mock->a = 'A'; - } - - function testCanSimulateAnOverloadmethod() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__call', array('amOverloaded', array('A'))); - $mock->returnsByValue('__call', 'aaa'); - $this->assertIdentical($mock->amOverloaded('A'), 'aaa'); - } - - function testToStringMagic() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__toString'); - $mock->returnsByValue('__toString', 'AAA'); - ob_start(); - print $mock; - $output = ob_get_contents(); - ob_end_clean(); - $this->assertEqual($output, 'AAA'); - } -} - -class WithStaticMethod { - static function aStaticMethod() { } -} -Mock::generate('WithStaticMethod'); - -class TestOfMockingClassesWithStaticMethods extends UnitTestCase { - - function testStaticMethodIsMockedAsStatic() { - $mock = new WithStaticMethod(); - $reflection = new ReflectionClass($mock); - $method = $reflection->getMethod('aStaticMethod'); - $this->assertTrue($method->isStatic()); - } -} - -class MockTestException extends Exception { } - -class TestOfThrowingExceptionsFromMocks extends UnitTestCase { - - function testCanThrowOnMethodCall() { - $mock = new MockDummy(); - $mock->throwOn('aMethod'); - $this->expectException(); - $mock->aMethod(); - } - - function testCanThrowSpecificExceptionOnMethodCall() { - $mock = new MockDummy(); - $mock->throwOn('aMethod', new MockTestException()); - $this->expectException(); - $mock->aMethod(); - } - - function testThrowsOnlyWhenCallSignatureMatches() { - $mock = new MockDummy(); - $mock->throwOn('aMethod', new MockTestException(), array(3)); - $mock->aMethod(1); - $mock->aMethod(2); - $this->expectException(); - $mock->aMethod(3); - } - - function testCanThrowOnParticularInvocation() { - $mock = new MockDummy(); - $mock->throwAt(2, 'aMethod', new MockTestException()); - $mock->aMethod(); - $mock->aMethod(); - $this->expectException(); - $mock->aMethod(); - } -} - -class TestOfThrowingErrorsFromMocks extends UnitTestCase { - - function testCanGenerateErrorFromMethodCall() { - $mock = new MockDummy(); - $mock->errorOn('aMethod', 'Ouch!'); - $this->expectError('Ouch!'); - $mock->aMethod(); - } - - function testGeneratesErrorOnlyWhenCallSignatureMatches() { - $mock = new MockDummy(); - $mock->errorOn('aMethod', 'Ouch!', array(3)); - $mock->aMethod(1); - $mock->aMethod(2); - $this->expectError(); - $mock->aMethod(3); - } - - function testCanGenerateErrorOnParticularInvocation() { - $mock = new MockDummy(); - $mock->errorAt(2, 'aMethod', 'Ouch!'); - $mock->aMethod(); - $mock->aMethod(); - $this->expectError(); - $mock->aMethod(); - } -} - -Mock::generatePartial('Dummy', 'TestDummy', array('anotherMethod', 'aReferenceMethod')); - -class TestOfPartialMocks extends UnitTestCase { - - function testMethodReplacementWithNoBehaviourReturnsNull() { - $mock = new TestDummy(); - $this->assertEqual($mock->aMethod(99), 99); - $this->assertNull($mock->anotherMethod()); - } - - function testSettingReturns() { - $mock = new TestDummy(); - $mock->returnsByValue('anotherMethod', 33, array(3)); - $mock->returnsByValue('anotherMethod', 22); - $mock->returnsByValueAt(2, 'anotherMethod', 44, array(3)); - $this->assertEqual($mock->anotherMethod(), 22); - $this->assertEqual($mock->anotherMethod(3), 33); - $this->assertEqual($mock->anotherMethod(3), 44); - } - - function testSetReturnReferenceGivesOriginal() { - $mock = new TestDummy(); - $object = 99; - $mock->returnsByReferenceAt(0, 'aReferenceMethod', $object, array(3)); - $this->assertReference($mock->aReferenceMethod(3), $object); - } - - function testReturnsAtGivesOriginalObjectHandle() { - $mock = new TestDummy(); - $object = new Dummy(); - $mock->returnsAt(0, 'anotherMethod', $object, array(3)); - $this->assertSame($mock->anotherMethod(3), $object); - } - - function testExpectations() { - $mock = new TestDummy(); - $mock->expectCallCount('anotherMethod', 2); - $mock->expect('anotherMethod', array(77)); - $mock->expectAt(1, 'anotherMethod', array(66)); - $mock->anotherMethod(77); - $mock->anotherMethod(66); - } - - function testSettingExpectationOnMissingMethodThrowsError() { - $mock = new TestDummy(); - $this->expectError(); - $mock->expectCallCount('aMissingMethod', 2); - } -} - -class ConstructorSuperClass { - function ConstructorSuperClass() { } -} - -class ConstructorSubClass extends ConstructorSuperClass { } - -class TestOfPHP4StyleSuperClassConstruct extends UnitTestCase { - function testBasicConstruct() { - Mock::generate('ConstructorSubClass'); - $mock = new MockConstructorSubClass(); - $this->assertIsA($mock, 'ConstructorSubClass'); - $this->assertTrue(method_exists($mock, 'ConstructorSuperClass')); - } -} - -class TestOfPHP5StaticMethodMocking extends UnitTestCase { - function testCanCreateAMockObjectWithStaticMethodsWithoutError() { - eval(' - class SimpleObjectContainingStaticMethod { - static function someStatic() { } - } - '); - Mock::generate('SimpleObjectContainingStaticMethod'); - } -} - -class TestOfPHP5AbstractMethodMocking extends UnitTestCase { - function testCanCreateAMockObjectFromAnAbstractWithProperFunctionDeclarations() { - eval(' - abstract class SimpleAbstractClassContainingAbstractMethods { - abstract function anAbstract(); - abstract function anAbstractWithParameter($foo); - abstract function anAbstractWithMultipleParameters($foo, $bar); - } - '); - Mock::generate('SimpleAbstractClassContainingAbstractMethods'); - $this->assertTrue( - method_exists( - // Testing with class name alone does not work in PHP 5.0 - new MockSimpleAbstractClassContainingAbstractMethods, - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleAbstractClassContainingAbstractMethods, - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleAbstractClassContainingAbstractMethods, - 'anAbstractWithMultipleParameters' - ) - ); - } - - function testMethodsDefinedAsAbstractInParentShouldHaveFullSignature() { - eval(' - abstract class SimpleParentAbstractClassContainingAbstractMethods { - abstract function anAbstract(); - abstract function anAbstractWithParameter($foo); - abstract function anAbstractWithMultipleParameters($foo, $bar); - } - - class SimpleChildAbstractClassContainingAbstractMethods extends SimpleParentAbstractClassContainingAbstractMethods { - function anAbstract(){} - function anAbstractWithParameter($foo){} - function anAbstractWithMultipleParameters($foo, $bar){} - } - - class EvenDeeperEmptyChildClass extends SimpleChildAbstractClassContainingAbstractMethods {} - '); - Mock::generate('SimpleChildAbstractClassContainingAbstractMethods'); - $this->assertTrue( - method_exists( - new MockSimpleChildAbstractClassContainingAbstractMethods, - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleChildAbstractClassContainingAbstractMethods, - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleChildAbstractClassContainingAbstractMethods, - 'anAbstractWithMultipleParameters' - ) - ); - Mock::generate('EvenDeeperEmptyChildClass'); - $this->assertTrue( - method_exists( - new MockEvenDeeperEmptyChildClass, - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - new MockEvenDeeperEmptyChildClass, - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - new MockEvenDeeperEmptyChildClass, - 'anAbstractWithMultipleParameters' - ) - ); - } -} - -class DummyWithProtected -{ - public function aMethodCallsProtected() { return $this->aProtectedMethod(); } - protected function aProtectedMethod() { return true; } -} - -Mock::generatePartial('DummyWithProtected', 'TestDummyWithProtected', array('aProtectedMethod')); -class TestOfProtectedMethodPartialMocks extends UnitTestCase -{ - function testProtectedMethodExists() { - $this->assertTrue( - method_exists( - new TestDummyWithProtected, - 'aProtectedMethod' - ) - ); - } - - function testProtectedMethodIsCalled() { - $object = new DummyWithProtected(); - $this->assertTrue($object->aMethodCallsProtected(), 'ensure original was called'); - } - - function testMockedMethodIsCalled() { - $object = new TestDummyWithProtected(); - $object->returnsByValue('aProtectedMethod', false); - $this->assertFalse($object->aMethodCallsProtected()); - } -} - -?> diff --git a/3rdparty/simpletest/test/page_test.php b/3rdparty/simpletest/test/page_test.php deleted file mode 100755 index fdc15c5d008b8ddfafa939e2c28b1dd278783f7f..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/page_test.php +++ /dev/null @@ -1,166 +0,0 @@ -<?php -// $Id: page_test.php 1913 2009-07-29 16:50:56Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../expectation.php'); -require_once(dirname(__FILE__) . '/../http.php'); -require_once(dirname(__FILE__) . '/../page.php'); -Mock::generate('SimpleHttpHeaders'); -Mock::generate('SimpleHttpResponse'); - -class TestOfPageInterface extends UnitTestCase { - function testInterfaceOnEmptyPage() { - $page = new SimplePage(); - $this->assertEqual($page->getTransportError(), 'No page fetched yet'); - $this->assertIdentical($page->getRaw(), false); - $this->assertIdentical($page->getHeaders(), false); - $this->assertIdentical($page->getMimeType(), false); - $this->assertIdentical($page->getResponseCode(), false); - $this->assertIdentical($page->getAuthentication(), false); - $this->assertIdentical($page->getRealm(), false); - $this->assertFalse($page->hasFrames()); - $this->assertIdentical($page->getUrls(), array()); - $this->assertIdentical($page->getTitle(), false); - } -} - -class TestOfPageHeaders extends UnitTestCase { - - function testUrlAccessor() { - $headers = new MockSimpleHttpHeaders(); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - $response->setReturnValue('getMethod', 'POST'); - $response->setReturnValue('getUrl', new SimpleUrl('here')); - $response->setReturnValue('getRequestData', array('a' => 'A')); - - $page = new SimplePage($response); - $this->assertEqual($page->getMethod(), 'POST'); - $this->assertEqual($page->getUrl(), new SimpleUrl('here')); - $this->assertEqual($page->getRequestData(), array('a' => 'A')); - } - - function testTransportError() { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getError', 'Ouch'); - - $page = new SimplePage($response); - $this->assertEqual($page->getTransportError(), 'Ouch'); - } - - function testHeadersAccessor() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getRaw', 'My: Headers'); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertEqual($page->getHeaders(), 'My: Headers'); - } - - function testMimeAccessor() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getMimeType', 'text/html'); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertEqual($page->getMimeType(), 'text/html'); - } - - function testResponseAccessor() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getResponseCode', 301); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertIdentical($page->getResponseCode(), 301); - } - - function testAuthenticationAccessors() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getAuthentication', 'Basic'); - $headers->setReturnValue('getRealm', 'Secret stuff'); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertEqual($page->getAuthentication(), 'Basic'); - $this->assertEqual($page->getRealm(), 'Secret stuff'); - } -} - -class TestOfHtmlStrippingAndNormalisation extends UnitTestCase { - - function testImageSuppressionWhileKeepingParagraphsAndAltText() { - $this->assertEqual( - SimplePage::normalise('<img src="foo.png" /><p>some text</p><img src="bar.png" alt="bar" />'), - 'some text bar'); - } - - function testSpaceNormalisation() { - $this->assertEqual( - SimplePage::normalise("\nOne\tTwo \nThree\t"), - 'One Two Three'); - } - - function testMultilinesCommentSuppression() { - $this->assertEqual( - SimplePage::normalise('<!--\n Hello \n-->'), - ''); - } - - function testCommentSuppression() { - $this->assertEqual( - SimplePage::normalise('<!--Hello-->'), - ''); - } - - function testJavascriptSuppression() { - $this->assertEqual( - SimplePage::normalise('<script attribute="test">\nHello\n</script>'), - ''); - $this->assertEqual( - SimplePage::normalise('<script attribute="test">Hello</script>'), - ''); - $this->assertEqual( - SimplePage::normalise('<script>Hello</script>'), - ''); - } - - function testTagSuppression() { - $this->assertEqual( - SimplePage::normalise('<b>Hello</b>'), - 'Hello'); - } - - function testAdjoiningTagSuppression() { - $this->assertEqual( - SimplePage::normalise('<b>Hello</b><em>Goodbye</em>'), - 'HelloGoodbye'); - } - - function testExtractImageAltTextWithDifferentQuotes() { - $this->assertEqual( - SimplePage::normalise('<img alt="One"><img alt=\'Two\'><img alt=Three>'), - 'One Two Three'); - } - - function testExtractImageAltTextMultipleTimes() { - $this->assertEqual( - SimplePage::normalise('<img alt="One"><img alt="Two"><img alt="Three">'), - 'One Two Three'); - } - - function testHtmlEntityTranslation() { - $this->assertEqual( - SimplePage::normalise('<>"&''), - '<>"&\''); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/parse_error_test.php b/3rdparty/simpletest/test/parse_error_test.php deleted file mode 100755 index c3ffb3d42057459a7590e5583d949e88e9afbca0..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/parse_error_test.php +++ /dev/null @@ -1,9 +0,0 @@ -<?php -// $Id: parse_error_test.php 1509 2007-05-08 22:11:49Z lastcraft $ -require_once('../unit_tester.php'); -require_once('../reporter.php'); - -$test = &new TestSuite('This should fail'); -$test->addFile('test_with_parse_error.php'); -$test->run(new HtmlReporter()); -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/parsing_test.php b/3rdparty/simpletest/test/parsing_test.php deleted file mode 100755 index 2c5e6cafe1d7bdab93e55b9d422ceb7d0ad378e3..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/parsing_test.php +++ /dev/null @@ -1,642 +0,0 @@ -<?php -// $Id: page_test.php 1912 2009-07-29 16:39:17Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../page.php'); -require_once(dirname(__FILE__) . '/../php_parser.php'); -require_once(dirname(__FILE__) . '/../tidy_parser.php'); -Mock::generate('SimpleHttpResponse'); - -abstract class TestOfParsing extends UnitTestCase { - - function testRawAccessor() { - $page = $this->whenVisiting('http://host/', 'Raw HTML'); - $this->assertEqual($page->getRaw(), 'Raw HTML'); - } - - function testTextAccessor() { - $page = $this->whenVisiting('http://host/', '<b>Some</b> "messy" HTML'); - $this->assertEqual($page->getText(), 'Some "messy" HTML'); - } - - function testFramesetAbsence() { - $page = $this->whenVisiting('http://here/', ''); - $this->assertFalse($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), false); - } - - function testPageWithNoUrlsGivesEmptyArrayOfLinks() { - $page = $this->whenVisiting('http://here/', '<html><body><p>Stuff</p></body></html>'); - $this->assertIdentical($page->getUrls(), array()); - } - - function testAddAbsoluteLink() { - $page = $this->whenVisiting('http://host', - '<html><a href="http://somewhere.com">Label</a></html>'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://somewhere.com'))); - } - - function testUrlLabelsHaveHtmlTagsStripped() { - $page = $this->whenVisiting('http://host', - '<html><a href="http://somewhere.com"><b>Label</b></a></html>'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://somewhere.com'))); - } - - function testAddStrictRelativeLink() { - $page = $this->whenVisiting('http://host', - '<html><a href="./somewhere.php">Label</a></html>'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testAddBareRelativeLink() { - $page = $this->whenVisiting('http://host', - '<html><a href="somewhere.php">Label</a></html>'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testAddRelativeLinkWithBaseTag() { - $raw = '<html><head><base href="http://www.lastcraft.com/stuff/"></head>' . - '<body><a href="somewhere.php">Label</a></body>' . - '</html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://www.lastcraft.com/stuff/somewhere.php'))); - } - - function testAddAbsoluteLinkWithBaseTag() { - $raw = '<html><head><base href="http://www.lastcraft.com/stuff/"></head>' . - '<body><a href="http://here.com/somewhere.php">Label</a></body>' . - '</html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://here.com/somewhere.php'))); - } - - function testCanFindLinkInsideForm() { - $raw = '<html><body><form><a href="./somewhere.php">Label</a></form></body></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testCanGetLinksByIdOrLabel() { - $raw = '<html><body><a href="./somewhere.php" id="33">Label</a></body></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - $this->assertFalse($page->getUrlById(0)); - $this->assertEqual( - $page->getUrlById(33), - new SimpleUrl('http://host/somewhere.php')); - } - - function testCanFindLinkByNormalisedLabel() { - $raw = '<html><body><a href="./somewhere.php" id="33"><em>Long & thin</em></a></body></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Long & thin'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testCanFindLinkByImageAltText() { - $raw = '<a href="./somewhere.php" id="33"><img src="pic.jpg" alt="<A picture>"></a>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - array_map(array($this, 'urlToString'), $page->getUrlsByLabel('<A picture>')), - array('http://host/somewhere.php')); - } - - function testTitle() { - $page = $this->whenVisiting('http://host', - '<html><head><title>Me</title></head></html>'); - $this->assertEqual($page->getTitle(), 'Me'); - } - - function testTitleWithEntityReference() { - $page = $this->whenVisiting('http://host', - '<html><head><Title>Me&Me</TITLE></head></html>'); - $this->assertEqual($page->getTitle(), "Me&Me"); - } - - function testOnlyFramesInFramesetAreRecognised() { - $raw = - '<frameset>' . - ' <frame src="2.html"></frame>' . - ' <frame src="3.html"></frame>' . - '</frameset>' . - '<frame src="4.html"></frame>'; - $page = $this->whenVisiting('http://here', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertSameFrameset($page->getFrameset(), array( - 1 => new SimpleUrl('http://here/2.html'), - 2 => new SimpleUrl('http://here/3.html'))); - } - - function testReadsNamesInFrames() { - $raw = - '<frameset>' . - ' <frame src="1.html"></frame>' . - ' <frame src="2.html" name="A"></frame>' . - ' <frame src="3.html" name="B"></frame>' . - ' <frame src="4.html"></frame>' . - '</frameset>'; - $page = $this->whenVisiting('http://here', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertSameFrameset($page->getFrameset(), array( - 1 => new SimpleUrl('http://here/1.html'), - 'A' => new SimpleUrl('http://here/2.html'), - 'B' => new SimpleUrl('http://here/3.html'), - 4 => new SimpleUrl('http://here/4.html'))); - } - - function testRelativeFramesRespectBaseTag() { - $raw = '<base href="https://there.com/stuff/"><frameset><frame src="1.html"></frameset>'; - $page = $this->whenVisiting('http://here', $raw); - $this->assertSameFrameset( - $page->getFrameset(), - array(1 => new SimpleUrl('https://there.com/stuff/1.html'))); - } - - function testSingleFrameInNestedFrameset() { - $raw = '<html><frameset><frameset>' . - '<frame src="a.html">' . - '</frameset></frameset></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical( - $page->getFrameset(), - array(1 => new SimpleUrl('http://host/a.html'))); - } - - function testFramesCollectedWithNestedFramesetTags() { - $raw = '<html><frameset>' . - '<frame src="a.html">' . - '<frameset><frame src="b.html"></frameset>' . - '<frame src="c.html">' . - '</frameset></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array( - 1 => new SimpleUrl('http://host/a.html'), - 2 => new SimpleUrl('http://host/b.html'), - 3 => new SimpleUrl('http://host/c.html'))); - } - - function testNamedFrames() { - $raw = '<html><frameset>' . - '<frame src="a.html">' . - '<frame name="_one" src="b.html">' . - '<frame src="c.html">' . - '<frame src="d.html" name="_two">' . - '</frameset></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array( - 1 => new SimpleUrl('http://host/a.html'), - '_one' => new SimpleUrl('http://host/b.html'), - 3 => new SimpleUrl('http://host/c.html'), - '_two' => new SimpleUrl('http://host/d.html'))); - } - - function testCanReadElementOfCompleteForm() { - $raw = '<html><head><form>' . - '<input type="text" name="here" value="Hello">' . - '</form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('here')), "Hello"); - } - - function testCanReadElementOfUnclosedForm() { - $raw = '<html><head><form>' . - '<input type="text" name="here" value="Hello">' . - '</head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('here')), "Hello"); - } - - function testCanReadElementByLabel() { - $raw = '<html><head><form>' . - '<label>Where<input type="text" name="here" value="Hello"></label>' . - '</head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Where')), "Hello"); - } - - function testCanFindFormByLabel() { - $raw = '<html><head><form><input type="submit"></form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('submit'))); - $this->assertNull($page->getFormBySubmit(new SimpleByName('submit'))); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('Submit')), - 'SimpleForm'); - } - - function testConfirmSubmitAttributesAreCaseSensitive() { - $raw = '<html><head><FORM><INPUT TYPE="SUBMIT" NAME="S" VALUE="S"></FORM></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByName('S')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('S')), - 'SimpleForm'); - } - - function testCanFindFormByImage() { - $raw = '<html><head><form>' . - '<input type="image" id=100 alt="Label" name="me">' . - '</form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertIsA( - $page->getFormByImage(new SimpleByLabel('Label')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormByImage(new SimpleByName('me')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormByImage(new SimpleById(100)), - 'SimpleForm'); - } - - function testCanFindFormByButtonTag() { - $raw = '<html><head><form>' . - '<button type="submit" name="b" value="B">BBB</button>' . - '</form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('b'))); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('B'))); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByName('b')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('BBB')), - 'SimpleForm'); - } - - function testCanFindFormById() { - $raw = '<html><head><form id="55"><input type="submit"></form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getFormById(54)); - $this->assertIsA($page->getFormById(55), 'SimpleForm'); - } - - function testFormCanBeSubmitted() { - $raw = '<html><head><form method="GET" action="here.php">' . - '<input type="submit" name="s" value="Submit">' . - '</form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $form = $page->getFormBySubmit(new SimpleByLabel('Submit')); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('s' => 'Submit'))); - } - - function testUnparsedTagDoesNotCrash() { - $raw = '<form><input type="reset" name="Clear"></form>'; - $this->whenVisiting('http://host', $raw); - } - - function testReadingTextField() { - $raw = '<html><head><form>' . - '<input type="text" name="a">' . - '<input type="text" name="b" value="bbb" id=3>' . - '</form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getField(new SimpleByName('missing'))); - $this->assertIdentical($page->getField(new SimpleByName('a')), ''); - $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); - } - - function testEntitiesAreDecodedInDefaultTextFieldValue() { - $raw = '<form><input type="text" name="a" value="&\'"<>"></form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), '&\'"<>'); - } - - function testReadingTextFieldIsCaseInsensitive() { - $raw = '<html><head><FORM>' . - '<INPUT TYPE="TEXT" NAME="a">' . - '<INPUT TYPE="TEXT" NAME="b" VALUE="bbb" id=3>' . - '</FORM></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getField(new SimpleByName('missing'))); - $this->assertIdentical($page->getField(new SimpleByName('a')), ''); - $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); - } - - function testSettingTextField() { - $raw = '<html><head><form>' . - '<input type="text" name="a">' . - '<input type="text" name="b" id=3>' . - '<input type="submit">' . - '</form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - $this->assertTrue($page->setField(new SimpleById(3), 'bbb')); - $this->assertEqual($page->getField(new SimpleBYId(3)), 'bbb'); - $this->assertFalse($page->setField(new SimpleByName('z'), 'zzz')); - $this->assertNull($page->getField(new SimpleByName('z'))); - } - - function testSettingTextFieldByEnclosingLabel() { - $raw = '<html><head><form>' . - '<label>Stuff' . - '<input type="text" name="a" value="A">' . - '</label>' . - '</form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); - } - - function testLabelsWithoutForDoNotAttachToInputsWithNoId() { - $raw = '<form action="network_confirm.php?x=X&y=Y" method="post"> - <label>Text A <input type="text" name="a" value="one"></label> - <label>Text B <input type="text" name="b" value="two"></label> - </form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text A')), 'one'); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text B')), 'two'); - $this->assertTrue($page->setField(new SimpleByLabelOrName('Text A'), '1')); - $this->assertTrue($page->setField(new SimpleByLabelOrName('Text B'), '2')); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text A')), '1'); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text B')), '2'); - } - - function testGettingTextFieldByEnclosingLabelWithConflictingOtherFields() { - $raw = '<html><head><form>' . - '<label>Stuff' . - '<input type="text" name="a" value="A">' . - '</label>' . - '<input type="text" name="b" value="B">' . - '</form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); - $this->assertEqual($page->getField(new SimpleByName('b')), 'B'); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - } - - function testSettingTextFieldByExternalLabel() { - $raw = '<html><head><form>' . - '<label for="aaa">Stuff</label>' . - '<input id="aaa" type="text" name="a" value="A">' . - '</form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); - } - - function testReadingTextArea() { - $raw = '<html><head><form>' . - '<textarea name="a">aaa</textarea>' . - '<input type="submit">' . - '</form></head></html>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - } - - function testEntitiesAreDecodedInTextareaValue() { - $raw = '<form><textarea name="a">&\'"<></textarea></form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), '&\'"<>'); - } - - function testNewlinesPreservedInTextArea() { - $raw = "<form><textarea name=\"a\">hello\r\nworld</textarea></form>"; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), "hello\r\nworld"); - } - - function testWhitespacePreservedInTextArea() { - $raw = '<form><textarea name="a"> </textarea></form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), ' '); - } - - function testComplexWhitespaceInTextArea() { - $raw = "<html>\n" . - " <head><title></title></head>\n" . - " <body>\n" . - " <form>\n". - " <label>Text area C\n" . - " <textarea name='c'>\n" . - " </textarea>\n" . - " </label>\n" . - " </form>\n" . - " </body>\n" . - "</html>"; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('c')), " "); - } - - function testSettingTextArea() { - $raw = '<form>' . - '<textarea name="a">aaa</textarea>' . - '<input type="submit">' . - '</form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('a'), 'AAA')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'AAA'); - } - - function testDontIncludeTextAreaContentInLabel() { - $raw = '<form><label>Text area C<textarea id=3 name="c">mouse</textarea></label></form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Text area C')), 'mouse'); - } - - function testSettingSelectionField() { - $raw = '<form>' . - '<select name="a">' . - '<option>aaa</option>' . - '<option selected>bbb</option>' . - '</select>' . - '<input type="submit">' . - '</form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'bbb'); - $this->assertFalse($page->setField(new SimpleByName('a'), 'ccc')); - $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - } - - function testSelectionOptionsAreNormalised() { - $raw = '<form>' . - '<select name="a">' . - '<option selected><b>Big</b> bold</option>' . - '<option>small <em>italic</em></option>' . - '</select>' . - '</form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'Big bold'); - $this->assertTrue($page->setField(new SimpleByName('a'), 'small italic')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'small italic'); - } - - function testCanParseBlankOptions() { - $raw = '<form> - <select id=4 name="d"> - <option value="d1">D1</option> - <option value="d2">D2</option> - <option></option> - </select> - </form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), '')); - } - - function testTwoSelectionFieldsAreIndependent() { - $raw = '<form> - <select id=4 name="d"> - <option value="d1" selected>D1</option> - <option value="d2">D2</option> - </select> - <select id=11 name="h"> - <option value="h1">H1</option> - <option value="h2" selected>H2</option> - </select> - </form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), 'd2')); - $this->assertTrue($page->setField(new SimpleByName('h'), 'h1')); - $this->assertEqual($page->getField(new SimpleByName('d')), 'd2'); - } - - function testEmptyOptionDoesNotScrewUpTwoSelectionFields() { - $raw = '<form> - <select name="d"> - <option value="d1" selected>D1</option> - <option value="d2">D2</option> - <option></option> - </select> - <select name="h"> - <option value="h1">H1</option> - <option value="h2" selected>H2</option> - </select> - </form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), 'd2')); - $this->assertTrue($page->setField(new SimpleByName('h'), 'h1')); - $this->assertEqual($page->getField(new SimpleByName('d')), 'd2'); - } - - function testSettingSelectionFieldByEnclosingLabel() { - $raw = '<form>' . - '<label>Stuff' . - '<select name="a"><option selected>A</option><option>B</option></select>' . - '</label>' . - '</form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'B')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'B'); - } - - function testTwoSelectionFieldsWithLabelsAreIndependent() { - $raw = '<form> - <label>Labelled D - <select id=4 name="d"> - <option value="d1" selected>D1</option> - <option value="d2">D2</option> - </select> - </label> - <label>Labelled H - <select id=11 name="h"> - <option value="h1">H1</option> - <option value="h2" selected>H2</option> - </select> - </label> - </form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByLabel('Labelled D'), 'd2')); - $this->assertTrue($page->setField(new SimpleByLabel('Labelled H'), 'h1')); - $this->assertEqual($page->getField(new SimpleByLabel('Labelled D')), 'd2'); - } - - function testSettingRadioButtonByEnclosingLabel() { - $raw = '<form>' . - '<label>A<input type="radio" name="r" value="a" checked></label>' . - '<label>B<input type="radio" name="r" value="b"></label>' . - '</form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('A')), 'a'); - $this->assertTrue($page->setField(new SimpleBylabel('B'), 'b')); - $this->assertEqual($page->getField(new SimpleByLabel('B')), 'b'); - } - - function testCanParseInputsWithAllKindsOfAttributeQuoting() { - $raw = '<form>' . - '<input type="checkbox" name=\'first\' value=one checked></input>' . - '<input type=checkbox name="second" value="two"></input>' . - '<input type=checkbox name="third" value=\'three\' checked="checked" />' . - '</form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('first')), 'one'); - $this->assertEqual($page->getField(new SimpleByName('second')), false); - $this->assertEqual($page->getField(new SimpleByName('third')), 'three'); - } - - function urlToString($url) { - return $url->asString(); - } - - function assertSameFrameset($actual, $expected) { - $this->assertIdentical(array_map(array($this, 'urlToString'), $actual), - array_map(array($this, 'urlToString'), $expected)); - } -} - -class TestOfParsingUsingPhpParser extends TestOfParsing { - - function whenVisiting($url, $content) { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnValue('getUrl', new SimpleUrl($url)); - $builder = new SimplePhpPageBuilder(); - return $builder->parse($response); - } - - function testNastyTitle() { - $page = $this->whenVisiting('http://host', - '<html><head><Title> <b>Me&Me </TITLE></b></head></html>'); - $this->assertEqual($page->getTitle(), "Me&Me"); - } - - function testLabelShouldStopAtClosingLabelTag() { - $raw = '<form><label>start<textarea id=3 name="c" wrap="hard">stuff</textarea>end</label>stuff</form>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('startend')), 'stuff'); - } -} - -class TestOfParsingUsingTidyParser extends TestOfParsing { - - function skip() { - $this->skipUnless(extension_loaded('tidy'), 'Install \'tidy\' php extension to enable html tidy based parser'); - } - - function whenVisiting($url, $content) { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnValue('getUrl', new SimpleUrl($url)); - $builder = new SimpleTidyPageBuilder(); - return $builder->parse($response); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/php_parser_test.php b/3rdparty/simpletest/test/php_parser_test.php deleted file mode 100755 index d95c7d06a60efd0f56ce6e899e5d21fc814922aa..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/php_parser_test.php +++ /dev/null @@ -1,489 +0,0 @@ -<?php -// $Id: php_parser_test.php 1911 2009-07-29 16:38:04Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../php_parser.php'); -require_once(dirname(__FILE__) . '/../tag.php'); -Mock::generate('SimplePage'); -Mock::generate('SimplePhpPageBuilder'); -Mock::generate('SimpleHttpResponse'); -Mock::generatePartial( - 'SimplePhpPageBuilder', - 'PartialSimplePhpPageBuilder', - array('createPage', 'createParser')); -Mock::generate('SimpleHtmlSaxParser'); -Mock::generate('SimplePhpPageBuilder'); - -class TestOfParallelRegex extends UnitTestCase { - - function testNoPatterns() { - $regex = new ParallelRegex(false); - $this->assertFalse($regex->match("Hello", $match)); - $this->assertEqual($match, ""); - } - - function testNoSubject() { - $regex = new ParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("", $match)); - $this->assertEqual($match, ""); - } - - function testMatchAll() { - $regex = new ParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("Hello", $match)); - $this->assertEqual($match, "Hello"); - } - - function testCaseSensitive() { - $regex = new ParallelRegex(true); - $regex->addPattern("abc"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "abc"); - } - - function testCaseInsensitive() { - $regex = new ParallelRegex(false); - $regex->addPattern("abc"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "ABC"); - } - - function testMatchMultiple() { - $regex = new ParallelRegex(true); - $regex->addPattern("abc"); - $regex->addPattern("ABC"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "ABC"); - $this->assertFalse($regex->match("Hello", $match)); - } - - function testPatternLabels() { - $regex = new ParallelRegex(false); - $regex->addPattern("abc", "letter"); - $regex->addPattern("123", "number"); - $this->assertIdentical($regex->match("abcdef", $match), "letter"); - $this->assertEqual($match, "abc"); - $this->assertIdentical($regex->match("0123456789", $match), "number"); - $this->assertEqual($match, "123"); - } -} - -class TestOfStateStack extends UnitTestCase { - - function testStartState() { - $stack = new SimpleStateStack("one"); - $this->assertEqual($stack->getCurrent(), "one"); - } - - function testExhaustion() { - $stack = new SimpleStateStack("one"); - $this->assertFalse($stack->leave()); - } - - function testStateMoves() { - $stack = new SimpleStateStack("one"); - $stack->enter("two"); - $this->assertEqual($stack->getCurrent(), "two"); - $stack->enter("three"); - $this->assertEqual($stack->getCurrent(), "three"); - $this->assertTrue($stack->leave()); - $this->assertEqual($stack->getCurrent(), "two"); - $stack->enter("third"); - $this->assertEqual($stack->getCurrent(), "third"); - $this->assertTrue($stack->leave()); - $this->assertTrue($stack->leave()); - $this->assertEqual($stack->getCurrent(), "one"); - } -} - -class TestParser { - - function accept() { - } - - function a() { - } - - function b() { - } -} -Mock::generate('TestParser'); - -class TestOfLexer extends UnitTestCase { - - function testEmptyPage() { - $handler = new MockTestParser(); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("")); - } - - function testSinglePattern() { - $handler = new MockTestParser(); - $handler->expectAt(0, "accept", array("aaa", LEXER_MATCHED)); - $handler->expectAt(1, "accept", array("x", LEXER_UNMATCHED)); - $handler->expectAt(2, "accept", array("a", LEXER_MATCHED)); - $handler->expectAt(3, "accept", array("yyy", LEXER_UNMATCHED)); - $handler->expectAt(4, "accept", array("a", LEXER_MATCHED)); - $handler->expectAt(5, "accept", array("x", LEXER_UNMATCHED)); - $handler->expectAt(6, "accept", array("aaa", LEXER_MATCHED)); - $handler->expectAt(7, "accept", array("z", LEXER_UNMATCHED)); - $handler->expectCallCount("accept", 8); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("aaaxayyyaxaaaz")); - } - - function testMultiplePattern() { - $handler = new MockTestParser(); - $target = array("a", "b", "a", "bb", "x", "b", "a", "xxxxxx", "a", "x"); - for ($i = 0; $i < count($target); $i++) { - $handler->expectAt($i, "accept", array($target[$i], '*')); - } - $handler->expectCallCount("accept", count($target)); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $lexer->addPattern("b+"); - $this->assertTrue($lexer->parse("ababbxbaxxxxxxax")); - } -} - -class TestOfLexerModes extends UnitTestCase { - - function testIsolatedPattern() { - $handler = new MockTestParser(); - $handler->expectAt(0, "a", array("a", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("bxb", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("aaa", LEXER_MATCHED)); - $handler->expectAt(5, "a", array("x", LEXER_UNMATCHED)); - $handler->expectAt(6, "a", array("aaaa", LEXER_MATCHED)); - $handler->expectAt(7, "a", array("x", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 8); - $handler->setReturnValue("a", true); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabxbaaaxaaaax")); - } - - function testModeChange() { - $handler = new MockTestParser(); - $handler->expectAt(0, "a", array("a", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("aaa", LEXER_MATCHED)); - $handler->expectAt(0, "b", array(":", LEXER_ENTER)); - $handler->expectAt(1, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(2, "b", array("b", LEXER_MATCHED)); - $handler->expectAt(3, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(4, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(5, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(6, "b", array("bbb", LEXER_MATCHED)); - $handler->expectAt(7, "b", array("a", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 5); - $handler->expectCallCount("b", 8); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern(":", "a", "b"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabaaa:ababbabbba")); - } - - function testNesting() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(0, "b", array("(", LEXER_ENTER)); - $handler->expectAt(1, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(2, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(3, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(4, "b", array(")", LEXER_EXIT)); - $handler->expectAt(4, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(5, "a", array("b", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 6); - $handler->expectCallCount("b", 5); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern("(", "a", "b"); - $lexer->addPattern("b+", "b"); - $lexer->addExitPattern(")", "b"); - $this->assertTrue($lexer->parse("aabaab(bbabb)aab")); - } - - function testSingular() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(2, "a", array("xx", LEXER_UNMATCHED)); - $handler->expectAt(3, "a", array("xx", LEXER_UNMATCHED)); - $handler->expectAt(0, "b", array("b", LEXER_SPECIAL)); - $handler->expectAt(1, "b", array("bbb", LEXER_SPECIAL)); - $handler->expectCallCount("a", 4); - $handler->expectCallCount("b", 2); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addSpecialPattern("b+", "a", "b"); - $this->assertTrue($lexer->parse("aabaaxxbbbxx")); - } - - function testUnwindTooFar() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array(")", LEXER_EXIT)); - $handler->expectCallCount("a", 2); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addExitPattern(")", "a"); - $this->assertFalse($lexer->parse("aa)aa")); - } -} - -class TestOfLexerHandlers extends UnitTestCase { - - function testModeMapping() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("(", LEXER_ENTER)); - $handler->expectAt(2, "a", array("bb", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("a", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("bb", LEXER_MATCHED)); - $handler->expectAt(5, "a", array(")", LEXER_EXIT)); - $handler->expectAt(6, "a", array("b", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 7); - $lexer = new SimpleLexer($handler, "mode_a"); - $lexer->addPattern("a+", "mode_a"); - $lexer->addEntryPattern("(", "mode_a", "mode_b"); - $lexer->addPattern("b+", "mode_b"); - $lexer->addExitPattern(")", "mode_b"); - $lexer->mapHandler("mode_a", "a"); - $lexer->mapHandler("mode_b", "a"); - $this->assertTrue($lexer->parse("aa(bbabb)b")); - } -} - -class TestOfSimpleHtmlLexer extends UnitTestCase { - - function &createParser() { - $parser = new MockSimpleHtmlSaxParser(); - $parser->setReturnValue('acceptStartToken', true); - $parser->setReturnValue('acceptEndToken', true); - $parser->setReturnValue('acceptAttributeToken', true); - $parser->setReturnValue('acceptEntityToken', true); - $parser->setReturnValue('acceptTextToken', true); - $parser->setReturnValue('ignore', true); - return $parser; - } - - function testNoContent() { - $parser = $this->createParser(); - $parser->expectNever('acceptStartToken'); - $parser->expectNever('acceptEndToken'); - $parser->expectNever('acceptAttributeToken'); - $parser->expectNever('acceptEntityToken'); - $parser->expectNever('acceptTextToken'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('')); - } - - function testUninteresting() { - $parser = $this->createParser(); - $parser->expectOnce('acceptTextToken', array('<html></html>', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('<html></html>')); - } - - function testSkipCss() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("<style>Lot's of styles</style>")); - } - - function testSkipJavaScript() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("<SCRIPT>Javascript code {';:^%^%�$'@\"*(}</SCRIPT>")); - } - - function testSkipHtmlComments() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("<!-- <title>title</title><style>styles</style> -->")); - } - - function testTagWithNoAttributes() { - $parser = $this->createParser(); - $parser->expectAt(0, 'acceptStartToken', array('<title', '*')); - $parser->expectAt(1, 'acceptStartToken', array('>', '*')); - $parser->expectCallCount('acceptStartToken', 2); - $parser->expectOnce('acceptTextToken', array('Hello', '*')); - $parser->expectOnce('acceptEndToken', array('</title>', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('<title>Hello</title>')); - } - - function testTagWithAttributes() { - $parser = $this->createParser(); - $parser->expectOnce('acceptTextToken', array('label', '*')); - $parser->expectAt(0, 'acceptStartToken', array('<a', '*')); - $parser->expectAt(1, 'acceptStartToken', array('href', '*')); - $parser->expectAt(2, 'acceptStartToken', array('>', '*')); - $parser->expectCallCount('acceptStartToken', 3); - $parser->expectAt(0, 'acceptAttributeToken', array('= "', '*')); - $parser->expectAt(1, 'acceptAttributeToken', array('here.html', '*')); - $parser->expectAt(2, 'acceptAttributeToken', array('"', '*')); - $parser->expectCallCount('acceptAttributeToken', 3); - $parser->expectOnce('acceptEndToken', array('</a>', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('<a href = "here.html">label</a>')); - } -} - -class TestOfHtmlSaxParser extends UnitTestCase { - - function createListener() { - $listener = new MockSimplePhpPageBuilder(); - $listener->setReturnValue('startElement', true); - $listener->setReturnValue('addContent', true); - $listener->setReturnValue('endElement', true); - return $listener; - } - - function testFramesetTag() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('frameset', array())); - $listener->expectOnce('addContent', array('Frames')); - $listener->expectOnce('endElement', array('frameset')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('<frameset>Frames</frameset>')); - } - - function testTagWithUnquotedAttributes() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('input', array('name' => 'a.b.c', 'value' => 'd'))); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('<input name=a.b.c value = d>')); - } - - function testTagInsideContent() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array())); - $listener->expectAt(0, 'addContent', array('<html>')); - $listener->expectAt(1, 'addContent', array('</html>')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('<html><a></a></html>')); - } - - function testTagWithInternalContent() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array())); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('<a>label</a>')); - } - - function testLinkAddress() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('href' => 'here.html'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse("<a href = 'here.html'>label</a>")); - } - - function testEncodedAttribute() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('href' => 'here&there.html'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse("<a href = 'here&there.html'>label</a>")); - } - - function testTagWithId() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('id' => '0'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('<a id="0">label</a>')); - } - - function testTagWithEmptyAttributes() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('option', array('value' => '', 'selected' => ''))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('option')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('<option value="" selected>label</option>')); - } - - function testComplexTagWithLotsOfCaseVariations() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('a', array('href' => 'here.html', 'style' => "'cool'"))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('<A HREF = \'here.html\' Style="\'cool\'">label</A>')); - } - - function testXhtmlSelfClosingTag() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('input', array('type' => 'submit', 'name' => 'N', 'value' => 'V'))); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('<input type="submit" name="N" value="V" />')); - } - - function testNestedFrameInFrameset() { - $listener = $this->createListener(); - $listener->expectAt(0, 'startElement', array('frameset', array())); - $listener->expectAt(1, 'startElement', array('frame', array('src' => 'frame.html'))); - $listener->expectCallCount('startElement', 2); - $listener->expectOnce('addContent', array('<noframes>Hello</noframes>')); - $listener->expectOnce('endElement', array('frameset')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse( - '<frameset><frame src="frame.html"><noframes>Hello</noframes></frameset>')); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/recorder_test.php b/3rdparty/simpletest/test/recorder_test.php deleted file mode 100755 index fdae4c1cccce69cfbca77e650180310fb58a446d..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/recorder_test.php +++ /dev/null @@ -1,23 +0,0 @@ -<?php -// $Id: test.php 1500 2007-04-29 14:33:31Z pp11 $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../recorder.php'); - -class TestOfRecorder extends UnitTestCase { - - function testContentOfRecorderWithOnePassAndOneFailure() { - $test = new TestSuite(); - $test->addFile(dirname(__FILE__) . '/support/recorder_sample.php'); - $recorder = new Recorder(new SimpleReporter()); - $test->run($recorder); - $this->assertEqual(count($recorder->results), 2); - $this->assertIsA($recorder->results[0], 'SimpleResultOfPass'); - $this->assertEqual('testTrueIsTrue', array_pop($recorder->results[0]->breadcrumb)); - $this->assertPattern('/ at \[.*\Wrecorder_sample\.php line 7\]/', $recorder->results[0]->message); - $this->assertIsA($recorder->results[1], 'SimpleResultOfFail'); - $this->assertEqual('testFalseIsTrue', array_pop($recorder->results[1]->breadcrumb)); - $this->assertPattern("/Expected false, got \[Boolean: true\] at \[.*\Wrecorder_sample\.php line 11\]/", - $recorder->results[1]->message); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/reflection_php5_test.php b/3rdparty/simpletest/test/reflection_php5_test.php deleted file mode 100755 index d9f46e6db78c886a543996b93543744b19ef6e1c..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/reflection_php5_test.php +++ /dev/null @@ -1,263 +0,0 @@ -<?php -// $Id: reflection_php5_test.php 1778 2008-04-21 16:13:08Z edwardzyang $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../reflection_php5.php'); - -class AnyOldLeafClass { - function aMethod() { } -} - -abstract class AnyOldClass { - function aMethod() { } -} - -class AnyOldLeafClassWithAFinal { - final function aMethod() { } -} - -interface AnyOldInterface { - function aMethod(); -} - -interface AnyOldArgumentInterface { - function aMethod(AnyOldInterface $argument); -} - -interface AnyDescendentInterface extends AnyOldInterface { -} - -class AnyOldImplementation implements AnyOldInterface { - function aMethod() { } - function extraMethod() { } -} - -abstract class AnyAbstractImplementation implements AnyOldInterface { -} - -abstract class AnotherOldAbstractClass { - protected abstract function aMethod(AnyOldInterface $argument); -} - -class AnyOldSubclass extends AnyOldImplementation { } - -class AnyOldArgumentClass { - function aMethod($argument) { } -} - -class AnyOldArgumentImplementation implements AnyOldArgumentInterface { - function aMethod(AnyOldInterface $argument) { } -} - -class AnyOldTypeHintedClass implements AnyOldArgumentInterface { - function aMethod(AnyOldInterface $argument) { } -} - -class AnyDescendentImplementation implements AnyDescendentInterface { - function aMethod() { } -} - -class AnyOldOverloadedClass { - function __isset($key) { } - function __unset($key) { } -} - -class AnyOldClassWithStaticMethods { - static function aStatic() { } - static function aStaticWithParameters($arg1, $arg2) { } -} - -abstract class AnyOldAbstractClassWithAbstractMethods { - abstract function anAbstract(); - abstract function anAbstractWithParameter($foo); - abstract function anAbstractWithMultipleParameters($foo, $bar); -} - -class TestOfReflection extends UnitTestCase { - - function testClassExistence() { - $reflection = new SimpleReflection('AnyOldLeafClass'); - $this->assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - $this->assertFalse($reflection->isAbstract()); - $this->assertFalse($reflection->isInterface()); - } - - function testClassNonExistence() { - $reflection = new SimpleReflection('UnknownThing'); - $this->assertFalse($reflection->classOrInterfaceExists()); - $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload()); - } - - function testDetectionOfAbstractClass() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertTrue($reflection->isAbstract()); - } - - function testDetectionOfFinalMethods() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertFalse($reflection->hasFinal()); - $reflection = new SimpleReflection('AnyOldLeafClassWithAFinal'); - $this->assertTrue($reflection->hasFinal()); - } - - function testFindingParentClass() { - $reflection = new SimpleReflection('AnyOldSubclass'); - $this->assertEqual($reflection->getParent(), 'AnyOldImplementation'); - } - - function testInterfaceExistence() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - $this->assertTrue($reflection->isInterface()); - } - - function testMethodsListFromClass() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testMethodsListFromInterface() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); - } - - function testMethodsComeFromDescendentInterfacesASWell() { - $reflection = new SimpleReflection('AnyDescendentInterface'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testCanSeparateInterfaceMethodsFromOthers() { - $reflection = new SimpleReflection('AnyOldImplementation'); - $this->assertIdentical($reflection->getMethods(), array('aMethod', 'extraMethod')); - $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); - } - - function testMethodsComeFromDescendentInterfacesInAbstractClass() { - $reflection = new SimpleReflection('AnyAbstractImplementation'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testInterfaceHasOnlyItselfToImplement() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testInterfacesListedForClass() { - $reflection = new SimpleReflection('AnyOldImplementation'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testInterfacesListedForSubclass() { - $reflection = new SimpleReflection('AnyOldSubclass'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testNoParameterCreationWhenNoInterface() { - $reflection = new SimpleReflection('AnyOldArgumentClass'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod($argument)', strtolower($function)); - } else { - $this->assertEqual('function aMethod($argument)', $function); - } - } - - function testParameterCreationWithoutTypeHinting() { - $reflection = new SimpleReflection('AnyOldArgumentImplementation'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); - } else { - $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); - } - } - - function testParameterCreationForTypeHinting() { - $reflection = new SimpleReflection('AnyOldTypeHintedClass'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); - } else { - $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); - } - } - - function testIssetFunctionSignature() { - $reflection = new SimpleReflection('AnyOldOverloadedClass'); - $function = $reflection->getSignature('__isset'); - $this->assertEqual('function __isset($key)', $function); - } - - function testUnsetFunctionSignature() { - $reflection = new SimpleReflection('AnyOldOverloadedClass'); - $function = $reflection->getSignature('__unset'); - $this->assertEqual('function __unset($key)', $function); - } - - function testProperlyReflectsTheFinalInterfaceWhenObjectImplementsAnExtendedInterface() { - $reflection = new SimpleReflection('AnyDescendentImplementation'); - $interfaces = $reflection->getInterfaces(); - $this->assertEqual(1, count($interfaces)); - $this->assertEqual('AnyDescendentInterface', array_shift($interfaces)); - } - - function testCreatingSignatureForAbstractMethod() { - $reflection = new SimpleReflection('AnotherOldAbstractClass'); - $this->assertEqual($reflection->getSignature('aMethod'), 'function aMethod(AnyOldInterface $argument)'); - } - - function testCanProperlyGenerateStaticMethodSignatures() { - $reflection = new SimpleReflection('AnyOldClassWithStaticMethods'); - $this->assertEqual('static function aStatic()', $reflection->getSignature('aStatic')); - $this->assertEqual( - 'static function aStaticWithParameters($arg1, $arg2)', - $reflection->getSignature('aStaticWithParameters') - ); - } -} - -class TestOfReflectionWithTypeHints extends UnitTestCase { - function skip() { - $this->skipIf(version_compare(phpversion(), '5.1.0', '<'), 'Reflection with type hints only tested for PHP 5.1.0 and above'); - } - - function testParameterCreationForTypeHintingWithArray() { - eval('interface AnyOldArrayTypeHintedInterface { - function amethod(array $argument); - } - class AnyOldArrayTypeHintedClass implements AnyOldArrayTypeHintedInterface { - function amethod(array $argument) {} - }'); - $reflection = new SimpleReflection('AnyOldArrayTypeHintedClass'); - $function = $reflection->getSignature('amethod'); - $this->assertEqual('function amethod(array $argument)', $function); - } -} - -class TestOfAbstractsWithAbstractMethods extends UnitTestCase { - function testCanProperlyGenerateAbstractMethods() { - $reflection = new SimpleReflection('AnyOldAbstractClassWithAbstractMethods'); - $this->assertEqual( - 'function anAbstract()', - $reflection->getSignature('anAbstract') - ); - $this->assertEqual( - 'function anAbstractWithParameter($foo)', - $reflection->getSignature('anAbstractWithParameter') - ); - $this->assertEqual( - 'function anAbstractWithMultipleParameters($foo, $bar)', - $reflection->getSignature('anAbstractWithMultipleParameters') - ); - } -} - -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/remote_test.php b/3rdparty/simpletest/test/remote_test.php deleted file mode 100755 index 5f3f96a4de9e176056b238e0fba78fa10ce2a117..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/remote_test.php +++ /dev/null @@ -1,19 +0,0 @@ -<?php -// $Id: remote_test.php 1759 2008-04-15 02:37:07Z edwardzyang $ -require_once('../remote.php'); -require_once('../reporter.php'); - -// The following URL will depend on your own installation. -if (isset($_SERVER['SCRIPT_URI'])) { - $base_uri = $_SERVER['SCRIPT_URI']; -} elseif (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['PHP_SELF'])) { - $base_uri = 'http://'. $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; -}; -$test_url = str_replace('remote_test.php', 'visual_test.php', $base_uri); - -$test = new TestSuite('Remote tests'); -$test->add(new RemoteTestCase($test_url . '?xml=yes', $test_url . '?xml=yes&dry=yes')); -if (SimpleReporter::inCli()) { - exit ($test->run(new TextReporter()) ? 0 : 1); -} -$test->run(new HtmlReporter()); diff --git a/3rdparty/simpletest/test/shell_test.php b/3rdparty/simpletest/test/shell_test.php deleted file mode 100755 index d1d769a679598999afad5f9c9876b731bd785d83..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/shell_test.php +++ /dev/null @@ -1,38 +0,0 @@ -<?php -// $Id: shell_test.php 1748 2008-04-14 01:50:41Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../shell_tester.php'); - -class TestOfShell extends UnitTestCase { - - function testEcho() { - $shell = new SimpleShell(); - $this->assertIdentical($shell->execute('echo Hello'), 0); - $this->assertPattern('/Hello/', $shell->getOutput()); - } - - function testBadCommand() { - $shell = new SimpleShell(); - $this->assertNotEqual($ret = $shell->execute('blurgh! 2>&1'), 0); - } -} - -class TestOfShellTesterAndShell extends ShellTestCase { - - function testEcho() { - $this->assertTrue($this->execute('echo Hello')); - $this->assertExitCode(0); - $this->assertoutput('Hello'); - } - - function testFileExistence() { - $this->assertFileExists(dirname(__FILE__) . '/all_tests.php'); - $this->assertFileNotExists('wibble'); - } - - function testFilePatterns() { - $this->assertFilePattern('/all[_ ]tests/i', dirname(__FILE__) . '/all_tests.php'); - $this->assertNoFilePattern('/sputnik/i', dirname(__FILE__) . '/all_tests.php'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/shell_tester_test.php b/3rdparty/simpletest/test/shell_tester_test.php deleted file mode 100755 index b12c602a39fd23edbd190f3e84c9dd7c42b48ac1..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/shell_tester_test.php +++ /dev/null @@ -1,42 +0,0 @@ -<?php -// $Id: shell_tester_test.php 1787 2008-04-26 20:35:39Z pp11 $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../shell_tester.php'); -Mock::generate('SimpleShell'); - -class TestOfShellTestCase extends ShellTestCase { - private $mock_shell = false; - - function getShell() { - return $this->mock_shell; - } - - function testGenericEquality() { - $this->assertEqual('a', 'a'); - $this->assertNotEqual('a', 'A'); - } - - function testExitCode() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->expectOnce('execute', array('ls')); - $this->assertTrue($this->execute('ls')); - $this->assertExitCode(0); - } - - function testOutput() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); - $this->assertOutput("Line 1\nLine 2\n"); - } - - function testOutputPatterns() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); - $this->assertOutputPattern('/line/i'); - $this->assertNoOutputPattern('/line 2/'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/simpletest_test.php b/3rdparty/simpletest/test/simpletest_test.php deleted file mode 100755 index daa65c6f4726f707e274642ba5016248f7668f1e..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/simpletest_test.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -// $Id: simpletest_test.php 1748 2008-04-14 01:50:41Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../simpletest.php'); - -SimpleTest::ignore('ShouldNeverBeRunEither'); - -class ShouldNeverBeRun extends UnitTestCase { - function testWithNoChanceOfSuccess() { - $this->fail('Should be ignored'); - } -} - -class ShouldNeverBeRunEither extends ShouldNeverBeRun { } - -class TestOfStackTrace extends UnitTestCase { - - function testCanFindAssertInTrace() { - $trace = new SimpleStackTrace(array('assert')); - $this->assertEqual( - $trace->traceMethod(array(array( - 'file' => '/my_test.php', - 'line' => 24, - 'function' => 'assertSomething'))), - ' at [/my_test.php line 24]'); - } -} - -class DummyResource { } - -class TestOfContext extends UnitTestCase { - - function testCurrentContextIsUnique() { - $this->assertSame( - SimpleTest::getContext(), - SimpleTest::getContext()); - } - - function testContextHoldsCurrentTestCase() { - $context = SimpleTest::getContext(); - $this->assertSame($this, $context->getTest()); - } - - function testResourceIsSingleInstanceWithContext() { - $context = new SimpleTestContext(); - $this->assertSame( - $context->get('DummyResource'), - $context->get('DummyResource')); - } - - function testClearingContextResetsResources() { - $context = new SimpleTestContext(); - $resource = $context->get('DummyResource'); - $context->clear(); - $this->assertClone($resource, $context->get('DummyResource')); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/site/file.html b/3rdparty/simpletest/test/site/file.html deleted file mode 100755 index cc41aee1b8b638347b7ef84533b3714c44b12005..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/site/file.html +++ /dev/null @@ -1,6 +0,0 @@ -<html> - <head><title>Link to SimpleTest</title></head> - <body> - <a href="http://simpletest.org/">Link to SimpleTest</a> - </body> -</html> \ No newline at end of file diff --git a/3rdparty/simpletest/test/socket_test.php b/3rdparty/simpletest/test/socket_test.php deleted file mode 100755 index 729adda4960d8e3e236bcaab3617348aa7321986..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/socket_test.php +++ /dev/null @@ -1,25 +0,0 @@ -<?php -// $Id: socket_test.php 1782 2008-04-25 17:09:06Z pp11 $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../socket.php'); -Mock::generate('SimpleSocket'); - -class TestOfSimpleStickyError extends UnitTestCase { - - function testSettingError() { - $error = new SimpleStickyError(); - $this->assertFalse($error->isError()); - $error->setError('Ouch'); - $this->assertTrue($error->isError()); - $this->assertEqual($error->getError(), 'Ouch'); - } - - function testClearingError() { - $error = new SimpleStickyError(); - $error->setError('Ouch'); - $this->assertTrue($error->isError()); - $error->clearError(); - $this->assertFalse($error->isError()); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/collector/collectable.1 b/3rdparty/simpletest/test/support/collector/collectable.1 deleted file mode 100755 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/3rdparty/simpletest/test/support/collector/collectable.2 b/3rdparty/simpletest/test/support/collector/collectable.2 deleted file mode 100755 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/3rdparty/simpletest/test/support/empty_test_file.php b/3rdparty/simpletest/test/support/empty_test_file.php deleted file mode 100755 index 31e3f7bed620a0064bdbdb28716698e04dcdfe4f..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/empty_test_file.php +++ /dev/null @@ -1,3 +0,0 @@ -<?php -require_once(dirname(__FILE__) . '/../../autorun.php'); -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/failing_test.php b/3rdparty/simpletest/test/support/failing_test.php deleted file mode 100755 index 30f0d7507d9877d7804ff67c55391dfb880093c8..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/failing_test.php +++ /dev/null @@ -1,9 +0,0 @@ -<?php -require_once(dirname(__FILE__) . '/../../autorun.php'); - -class FailingTest extends UnitTestCase { - function test_fail() { - $this->assertEqual(1,2); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/latin1_sample b/3rdparty/simpletest/test/support/latin1_sample deleted file mode 100755 index 190352577660774b2d23243f9a1169b16fb53ad9..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/latin1_sample +++ /dev/null @@ -1 +0,0 @@ -�������@�����櫻�� \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/passing_test.php b/3rdparty/simpletest/test/support/passing_test.php deleted file mode 100755 index b786321635357733a8356e9dd1911cb0a6d55d04..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/passing_test.php +++ /dev/null @@ -1,9 +0,0 @@ -<?php -require_once(dirname(__FILE__) . '/../../autorun.php'); - -class PassingTest extends UnitTestCase { - function test_pass() { - $this->assertEqual(2,2); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/recorder_sample.php b/3rdparty/simpletest/test/support/recorder_sample.php deleted file mode 100755 index 4f157f6b601312e8a0afe2617e1c4ef75565e9b6..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/recorder_sample.php +++ /dev/null @@ -1,14 +0,0 @@ -<?php -// $Id: sample_test.php 1500 2007-04-29 14:33:31Z pp11 $ -require_once dirname(__FILE__) . '/../../autorun.php'; - -class SampleTestForRecorder extends UnitTestCase { - function testTrueIsTrue() { - $this->assertTrue(true); - } - - function testFalseIsTrue() { - $this->assertFalse(true); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/spl_examples.php b/3rdparty/simpletest/test/support/spl_examples.php deleted file mode 100755 index 45add356c445f3df47692b746a1cdd409446ff6d..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/spl_examples.php +++ /dev/null @@ -1,15 +0,0 @@ -<?php - // $Id: spl_examples.php 1262 2006-02-05 19:35:31Z lastcraft $ - - class IteratorImplementation implements Iterator { - function current() { } - function next() { } - function key() { } - function valid() { } - function rewind() { } - } - - class IteratorAggregateImplementation implements IteratorAggregate { - function getIterator() { } - } -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/supplementary_upload_sample.txt b/3rdparty/simpletest/test/support/supplementary_upload_sample.txt deleted file mode 100755 index d8aa9e8101328e4d96244187a9a11a8f6d460478..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/supplementary_upload_sample.txt +++ /dev/null @@ -1 +0,0 @@ -Some more text content \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/test1.php b/3rdparty/simpletest/test/support/test1.php deleted file mode 100755 index b414586d64212af6913d30eeadfec0f0d4817ad0..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/test1.php +++ /dev/null @@ -1,7 +0,0 @@ -<?php -class test1 extends UnitTestCase { - function test_pass(){ - $this->assertEqual(3,1+2, "pass1"); - } -} -?> diff --git a/3rdparty/simpletest/test/support/upload_sample.txt b/3rdparty/simpletest/test/support/upload_sample.txt deleted file mode 100755 index ec98d7c5e3fe88d9be026122fc63e089aa504f56..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/upload_sample.txt +++ /dev/null @@ -1 +0,0 @@ -Sample for testing file upload \ No newline at end of file diff --git a/3rdparty/simpletest/test/tag_test.php b/3rdparty/simpletest/test/tag_test.php deleted file mode 100755 index 5e8a377f089cf7d3a79c8fef811aa27cb560c0a5..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/tag_test.php +++ /dev/null @@ -1,554 +0,0 @@ -<?php -// $Id: tag_test.php 1748 2008-04-14 01:50:41Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../tag.php'); -require_once(dirname(__FILE__) . '/../encoding.php'); -Mock::generate('SimpleMultipartEncoding'); - -class TestOfTag extends UnitTestCase { - - function testStartValuesWithoutAdditionalContent() { - $tag = new SimpleTitleTag(array('a' => '1', 'b' => '')); - $this->assertEqual($tag->getTagName(), 'title'); - $this->assertIdentical($tag->getAttribute('a'), '1'); - $this->assertIdentical($tag->getAttribute('b'), ''); - $this->assertIdentical($tag->getAttribute('c'), false); - $this->assertIdentical($tag->getContent(), ''); - } - - function testTitleContent() { - $tag = new SimpleTitleTag(array()); - $this->assertTrue($tag->expectEndTag()); - $tag->addContent('Hello'); - $tag->addContent('World'); - $this->assertEqual($tag->getText(), 'HelloWorld'); - } - - function testMessyTitleContent() { - $tag = new SimpleTitleTag(array()); - $this->assertTrue($tag->expectEndTag()); - $tag->addContent('<b>Hello</b>'); - $tag->addContent('<em>World</em>'); - $this->assertEqual($tag->getText(), 'HelloWorld'); - } - - function testTagWithNoEnd() { - $tag = new SimpleTextTag(array()); - $this->assertFalse($tag->expectEndTag()); - } - - function testAnchorHref() { - $tag = new SimpleAnchorTag(array('href' => 'http://here/')); - $this->assertEqual($tag->getHref(), 'http://here/'); - - $tag = new SimpleAnchorTag(array('href' => '')); - $this->assertIdentical($tag->getAttribute('href'), ''); - $this->assertIdentical($tag->getHref(), ''); - - $tag = new SimpleAnchorTag(array()); - $this->assertIdentical($tag->getAttribute('href'), false); - $this->assertIdentical($tag->getHref(), ''); - } - - function testIsIdMatchesIdAttribute() { - $tag = new SimpleAnchorTag(array('href' => 'http://here/', 'id' => 7)); - $this->assertIdentical($tag->getAttribute('id'), '7'); - $this->assertTrue($tag->isId(7)); - } -} - -class TestOfWidget extends UnitTestCase { - - function testTextEmptyDefault() { - $tag = new SimpleTextTag(array('type' => 'text')); - $this->assertIdentical($tag->getDefault(), ''); - $this->assertIdentical($tag->getValue(), ''); - } - - function testSettingOfExternalLabel() { - $tag = new SimpleTextTag(array('type' => 'text')); - $tag->setLabel('it'); - $this->assertTrue($tag->isLabel('it')); - } - - function testTextDefault() { - $tag = new SimpleTextTag(array('value' => 'aaa')); - $this->assertEqual($tag->getDefault(), 'aaa'); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testSettingTextValue() { - $tag = new SimpleTextTag(array('value' => 'aaa')); - $tag->setValue('bbb'); - $this->assertEqual($tag->getValue(), 'bbb'); - $tag->resetValue(); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testFailToSetHiddenValue() { - $tag = new SimpleTextTag(array('value' => 'aaa', 'type' => 'hidden')); - $this->assertFalse($tag->setValue('bbb')); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testSubmitDefaults() { - $tag = new SimpleSubmitTag(array('type' => 'submit')); - $this->assertIdentical($tag->getName(), false); - $this->assertEqual($tag->getValue(), 'Submit'); - $this->assertFalse($tag->setValue('Cannot set this')); - $this->assertEqual($tag->getValue(), 'Submit'); - $this->assertEqual($tag->getLabel(), 'Submit'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectNever('add'); - $tag->write($encoding); - } - - function testPopulatedSubmit() { - $tag = new SimpleSubmitTag( - array('type' => 'submit', 'name' => 's', 'value' => 'Ok!')); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getValue(), 'Ok!'); - $this->assertEqual($tag->getLabel(), 'Ok!'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('add', array('s', 'Ok!')); - $tag->write($encoding); - } - - function testImageSubmit() { - $tag = new SimpleImageSubmitTag( - array('type' => 'image', 'name' => 's', 'alt' => 'Label')); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getLabel(), 'Label'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectAt(0, 'add', array('s.x', 20)); - $encoding->expectAt(1, 'add', array('s.y', 30)); - $tag->write($encoding, 20, 30); - } - - function testImageSubmitTitlePreferredOverAltForLabel() { - $tag = new SimpleImageSubmitTag( - array('type' => 'image', 'name' => 's', 'alt' => 'Label', 'title' => 'Title')); - $this->assertEqual($tag->getLabel(), 'Title'); - } - - function testButton() { - $tag = new SimpleButtonTag( - array('type' => 'submit', 'name' => 's', 'value' => 'do')); - $tag->addContent('I am a button'); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getValue(), 'do'); - $this->assertEqual($tag->getLabel(), 'I am a button'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('add', array('s', 'do')); - $tag->write($encoding); - } -} - -class TestOfTextArea extends UnitTestCase { - - function testDefault() { - $tag = new SimpleTextAreaTag(array('name' => 'a')); - $tag->addContent('Some text'); - $this->assertEqual($tag->getName(), 'a'); - $this->assertEqual($tag->getDefault(), 'Some text'); - } - - function testWrapping() { - $tag = new SimpleTextAreaTag(array('cols' => '10', 'wrap' => 'physical')); - $tag->addContent("Lot's of text that should be wrapped"); - $this->assertEqual( - $tag->getDefault(), - "Lot's of\r\ntext that\r\nshould be\r\nwrapped"); - $tag->setValue("New long text\r\nwith two lines"); - $this->assertEqual( - $tag->getValue(), - "New long\r\ntext\r\nwith two\r\nlines"); - } - - function testWrappingRemovesLeadingcariageReturn() { - $tag = new SimpleTextAreaTag(array('cols' => '20', 'wrap' => 'physical')); - $tag->addContent("\rStuff"); - $this->assertEqual($tag->getDefault(), 'Stuff'); - $tag->setValue("\nNew stuff\n"); - $this->assertEqual($tag->getValue(), "New stuff\r\n"); - } - - function testBreaksAreNewlineAndCarriageReturn() { - $tag = new SimpleTextAreaTag(array('cols' => '10')); - $tag->addContent("Some\nText\rwith\r\nbreaks"); - $this->assertEqual($tag->getValue(), "Some\r\nText\r\nwith\r\nbreaks"); - } -} - -class TestOfCheckbox extends UnitTestCase { - - function testCanSetCheckboxToNamedValueWithBooleanTrue() { - $tag = new SimpleCheckboxTag(array('name' => 'a', 'value' => 'A')); - $this->assertEqual($tag->getValue(), false); - $tag->setValue(true); - $this->assertIdentical($tag->getValue(), 'A'); - } -} - -class TestOfSelection extends UnitTestCase { - - function testEmpty() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $this->assertIdentical($tag->getValue(), ''); - } - - function testSingle() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array()); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSingleDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array('selected' => '')); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSingleMappedDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array('selected' => '', 'value' => 'aaa')); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testStartsWithDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertEqual($tag->getValue(), 'BBB'); - } - - function testSettingOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSettingMappedOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array('value' => 'aaa')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('value' => 'bbb', 'selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array('value' => 'ccc')); - $c->addContent('CCC'); - $tag->addTag($c); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), 'aaa'); - $tag->setValue('ccc'); - $this->assertEqual($tag->getValue(), 'ccc'); - } - - function testSelectionDespiteSpuriousWhitespace() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent(' AAA '); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent(' BBB '); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent(' CCC '); - $tag->addTag($c); - $this->assertEqual($tag->getValue(), ' BBB '); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), ' AAA '); - } - - function testFailToSetIllegalOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertFalse($tag->setValue('Not present')); - $this->assertEqual($tag->getValue(), 'BBB'); - } - - function testNastyOptionValuesThatLookLikeFalse() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array('value' => '1')); - $a->addContent('One'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('value' => '0')); - $b->addContent('Zero'); - $tag->addTag($b); - $this->assertIdentical($tag->getValue(), '1'); - $tag->setValue('Zero'); - $this->assertIdentical($tag->getValue(), '0'); - } - - function testBlankOption() { - $tag = new SimpleSelectionTag(array('name' => 'A')); - $a = new SimpleOptionTag(array()); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('b'); - $tag->addTag($b); - $this->assertIdentical($tag->getValue(), ''); - $tag->setValue('b'); - $this->assertIdentical($tag->getValue(), 'b'); - $tag->setValue(''); - $this->assertIdentical($tag->getValue(), ''); - } - - function testMultipleDefaultWithNoSelections() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertIdentical($tag->getDefault(), array()); - $this->assertIdentical($tag->getValue(), array()); - } - - function testMultipleDefaultWithSelections() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertIdentical($tag->getDefault(), array('AAA', 'BBB')); - $this->assertIdentical($tag->getValue(), array('AAA', 'BBB')); - } - - function testSettingMultiple() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array('selected' => '', 'value' => 'ccc')); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertIdentical($tag->getDefault(), array('AAA', 'ccc')); - $this->assertTrue($tag->setValue(array('BBB', 'ccc'))); - $this->assertIdentical($tag->getValue(), array('BBB', 'ccc')); - $this->assertTrue($tag->setValue(array())); - $this->assertIdentical($tag->getValue(), array()); - } - - function testFailToSetIllegalOptionsInMultiple() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertFalse($tag->setValue(array('CCC'))); - $this->assertTrue($tag->setValue(array('AAA', 'BBB'))); - $this->assertFalse($tag->setValue(array('AAA', 'CCC'))); - } -} - -class TestOfRadioGroup extends UnitTestCase { - - function testEmptyGroup() { - $group = new SimpleRadioGroup(); - $this->assertIdentical($group->getDefault(), false); - $this->assertIdentical($group->getValue(), false); - $this->assertFalse($group->setValue('a')); - } - - function testReadingSingleButtonGroup() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'A'); - $this->assertIdentical($group->getValue(), 'A'); - } - - function testReadingMultipleButtonGroup() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'B'); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testFailToSetUnlistedValue() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag(array('value' => 'z'))); - $this->assertFalse($group->setValue('a')); - $this->assertIdentical($group->getValue(), false); - } - - function testSettingNewValueClearsTheOldOne() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'checked' => ''))); - $this->assertTrue($group->setValue('A')); - $this->assertIdentical($group->getValue(), 'A'); - } - - function testIsIdMatchesAnyWidgetInSet() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A', 'id' => 'i1'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'id' => 'i2'))); - $this->assertFalse($group->isId('i0')); - $this->assertTrue($group->isId('i1')); - $this->assertTrue($group->isId('i2')); - } - - function testIsLabelMatchesAnyWidgetInSet() { - $group = new SimpleRadioGroup(); - $button1 = new SimpleRadioButtonTag(array('value' => 'A')); - $button1->setLabel('one'); - $group->addWidget($button1); - $button2 = new SimpleRadioButtonTag(array('value' => 'B')); - $button2->setLabel('two'); - $group->addWidget($button2); - $this->assertFalse($group->isLabel('three')); - $this->assertTrue($group->isLabel('one')); - $this->assertTrue($group->isLabel('two')); - } -} - -class TestOfTagGroup extends UnitTestCase { - - function testReadingMultipleCheckboxGroup() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'B'); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testReadingMultipleUncheckedItems() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertIdentical($group->getDefault(), false); - $this->assertIdentical($group->getValue(), false); - } - - function testReadingMultipleCheckedItems() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'A', 'checked' => ''))); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), array('A', 'B')); - $this->assertIdentical($group->getValue(), array('A', 'B')); - } - - function testSettingSingleValue() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue('A')); - $this->assertIdentical($group->getValue(), 'A'); - $this->assertTrue($group->setValue('B')); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testSettingMultipleValues() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue(array('A', 'B'))); - $this->assertIdentical($group->getValue(), array('A', 'B')); - } - - function testSettingNoValue() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue(false)); - $this->assertIdentical($group->getValue(), false); - } - - function testIsIdMatchesAnyIdInSet() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('id' => 1, 'value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('id' => 2, 'value' => 'B'))); - $this->assertFalse($group->isId(0)); - $this->assertTrue($group->isId(1)); - $this->assertTrue($group->isId(2)); - } -} - -class TestOfUploadWidget extends UnitTestCase { - - function testValueIsFilePath() { - $upload = new SimpleUploadTag(array('name' => 'a')); - $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); - $this->assertEqual($upload->getValue(), dirname(__FILE__) . '/support/upload_sample.txt'); - } - - function testSubmitsFileContents() { - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('attach', array( - 'a', - 'Sample for testing file upload', - 'upload_sample.txt')); - $upload = new SimpleUploadTag(array('name' => 'a')); - $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); - $upload->write($encoding); - } -} - -class TestOfLabelTag extends UnitTestCase { - - function testLabelShouldHaveAnEndTag() { - $label = new SimpleLabelTag(array()); - $this->assertTrue($label->expectEndTag()); - } - - function testContentIsTextOnly() { - $label = new SimpleLabelTag(array()); - $label->addContent('Here <tag>are</tag> words'); - $this->assertEqual($label->getText(), 'Here are words'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/test_with_parse_error.php b/3rdparty/simpletest/test/test_with_parse_error.php deleted file mode 100755 index 41a5832a5cb9fe5e8589115921527f73b4298a0d..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/test_with_parse_error.php +++ /dev/null @@ -1,8 +0,0 @@ -<?php - // $Id: test_with_parse_error.php 901 2005-01-24 00:32:14Z lastcraft $ - - class TestCaseWithParseError extends UnitTestCase { - wibble - } - -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/unit_tester_test.php b/3rdparty/simpletest/test/unit_tester_test.php deleted file mode 100755 index ce9850f09abd2ae28d0a8e95a67bbe0573e65942..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/unit_tester_test.php +++ /dev/null @@ -1,61 +0,0 @@ -<?php -// $Id: unit_tester_test.php 1748 2008-04-14 01:50:41Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); - -class ReferenceForTesting { -} - -class TestOfUnitTester extends UnitTestCase { - - function testAssertTrueReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertTrue(true)); - } - - function testAssertFalseReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertFalse(false)); - } - - function testAssertEqualReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertEqual(5, 5)); - } - - function testAssertIdenticalReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertIdentical(5, 5)); - } - - function testCoreAssertionsDoNotThrowErrors() { - $this->assertIsA($this, 'UnitTestCase'); - $this->assertNotA($this, 'WebTestCase'); - } - - function testReferenceAssertionOnObjects() { - $a = new ReferenceForTesting(); - $b = $a; - $this->assertSame($a, $b); - } - - function testReferenceAssertionOnScalars() { - $a = 25; - $b = &$a; - $this->assertReference($a, $b); - } - - function testCloneOnObjects() { - $a = new ReferenceForTesting(); - $b = new ReferenceForTesting(); - $this->assertClone($a, $b); - } - - function TODO_testCloneOnScalars() { - $a = 25; - $b = 25; - $this->assertClone($a, $b); - } - - function testCopyOnScalars() { - $a = 25; - $b = 25; - $this->assertCopy($a, $b); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/unit_tests.php b/3rdparty/simpletest/test/unit_tests.php deleted file mode 100755 index 9e621293f9e1640e0006c765c4ff0c2709aa7536..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/unit_tests.php +++ /dev/null @@ -1,49 +0,0 @@ -<?php -// $Id: unit_tests.php 1986 2010-04-02 10:02:42Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../unit_tester.php'); -require_once(dirname(__FILE__) . '/../shell_tester.php'); -require_once(dirname(__FILE__) . '/../mock_objects.php'); -require_once(dirname(__FILE__) . '/../web_tester.php'); -require_once(dirname(__FILE__) . '/../extensions/pear_test_case.php'); - -class UnitTests extends TestSuite { - function UnitTests() { - $this->TestSuite('Unit tests'); - $path = dirname(__FILE__); - $this->addFile($path . '/errors_test.php'); - $this->addFile($path . '/exceptions_test.php'); - $this->addFile($path . '/arguments_test.php'); - $this->addFile($path . '/autorun_test.php'); - $this->addFile($path . '/compatibility_test.php'); - $this->addFile($path . '/simpletest_test.php'); - $this->addFile($path . '/dumper_test.php'); - $this->addFile($path . '/expectation_test.php'); - $this->addFile($path . '/unit_tester_test.php'); - $this->addFile($path . '/reflection_php5_test.php'); - $this->addFile($path . '/mock_objects_test.php'); - $this->addFile($path . '/interfaces_test.php'); - $this->addFile($path . '/collector_test.php'); - $this->addFile($path . '/recorder_test.php'); - $this->addFile($path . '/adapter_test.php'); - $this->addFile($path . '/socket_test.php'); - $this->addFile($path . '/encoding_test.php'); - $this->addFile($path . '/url_test.php'); - $this->addFile($path . '/cookies_test.php'); - $this->addFile($path . '/http_test.php'); - $this->addFile($path . '/authentication_test.php'); - $this->addFile($path . '/user_agent_test.php'); - $this->addFile($path . '/php_parser_test.php'); - $this->addFile($path . '/parsing_test.php'); - $this->addFile($path . '/tag_test.php'); - $this->addFile($path . '/form_test.php'); - $this->addFile($path . '/page_test.php'); - $this->addFile($path . '/frames_test.php'); - $this->addFile($path . '/browser_test.php'); - $this->addFile($path . '/web_tester_test.php'); - $this->addFile($path . '/shell_tester_test.php'); - $this->addFile($path . '/xml_test.php'); - $this->addFile($path . '/../extensions/testdox/test.php'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/url_test.php b/3rdparty/simpletest/test/url_test.php deleted file mode 100755 index 80119afbdde88d7aa78fa654f9c5dc0d7b0e7513..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/url_test.php +++ /dev/null @@ -1,515 +0,0 @@ -<?php -// $Id: url_test.php 1998 2010-07-27 09:55:55Z pp11 $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../url.php'); - -class TestOfUrl extends UnitTestCase { - - function testDefaultUrl() { - $url = new SimpleUrl(''); - $this->assertEqual($url->getScheme(), ''); - $this->assertEqual($url->getHost(), ''); - $this->assertEqual($url->getScheme('http'), 'http'); - $this->assertEqual($url->getHost('localhost'), 'localhost'); - $this->assertEqual($url->getPath(), ''); - } - - function testBasicParsing() { - $url = new SimpleUrl('https://www.lastcraft.com/test/'); - $this->assertEqual($url->getScheme(), 'https'); - $this->assertEqual($url->getHost(), 'www.lastcraft.com'); - $this->assertEqual($url->getPath(), '/test/'); - } - - function testRelativeUrls() { - $url = new SimpleUrl('../somewhere.php'); - $this->assertEqual($url->getScheme(), false); - $this->assertEqual($url->getHost(), false); - $this->assertEqual($url->getPath(), '../somewhere.php'); - } - - function testParseBareParameter() { - $url = new SimpleUrl('?a'); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); - } - - function testParseEmptyParameter() { - $url = new SimpleUrl('?a='); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a='); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); - } - - function testParseParameterPair() { - $url = new SimpleUrl('?a=A'); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a=A'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&x=X'); - } - - function testParseMultipleParameters() { - $url = new SimpleUrl('?a=A&b=B'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&x=X'); - } - - function testParsingParameterMixture() { - $url = new SimpleUrl('?a=A&b=&c'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c=&x=X'); - } - - function testAddParametersFromScratch() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', 'A'); - $this->assertEqual($url->getEncodedRequest(), '?a=A'); - $url->addRequestParameter('b', 'B'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); - $url->addRequestParameter('a', 'aaa'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&a=aaa'); - } - - function testClearingParameters() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', 'A'); - $url->clearRequest(); - $this->assertIdentical($url->getEncodedRequest(), ''); - } - - function testEncodingParameters() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', '?!"\'#~@[]{}:;<>,./|$%^&*()_+-='); - $this->assertIdentical( - $request = $url->getEncodedRequest(), - '?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%24%25%5E%26%2A%28%29_%2B-%3D'); - } - - function testDecodingParameters() { - $url = new SimpleUrl('?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%24%25%5E%26%2A%28%29_%2B-%3D'); - $this->assertEqual( - $url->getEncodedRequest(), - '?a=' . urlencode('?!"\'#~@[]{}:;<>,./|$%^&*()_+-=')); - } - - function testUrlInQueryDoesNotConfuseParsing() { - $url = new SimpleUrl('wibble/login.php?url=http://www.google.com/moo/'); - $this->assertFalse($url->getScheme()); - $this->assertFalse($url->getHost()); - $this->assertEqual($url->getPath(), 'wibble/login.php'); - $this->assertEqual($url->getEncodedRequest(), '?url=http://www.google.com/moo/'); - } - - function testSettingCordinates() { - $url = new SimpleUrl(''); - $url->setCoordinates('32', '45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - $this->assertEqual($url->getEncodedRequest(), ''); - } - - function testParseCordinates() { - $url = new SimpleUrl('?32,45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - } - - function testClearingCordinates() { - $url = new SimpleUrl('?32,45'); - $url->setCoordinates(); - $this->assertIdentical($url->getX(), false); - $this->assertIdentical($url->getY(), false); - } - - function testParsingParameterCordinateMixture() { - $url = new SimpleUrl('?a=A&b=&c?32,45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); - } - - function testParsingParameterWithBadCordinates() { - $url = new SimpleUrl('?a=A&b=&c?32'); - $this->assertIdentical($url->getX(), false); - $this->assertIdentical($url->getY(), false); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c?32'); - } - - function testPageSplitting() { - $url = new SimpleUrl('./here/../there/somewhere.php'); - $this->assertEqual($url->getPath(), './here/../there/somewhere.php'); - $this->assertEqual($url->getPage(), 'somewhere.php'); - $this->assertEqual($url->getBasePath(), './here/../there/'); - } - - function testAbsolutePathPageSplitting() { - $url = new SimpleUrl("http://host.com/here/there/somewhere.php"); - $this->assertEqual($url->getPath(), "/here/there/somewhere.php"); - $this->assertEqual($url->getPage(), "somewhere.php"); - $this->assertEqual($url->getBasePath(), "/here/there/"); - } - - function testSplittingUrlWithNoPageGivesEmptyPage() { - $url = new SimpleUrl('/here/there/'); - $this->assertEqual($url->getPath(), '/here/there/'); - $this->assertEqual($url->getPage(), ''); - $this->assertEqual($url->getBasePath(), '/here/there/'); - } - - function testPathNormalisation() { - $url = new SimpleUrl(); - $this->assertEqual( - $url->normalisePath('https://host.com/I/am/here/../there/somewhere.php'), - 'https://host.com/I/am/there/somewhere.php'); - } - - // regression test for #1535407 - function testPathNormalisationWithSinglePeriod() { - $url = new SimpleUrl(); - $this->assertEqual( - $url->normalisePath('https://host.com/I/am/here/./../there/somewhere.php'), - 'https://host.com/I/am/there/somewhere.php'); - } - - // regression test for #1852413 - function testHostnameExtractedFromUContainingAtSign() { - $url = new SimpleUrl("http://localhost/name@example.com"); - $this->assertEqual($url->getScheme(), "http"); - $this->assertEqual($url->getUsername(), ""); - $this->assertEqual($url->getPassword(), ""); - $this->assertEqual($url->getHost(), "localhost"); - $this->assertEqual($url->getPath(), "/name@example.com"); - } - - function testHostnameInLocalhost() { - $url = new SimpleUrl("http://localhost/name/example.com"); - $this->assertEqual($url->getScheme(), "http"); - $this->assertEqual($url->getUsername(), ""); - $this->assertEqual($url->getPassword(), ""); - $this->assertEqual($url->getHost(), "localhost"); - $this->assertEqual($url->getPath(), "/name/example.com"); - } - - function testUsernameAndPasswordAreUrlDecoded() { - $url = new SimpleUrl('http://' . urlencode('test@test') . - ':' . urlencode('$!�@*&%') . '@www.lastcraft.com'); - $this->assertEqual($url->getUsername(), 'test@test'); - $this->assertEqual($url->getPassword(), '$!�@*&%'); - } - - function testBlitz() { - $this->assertUrl( - "https://username:password@www.somewhere.com:243/this/that/here.php?a=1&b=2#anchor", - array("https", "username", "password", "www.somewhere.com", 243, "/this/that/here.php", "com", "?a=1&b=2", "anchor"), - array("a" => "1", "b" => "2")); - $this->assertUrl( - "username:password@www.somewhere.com/this/that/here.php?a=1", - array(false, "username", "password", "www.somewhere.com", false, "/this/that/here.php", "com", "?a=1", false), - array("a" => "1")); - $this->assertUrl( - "username:password@somewhere.com:243?1,2", - array(false, "username", "password", "somewhere.com", 243, "/", "com", "", false), - array(), - array(1, 2)); - $this->assertUrl( - "https://www.somewhere.com", - array("https", false, false, "www.somewhere.com", false, "/", "com", "", false)); - $this->assertUrl( - "username@www.somewhere.com:243#anchor", - array(false, "username", false, "www.somewhere.com", 243, "/", "com", "", "anchor")); - $this->assertUrl( - "/this/that/here.php?a=1&b=2?3,4", - array(false, false, false, false, false, "/this/that/here.php", false, "?a=1&b=2", false), - array("a" => "1", "b" => "2"), - array(3, 4)); - $this->assertUrl( - "username@/here.php?a=1&b=2", - array(false, "username", false, false, false, "/here.php", false, "?a=1&b=2", false), - array("a" => "1", "b" => "2")); - } - - function testAmbiguousHosts() { - $this->assertUrl( - "tigger", - array(false, false, false, false, false, "tigger", false, "", false)); - $this->assertUrl( - "/tigger", - array(false, false, false, false, false, "/tigger", false, "", false)); - $this->assertUrl( - "//tigger", - array(false, false, false, "tigger", false, "/", false, "", false)); - $this->assertUrl( - "//tigger/", - array(false, false, false, "tigger", false, "/", false, "", false)); - $this->assertUrl( - "tigger.com", - array(false, false, false, "tigger.com", false, "/", "com", "", false)); - $this->assertUrl( - "me.net/tigger", - array(false, false, false, "me.net", false, "/tigger", "net", "", false)); - } - - function testAsString() { - $this->assertPreserved('https://www.here.com'); - $this->assertPreserved('http://me:secret@www.here.com'); - $this->assertPreserved('http://here/there'); - $this->assertPreserved('http://here/there?a=A&b=B'); - $this->assertPreserved('http://here/there?a=1&a=2'); - $this->assertPreserved('http://here/there?a=1&a=2?9,8'); - $this->assertPreserved('http://host?a=1&a=2'); - $this->assertPreserved('http://host#stuff'); - $this->assertPreserved('http://me:secret@www.here.com/a/b/c/here.html?a=A?7,6'); - $this->assertPreserved('http://www.here.com/?a=A__b=B'); - $this->assertPreserved('http://www.example.com:8080/'); - } - - function testUrlWithTwoSlashesInPath() { - $url = new SimpleUrl('/article/categoryedit/insert//'); - $this->assertEqual($url->getPath(), '/article/categoryedit/insert//'); - } - - function testUrlWithRequestKeyEncoded() { - $url = new SimpleUrl('/?foo%5B1%5D=bar'); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B1%5D=bar'); - $url->addRequestParameter('a[1]', 'b[]'); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B1%5D=bar&a%5B1%5D=b%5B%5D'); - - $url = new SimpleUrl('/'); - $url->addRequestParameter('a[1]', 'b[]'); - $this->assertEqual($url->getEncodedRequest(), '?a%5B1%5D=b%5B%5D'); - } - - function testUrlWithRequestKeyEncodedAndParamNamLookingLikePair() { - $url = new SimpleUrl('/'); - $url->addRequestParameter('foo[]=bar', ''); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B%5D%3Dbar='); - $url = new SimpleUrl('/?foo%5B%5D%3Dbar='); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B%5D%3Dbar='); - } - - function assertUrl($raw, $parts, $params = false, $coords = false) { - if (! is_array($params)) { - $params = array(); - } - $url = new SimpleUrl($raw); - $this->assertIdentical($url->getScheme(), $parts[0], "[$raw] scheme -> %s"); - $this->assertIdentical($url->getUsername(), $parts[1], "[$raw] username -> %s"); - $this->assertIdentical($url->getPassword(), $parts[2], "[$raw] password -> %s"); - $this->assertIdentical($url->getHost(), $parts[3], "[$raw] host -> %s"); - $this->assertIdentical($url->getPort(), $parts[4], "[$raw] port -> %s"); - $this->assertIdentical($url->getPath(), $parts[5], "[$raw] path -> %s"); - $this->assertIdentical($url->getTld(), $parts[6], "[$raw] tld -> %s"); - $this->assertIdentical($url->getEncodedRequest(), $parts[7], "[$raw] encoded -> %s"); - $this->assertIdentical($url->getFragment(), $parts[8], "[$raw] fragment -> %s"); - if ($coords) { - $this->assertIdentical($url->getX(), $coords[0], "[$raw] x -> %s"); - $this->assertIdentical($url->getY(), $coords[1], "[$raw] y -> %s"); - } - } - - function assertPreserved($string) { - $url = new SimpleUrl($string); - $this->assertEqual($url->asString(), $string); - } -} - -class TestOfAbsoluteUrls extends UnitTestCase { - - function testDirectoriesAfterFilename() { - $string = '../../index.php/foo/bar'; - $url = new SimpleUrl($string); - $this->assertEqual($url->asString(), $string); - - $absolute = $url->makeAbsolute('http://www.domain.com/some/path/'); - $this->assertEqual($absolute->asString(), 'http://www.domain.com/index.php/foo/bar'); - } - - function testMakingAbsolute() { - $url = new SimpleUrl('../there/somewhere.php'); - $this->assertEqual($url->getPath(), '../there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com:1234/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'https'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPort(), 1234); - $this->assertEqual($absolute->getPath(), '/I/am/there/somewhere.php'); - } - - function testMakingAnEmptyUrlAbsolute() { - $url = new SimpleUrl(''); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/page.html'); - } - - function testMakingAnEmptyUrlAbsoluteWithMissingPageName() { - $url = new SimpleUrl(''); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - } - - function testMakingAShortQueryUrlAbsolute() { - $url = new SimpleUrl('?a#b'); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - $this->assertEqual($absolute->getEncodedRequest(), '?a'); - $this->assertEqual($absolute->getFragment(), 'b'); - } - - function testMakingADirectoryUrlAbsolute() { - $url = new SimpleUrl('hello/'); - $this->assertEqual($url->getPath(), 'hello/'); - $this->assertEqual($url->getBasePath(), 'hello/'); - $this->assertEqual($url->getPage(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/I/am/here/hello/'); - } - - function testMakingARootUrlAbsolute() { - $url = new SimpleUrl('/'); - $this->assertEqual($url->getPath(), '/'); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/'); - } - - function testMakingARootPageUrlAbsolute() { - $url = new SimpleUrl('/here.html'); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/here.html'); - } - - function testCarryAuthenticationFromRootPage() { - $url = new SimpleUrl('here.html'); - $absolute = $url->makeAbsolute('http://test:secret@host.com/'); - $this->assertEqual($absolute->getPath(), '/here.html'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - } - - function testMakingCoordinateUrlAbsolute() { - $url = new SimpleUrl('?1,2'); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - $this->assertEqual($absolute->getX(), 1); - $this->assertEqual($absolute->getY(), 2); - } - - function testMakingAbsoluteAppendedPath() { - $url = new SimpleUrl('./there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com/here/'); - $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); - } - - function testMakingAbsoluteBadlyFormedAppendedPath() { - $url = new SimpleUrl('there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com/here/'); - $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); - } - - function testMakingAbsoluteHasNoEffectWhenAlreadyAbsolute() { - $url = new SimpleUrl('https://test:secret@www.lastcraft.com:321/stuff/?a=1#f'); - $absolute = $url->makeAbsolute('http://host.com/here/'); - $this->assertEqual($absolute->getScheme(), 'https'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertEqual($absolute->getPort(), 321); - $this->assertEqual($absolute->getPath(), '/stuff/'); - $this->assertEqual($absolute->getEncodedRequest(), '?a=1'); - $this->assertEqual($absolute->getFragment(), 'f'); - } - - function testMakingAbsoluteCarriesAuthenticationWhenAlreadyAbsolute() { - $url = new SimpleUrl('https://www.lastcraft.com'); - $absolute = $url->makeAbsolute('http://test:secret@host.com/here/'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - } - - function testMakingHostOnlyAbsoluteDoesNotCarryAnyOtherInformation() { - $url = new SimpleUrl('http://www.lastcraft.com'); - $absolute = $url->makeAbsolute('https://host.com:81/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertIdentical($absolute->getPort(), false); - $this->assertEqual($absolute->getPath(), '/'); - } -} - -class TestOfFrameUrl extends UnitTestCase { - - function testTargetAttachment() { - $url = new SimpleUrl('http://www.site.com/home.html'); - $this->assertIdentical($url->getTarget(), false); - $url->setTarget('A frame'); - $this->assertIdentical($url->getTarget(), 'A frame'); - } -} - -/** - * @note Based off of http://www.mozilla.org/quality/networking/testing/filetests.html - */ -class TestOfFileUrl extends UnitTestCase { - - function testMinimalUrl() { - $url = new SimpleUrl('file:///'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/'); - } - - function testUnixUrl() { - $url = new SimpleUrl('file:///fileInRoot'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/fileInRoot'); - } - - function testDOSVolumeUrl() { - $url = new SimpleUrl('file:///C:/config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSVolumePromotion() { - $url = new SimpleUrl('file://C:/config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSBackslashes() { - $url = new SimpleUrl('file:///C:\config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSDirnameAfterFile() { - $url = new SimpleUrl('file://C:\config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - -} - -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/user_agent_test.php b/3rdparty/simpletest/test/user_agent_test.php deleted file mode 100755 index 030abeb257d84bb30204a88f0a7c54809803622e..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/user_agent_test.php +++ /dev/null @@ -1,348 +0,0 @@ -<?php -// $Id: user_agent_test.php 1788 2008-04-27 11:01:59Z pp11 $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../user_agent.php'); -require_once(dirname(__FILE__) . '/../authentication.php'); -require_once(dirname(__FILE__) . '/../http.php'); -require_once(dirname(__FILE__) . '/../encoding.php'); -Mock::generate('SimpleHttpRequest'); -Mock::generate('SimpleHttpResponse'); -Mock::generate('SimpleHttpHeaders'); -Mock::generatePartial('SimpleUserAgent', 'MockRequestUserAgent', array('createHttpRequest')); - -class TestOfFetchingUrlParameters extends UnitTestCase { - - function setUp() { - $this->headers = new MockSimpleHttpHeaders(); - $this->response = new MockSimpleHttpResponse(); - $this->response->setReturnValue('isError', false); - $this->response->returns('getHeaders', new MockSimpleHttpHeaders()); - $this->request = new MockSimpleHttpRequest(); - $this->request->returns('fetch', $this->response); - } - - function testGetRequestWithoutIncidentGivesNoErrors() { - $url = new SimpleUrl('http://test:secret@this.com/page.html'); - $url->addRequestParameters(array('a' => 'A', 'b' => 'B')); - - $agent = new MockRequestUserAgent(); - $agent->returns('createHttpRequest', $this->request); - $agent->__construct(); - - $response = $agent->fetchResponse( - new SimpleUrl('http://test:secret@this.com/page.html'), - new SimpleGetEncoding(array('a' => 'A', 'b' => 'B'))); - $this->assertFalse($response->isError()); - } -} - -class TestOfAdditionalHeaders extends UnitTestCase { - - function testAdditionalHeaderAddedToRequest() { - $response = new MockSimpleHttpResponse(); - $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); - - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - $request->expectOnce( - 'addHeaderLine', - array('User-Agent: SimpleTest')); - - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - $agent->addHeader('User-Agent: SimpleTest'); - $response = $agent->fetchResponse(new SimpleUrl('http://this.host/'), new SimpleGetEncoding()); - } -} - -class TestOfBrowserCookies extends UnitTestCase { - - private function createStandardResponse() { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue("isError", false); - $response->setReturnValue("getContent", "stuff"); - $response->setReturnReference("getHeaders", new MockSimpleHttpHeaders()); - return $response; - } - - private function createCookieSite($header_lines) { - $headers = new SimpleHttpHeaders($header_lines); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue("isError", false); - $response->setReturnReference("getHeaders", $headers); - $response->setReturnValue("getContent", "stuff"); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference("fetch", $response); - return $request; - } - - private function createMockedRequestUserAgent(&$request) { - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - return $agent; - } - - function testCookieJarIsSentToRequest() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $this->createStandardResponse()); - $request->expectOnce('readCookiesFromJar', array($jar, '*')); - - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - } - - function testNoCookieJarIsSentToRequestWhenCookiesAreDisabled() { - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $this->createStandardResponse()); - $request->expectNever('readCookiesFromJar'); - - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->ignoreCookies(); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - } - - function testReadingNewCookie() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); - } - - function testIgnoringNewCookieWhenCookiesDisabled() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->ignoreCookies(); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertIdentical($agent->getCookieValue("this.com", "this/path/", "a"), false); - } - - function testOverwriteCookieThatAlreadyExists() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); - } - - function testClearCookieBySettingExpiry() { - $request = $this->createCookieSite('Set-cookie: a=b'); - $agent = $this->createMockedRequestUserAgent($request); - - $agent->setCookie("a", "A", "this/path/", "Wed, 25-Dec-02 04:24:21 GMT"); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - "b"); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - false); - } - - function testAgeingAndClearing() { - $request = $this->createCookieSite('Set-cookie: a=A; expires=Wed, 25-Dec-02 04:24:21 GMT; path=/this/path'); - $agent = $this->createMockedRequestUserAgent($request); - - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - "A"); - $agent->ageCookies(2); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - false); - } - - function testReadingIncomingAndSettingNewCookies() { - $request = $this->createCookieSite('Set-cookie: a=AAA'); - $agent = $this->createMockedRequestUserAgent($request); - - $this->assertNull($agent->getBaseCookieValue("a", false)); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $agent->setCookie("b", "BBB", "this.com", "this/path/"); - $this->assertEqual( - $agent->getBaseCookieValue("a", new SimpleUrl('http://this.com/this/path/page.html')), - "AAA"); - $this->assertEqual( - $agent->getBaseCookieValue("b", new SimpleUrl('http://this.com/this/path/page.html')), - "BBB"); - } -} - -class TestOfHttpRedirects extends UnitTestCase { - - function createRedirect($content, $redirect) { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('isRedirect', (boolean)$redirect); - $headers->setReturnValue('getLocation', $redirect); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnReference('getHeaders', $headers); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - return $request; - } - - function testDisabledRedirects() { - $agent = new MockRequestUserAgent(); - $agent->returns( - 'createHttpRequest', - $this->createRedirect('stuff', 'there.html')); - $agent->expectOnce('createHttpRequest'); - $agent->__construct(); - $agent->setMaximumRedirects(0); - $response = $agent->fetchResponse(new SimpleUrl('here.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'stuff'); - } - - function testSingleRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - - $agent->setMaximumRedirects(1); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'second'); - } - - function testDoubleRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->returnsAt( - 2, - 'createHttpRequest', - $this->createRedirect('third', 'four.html')); - $agent->expectCallCount('createHttpRequest', 3); - $agent->__construct(); - - $agent->setMaximumRedirects(2); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'third'); - } - - function testSuccessAfterRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', false)); - $agent->returnsAt( - 2, - 'createHttpRequest', - $this->createRedirect('third', 'four.html')); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - - $agent->setMaximumRedirects(2); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'second'); - } - - function testRedirectChangesPostToGet() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->expectAt(0, 'createHttpRequest', array('*', new IsAExpectation('SimplePostEncoding'))); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->expectAt(1, 'createHttpRequest', array('*', new IsAExpectation('SimpleGetEncoding'))); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - $agent->setMaximumRedirects(1); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimplePostEncoding()); - } -} - -class TestOfBadHosts extends UnitTestCase { - - private function createSimulatedBadHost() { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('isError', true); - $response->setReturnValue('getError', 'Bad socket'); - $response->setReturnValue('getContent', false); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - return $request; - } - - function testUntestedHost() { - $request = $this->createSimulatedBadHost(); - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - $response = $agent->fetchResponse( - new SimpleUrl('http://this.host/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - } -} - -class TestOfAuthorisation extends UnitTestCase { - - function testAuthenticateHeaderAdded() { - $response = new MockSimpleHttpResponse(); - $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); - - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $response); - $request->expectOnce( - 'addHeaderLine', - array('Authorization: Basic ' . base64_encode('test:secret'))); - - $agent = new MockRequestUserAgent(); - $agent->returns('createHttpRequest', $request); - $agent->__construct(); - $response = $agent->fetchResponse( - new SimpleUrl('http://test:secret@this.host'), - new SimpleGetEncoding()); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/visual_test.php b/3rdparty/simpletest/test/visual_test.php deleted file mode 100755 index 6b9d085d67f9bd2939e56b98695034462a152998..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/visual_test.php +++ /dev/null @@ -1,495 +0,0 @@ -<?php -// $Id: visual_test.php 1884 2009-07-01 16:30:40Z lastcraft $ - -// NOTE: -// Some of these tests are designed to fail! Do not be alarmed. -// ---------------- - -// The following tests are a bit hacky. Whilst Kent Beck tried to -// build a unit tester with a unit tester, I am not that brave. -// Instead I have just hacked together odd test scripts until -// I have enough of a tester to procede more formally. -// -// The proper tests start in all_tests.php -require_once('../unit_tester.php'); -require_once('../shell_tester.php'); -require_once('../mock_objects.php'); -require_once('../reporter.php'); -require_once('../xml.php'); - -class TestDisplayClass { - private $a; - - function TestDisplayClass($a) { - $this->a = $a; - } -} - -class PassingUnitTestCaseOutput extends UnitTestCase { - - function testOfResults() { - $this->pass('Pass'); - } - - function testTrue() { - $this->assertTrue(true); - } - - function testFalse() { - $this->assertFalse(false); - } - - function testExpectation() { - $expectation = &new EqualExpectation(25, 'My expectation message: %s'); - $this->assert($expectation, 25, 'My assert message : %s'); - } - - function testNull() { - $this->assertNull(null, "%s -> Pass"); - $this->assertNotNull(false, "%s -> Pass"); - } - - function testType() { - $this->assertIsA("hello", "string", "%s -> Pass"); - $this->assertIsA($this, "PassingUnitTestCaseOutput", "%s -> Pass"); - $this->assertIsA($this, "UnitTestCase", "%s -> Pass"); - } - - function testTypeEquality() { - $this->assertEqual("0", 0, "%s -> Pass"); - } - - function testNullEquality() { - $this->assertNotEqual(null, 1, "%s -> Pass"); - $this->assertNotEqual(1, null, "%s -> Pass"); - } - - function testIntegerEquality() { - $this->assertNotEqual(1, 2, "%s -> Pass"); - } - - function testStringEquality() { - $this->assertEqual("a", "a", "%s -> Pass"); - $this->assertNotEqual("aa", "ab", "%s -> Pass"); - } - - function testHashEquality() { - $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> Pass"); - } - - function testWithin() { - $this->assertWithinMargin(5, 5.4, 0.5, "%s -> Pass"); - } - - function testOutside() { - $this->assertOutsideMargin(5, 5.6, 0.5, "%s -> Pass"); - } - - function testStringIdentity() { - $a = "fred"; - $b = $a; - $this->assertIdentical($a, $b, "%s -> Pass"); - } - - function testTypeIdentity() { - $a = "0"; - $b = 0; - $this->assertNotIdentical($a, $b, "%s -> Pass"); - } - - function testNullIdentity() { - $this->assertNotIdentical(null, 1, "%s -> Pass"); - $this->assertNotIdentical(1, null, "%s -> Pass"); - } - - function testHashIdentity() { - } - - function testObjectEquality() { - $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Pass"); - $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Pass"); - } - - function testObjectIndentity() { - $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Pass"); - $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Pass"); - } - - function testReference() { - $a = "fred"; - $b = &$a; - $this->assertReference($a, $b, "%s -> Pass"); - } - - function testCloneOnDifferentObjects() { - $a = "fred"; - $b = $a; - $c = "Hello"; - $this->assertClone($a, $b, "%s -> Pass"); - } - - function testPatterns() { - $this->assertPattern('/hello/i', "Hello there", "%s -> Pass"); - $this->assertNoPattern('/hello/', "Hello there", "%s -> Pass"); - } - - function testLongStrings() { - $text = ""; - for ($i = 0; $i < 10; $i++) { - $text .= "0123456789"; - } - $this->assertEqual($text, $text); - } -} - -class FailingUnitTestCaseOutput extends UnitTestCase { - - function testOfResults() { - $this->fail('Fail'); // Fail. - } - - function testTrue() { - $this->assertTrue(false); // Fail. - } - - function testFalse() { - $this->assertFalse(true); // Fail. - } - - function testExpectation() { - $expectation = &new EqualExpectation(25, 'My expectation message: %s'); - $this->assert($expectation, 24, 'My assert message : %s'); // Fail. - } - - function testNull() { - $this->assertNull(false, "%s -> Fail"); // Fail. - $this->assertNotNull(null, "%s -> Fail"); // Fail. - } - - function testType() { - $this->assertIsA(14, "string", "%s -> Fail"); // Fail. - $this->assertIsA(14, "TestOfUnitTestCaseOutput", "%s -> Fail"); // Fail. - $this->assertIsA($this, "TestReporter", "%s -> Fail"); // Fail. - } - - function testTypeEquality() { - $this->assertNotEqual("0", 0, "%s -> Fail"); // Fail. - } - - function testNullEquality() { - $this->assertEqual(null, 1, "%s -> Fail"); // Fail. - $this->assertEqual(1, null, "%s -> Fail"); // Fail. - } - - function testIntegerEquality() { - $this->assertEqual(1, 2, "%s -> Fail"); // Fail. - } - - function testStringEquality() { - $this->assertNotEqual("a", "a", "%s -> Fail"); // Fail. - $this->assertEqual("aa", "ab", "%s -> Fail"); // Fail. - } - - function testHashEquality() { - $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "Z"), "%s -> Fail"); - } - - function testWithin() { - $this->assertWithinMargin(5, 5.6, 0.5, "%s -> Fail"); // Fail. - } - - function testOutside() { - $this->assertOutsideMargin(5, 5.4, 0.5, "%s -> Fail"); // Fail. - } - - function testStringIdentity() { - $a = "fred"; - $b = $a; - $this->assertNotIdentical($a, $b, "%s -> Fail"); // Fail. - } - - function testTypeIdentity() { - $a = "0"; - $b = 0; - $this->assertIdentical($a, $b, "%s -> Fail"); // Fail. - } - - function testNullIdentity() { - $this->assertIdentical(null, 1, "%s -> Fail"); // Fail. - $this->assertIdentical(1, null, "%s -> Fail"); // Fail. - } - - function testHashIdentity() { - $this->assertIdentical(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> fail"); // Fail. - } - - function testObjectEquality() { - $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Fail"); // Fail. - $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Fail"); // Fail. - } - - function testObjectIndentity() { - $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Fail"); // Fail. - $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Fail"); // Fail. - } - - function testReference() { - $a = "fred"; - $b = &$a; - $this->assertClone($a, $b, "%s -> Fail"); // Fail. - } - - function testCloneOnDifferentObjects() { - $a = "fred"; - $b = $a; - $c = "Hello"; - $this->assertClone($a, $c, "%s -> Fail"); // Fail. - } - - function testPatterns() { - $this->assertPattern('/hello/', "Hello there", "%s -> Fail"); // Fail. - $this->assertNoPattern('/hello/i', "Hello there", "%s -> Fail"); // Fail. - } - - function testLongStrings() { - $text = ""; - for ($i = 0; $i < 10; $i++) { - $text .= "0123456789"; - } - $this->assertEqual($text . $text, $text . "a" . $text); // Fail. - } -} - -class Dummy { - function Dummy() { - } - - function a() { - } -} -Mock::generate('Dummy'); - -class TestOfMockObjectsOutput extends UnitTestCase { - - function testCallCounts() { - $dummy = &new MockDummy(); - $dummy->expectCallCount('a', 1, 'My message: %s'); - $dummy->a(); - $dummy->a(); - } - - function testMinimumCallCounts() { - $dummy = &new MockDummy(); - $dummy->expectMinimumCallCount('a', 2, 'My message: %s'); - $dummy->a(); - $dummy->a(); - } - - function testEmptyMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array()); - $dummy->a(); - $dummy->a(null); // Fail. - } - - function testEmptyMatchingWithCustomMessage() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(), 'My expectation message: %s'); - $dummy->a(); - $dummy->a(null); // Fail. - } - - function testNullMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(null)); - $dummy->a(null); - $dummy->a(); // Fail. - } - - function testBooleanMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(true, false)); - $dummy->a(true, false); - $dummy->a(true, true); // Fail. - } - - function testIntegerMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(32, 33)); - $dummy->a(32, 33); - $dummy->a(32, 34); // Fail. - } - - function testFloatMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(3.2, 3.3)); - $dummy->a(3.2, 3.3); - $dummy->a(3.2, 3.4); // Fail. - } - - function testStringMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array('32', '33')); - $dummy->a('32', '33'); - $dummy->a('32', '34'); // Fail. - } - - function testEmptyMatchingWithCustomExpectationMessage() { - $dummy = &new MockDummy(); - $dummy->expect( - 'a', - array(new EqualExpectation('A', 'My part expectation message: %s')), - 'My expectation message: %s'); - $dummy->a('A'); - $dummy->a('B'); // Fail. - } - - function testArrayMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(array(32), array(33))); - $dummy->a(array(32), array(33)); - $dummy->a(array(32), array('33')); // Fail. - } - - function testObjectMatching() { - $a = new Dummy(); - $a->a = 'a'; - $b = new Dummy(); - $b->b = 'b'; - $dummy = &new MockDummy(); - $dummy->expect('a', array($a, $b)); - $dummy->a($a, $b); - $dummy->a($a, $a); // Fail. - } - - function testBigList() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(false, 0, 1, 1.0)); - $dummy->a(false, 0, 1, 1.0); - $dummy->a(true, false, 2, 2.0); // Fail. - } -} - -class TestOfPastBugs extends UnitTestCase { - - function testMixedTypes() { - $this->assertEqual(array(), null, "%s -> Pass"); - $this->assertIdentical(array(), null, "%s -> Fail"); // Fail. - } - - function testMockWildcards() { - $dummy = &new MockDummy(); - $dummy->expect('a', array('*', array(33))); - $dummy->a(array(32), array(33)); - $dummy->a(array(32), array('33')); // Fail. - } -} - -class TestOfVisualShell extends ShellTestCase { - - function testDump() { - $this->execute('ls'); - $this->dumpOutput(); - $this->execute('dir'); - $this->dumpOutput(); - } - - function testDumpOfList() { - $this->execute('ls'); - $this->dump($this->getOutputAsList()); - } -} - -class PassesAsWellReporter extends HtmlReporter { - - protected function getCss() { - return parent::getCss() . ' .pass { color: darkgreen; }'; - } - - function paintPass($message) { - parent::paintPass($message); - print "<span class=\"pass\">Pass</span>: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . htmlentities($message) . "<br />\n"; - } - - function paintSignal($type, &$payload) { - print "<span class=\"fail\">$type</span>: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . htmlentities(serialize($payload)) . "<br />\n"; - } -} - -class TestOfSkippingNoMatterWhat extends UnitTestCase { - function skip() { - $this->skipIf(true, 'Always skipped -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestOfSkippingOrElse extends UnitTestCase { - function skip() { - $this->skipUnless(false, 'Always skipped -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestOfSkippingTwiceOver extends UnitTestCase { - function skip() { - $this->skipIf(true, 'First reason -> %s'); - $this->skipIf(true, 'Second reason -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestThatShouldNotBeSkipped extends UnitTestCase { - function skip() { - $this->skipIf(false); - $this->skipUnless(true); - } - - function testFail() { - $this->fail('We should see this message'); - } - - function testPass() { - $this->pass('We should see this message'); - } -} - -$test = &new TestSuite('Visual test with 46 passes, 47 fails and 0 exceptions'); -$test->add(new PassingUnitTestCaseOutput()); -$test->add(new FailingUnitTestCaseOutput()); -$test->add(new TestOfMockObjectsOutput()); -$test->add(new TestOfPastBugs()); -$test->add(new TestOfVisualShell()); -$test->add(new TestOfSkippingNoMatterWhat()); -$test->add(new TestOfSkippingOrElse()); -$test->add(new TestOfSkippingTwiceOver()); -$test->add(new TestThatShouldNotBeSkipped()); - -if (isset($_GET['xml']) || in_array('xml', (isset($argv) ? $argv : array()))) { - $reporter = new XmlReporter(); -} elseif (TextReporter::inCli()) { - $reporter = new TextReporter(); -} else { - $reporter = new PassesAsWellReporter(); -} -if (isset($_GET['dry']) || in_array('dry', (isset($argv) ? $argv : array()))) { - $reporter->makeDry(); -} -exit ($test->run($reporter) ? 0 : 1); -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/web_tester_test.php b/3rdparty/simpletest/test/web_tester_test.php deleted file mode 100755 index 8c3bf1adf639e8587c048f314239cc86928629a1..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/web_tester_test.php +++ /dev/null @@ -1,155 +0,0 @@ -<?php -// $Id: web_tester_test.php 1748 2008-04-14 01:50:41Z lastcraft $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../web_tester.php'); - -class TestOfFieldExpectation extends UnitTestCase { - - function testStringMatchingIsCaseSensitive() { - $expectation = new FieldExpectation('a'); - $this->assertTrue($expectation->test('a')); - $this->assertTrue($expectation->test(array('a'))); - $this->assertFalse($expectation->test('A')); - } - - function testMatchesInteger() { - $expectation = new FieldExpectation('1'); - $this->assertTrue($expectation->test('1')); - $this->assertTrue($expectation->test(1)); - $this->assertTrue($expectation->test(array('1'))); - $this->assertTrue($expectation->test(array(1))); - } - - function testNonStringFailsExpectation() { - $expectation = new FieldExpectation('a'); - $this->assertFalse($expectation->test(null)); - } - - function testUnsetFieldCanBeTestedFor() { - $expectation = new FieldExpectation(false); - $this->assertTrue($expectation->test(false)); - } - - function testMultipleValuesCanBeInAnyOrder() { - $expectation = new FieldExpectation(array('a', 'b')); - $this->assertTrue($expectation->test(array('a', 'b'))); - $this->assertTrue($expectation->test(array('b', 'a'))); - $this->assertFalse($expectation->test(array('a', 'a'))); - $this->assertFalse($expectation->test('a')); - } - - function testSingleItemCanBeArrayOrString() { - $expectation = new FieldExpectation(array('a')); - $this->assertTrue($expectation->test(array('a'))); - $this->assertTrue($expectation->test('a')); - } -} - -class TestOfHeaderExpectations extends UnitTestCase { - - function testExpectingOnlyTheHeaderName() { - $expectation = new HttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test(false), false); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('a: B'), true); - $this->assertIdentical($expectation->test(' a : A '), true); - } - - function testHeaderValueAsWell() { - $expectation = new HttpHeaderExpectation('a', 'A'); - $this->assertIdentical($expectation->test(false), false); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('A: a'), false); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : AB '), false); - } - - function testHeaderValueWithColons() { - $expectation = new HttpHeaderExpectation('a', 'A:B:C'); - $this->assertIdentical($expectation->test('a: A'), false); - $this->assertIdentical($expectation->test('a: A:B'), false); - $this->assertIdentical($expectation->test('a: A:B:C'), true); - $this->assertIdentical($expectation->test('a: A:B:C:D'), false); - } - - function testMultilineSearch() { - $expectation = new HttpHeaderExpectation('a', 'A'); - $this->assertIdentical($expectation->test("aa: A\r\nb: B\r\nc: C"), false); - $this->assertIdentical($expectation->test("aa: A\r\na: A\r\nb: B"), true); - } - - function testMultilineSearchWithPadding() { - $expectation = new HttpHeaderExpectation('a', ' A '); - $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), false); - $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), true); - } - - function testPatternMatching() { - $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/')); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('A: a'), false); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : AB '), true); - } - - function testCaseInsensitivePatternMatching() { - $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/i')); - $this->assertIdentical($expectation->test('a: a'), true); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : BAB '), true); - $this->assertIdentical($expectation->test(' a : bab '), true); - } - - function testUnwantedHeader() { - $expectation = new NoHttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test(''), true); - $this->assertIdentical($expectation->test('stuff'), true); - $this->assertIdentical($expectation->test('b: B'), true); - $this->assertIdentical($expectation->test('a: A'), false); - $this->assertIdentical($expectation->test('A: A'), false); - } - - function testMultilineUnwantedSearch() { - $expectation = new NoHttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), true); - $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), false); - } - - function testLocationHeaderSplitsCorrectly() { - $expectation = new HttpHeaderExpectation('Location', 'http://here/'); - $this->assertIdentical($expectation->test('Location: http://here/'), true); - } -} - -class TestOfTextExpectations extends UnitTestCase { - - function testMatchingSubString() { - $expectation = new TextExpectation('wanted'); - $this->assertIdentical($expectation->test(''), false); - $this->assertIdentical($expectation->test('Wanted'), false); - $this->assertIdentical($expectation->test('wanted'), true); - $this->assertIdentical($expectation->test('the wanted text is here'), true); - } - - function testNotMatchingSubString() { - $expectation = new NoTextExpectation('wanted'); - $this->assertIdentical($expectation->test(''), true); - $this->assertIdentical($expectation->test('Wanted'), true); - $this->assertIdentical($expectation->test('wanted'), false); - $this->assertIdentical($expectation->test('the wanted text is here'), false); - } -} - -class TestOfGenericAssertionsInWebTester extends WebTestCase { - function testEquality() { - $this->assertEqual('a', 'a'); - $this->assertNotEqual('a', 'A'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/xml_test.php b/3rdparty/simpletest/test/xml_test.php deleted file mode 100755 index f99e0dcd98b07dbe7489512ee6cf14f38e2e4253..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/xml_test.php +++ /dev/null @@ -1,187 +0,0 @@ -<?php -// $Id: xml_test.php 1787 2008-04-26 20:35:39Z pp11 $ -require_once(dirname(__FILE__) . '/../autorun.php'); -require_once(dirname(__FILE__) . '/../xml.php'); -Mock::generate('SimpleScorer'); - -if (! function_exists('xml_parser_create')) { - SimpleTest::ignore('TestOfXmlStructureParsing'); - SimpleTest::ignore('TestOfXmlResultsParsing'); -} - -class TestOfNestingTags extends UnitTestCase { - function testGroupSize() { - $nesting = new NestingGroupTag(array('SIZE' => 2)); - $this->assertEqual($nesting->getSize(), 2); - } -} - -class TestOfXmlStructureParsing extends UnitTestCase { - function testValidXml() { - $listener = new MockSimpleScorer(); - $listener->expectNever('paintGroupStart'); - $listener->expectNever('paintGroupEnd'); - $listener->expectNever('paintCaseStart'); - $listener->expectNever('paintCaseEnd'); - $parser = new SimpleTestXmlParser($listener); - $this->assertTrue($parser->parse("<?xml version=\"1.0\"?>\n")); - $this->assertTrue($parser->parse("<run>\n")); - $this->assertTrue($parser->parse("</run>\n")); - } - - function testEmptyGroup() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintGroupStart', array('a_group', 7)); - $listener->expectOnce('paintGroupEnd', array('a_group')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("<?xml version=\"1.0\"?>\n"); - $parser->parse("<run>\n"); - $this->assertTrue($parser->parse("<group size=\"7\">\n")); - $this->assertTrue($parser->parse("<name>a_group</name>\n")); - $this->assertTrue($parser->parse("</group>\n")); - $parser->parse("</run>\n"); - } - - function testEmptyCase() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintCaseStart', array('a_case')); - $listener->expectOnce('paintCaseEnd', array('a_case')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("<?xml version=\"1.0\"?>\n"); - $parser->parse("<run>\n"); - $this->assertTrue($parser->parse("<case>\n")); - $this->assertTrue($parser->parse("<name>a_case</name>\n")); - $this->assertTrue($parser->parse("</case>\n")); - $parser->parse("</run>\n"); - } - - function testEmptyMethod() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintCaseStart', array('a_case')); - $listener->expectOnce('paintCaseEnd', array('a_case')); - $listener->expectOnce('paintMethodStart', array('a_method')); - $listener->expectOnce('paintMethodEnd', array('a_method')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("<?xml version=\"1.0\"?>\n"); - $parser->parse("<run>\n"); - $parser->parse("<case>\n"); - $parser->parse("<name>a_case</name>\n"); - $this->assertTrue($parser->parse("<test>\n")); - $this->assertTrue($parser->parse("<name>a_method</name>\n")); - $this->assertTrue($parser->parse("</test>\n")); - $parser->parse("</case>\n"); - $parser->parse("</run>\n"); - } - - function testNestedGroup() { - $listener = new MockSimpleScorer(); - $listener->expectAt(0, 'paintGroupStart', array('a_group', 7)); - $listener->expectAt(1, 'paintGroupStart', array('b_group', 3)); - $listener->expectCallCount('paintGroupStart', 2); - $listener->expectAt(0, 'paintGroupEnd', array('b_group')); - $listener->expectAt(1, 'paintGroupEnd', array('a_group')); - $listener->expectCallCount('paintGroupEnd', 2); - - $parser = new SimpleTestXmlParser($listener); - $parser->parse("<?xml version=\"1.0\"?>\n"); - $parser->parse("<run>\n"); - - $this->assertTrue($parser->parse("<group size=\"7\">\n")); - $this->assertTrue($parser->parse("<name>a_group</name>\n")); - $this->assertTrue($parser->parse("<group size=\"3\">\n")); - $this->assertTrue($parser->parse("<name>b_group</name>\n")); - $this->assertTrue($parser->parse("</group>\n")); - $this->assertTrue($parser->parse("</group>\n")); - $parser->parse("</run>\n"); - } -} - -class AnyOldSignal { - public $stuff = true; -} - -class TestOfXmlResultsParsing extends UnitTestCase { - - function sendValidStart(&$parser) { - $parser->parse("<?xml version=\"1.0\"?>\n"); - $parser->parse("<run>\n"); - $parser->parse("<case>\n"); - $parser->parse("<name>a_case</name>\n"); - $parser->parse("<test>\n"); - $parser->parse("<name>a_method</name>\n"); - } - - function sendValidEnd(&$parser) { - $parser->parse("</test>\n"); - $parser->parse("</case>\n"); - $parser->parse("</run>\n"); - } - - function testPass() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintPass', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("<pass>a_message</pass>\n")); - $this->sendValidEnd($parser); - } - - function testFail() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintFail', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("<fail>a_message</fail>\n")); - $this->sendValidEnd($parser); - } - - function testException() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintError', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("<exception>a_message</exception>\n")); - $this->sendValidEnd($parser); - } - - function testSkip() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintSkip', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("<skip>a_message</skip>\n")); - $this->sendValidEnd($parser); - } - - function testSignal() { - $signal = new AnyOldSignal(); - $signal->stuff = "Hello"; - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintSignal', array('a_signal', $signal)); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse( - "<signal type=\"a_signal\"><![CDATA[" . - serialize($signal) . "]]></signal>\n")); - $this->sendValidEnd($parser); - } - - function testMessage() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintMessage', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("<message>a_message</message>\n")); - $this->sendValidEnd($parser); - } - - function testFormattedMessage() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintFormattedMessage', array("\na\tmessage\n")); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("<formatted><![CDATA[\na\tmessage\n]]></formatted>\n")); - $this->sendValidEnd($parser); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test_case.php b/3rdparty/simpletest/test_case.php deleted file mode 100644 index ba023c3b2ea8746464166b685541bdd63c791960..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test_case.php +++ /dev/null @@ -1,658 +0,0 @@ -<?php -/** - * Base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: test_case.php 2012 2011-04-29 08:57:00Z pp11 $ - */ - -/**#@+ - * Includes SimpleTest files and defined the root constant - * for dependent libraries. - */ -require_once(dirname(__FILE__) . '/invoker.php'); -require_once(dirname(__FILE__) . '/errors.php'); -require_once(dirname(__FILE__) . '/compatibility.php'); -require_once(dirname(__FILE__) . '/scorer.php'); -require_once(dirname(__FILE__) . '/expectation.php'); -require_once(dirname(__FILE__) . '/dumper.php'); -require_once(dirname(__FILE__) . '/simpletest.php'); -require_once(dirname(__FILE__) . '/exceptions.php'); -require_once(dirname(__FILE__) . '/reflection_php5.php'); -/**#@-*/ -if (! defined('SIMPLE_TEST')) { - /** - * @ignore - */ - define('SIMPLE_TEST', dirname(__FILE__) . DIRECTORY_SEPARATOR); -} - -/** - * Basic test case. This is the smallest unit of a test - * suite. It searches for - * all methods that start with the the string "test" and - * runs them. Working test cases extend this class. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleTestCase { - private $label = false; - protected $reporter; - private $observers; - private $should_skip = false; - - /** - * Sets up the test with no display. - * @param string $label If no test name is given then - * the class name is used. - * @access public - */ - function __construct($label = false) { - if ($label) { - $this->label = $label; - } - } - - /** - * Accessor for the test name for subclasses. - * @return string Name of the test. - * @access public - */ - function getLabel() { - return $this->label ? $this->label : get_class($this); - } - - /** - * This is a placeholder for skipping tests. In this - * method you place skipIf() and skipUnless() calls to - * set the skipping state. - * @access public - */ - function skip() { - } - - /** - * Will issue a message to the reporter and tell the test - * case to skip if the incoming flag is true. - * @param string $should_skip Condition causing the tests to be skipped. - * @param string $message Text of skip condition. - * @access public - */ - function skipIf($should_skip, $message = '%s') { - if ($should_skip && ! $this->should_skip) { - $this->should_skip = true; - $message = sprintf($message, 'Skipping [' . get_class($this) . ']'); - $this->reporter->paintSkip($message . $this->getAssertionLine()); - } - } - - /** - * Accessor for the private variable $_shoud_skip - * @access public - */ - function shouldSkip() { - return $this->should_skip; - } - - /** - * Will issue a message to the reporter and tell the test - * case to skip if the incoming flag is false. - * @param string $shouldnt_skip Condition causing the tests to be run. - * @param string $message Text of skip condition. - * @access public - */ - function skipUnless($shouldnt_skip, $message = false) { - $this->skipIf(! $shouldnt_skip, $message); - } - - /** - * Used to invoke the single tests. - * @return SimpleInvoker Individual test runner. - * @access public - */ - function createInvoker() { - return new SimpleErrorTrappingInvoker( - new SimpleExceptionTrappingInvoker(new SimpleInvoker($this))); - } - - /** - * Uses reflection to run every method within itself - * starting with the string "test" unless a method - * is specified. - * @param SimpleReporter $reporter Current test reporter. - * @return boolean True if all tests passed. - * @access public - */ - function run($reporter) { - $context = SimpleTest::getContext(); - $context->setTest($this); - $context->setReporter($reporter); - $this->reporter = $reporter; - $started = false; - foreach ($this->getTests() as $method) { - if ($reporter->shouldInvoke($this->getLabel(), $method)) { - $this->skip(); - if ($this->should_skip) { - break; - } - if (! $started) { - $reporter->paintCaseStart($this->getLabel()); - $started = true; - } - $invoker = $this->reporter->createInvoker($this->createInvoker()); - $invoker->before($method); - $invoker->invoke($method); - $invoker->after($method); - } - } - if ($started) { - $reporter->paintCaseEnd($this->getLabel()); - } - unset($this->reporter); - $context->setTest(null); - return $reporter->getStatus(); - } - - /** - * Gets a list of test names. Normally that will - * be all internal methods that start with the - * name "test". This method should be overridden - * if you want a different rule. - * @return array List of test names. - * @access public - */ - function getTests() { - $methods = array(); - foreach (get_class_methods(get_class($this)) as $method) { - if ($this->isTest($method)) { - $methods[] = $method; - } - } - return $methods; - } - - /** - * Tests to see if the method is a test that should - * be run. Currently any method that starts with 'test' - * is a candidate unless it is the constructor. - * @param string $method Method name to try. - * @return boolean True if test method. - * @access protected - */ - protected function isTest($method) { - if (strtolower(substr($method, 0, 4)) == 'test') { - return ! SimpleTestCompatibility::isA($this, strtolower($method)); - } - return false; - } - - /** - * Announces the start of the test. - * @param string $method Test method just started. - * @access public - */ - function before($method) { - $this->reporter->paintMethodStart($method); - $this->observers = array(); - } - - /** - * Sets up unit test wide variables at the start - * of each test method. To be overridden in - * actual user test cases. - * @access public - */ - function setUp() { - } - - /** - * Clears the data set in the setUp() method call. - * To be overridden by the user in actual user test cases. - * @access public - */ - function tearDown() { - } - - /** - * Announces the end of the test. Includes private clean up. - * @param string $method Test method just finished. - * @access public - */ - function after($method) { - for ($i = 0; $i < count($this->observers); $i++) { - $this->observers[$i]->atTestEnd($method, $this); - } - $this->reporter->paintMethodEnd($method); - } - - /** - * Sets up an observer for the test end. - * @param object $observer Must have atTestEnd() - * method. - * @access public - */ - function tell($observer) { - $this->observers[] = &$observer; - } - - /** - * @deprecated - */ - function pass($message = "Pass") { - if (! isset($this->reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->reporter->paintPass( - $message . $this->getAssertionLine()); - return true; - } - - /** - * Sends a fail event with a message. - * @param string $message Message to send. - * @access public - */ - function fail($message = "Fail") { - if (! isset($this->reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->reporter->paintFail( - $message . $this->getAssertionLine()); - return false; - } - - /** - * Formats a PHP error and dispatches it to the - * reporter. - * @param integer $severity PHP error code. - * @param string $message Text of error. - * @param string $file File error occoured in. - * @param integer $line Line number of error. - * @access public - */ - function error($severity, $message, $file, $line) { - if (! isset($this->reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->reporter->paintError( - "Unexpected PHP error [$message] severity [$severity] in [$file line $line]"); - } - - /** - * Formats an exception and dispatches it to the - * reporter. - * @param Exception $exception Object thrown. - * @access public - */ - function exception($exception) { - $this->reporter->paintException($exception); - } - - /** - * For user defined expansion of the available messages. - * @param string $type Tag for sorting the signals. - * @param mixed $payload Extra user specific information. - */ - function signal($type, $payload) { - if (! isset($this->reporter)) { - trigger_error('Can only make assertions within test methods'); - } - $this->reporter->paintSignal($type, $payload); - } - - /** - * Runs an expectation directly, for extending the - * tests with new expectation classes. - * @param SimpleExpectation $expectation Expectation subclass. - * @param mixed $compare Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assert($expectation, $compare, $message = '%s') { - if ($expectation->test($compare)) { - return $this->pass(sprintf( - $message, - $expectation->overlayMessage($compare, $this->reporter->getDumper()))); - } else { - return $this->fail(sprintf( - $message, - $expectation->overlayMessage($compare, $this->reporter->getDumper()))); - } - } - - /** - * Uses a stack trace to find the line of an assertion. - * @return string Line number of first assert* - * method embedded in format string. - * @access public - */ - function getAssertionLine() { - $trace = new SimpleStackTrace(array('assert', 'expect', 'pass', 'fail', 'skip')); - return $trace->traceMethod(); - } - - /** - * Sends a formatted dump of a variable to the - * test suite for those emergency debugging - * situations. - * @param mixed $variable Variable to display. - * @param string $message Message to display. - * @return mixed The original variable. - * @access public - */ - function dump($variable, $message = false) { - $dumper = $this->reporter->getDumper(); - $formatted = $dumper->dump($variable); - if ($message) { - $formatted = $message . "\n" . $formatted; - } - $this->reporter->paintFormattedMessage($formatted); - return $variable; - } - - /** - * Accessor for the number of subtests including myelf. - * @return integer Number of test cases. - * @access public - */ - function getSize() { - return 1; - } -} - -/** - * Helps to extract test cases automatically from a file. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleFileLoader { - - /** - * Builds a test suite from a library of test cases. - * The new suite is composed into this one. - * @param string $test_file File name of library with - * test case classes. - * @return TestSuite The new test suite. - * @access public - */ - function load($test_file) { - $existing_classes = get_declared_classes(); - $existing_globals = get_defined_vars(); - include_once($test_file); - $new_globals = get_defined_vars(); - $this->makeFileVariablesGlobal($existing_globals, $new_globals); - $new_classes = array_diff(get_declared_classes(), $existing_classes); - if (empty($new_classes)) { - $new_classes = $this->scrapeClassesFromFile($test_file); - } - $classes = $this->selectRunnableTests($new_classes); - return $this->createSuiteFromClasses($test_file, $classes); - } - - /** - * Imports new variables into the global namespace. - * @param hash $existing Variables before the file was loaded. - * @param hash $new Variables after the file was loaded. - * @access private - */ - protected function makeFileVariablesGlobal($existing, $new) { - $globals = array_diff(array_keys($new), array_keys($existing)); - foreach ($globals as $global) { - $GLOBALS[$global] = $new[$global]; - } - } - - /** - * Lookup classnames from file contents, in case the - * file may have been included before. - * Note: This is probably too clever by half. Figuring this - * out after a failed test case is going to be tricky for us, - * never mind the user. A test case should not be included - * twice anyway. - * @param string $test_file File name with classes. - * @access private - */ - protected function scrapeClassesFromFile($test_file) { - preg_match_all('~^\s*class\s+(\w+)(\s+(extends|implements)\s+\w+)*\s*\{~mi', - file_get_contents($test_file), - $matches ); - return $matches[1]; - } - - /** - * Calculates the incoming test cases. Skips abstract - * and ignored classes. - * @param array $candidates Candidate classes. - * @return array New classes which are test - * cases that shouldn't be ignored. - * @access public - */ - function selectRunnableTests($candidates) { - $classes = array(); - foreach ($candidates as $class) { - if (TestSuite::getBaseTestCase($class)) { - $reflection = new SimpleReflection($class); - if ($reflection->isAbstract()) { - SimpleTest::ignore($class); - } else { - $classes[] = $class; - } - } - } - return $classes; - } - - /** - * Builds a test suite from a class list. - * @param string $title Title of new group. - * @param array $classes Test classes. - * @return TestSuite Group loaded with the new - * test cases. - * @access public - */ - function createSuiteFromClasses($title, $classes) { - if (count($classes) == 0) { - $suite = new BadTestSuite($title, "No runnable test cases in [$title]"); - return $suite; - } - SimpleTest::ignoreParentsIfIgnored($classes); - $suite = new TestSuite($title); - foreach ($classes as $class) { - if (! SimpleTest::isIgnored($class)) { - $suite->add($class); - } - } - return $suite; - } -} - -/** - * This is a composite test class for combining - * test cases and other RunnableTest classes into - * a group test. - * @package SimpleTest - * @subpackage UnitTester - */ -class TestSuite { - private $label; - private $test_cases; - - /** - * Sets the name of the test suite. - * @param string $label Name sent at the start and end - * of the test. - * @access public - */ - function TestSuite($label = false) { - $this->label = $label; - $this->test_cases = array(); - } - - /** - * Accessor for the test name for subclasses. If the suite - * wraps a single test case the label defaults to the name of that test. - * @return string Name of the test. - * @access public - */ - function getLabel() { - if (! $this->label) { - return ($this->getSize() == 1) ? - get_class($this->test_cases[0]) : get_class($this); - } else { - return $this->label; - } - } - - /** - * Adds a test into the suite by instance or class. The class will - * be instantiated if it's a test suite. - * @param SimpleTestCase $test_case Suite or individual test - * case implementing the - * runnable test interface. - * @access public - */ - function add($test_case) { - if (! is_string($test_case)) { - $this->test_cases[] = $test_case; - } elseif (TestSuite::getBaseTestCase($test_case) == 'testsuite') { - $this->test_cases[] = new $test_case(); - } else { - $this->test_cases[] = $test_case; - } - } - - /** - * Builds a test suite from a library of test cases. - * The new suite is composed into this one. - * @param string $test_file File name of library with - * test case classes. - * @access public - */ - function addFile($test_file) { - $extractor = new SimpleFileLoader(); - $this->add($extractor->load($test_file)); - } - - /** - * Delegates to a visiting collector to add test - * files. - * @param string $path Path to scan from. - * @param SimpleCollector $collector Directory scanner. - * @access public - */ - function collect($path, $collector) { - $collector->collect($this, $path); - } - - /** - * Invokes run() on all of the held test cases, instantiating - * them if necessary. - * @param SimpleReporter $reporter Current test reporter. - * @access public - */ - function run($reporter) { - $reporter->paintGroupStart($this->getLabel(), $this->getSize()); - for ($i = 0, $count = count($this->test_cases); $i < $count; $i++) { - if (is_string($this->test_cases[$i])) { - $class = $this->test_cases[$i]; - $test = new $class(); - $test->run($reporter); - unset($test); - } else { - $this->test_cases[$i]->run($reporter); - } - } - $reporter->paintGroupEnd($this->getLabel()); - return $reporter->getStatus(); - } - - /** - * Number of contained test cases. - * @return integer Total count of cases in the group. - * @access public - */ - function getSize() { - $count = 0; - foreach ($this->test_cases as $case) { - if (is_string($case)) { - if (! SimpleTest::isIgnored($case)) { - $count++; - } - } else { - $count += $case->getSize(); - } - } - return $count; - } - - /** - * Test to see if a class is derived from the - * SimpleTestCase class. - * @param string $class Class name. - * @access public - */ - static function getBaseTestCase($class) { - while ($class = get_parent_class($class)) { - $class = strtolower($class); - if ($class == 'simpletestcase' || $class == 'testsuite') { - return $class; - } - } - return false; - } -} - -/** - * This is a failing group test for when a test suite hasn't - * loaded properly. - * @package SimpleTest - * @subpackage UnitTester - */ -class BadTestSuite { - private $label; - private $error; - - /** - * Sets the name of the test suite and error message. - * @param string $label Name sent at the start and end - * of the test. - * @access public - */ - function BadTestSuite($label, $error) { - $this->label = $label; - $this->error = $error; - } - - /** - * Accessor for the test name for subclasses. - * @return string Name of the test. - * @access public - */ - function getLabel() { - return $this->label; - } - - /** - * Sends a single error to the reporter. - * @param SimpleReporter $reporter Current test reporter. - * @access public - */ - function run($reporter) { - $reporter->paintGroupStart($this->getLabel(), $this->getSize()); - $reporter->paintFail('Bad TestSuite [' . $this->getLabel() . - '] with error [' . $this->error . ']'); - $reporter->paintGroupEnd($this->getLabel()); - return $reporter->getStatus(); - } - - /** - * Number of contained test cases. Always zero. - * @return integer Total count of cases in the group. - * @access public - */ - function getSize() { - return 0; - } -} -?> diff --git a/3rdparty/simpletest/tidy_parser.php b/3rdparty/simpletest/tidy_parser.php deleted file mode 100755 index 3d8b4b2ac7dc8217dfbe929fd250430c6d892645..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/tidy_parser.php +++ /dev/null @@ -1,382 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage WebTester - * @version $Id: php_parser.php 1911 2009-07-29 16:38:04Z lastcraft $ - */ - -/** - * Builds the page object. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleTidyPageBuilder { - private $page; - private $forms = array(); - private $labels = array(); - private $widgets_by_id = array(); - - public function __destruct() { - $this->free(); - } - - /** - * Frees up any references so as to allow the PHP garbage - * collection from unset() to work. - */ - private function free() { - unset($this->page); - $this->forms = array(); - $this->labels = array(); - } - - /** - * This builder is only available if the 'tidy' extension is loaded. - * @return boolean True if available. - */ - function can() { - return extension_loaded('tidy'); - } - - /** - * Reads the raw content the page using HTML Tidy. - * @param $response SimpleHttpResponse Fetched response. - * @return SimplePage Newly parsed page. - */ - function parse($response) { - $this->page = new SimplePage($response); - $tidied = tidy_parse_string($input = $this->insertGuards($response->getContent()), - array('output-xml' => false, 'wrap' => '0', 'indent' => 'no'), - 'latin1'); - $this->walkTree($tidied->html()); - $this->attachLabels($this->widgets_by_id, $this->labels); - $this->page->setForms($this->forms); - $page = $this->page; - $this->free(); - return $page; - } - - /** - * Stops HTMLTidy stripping content that we wish to preserve. - * @param string The raw html. - * @return string The html with guard tags inserted. - */ - private function insertGuards($html) { - return $this->insertEmptyTagGuards($this->insertTextareaSimpleWhitespaceGuards($html)); - } - - /** - * Removes the extra content added during the parse stage - * in order to preserve content we don't want stripped - * out by HTMLTidy. - * @param string The raw html. - * @return string The html with guard tags removed. - */ - private function stripGuards($html) { - return $this->stripTextareaWhitespaceGuards($this->stripEmptyTagGuards($html)); - } - - /** - * HTML tidy strips out empty tags such as <option> which we - * need to preserve. This method inserts an additional marker. - * @param string The raw html. - * @return string The html with guards inserted. - */ - private function insertEmptyTagGuards($html) { - return preg_replace('#<(option|textarea)([^>]*)>(\s*)</(option|textarea)>#is', - '<\1\2>___EMPTY___\3</\4>', - $html); - } - - /** - * HTML tidy strips out empty tags such as <option> which we - * need to preserve. This method strips additional markers - * inserted by SimpleTest to the tidy output used to make the - * tags non-empty. This ensures their preservation. - * @param string The raw html. - * @return string The html with guards removed. - */ - private function stripEmptyTagGuards($html) { - return preg_replace('#(^|>)(\s*)___EMPTY___(\s*)(</|$)#i', '\2\3', $html); - } - - /** - * By parsing the XML output of tidy, we lose some whitespace - * information in textarea tags. We temporarily recode this - * data ourselves so as not to lose it. - * @param string The raw html. - * @return string The html with guards inserted. - */ - private function insertTextareaSimpleWhitespaceGuards($html) { - return preg_replace_callback('#<textarea([^>]*)>(.*?)</textarea>#is', - array($this, 'insertWhitespaceGuards'), - $html); - } - - /** - * Callback for insertTextareaSimpleWhitespaceGuards(). - * @param array $matches Result of preg_replace_callback(). - * @return string Guard tags now replace whitespace. - */ - private function insertWhitespaceGuards($matches) { - return '<textarea' . $matches[1] . '>' . - str_replace(array("\n", "\r", "\t", ' '), - array('___NEWLINE___', '___CR___', '___TAB___', '___SPACE___'), - $matches[2]) . - '</textarea>'; - } - - /** - * Removes the whitespace preserving guards we added - * before parsing. - * @param string The raw html. - * @return string The html with guards removed. - */ - private function stripTextareaWhitespaceGuards($html) { - return str_replace(array('___NEWLINE___', '___CR___', '___TAB___', '___SPACE___'), - array("\n", "\r", "\t", ' '), - $html); - } - - /** - * Visits the given node and all children - * @param object $node Tidy XML node. - */ - private function walkTree($node) { - if ($node->name == 'a') { - $this->page->addLink($this->tags()->createTag($node->name, (array)$node->attribute) - ->addContent($this->innerHtml($node))); - } elseif ($node->name == 'base' and isset($node->attribute['href'])) { - $this->page->setBase($node->attribute['href']); - } elseif ($node->name == 'title') { - $this->page->setTitle($this->tags()->createTag($node->name, (array)$node->attribute) - ->addContent($this->innerHtml($node))); - } elseif ($node->name == 'frameset') { - $this->page->setFrames($this->collectFrames($node)); - } elseif ($node->name == 'form') { - $this->forms[] = $this->walkForm($node, $this->createEmptyForm($node)); - } elseif ($node->name == 'label') { - $this->labels[] = $this->tags()->createTag($node->name, (array)$node->attribute) - ->addContent($this->innerHtml($node)); - } else { - $this->walkChildren($node); - } - } - - /** - * Helper method for traversing the XML tree. - * @param object $node Tidy XML node. - */ - private function walkChildren($node) { - if ($node->hasChildren()) { - foreach ($node->child as $child) { - $this->walkTree($child); - } - } - } - - /** - * Facade for forms containing preparsed widgets. - * @param object $node Tidy XML node. - * @return SimpleForm Facade for SimpleBrowser. - */ - private function createEmptyForm($node) { - return new SimpleForm($this->tags()->createTag($node->name, (array)$node->attribute), $this->page); - } - - /** - * Visits the given node and all children - * @param object $node Tidy XML node. - */ - private function walkForm($node, $form, $enclosing_label = '') { - if ($node->name == 'a') { - $this->page->addLink($this->tags()->createTag($node->name, (array)$node->attribute) - ->addContent($this->innerHtml($node))); - } elseif (in_array($node->name, array('input', 'button', 'textarea', 'select'))) { - $this->addWidgetToForm($node, $form, $enclosing_label); - } elseif ($node->name == 'label') { - $this->labels[] = $this->tags()->createTag($node->name, (array)$node->attribute) - ->addContent($this->innerHtml($node)); - if ($node->hasChildren()) { - foreach ($node->child as $child) { - $this->walkForm($child, $form, SimplePage::normalise($this->innerHtml($node))); - } - } - } elseif ($node->hasChildren()) { - foreach ($node->child as $child) { - $this->walkForm($child, $form); - } - } - return $form; - } - - /** - * Tests a node for a "for" atribute. Used for - * attaching labels. - * @param object $node Tidy XML node. - * @return boolean True if the "for" attribute exists. - */ - private function hasFor($node) { - return isset($node->attribute) and $node->attribute['for']; - } - - /** - * Adds the widget into the form container. - * @param object $node Tidy XML node of widget. - * @param SimpleForm $form Form to add it to. - * @param string $enclosing_label The label of any label - * tag we might be in. - */ - private function addWidgetToForm($node, $form, $enclosing_label) { - $widget = $this->tags()->createTag($node->name, $this->attributes($node)); - if (! $widget) { - return; - } - $widget->setLabel($enclosing_label) - ->addContent($this->innerHtml($node)); - if ($node->name == 'select') { - $widget->addTags($this->collectSelectOptions($node)); - } - $form->addWidget($widget); - $this->indexWidgetById($widget); - } - - /** - * Fills the widget cache to speed up searching. - * @param SimpleTag $widget Parsed widget to cache. - */ - private function indexWidgetById($widget) { - $id = $widget->getAttribute('id'); - if (! $id) { - return; - } - if (! isset($this->widgets_by_id[$id])) { - $this->widgets_by_id[$id] = array(); - } - $this->widgets_by_id[$id][] = $widget; - } - - /** - * Parses the options from inside an XML select node. - * @param object $node Tidy XML node. - * @return array List of SimpleTag options. - */ - private function collectSelectOptions($node) { - $options = array(); - if ($node->name == 'option') { - $options[] = $this->tags()->createTag($node->name, $this->attributes($node)) - ->addContent($this->innerHtml($node)); - } - if ($node->hasChildren()) { - foreach ($node->child as $child) { - $options = array_merge($options, $this->collectSelectOptions($child)); - } - } - return $options; - } - - /** - * Convenience method for collecting all the attributes - * of a tag. Not sure why Tidy does not have this. - * @param object $node Tidy XML node. - * @return array Hash of attribute strings. - */ - private function attributes($node) { - if (! preg_match('|<[^ ]+\s(.*?)/?>|s', $node->value, $first_tag_contents)) { - return array(); - } - $attributes = array(); - preg_match_all('/\S+\s*=\s*\'[^\']*\'|(\S+\s*=\s*"[^"]*")|([^ =]+\s*=\s*[^ "\']+?)|[^ "\']+/', $first_tag_contents[1], $matches); - foreach($matches[0] as $unparsed) { - $attributes = $this->mergeAttribute($attributes, $unparsed); - } - return $attributes; - } - - /** - * Overlay an attribute into the attributes hash. - * @param array $attributes Current attribute list. - * @param string $raw Raw attribute string with - * both key and value. - * @return array New attribute hash. - */ - private function mergeAttribute($attributes, $raw) { - $parts = explode('=', $raw); - list($name, $value) = count($parts) == 1 ? array($parts[0], $parts[0]) : $parts; - $attributes[trim($name)] = html_entity_decode($this->dequote(trim($value)), ENT_QUOTES); - return $attributes; - } - - /** - * Remove start and end quotes. - * @param string $quoted A quoted string. - * @return string Quotes are gone. - */ - private function dequote($quoted) { - if (preg_match('/^(\'([^\']*)\'|"([^"]*)")$/', $quoted, $matches)) { - return isset($matches[3]) ? $matches[3] : $matches[2]; - } - return $quoted; - } - - /** - * Collects frame information inside a frameset tag. - * @param object $node Tidy XML node. - * @return array List of SimpleTag frame descriptions. - */ - private function collectFrames($node) { - $frames = array(); - if ($node->name == 'frame') { - $frames = array($this->tags()->createTag($node->name, (array)$node->attribute)); - } else if ($node->hasChildren()) { - $frames = array(); - foreach ($node->child as $child) { - $frames = array_merge($frames, $this->collectFrames($child)); - } - } - return $frames; - } - - /** - * Extracts the XML node text. - * @param object $node Tidy XML node. - * @return string The text only. - */ - private function innerHtml($node) { - $raw = ''; - if ($node->hasChildren()) { - foreach ($node->child as $child) { - $raw .= $child->value; - } - } - return $this->stripGuards($raw); - } - - /** - * Factory for parsed content holders. - * @return SimpleTagBuilder Factory. - */ - private function tags() { - return new SimpleTagBuilder(); - } - - /** - * Called at the end of a parse run. Attaches any - * non-wrapping labels to their form elements. - * @param array $widgets_by_id Cached SimpleTag hash. - * @param array $labels SimpleTag label elements. - */ - private function attachLabels($widgets_by_id, $labels) { - foreach ($labels as $label) { - $for = $label->getFor(); - if ($for and isset($widgets_by_id[$for])) { - $text = $label->getText(); - foreach ($widgets_by_id[$for] as $widget) { - $widget->setLabel($text); - } - } - } - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/unit_tester.php b/3rdparty/simpletest/unit_tester.php deleted file mode 100755 index ce82660afa272695187be86caabfeab3034d5d14..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/unit_tester.php +++ /dev/null @@ -1,413 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: unit_tester.php 1882 2009-07-01 14:30:05Z lastcraft $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/test_case.php'); -require_once(dirname(__FILE__) . '/dumper.php'); -/**#@-*/ - -/** - * Standard unit test class for day to day testing - * of PHP code XP style. Adds some useful standard - * assertions. - * @package SimpleTest - * @subpackage UnitTester - */ -class UnitTestCase extends SimpleTestCase { - - /** - * Creates an empty test case. Should be subclassed - * with test methods for a functional test case. - * @param string $label Name of test case. Will use - * the class name if none specified. - * @access public - */ - function __construct($label = false) { - if (! $label) { - $label = get_class($this); - } - parent::__construct($label); - } - - /** - * Called from within the test methods to register - * passes and failures. - * @param boolean $result Pass on true. - * @param string $message Message to display describing - * the test state. - * @return boolean True on pass - * @access public - */ - function assertTrue($result, $message = '%s') { - return $this->assert(new TrueExpectation(), $result, $message); - } - - /** - * Will be true on false and vice versa. False - * is the PHP definition of false, so that null, - * empty strings, zero and an empty array all count - * as false. - * @param boolean $result Pass on false. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertFalse($result, $message = '%s') { - return $this->assert(new FalseExpectation(), $result, $message); - } - - /** - * Will be true if the value is null. - * @param null $value Supposedly null value. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNull($value, $message = '%s') { - $dumper = new SimpleDumper(); - $message = sprintf( - $message, - '[' . $dumper->describeValue($value) . '] should be null'); - return $this->assertTrue(! isset($value), $message); - } - - /** - * Will be true if the value is set. - * @param mixed $value Supposedly set value. - * @param string $message Message to display. - * @return boolean True on pass. - * @access public - */ - function assertNotNull($value, $message = '%s') { - $dumper = new SimpleDumper(); - $message = sprintf( - $message, - '[' . $dumper->describeValue($value) . '] should not be null'); - return $this->assertTrue(isset($value), $message); - } - - /** - * Type and class test. Will pass if class - * matches the type name or is a subclass or - * if not an object, but the type is correct. - * @param mixed $object Object to test. - * @param string $type Type name as string. - * @param string $message Message to display. - * @return boolean True on pass. - * @access public - */ - function assertIsA($object, $type, $message = '%s') { - return $this->assert( - new IsAExpectation($type), - $object, - $message); - } - - /** - * Type and class mismatch test. Will pass if class - * name or underling type does not match the one - * specified. - * @param mixed $object Object to test. - * @param string $type Type name as string. - * @param string $message Message to display. - * @return boolean True on pass. - * @access public - */ - function assertNotA($object, $type, $message = '%s') { - return $this->assert( - new NotAExpectation($type), - $object, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * the same value only. Otherwise a fail. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertEqual($first, $second, $message = '%s') { - return $this->assert( - new EqualExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * a different value. Otherwise a fail. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNotEqual($first, $second, $message = '%s') { - return $this->assert( - new NotEqualExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if the if the first parameter - * is near enough to the second by the margin. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param mixed $margin Fuzziness of match. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertWithinMargin($first, $second, $margin, $message = '%s') { - return $this->assert( - new WithinMarginExpectation($first, $margin), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters differ - * by more than the margin. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param mixed $margin Fuzziness of match. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertOutsideMargin($first, $second, $margin, $message = '%s') { - return $this->assert( - new OutsideMarginExpectation($first, $margin), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * the same value and same type. Otherwise a fail. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertIdentical($first, $second, $message = '%s') { - return $this->assert( - new IdenticalExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * the different value or different type. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNotIdentical($first, $second, $message = '%s') { - return $this->assert( - new NotIdenticalExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if both parameters refer - * to the same object or value. Fail otherwise. - * This will cause problems testing objects under - * E_STRICT. - * TODO: Replace with expectation. - * @param mixed $first Reference to check. - * @param mixed $second Hopefully the same variable. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertReference(&$first, &$second, $message = '%s') { - $dumper = new SimpleDumper(); - $message = sprintf( - $message, - '[' . $dumper->describeValue($first) . - '] and [' . $dumper->describeValue($second) . - '] should reference the same object'); - return $this->assertTrue( - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * Will trigger a pass if both parameters refer - * to the same object. Fail otherwise. This has - * the same semantics at the PHPUnit assertSame. - * That is, if values are passed in it has roughly - * the same affect as assertIdentical. - * TODO: Replace with expectation. - * @param mixed $first Object reference to check. - * @param mixed $second Hopefully the same object. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertSame($first, $second, $message = '%s') { - $dumper = new SimpleDumper(); - $message = sprintf( - $message, - '[' . $dumper->describeValue($first) . - '] and [' . $dumper->describeValue($second) . - '] should reference the same object'); - return $this->assertTrue($first === $second, $message); - } - - /** - * Will trigger a pass if both parameters refer - * to different objects. Fail otherwise. The objects - * have to be identical though. - * @param mixed $first Object reference to check. - * @param mixed $second Hopefully not the same object. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertClone($first, $second, $message = '%s') { - $dumper = new SimpleDumper(); - $message = sprintf( - $message, - '[' . $dumper->describeValue($first) . - '] and [' . $dumper->describeValue($second) . - '] should not be the same object'); - $identical = new IdenticalExpectation($first); - return $this->assertTrue( - $identical->test($second) && ! ($first === $second), - $message); - } - - /** - * Will trigger a pass if both parameters refer - * to different variables. Fail otherwise. The objects - * have to be identical references though. - * This will fail under E_STRICT with objects. Use - * assertClone() for this. - * @param mixed $first Object reference to check. - * @param mixed $second Hopefully not the same object. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertCopy(&$first, &$second, $message = "%s") { - $dumper = new SimpleDumper(); - $message = sprintf( - $message, - "[" . $dumper->describeValue($first) . - "] and [" . $dumper->describeValue($second) . - "] should not be the same object"); - return $this->assertFalse( - SimpleTestCompatibility::isReference($first, $second), - $message); - } - - /** - * Will trigger a pass if the Perl regex pattern - * is found in the subject. Fail otherwise. - * @param string $pattern Perl regex to look for including - * the regex delimiters. - * @param string $subject String to search in. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertPattern($pattern, $subject, $message = '%s') { - return $this->assert( - new PatternExpectation($pattern), - $subject, - $message); - } - - /** - * Will trigger a pass if the perl regex pattern - * is not present in subject. Fail if found. - * @param string $pattern Perl regex to look for including - * the regex delimiters. - * @param string $subject String to search in. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNoPattern($pattern, $subject, $message = '%s') { - return $this->assert( - new NoPatternExpectation($pattern), - $subject, - $message); - } - - /** - * Prepares for an error. If the error mismatches it - * passes through, otherwise it is swallowed. Any - * left over errors trigger failures. - * @param SimpleExpectation/string $expected The error to match. - * @param string $message Message on failure. - * @access public - */ - function expectError($expected = false, $message = '%s') { - $queue = SimpleTest::getContext()->get('SimpleErrorQueue'); - $queue->expectError($this->coerceExpectation($expected), $message); - } - - /** - * Prepares for an exception. If the error mismatches it - * passes through, otherwise it is swallowed. Any - * left over errors trigger failures. - * @param SimpleExpectation/Exception $expected The error to match. - * @param string $message Message on failure. - * @access public - */ - function expectException($expected = false, $message = '%s') { - $queue = SimpleTest::getContext()->get('SimpleExceptionTrap'); - $line = $this->getAssertionLine(); - $queue->expectException($expected, $message . $line); - } - - /** - * Tells SimpleTest to ignore an upcoming exception as not relevant - * to the current test. It doesn't affect the test, whether thrown or - * not. - * @param SimpleExpectation/Exception $ignored The error to ignore. - * @access public - */ - function ignoreException($ignored = false) { - SimpleTest::getContext()->get('SimpleExceptionTrap')->ignoreException($ignored); - } - - /** - * Creates an equality expectation if the - * object/value is not already some type - * of expectation. - * @param mixed $expected Expected value. - * @return SimpleExpectation Expectation object. - * @access private - */ - protected function coerceExpectation($expected) { - if ($expected == false) { - return new TrueExpectation(); - } - if (SimpleTestCompatibility::isA($expected, 'SimpleExpectation')) { - return $expected; - } - return new EqualExpectation( - is_string($expected) ? str_replace('%', '%%', $expected) : $expected); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/url.php b/3rdparty/simpletest/url.php deleted file mode 100644 index 11d70e745ee4bf941d606e2edf6dbaa05d769c9b..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/url.php +++ /dev/null @@ -1,550 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage WebTester - * @version $Id: url.php 2011 2011-04-29 08:22:48Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/encoding.php'); -/**#@-*/ - -/** - * URL parser to replace parse_url() PHP function which - * got broken in PHP 4.3.0. Adds some browser specific - * functionality such as expandomatics. - * Guesses a bit trying to separate the host from - * the path and tries to keep a raw, possibly unparsable, - * request string as long as possible. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleUrl { - private $scheme; - private $username; - private $password; - private $host; - private $port; - public $path; - private $request; - private $fragment; - private $x; - private $y; - private $target; - private $raw = false; - - /** - * Constructor. Parses URL into sections. - * @param string $url Incoming URL. - * @access public - */ - function __construct($url = '') { - list($x, $y) = $this->chompCoordinates($url); - $this->setCoordinates($x, $y); - $this->scheme = $this->chompScheme($url); - if ($this->scheme === 'file') { - // Unescaped backslashes not used in directory separator context - // will get caught by this, but they should have been urlencoded - // anyway so we don't care. If this ends up being a problem, the - // host regexp must be modified to match for backslashes when - // the scheme is file. - $url = str_replace('\\', '/', $url); - } - list($this->username, $this->password) = $this->chompLogin($url); - $this->host = $this->chompHost($url); - $this->port = false; - if (preg_match('/(.*?):(.*)/', $this->host, $host_parts)) { - if ($this->scheme === 'file' && strlen($this->host) === 2) { - // DOS drive was placed in authority; promote it to path. - $url = '/' . $this->host . $url; - $this->host = false; - } else { - $this->host = $host_parts[1]; - $this->port = (integer)$host_parts[2]; - } - } - $this->path = $this->chompPath($url); - $this->request = $this->parseRequest($this->chompRequest($url)); - $this->fragment = (strncmp($url, "#", 1) == 0 ? substr($url, 1) : false); - $this->target = false; - } - - /** - * Extracts the X, Y coordinate pair from an image map. - * @param string $url URL so far. The coordinates will be - * removed. - * @return array X, Y as a pair of integers. - * @access private - */ - protected function chompCoordinates(&$url) { - if (preg_match('/(.*)\?(\d+),(\d+)$/', $url, $matches)) { - $url = $matches[1]; - return array((integer)$matches[2], (integer)$matches[3]); - } - return array(false, false); - } - - /** - * Extracts the scheme part of an incoming URL. - * @param string $url URL so far. The scheme will be - * removed. - * @return string Scheme part or false. - * @access private - */ - protected function chompScheme(&$url) { - if (preg_match('#^([^/:]*):(//)(.*)#', $url, $matches)) { - $url = $matches[2] . $matches[3]; - return $matches[1]; - } - return false; - } - - /** - * Extracts the username and password from the - * incoming URL. The // prefix will be reattached - * to the URL after the doublet is extracted. - * @param string $url URL so far. The username and - * password are removed. - * @return array Two item list of username and - * password. Will urldecode() them. - * @access private - */ - protected function chompLogin(&$url) { - $prefix = ''; - if (preg_match('#^(//)(.*)#', $url, $matches)) { - $prefix = $matches[1]; - $url = $matches[2]; - } - if (preg_match('#^([^/]*)@(.*)#', $url, $matches)) { - $url = $prefix . $matches[2]; - $parts = explode(":", $matches[1]); - return array( - urldecode($parts[0]), - isset($parts[1]) ? urldecode($parts[1]) : false); - } - $url = $prefix . $url; - return array(false, false); - } - - /** - * Extracts the host part of an incoming URL. - * Includes the port number part. Will extract - * the host if it starts with // or it has - * a top level domain or it has at least two - * dots. - * @param string $url URL so far. The host will be - * removed. - * @return string Host part guess or false. - * @access private - */ - protected function chompHost(&$url) { - if (preg_match('!^(//)(.*?)(/.*|\?.*|#.*|$)!', $url, $matches)) { - $url = $matches[3]; - return $matches[2]; - } - if (preg_match('!(.*?)(\.\./|\./|/|\?|#|$)(.*)!', $url, $matches)) { - $tlds = SimpleUrl::getAllTopLevelDomains(); - if (preg_match('/[a-z0-9\-]+\.(' . $tlds . ')/i', $matches[1])) { - $url = $matches[2] . $matches[3]; - return $matches[1]; - } elseif (preg_match('/[a-z0-9\-]+\.[a-z0-9\-]+\.[a-z0-9\-]+/i', $matches[1])) { - $url = $matches[2] . $matches[3]; - return $matches[1]; - } - } - return false; - } - - /** - * Extracts the path information from the incoming - * URL. Strips this path from the URL. - * @param string $url URL so far. The host will be - * removed. - * @return string Path part or '/'. - * @access private - */ - protected function chompPath(&$url) { - if (preg_match('/(.*?)(\?|#|$)(.*)/', $url, $matches)) { - $url = $matches[2] . $matches[3]; - return ($matches[1] ? $matches[1] : ''); - } - return ''; - } - - /** - * Strips off the request data. - * @param string $url URL so far. The request will be - * removed. - * @return string Raw request part. - * @access private - */ - protected function chompRequest(&$url) { - if (preg_match('/\?(.*?)(#|$)(.*)/', $url, $matches)) { - $url = $matches[2] . $matches[3]; - return $matches[1]; - } - return ''; - } - - /** - * Breaks the request down into an object. - * @param string $raw Raw request. - * @return SimpleFormEncoding Parsed data. - * @access private - */ - protected function parseRequest($raw) { - $this->raw = $raw; - $request = new SimpleGetEncoding(); - foreach (explode("&", $raw) as $pair) { - if (preg_match('/(.*?)=(.*)/', $pair, $matches)) { - $request->add(urldecode($matches[1]), urldecode($matches[2])); - } elseif ($pair) { - $request->add(urldecode($pair), ''); - } - } - return $request; - } - - /** - * Accessor for protocol part. - * @param string $default Value to use if not present. - * @return string Scheme name, e.g "http". - * @access public - */ - function getScheme($default = false) { - return $this->scheme ? $this->scheme : $default; - } - - /** - * Accessor for user name. - * @return string Username preceding host. - * @access public - */ - function getUsername() { - return $this->username; - } - - /** - * Accessor for password. - * @return string Password preceding host. - * @access public - */ - function getPassword() { - return $this->password; - } - - /** - * Accessor for hostname and port. - * @param string $default Value to use if not present. - * @return string Hostname only. - * @access public - */ - function getHost($default = false) { - return $this->host ? $this->host : $default; - } - - /** - * Accessor for top level domain. - * @return string Last part of host. - * @access public - */ - function getTld() { - $path_parts = pathinfo($this->getHost()); - return (isset($path_parts['extension']) ? $path_parts['extension'] : false); - } - - /** - * Accessor for port number. - * @return integer TCP/IP port number. - * @access public - */ - function getPort() { - return $this->port; - } - - /** - * Accessor for path. - * @return string Full path including leading slash if implied. - * @access public - */ - function getPath() { - if (! $this->path && $this->host) { - return '/'; - } - return $this->path; - } - - /** - * Accessor for page if any. This may be a - * directory name if ambiguious. - * @return Page name. - * @access public - */ - function getPage() { - if (! preg_match('/([^\/]*?)$/', $this->getPath(), $matches)) { - return false; - } - return $matches[1]; - } - - /** - * Gets the path to the page. - * @return string Path less the page. - * @access public - */ - function getBasePath() { - if (! preg_match('/(.*\/)[^\/]*?$/', $this->getPath(), $matches)) { - return false; - } - return $matches[1]; - } - - /** - * Accessor for fragment at end of URL after the "#". - * @return string Part after "#". - * @access public - */ - function getFragment() { - return $this->fragment; - } - - /** - * Sets image coordinates. Set to false to clear - * them. - * @param integer $x Horizontal position. - * @param integer $y Vertical position. - * @access public - */ - function setCoordinates($x = false, $y = false) { - if (($x === false) || ($y === false)) { - $this->x = $this->y = false; - return; - } - $this->x = (integer)$x; - $this->y = (integer)$y; - } - - /** - * Accessor for horizontal image coordinate. - * @return integer X value. - * @access public - */ - function getX() { - return $this->x; - } - - /** - * Accessor for vertical image coordinate. - * @return integer Y value. - * @access public - */ - function getY() { - return $this->y; - } - - /** - * Accessor for current request parameters - * in URL string form. Will return teh original request - * if at all possible even if it doesn't make much - * sense. - * @return string Form is string "?a=1&b=2", etc. - * @access public - */ - function getEncodedRequest() { - if ($this->raw) { - $encoded = $this->raw; - } else { - $encoded = $this->request->asUrlRequest(); - } - if ($encoded) { - return '?' . preg_replace('/^\?/', '', $encoded); - } - return ''; - } - - /** - * Adds an additional parameter to the request. - * @param string $key Name of parameter. - * @param string $value Value as string. - * @access public - */ - function addRequestParameter($key, $value) { - $this->raw = false; - $this->request->add($key, $value); - } - - /** - * Adds additional parameters to the request. - * @param hash/SimpleFormEncoding $parameters Additional - * parameters. - * @access public - */ - function addRequestParameters($parameters) { - $this->raw = false; - $this->request->merge($parameters); - } - - /** - * Clears down all parameters. - * @access public - */ - function clearRequest() { - $this->raw = false; - $this->request = new SimpleGetEncoding(); - } - - /** - * Gets the frame target if present. Although - * not strictly part of the URL specification it - * acts as similarily to the browser. - * @return boolean/string Frame name or false if none. - * @access public - */ - function getTarget() { - return $this->target; - } - - /** - * Attaches a frame target. - * @param string $frame Name of frame. - * @access public - */ - function setTarget($frame) { - $this->raw = false; - $this->target = $frame; - } - - /** - * Renders the URL back into a string. - * @return string URL in canonical form. - * @access public - */ - function asString() { - $path = $this->path; - $scheme = $identity = $host = $port = $encoded = $fragment = ''; - if ($this->username && $this->password) { - $identity = $this->username . ':' . $this->password . '@'; - } - if ($this->getHost()) { - $scheme = $this->getScheme() ? $this->getScheme() : 'http'; - $scheme .= '://'; - $host = $this->getHost(); - } elseif ($this->getScheme() === 'file') { - // Safest way; otherwise, file URLs on Windows have an extra - // leading slash. It might be possible to convert file:// - // URIs to local file paths, but that requires more research. - $scheme = 'file://'; - } - if ($this->getPort() && $this->getPort() != 80 ) { - $port = ':'.$this->getPort(); - } - - if (substr($this->path, 0, 1) == '/') { - $path = $this->normalisePath($this->path); - } - $encoded = $this->getEncodedRequest(); - $fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; - $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); - return "$scheme$identity$host$port$path$encoded$fragment$coords"; - } - - /** - * Replaces unknown sections to turn a relative - * URL into an absolute one. The base URL can - * be either a string or a SimpleUrl object. - * @param string/SimpleUrl $base Base URL. - * @access public - */ - function makeAbsolute($base) { - if (! is_object($base)) { - $base = new SimpleUrl($base); - } - if ($this->getHost()) { - $scheme = $this->getScheme(); - $host = $this->getHost(); - $port = $this->getPort() ? ':' . $this->getPort() : ''; - $identity = $this->getIdentity() ? $this->getIdentity() . '@' : ''; - if (! $identity) { - $identity = $base->getIdentity() ? $base->getIdentity() . '@' : ''; - } - } else { - $scheme = $base->getScheme(); - $host = $base->getHost(); - $port = $base->getPort() ? ':' . $base->getPort() : ''; - $identity = $base->getIdentity() ? $base->getIdentity() . '@' : ''; - } - $path = $this->normalisePath($this->extractAbsolutePath($base)); - $encoded = $this->getEncodedRequest(); - $fragment = $this->getFragment() ? '#'. $this->getFragment() : ''; - $coords = $this->getX() === false ? '' : '?' . $this->getX() . ',' . $this->getY(); - return new SimpleUrl("$scheme://$identity$host$port$path$encoded$fragment$coords"); - } - - /** - * Replaces unknown sections of the path with base parts - * to return a complete absolute one. - * @param string/SimpleUrl $base Base URL. - * @param string Absolute path. - * @access private - */ - protected function extractAbsolutePath($base) { - if ($this->getHost()) { - return $this->path; - } - if (! $this->isRelativePath($this->path)) { - return $this->path; - } - if ($this->path) { - return $base->getBasePath() . $this->path; - } - return $base->getPath(); - } - - /** - * Simple test to see if a path part is relative. - * @param string $path Path to test. - * @return boolean True if starts with a "/". - * @access private - */ - protected function isRelativePath($path) { - return (substr($path, 0, 1) != '/'); - } - - /** - * Extracts the username and password for use in rendering - * a URL. - * @return string/boolean Form of username:password or false. - * @access public - */ - function getIdentity() { - if ($this->username && $this->password) { - return $this->username . ':' . $this->password; - } - return false; - } - - /** - * Replaces . and .. sections of the path. - * @param string $path Unoptimised path. - * @return string Path with dots removed if possible. - * @access public - */ - function normalisePath($path) { - $path = preg_replace('|/\./|', '/', $path); - return preg_replace('|/[^/]+/\.\./|', '/', $path); - } - - /** - * A pipe seperated list of all TLDs that result in two part - * domain names. - * @return string Pipe separated list. - * @access public - */ - static function getAllTopLevelDomains() { - return 'com|edu|net|org|gov|mil|int|biz|info|name|pro|aero|coop|museum'; - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/user_agent.php b/3rdparty/simpletest/user_agent.php deleted file mode 100644 index ea5360200174e45b96bb11305a94f3242fe3fbed..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/user_agent.php +++ /dev/null @@ -1,328 +0,0 @@ -<?php -/** - * Base include file for SimpleTest - * @package SimpleTest - * @subpackage WebTester - * @version $Id: user_agent.php 2039 2011-11-30 18:16:15Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/cookies.php'); -require_once(dirname(__FILE__) . '/http.php'); -require_once(dirname(__FILE__) . '/encoding.php'); -require_once(dirname(__FILE__) . '/authentication.php'); -/**#@-*/ - -if (! defined('DEFAULT_MAX_REDIRECTS')) { - define('DEFAULT_MAX_REDIRECTS', 3); -} -if (! defined('DEFAULT_CONNECTION_TIMEOUT')) { - define('DEFAULT_CONNECTION_TIMEOUT', 15); -} - -/** - * Fetches web pages whilst keeping track of - * cookies and authentication. - * @package SimpleTest - * @subpackage WebTester - */ -class SimpleUserAgent { - private $cookie_jar; - private $cookies_enabled = true; - private $authenticator; - private $max_redirects = DEFAULT_MAX_REDIRECTS; - private $proxy = false; - private $proxy_username = false; - private $proxy_password = false; - private $connection_timeout = DEFAULT_CONNECTION_TIMEOUT; - private $additional_headers = array(); - - /** - * Starts with no cookies, realms or proxies. - * @access public - */ - function __construct() { - $this->cookie_jar = new SimpleCookieJar(); - $this->authenticator = new SimpleAuthenticator(); - } - - /** - * Removes expired and temporary cookies as if - * the browser was closed and re-opened. Authorisation - * has to be obtained again as well. - * @param string/integer $date Time when session restarted. - * If omitted then all persistent - * cookies are kept. - * @access public - */ - function restart($date = false) { - $this->cookie_jar->restartSession($date); - $this->authenticator->restartSession(); - } - - /** - * Adds a header to every fetch. - * @param string $header Header line to add to every - * request until cleared. - * @access public - */ - function addHeader($header) { - $this->additional_headers[] = $header; - } - - /** - * Ages the cookies by the specified time. - * @param integer $interval Amount in seconds. - * @access public - */ - function ageCookies($interval) { - $this->cookie_jar->agePrematurely($interval); - } - - /** - * Sets an additional cookie. If a cookie has - * the same name and path it is replaced. - * @param string $name Cookie key. - * @param string $value Value of cookie. - * @param string $host Host upon which the cookie is valid. - * @param string $path Cookie path if not host wide. - * @param string $expiry Expiry date. - * @access public - */ - function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { - $this->cookie_jar->setCookie($name, $value, $host, $path, $expiry); - } - - /** - * Reads the most specific cookie value from the - * browser cookies. - * @param string $host Host to search. - * @param string $path Applicable path. - * @param string $name Name of cookie to read. - * @return string False if not present, else the - * value as a string. - * @access public - */ - function getCookieValue($host, $path, $name) { - return $this->cookie_jar->getCookieValue($host, $path, $name); - } - - /** - * Reads the current cookies within the base URL. - * @param string $name Key of cookie to find. - * @param SimpleUrl $base Base URL to search from. - * @return string/boolean Null if there is no base URL, false - * if the cookie is not set. - * @access public - */ - function getBaseCookieValue($name, $base) { - if (! $base) { - return null; - } - return $this->getCookieValue($base->getHost(), $base->getPath(), $name); - } - - /** - * Switches off cookie sending and recieving. - * @access public - */ - function ignoreCookies() { - $this->cookies_enabled = false; - } - - /** - * Switches back on the cookie sending and recieving. - * @access public - */ - function useCookies() { - $this->cookies_enabled = true; - } - - /** - * Sets the socket timeout for opening a connection. - * @param integer $timeout Maximum time in seconds. - * @access public - */ - function setConnectionTimeout($timeout) { - $this->connection_timeout = $timeout; - } - - /** - * Sets the maximum number of redirects before - * a page will be loaded anyway. - * @param integer $max Most hops allowed. - * @access public - */ - function setMaximumRedirects($max) { - $this->max_redirects = $max; - } - - /** - * Sets proxy to use on all requests for when - * testing from behind a firewall. Set URL - * to false to disable. - * @param string $proxy Proxy URL. - * @param string $username Proxy username for authentication. - * @param string $password Proxy password for authentication. - * @access public - */ - function useProxy($proxy, $username, $password) { - if (! $proxy) { - $this->proxy = false; - return; - } - if ((strncmp($proxy, 'http://', 7) != 0) && (strncmp($proxy, 'https://', 8) != 0)) { - $proxy = 'http://'. $proxy; - } - $this->proxy = new SimpleUrl($proxy); - $this->proxy_username = $username; - $this->proxy_password = $password; - } - - /** - * Test to see if the redirect limit is passed. - * @param integer $redirects Count so far. - * @return boolean True if over. - * @access private - */ - protected function isTooManyRedirects($redirects) { - return ($redirects > $this->max_redirects); - } - - /** - * Sets the identity for the current realm. - * @param string $host Host to which realm applies. - * @param string $realm Full name of realm. - * @param string $username Username for realm. - * @param string $password Password for realm. - * @access public - */ - function setIdentity($host, $realm, $username, $password) { - $this->authenticator->setIdentityForRealm($host, $realm, $username, $password); - } - - /** - * Fetches a URL as a response object. Will keep trying if redirected. - * It will also collect authentication realm information. - * @param string/SimpleUrl $url Target to fetch. - * @param SimpleEncoding $encoding Additional parameters for request. - * @return SimpleHttpResponse Hopefully the target page. - * @access public - */ - function fetchResponse($url, $encoding) { - if ($encoding->getMethod() != 'POST') { - $url->addRequestParameters($encoding); - $encoding->clear(); - } - $response = $this->fetchWhileRedirected($url, $encoding); - if ($headers = $response->getHeaders()) { - if ($headers->isChallenge()) { - $this->authenticator->addRealm( - $url, - $headers->getAuthentication(), - $headers->getRealm()); - } - } - return $response; - } - - /** - * Fetches the page until no longer redirected or - * until the redirect limit runs out. - * @param SimpleUrl $url Target to fetch. - * @param SimpelFormEncoding $encoding Additional parameters for request. - * @return SimpleHttpResponse Hopefully the target page. - * @access private - */ - protected function fetchWhileRedirected($url, $encoding) { - $redirects = 0; - do { - $response = $this->fetch($url, $encoding); - if ($response->isError()) { - return $response; - } - $headers = $response->getHeaders(); - if ($this->cookies_enabled) { - $headers->writeCookiesToJar($this->cookie_jar, $url); - } - if (! $headers->isRedirect()) { - break; - } - $location = new SimpleUrl($headers->getLocation()); - $url = $location->makeAbsolute($url); - $encoding = new SimpleGetEncoding(); - } while (! $this->isTooManyRedirects(++$redirects)); - return $response; - } - - /** - * Actually make the web request. - * @param SimpleUrl $url Target to fetch. - * @param SimpleFormEncoding $encoding Additional parameters for request. - * @return SimpleHttpResponse Headers and hopefully content. - * @access protected - */ - protected function fetch($url, $encoding) { - $request = $this->createRequest($url, $encoding); - return $request->fetch($this->connection_timeout); - } - - /** - * Creates a full page request. - * @param SimpleUrl $url Target to fetch as url object. - * @param SimpleFormEncoding $encoding POST/GET parameters. - * @return SimpleHttpRequest New request. - * @access private - */ - protected function createRequest($url, $encoding) { - $request = $this->createHttpRequest($url, $encoding); - $this->addAdditionalHeaders($request); - if ($this->cookies_enabled) { - $request->readCookiesFromJar($this->cookie_jar, $url); - } - $this->authenticator->addHeaders($request, $url); - return $request; - } - - /** - * Builds the appropriate HTTP request object. - * @param SimpleUrl $url Target to fetch as url object. - * @param SimpleFormEncoding $parameters POST/GET parameters. - * @return SimpleHttpRequest New request object. - * @access protected - */ - protected function createHttpRequest($url, $encoding) { - return new SimpleHttpRequest($this->createRoute($url), $encoding); - } - - /** - * Sets up either a direct route or via a proxy. - * @param SimpleUrl $url Target to fetch as url object. - * @return SimpleRoute Route to take to fetch URL. - * @access protected - */ - protected function createRoute($url) { - if ($this->proxy) { - return new SimpleProxyRoute( - $url, - $this->proxy, - $this->proxy_username, - $this->proxy_password); - } - return new SimpleRoute($url); - } - - /** - * Adds additional manual headers. - * @param SimpleHttpRequest $request Outgoing request. - * @access private - */ - protected function addAdditionalHeaders(&$request) { - foreach ($this->additional_headers as $header) { - $request->addHeaderLine($header); - } - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/web_tester.php b/3rdparty/simpletest/web_tester.php deleted file mode 100644 index a17230e7b33c4b35f28c39fbf7ea39f6c5e04a22..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/web_tester.php +++ /dev/null @@ -1,1532 +0,0 @@ -<?php -/** - * Base include file for SimpleTest. - * @package SimpleTest - * @subpackage WebTester - * @version $Id: web_tester.php 2013 2011-04-29 09:29:45Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/test_case.php'); -require_once(dirname(__FILE__) . '/browser.php'); -require_once(dirname(__FILE__) . '/page.php'); -require_once(dirname(__FILE__) . '/expectation.php'); -/**#@-*/ - -/** - * Test for an HTML widget value match. - * @package SimpleTest - * @subpackage WebTester - */ -class FieldExpectation extends SimpleExpectation { - private $value; - - /** - * Sets the field value to compare against. - * @param mixed $value Test value to match. Can be an - * expectation for say pattern matching. - * @param string $message Optiona message override. Can use %s as - * a placeholder for the original message. - * @access public - */ - function __construct($value, $message = '%s') { - parent::__construct($message); - if (is_array($value)) { - sort($value); - } - $this->value = $value; - } - - /** - * Tests the expectation. True if it matches - * a string value or an array value in any order. - * @param mixed $compare Comparison value. False for - * an unset field. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - if ($this->value === false) { - return ($compare === false); - } - if ($this->isSingle($this->value)) { - return $this->testSingle($compare); - } - if (is_array($this->value)) { - return $this->testMultiple($compare); - } - return false; - } - - /** - * Tests for valid field comparisons with a single option. - * @param mixed $value Value to type check. - * @return boolean True if integer, string or float. - * @access private - */ - protected function isSingle($value) { - return is_string($value) || is_integer($value) || is_float($value); - } - - /** - * String comparison for simple field with a single option. - * @param mixed $compare String to test against. - * @returns boolean True if matching. - * @access private - */ - protected function testSingle($compare) { - if (is_array($compare) && count($compare) == 1) { - $compare = $compare[0]; - } - if (! $this->isSingle($compare)) { - return false; - } - return ($this->value == $compare); - } - - /** - * List comparison for multivalue field. - * @param mixed $compare List in any order to test against. - * @returns boolean True if matching. - * @access private - */ - protected function testMultiple($compare) { - if (is_string($compare)) { - $compare = array($compare); - } - if (! is_array($compare)) { - return false; - } - sort($compare); - return ($this->value === $compare); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $dumper = $this->getDumper(); - if (is_array($compare)) { - sort($compare); - } - if ($this->test($compare)) { - return "Field expectation [" . $dumper->describeValue($this->value) . "]"; - } else { - return "Field expectation [" . $dumper->describeValue($this->value) . - "] fails with [" . - $dumper->describeValue($compare) . "] " . - $dumper->describeDifference($this->value, $compare); - } - } -} - -/** - * Test for a specific HTTP header within a header block. - * @package SimpleTest - * @subpackage WebTester - */ -class HttpHeaderExpectation extends SimpleExpectation { - private $expected_header; - private $expected_value; - - /** - * Sets the field and value to compare against. - * @param string $header Case insenstive trimmed header name. - * @param mixed $value Optional value to compare. If not - * given then any value will match. If - * an expectation object then that will - * be used instead. - * @param string $message Optiona message override. Can use %s as - * a placeholder for the original message. - */ - function __construct($header, $value = false, $message = '%s') { - parent::__construct($message); - $this->expected_header = $this->normaliseHeader($header); - $this->expected_value = $value; - } - - /** - * Accessor for aggregated object. - * @return mixed Expectation set in constructor. - * @access protected - */ - protected function getExpectation() { - return $this->expected_value; - } - - /** - * Removes whitespace at ends and case variations. - * @param string $header Name of header. - * @param string Trimmed and lowecased header - * name. - * @access private - */ - protected function normaliseHeader($header) { - return strtolower(trim($header)); - } - - /** - * Tests the expectation. True if it matches - * a string value or an array value in any order. - * @param mixed $compare Raw header block to search. - * @return boolean True if header present. - * @access public - */ - function test($compare) { - return is_string($this->findHeader($compare)); - } - - /** - * Searches the incoming result. Will extract the matching - * line as text. - * @param mixed $compare Raw header block to search. - * @return string Matching header line. - * @access protected - */ - protected function findHeader($compare) { - $lines = explode("\r\n", $compare); - foreach ($lines as $line) { - if ($this->testHeaderLine($line)) { - return $line; - } - } - return false; - } - - /** - * Compares a single header line against the expectation. - * @param string $line A single line to compare. - * @return boolean True if matched. - * @access private - */ - protected function testHeaderLine($line) { - if (count($parsed = explode(':', $line, 2)) < 2) { - return false; - } - list($header, $value) = $parsed; - if ($this->normaliseHeader($header) != $this->expected_header) { - return false; - } - return $this->testHeaderValue($value, $this->expected_value); - } - - /** - * Tests the value part of the header. - * @param string $value Value to test. - * @param mixed $expected Value to test against. - * @return boolean True if matched. - * @access protected - */ - protected function testHeaderValue($value, $expected) { - if ($expected === false) { - return true; - } - if (SimpleExpectation::isExpectation($expected)) { - return $expected->test(trim($value)); - } - return (trim($value) == trim($expected)); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Raw header block to search. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if (SimpleExpectation::isExpectation($this->expected_value)) { - $message = $this->expected_value->overlayMessage($compare, $this->getDumper()); - } else { - $message = $this->expected_header . - ($this->expected_value ? ': ' . $this->expected_value : ''); - } - if (is_string($line = $this->findHeader($compare))) { - return "Searching for header [$message] found [$line]"; - } else { - return "Failed to find header [$message]"; - } - } -} - -/** - * Test for a specific HTTP header within a header block that - * should not be found. - * @package SimpleTest - * @subpackage WebTester - */ -class NoHttpHeaderExpectation extends HttpHeaderExpectation { - private $expected_header; - private $expected_value; - - /** - * Sets the field and value to compare against. - * @param string $unwanted Case insenstive trimmed header name. - * @param string $message Optiona message override. Can use %s as - * a placeholder for the original message. - */ - function __construct($unwanted, $message = '%s') { - parent::__construct($unwanted, false, $message); - } - - /** - * Tests that the unwanted header is not found. - * @param mixed $compare Raw header block to search. - * @return boolean True if header present. - * @access public - */ - function test($compare) { - return ($this->findHeader($compare) === false); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Raw header block to search. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - $expectation = $this->getExpectation(); - if (is_string($line = $this->findHeader($compare))) { - return "Found unwanted header [$expectation] with [$line]"; - } else { - return "Did not find unwanted header [$expectation]"; - } - } -} - -/** - * Test for a text substring. - * @package SimpleTest - * @subpackage UnitTester - */ -class TextExpectation extends SimpleExpectation { - private $substring; - - /** - * Sets the value to compare against. - * @param string $substring Text to search for. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($substring, $message = '%s') { - parent::__construct($message); - $this->substring = $substring; - } - - /** - * Accessor for the substring. - * @return string Text to match. - * @access protected - */ - protected function getSubstring() { - return $this->substring; - } - - /** - * Tests the expectation. True if the text contains the - * substring. - * @param string $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return (strpos($compare, $this->substring) !== false); - } - - /** - * Returns a human readable test message. - * @param mixed $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - return $this->describeTextMatch($this->getSubstring(), $compare); - } else { - $dumper = $this->getDumper(); - return "Text [" . $this->getSubstring() . - "] not detected in [" . - $dumper->describeValue($compare) . "]"; - } - } - - /** - * Describes a pattern match including the string - * found and it's position. - * @param string $substring Text to search for. - * @param string $subject Subject to search. - * @access protected - */ - protected function describeTextMatch($substring, $subject) { - $position = strpos($subject, $substring); - $dumper = $this->getDumper(); - return "Text [$substring] detected at character [$position] in [" . - $dumper->describeValue($subject) . "] in region [" . - $dumper->clipString($subject, 100, $position) . "]"; - } -} - -/** - * Fail if a substring is detected within the - * comparison text. - * @package SimpleTest - * @subpackage UnitTester - */ -class NoTextExpectation extends TextExpectation { - - /** - * Sets the reject pattern - * @param string $substring Text to search for. - * @param string $message Customised message on failure. - * @access public - */ - function __construct($substring, $message = '%s') { - parent::__construct($substring, $message); - } - - /** - * Tests the expectation. False if the substring appears - * in the text. - * @param string $compare Comparison value. - * @return boolean True if correct. - * @access public - */ - function test($compare) { - return ! parent::test($compare); - } - - /** - * Returns a human readable test message. - * @param string $compare Comparison value. - * @return string Description of success - * or failure. - * @access public - */ - function testMessage($compare) { - if ($this->test($compare)) { - $dumper = $this->getDumper(); - return "Text [" . $this->getSubstring() . - "] not detected in [" . - $dumper->describeValue($compare) . "]"; - } else { - return $this->describeTextMatch($this->getSubstring(), $compare); - } - } -} - -/** - * Test case for testing of web pages. Allows - * fetching of pages, parsing of HTML and - * submitting forms. - * @package SimpleTest - * @subpackage WebTester - */ -class WebTestCase extends SimpleTestCase { - private $browser; - private $ignore_errors = false; - - /** - * Creates an empty test case. Should be subclassed - * with test methods for a functional test case. - * @param string $label Name of test case. Will use - * the class name if none specified. - * @access public - */ - function __construct($label = false) { - parent::__construct($label); - } - - /** - * Announces the start of the test. - * @param string $method Test method just started. - * @access public - */ - function before($method) { - parent::before($method); - $this->setBrowser($this->createBrowser()); - } - - /** - * Announces the end of the test. Includes private clean up. - * @param string $method Test method just finished. - * @access public - */ - function after($method) { - $this->unsetBrowser(); - parent::after($method); - } - - /** - * Gets a current browser reference for setting - * special expectations or for detailed - * examination of page fetches. - * @return SimpleBrowser Current test browser object. - * @access public - */ - function getBrowser() { - return $this->browser; - } - - /** - * Gets a current browser reference for setting - * special expectations or for detailed - * examination of page fetches. - * @param SimpleBrowser $browser New test browser object. - * @access public - */ - function setBrowser($browser) { - return $this->browser = $browser; - } - - /** - * Sets the HTML parser to use within this browser. - * @param object The parser, one of SimplePHPPageBuilder or - * SimpleTidyPageBuilder. - */ - function setParser($parser) { - $this->browser->setParser($parser); - } - - /** - * Clears the current browser reference to help the - * PHP garbage collector. - * @access public - */ - function unsetBrowser() { - unset($this->browser); - } - - /** - * Creates a new default web browser object. - * Will be cleared at the end of the test method. - * @return TestBrowser New browser. - * @access public - */ - function createBrowser() { - return new SimpleBrowser(); - } - - /** - * Gets the last response error. - * @return string Last low level HTTP error. - * @access public - */ - function getTransportError() { - return $this->browser->getTransportError(); - } - - /** - * Accessor for the currently selected URL. - * @return string Current location or false if - * no page yet fetched. - * @access public - */ - function getUrl() { - return $this->browser->getUrl(); - } - - /** - * Dumps the current request for debugging. - * @access public - */ - function showRequest() { - $this->dump($this->browser->getRequest()); - } - - /** - * Dumps the current HTTP headers for debugging. - * @access public - */ - function showHeaders() { - $this->dump($this->browser->getHeaders()); - } - - /** - * Dumps the current HTML source for debugging. - * @access public - */ - function showSource() { - $this->dump($this->browser->getContent()); - } - - /** - * Dumps the visible text only for debugging. - * @access public - */ - function showText() { - $this->dump(wordwrap($this->browser->getContentAsText(), 80)); - } - - /** - * Simulates the closing and reopening of the browser. - * Temporary cookies will be discarded and timed - * cookies will be expired if later than the - * specified time. - * @param string/integer $date Time when session restarted. - * If ommitted then all persistent - * cookies are kept. Time is either - * Cookie format string or timestamp. - * @access public - */ - function restart($date = false) { - if ($date === false) { - $date = time(); - } - $this->browser->restart($date); - } - - /** - * Moves cookie expiry times back into the past. - * Useful for testing timeouts and expiries. - * @param integer $interval Amount to age in seconds. - * @access public - */ - function ageCookies($interval) { - $this->browser->ageCookies($interval); - } - - /** - * Disables frames support. Frames will not be fetched - * and the frameset page will be used instead. - * @access public - */ - function ignoreFrames() { - $this->browser->ignoreFrames(); - } - - /** - * Switches off cookie sending and recieving. - * @access public - */ - function ignoreCookies() { - $this->browser->ignoreCookies(); - } - - /** - * Skips errors for the next request only. You might - * want to confirm that a page is unreachable for - * example. - * @access public - */ - function ignoreErrors() { - $this->ignore_errors = true; - } - - /** - * Issues a fail if there is a transport error anywhere - * in the current frameset. Only one such error is - * reported. - * @param string/boolean $result HTML or failure. - * @return string/boolean $result Passes through result. - * @access private - */ - protected function failOnError($result) { - if (! $this->ignore_errors) { - if ($error = $this->browser->getTransportError()) { - $this->fail($error); - } - } - $this->ignore_errors = false; - return $result; - } - - /** - * Adds a header to every fetch. - * @param string $header Header line to add to every - * request until cleared. - * @access public - */ - function addHeader($header) { - $this->browser->addHeader($header); - } - - /** - * Sets the maximum number of redirects before - * the web page is loaded regardless. - * @param integer $max Maximum hops. - * @access public - */ - function setMaximumRedirects($max) { - if (! $this->browser) { - trigger_error( - 'Can only set maximum redirects in a test method, setUp() or tearDown()'); - } - $this->browser->setMaximumRedirects($max); - } - - /** - * Sets the socket timeout for opening a connection and - * receiving at least one byte of information. - * @param integer $timeout Maximum time in seconds. - * @access public - */ - function setConnectionTimeout($timeout) { - $this->browser->setConnectionTimeout($timeout); - } - - /** - * Sets proxy to use on all requests for when - * testing from behind a firewall. Set URL - * to false to disable. - * @param string $proxy Proxy URL. - * @param string $username Proxy username for authentication. - * @param string $password Proxy password for authentication. - * @access public - */ - function useProxy($proxy, $username = false, $password = false) { - $this->browser->useProxy($proxy, $username, $password); - } - - /** - * Fetches a page into the page buffer. If - * there is no base for the URL then the - * current base URL is used. After the fetch - * the base URL reflects the new location. - * @param string $url URL to fetch. - * @param hash $parameters Optional additional GET data. - * @return boolean/string Raw page on success. - * @access public - */ - function get($url, $parameters = false) { - return $this->failOnError($this->browser->get($url, $parameters)); - } - - /** - * Fetches a page by POST into the page buffer. - * If there is no base for the URL then the - * current base URL is used. After the fetch - * the base URL reflects the new location. - * @param string $url URL to fetch. - * @param mixed $parameters Optional POST parameters or content body to send - * @param string $content_type Content type of provided body - * @return boolean/string Raw page on success. - * @access public - */ - function post($url, $parameters = false, $content_type = false) { - return $this->failOnError($this->browser->post($url, $parameters, $content_type)); - } - - /** - * Fetches a page by PUT into the page buffer. - * If there is no base for the URL then the - * current base URL is used. After the fetch - * the base URL reflects the new location. - * @param string $url URL to fetch. - * @param mixed $body Optional content body to send - * @param string $content_type Content type of provided body - * @return boolean/string Raw page on success. - * @access public - */ - function put($url, $body = false, $content_type = false) { - return $this->failOnError($this->browser->put($url, $body, $content_type)); - } - - /** - * Fetches a page by a DELETE request - * @param string $url URL to fetch. - * @param hash $parameters Optional additional parameters. - * @return boolean/string Raw page on success. - * @access public - */ - function delete($url, $parameters = false) { - return $this->failOnError($this->browser->delete($url, $parameters)); - } - - - /** - * Does a HTTP HEAD fetch, fetching only the page - * headers. The current base URL is unchanged by this. - * @param string $url URL to fetch. - * @param hash $parameters Optional additional GET data. - * @return boolean True on success. - * @access public - */ - function head($url, $parameters = false) { - return $this->failOnError($this->browser->head($url, $parameters)); - } - - /** - * Equivalent to hitting the retry button on the - * browser. Will attempt to repeat the page fetch. - * @return boolean True if fetch succeeded. - * @access public - */ - function retry() { - return $this->failOnError($this->browser->retry()); - } - - /** - * Equivalent to hitting the back button on the - * browser. - * @return boolean True if history entry and - * fetch succeeded. - * @access public - */ - function back() { - return $this->failOnError($this->browser->back()); - } - - /** - * Equivalent to hitting the forward button on the - * browser. - * @return boolean True if history entry and - * fetch succeeded. - * @access public - */ - function forward() { - return $this->failOnError($this->browser->forward()); - } - - /** - * Retries a request after setting the authentication - * for the current realm. - * @param string $username Username for realm. - * @param string $password Password for realm. - * @return boolean/string HTML on successful fetch. Note - * that authentication may still have - * failed. - * @access public - */ - function authenticate($username, $password) { - return $this->failOnError( - $this->browser->authenticate($username, $password)); - } - - /** - * Gets the cookie value for the current browser context. - * @param string $name Name of cookie. - * @return string Value of cookie or false if unset. - * @access public - */ - function getCookie($name) { - return $this->browser->getCurrentCookieValue($name); - } - - /** - * Sets a cookie in the current browser. - * @param string $name Name of cookie. - * @param string $value Cookie value. - * @param string $host Host upon which the cookie is valid. - * @param string $path Cookie path if not host wide. - * @param string $expiry Expiry date. - * @access public - */ - function setCookie($name, $value, $host = false, $path = '/', $expiry = false) { - $this->browser->setCookie($name, $value, $host, $path, $expiry); - } - - /** - * Accessor for current frame focus. Will be - * false if no frame has focus. - * @return integer/string/boolean Label if any, otherwise - * the position in the frameset - * or false if none. - * @access public - */ - function getFrameFocus() { - return $this->browser->getFrameFocus(); - } - - /** - * Sets the focus by index. The integer index starts from 1. - * @param integer $choice Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocusByIndex($choice) { - return $this->browser->setFrameFocusByIndex($choice); - } - - /** - * Sets the focus by name. - * @param string $name Chosen frame. - * @return boolean True if frame exists. - * @access public - */ - function setFrameFocus($name) { - return $this->browser->setFrameFocus($name); - } - - /** - * Clears the frame focus. All frames will be searched - * for content. - * @access public - */ - function clearFrameFocus() { - return $this->browser->clearFrameFocus(); - } - - /** - * Clicks a visible text item. Will first try buttons, - * then links and then images. - * @param string $label Visible text or alt text. - * @return string/boolean Raw page or false. - * @access public - */ - function click($label) { - return $this->failOnError($this->browser->click($label)); - } - - /** - * Checks for a click target. - * @param string $label Visible text or alt text. - * @return boolean True if click target. - * @access public - */ - function assertClickable($label, $message = '%s') { - return $this->assertTrue( - $this->browser->isClickable($label), - sprintf($message, "Click target [$label] should exist")); - } - - /** - * Clicks the submit button by label. The owning - * form will be submitted by this. - * @param string $label Button label. An unlabeled - * button can be triggered by 'Submit'. - * @param hash $additional Additional form values. - * @return boolean/string Page on success, else false. - * @access public - */ - function clickSubmit($label = 'Submit', $additional = false) { - return $this->failOnError( - $this->browser->clickSubmit($label, $additional)); - } - - /** - * Clicks the submit button by name attribute. The owning - * form will be submitted by this. - * @param string $name Name attribute of button. - * @param hash $additional Additional form values. - * @return boolean/string Page on success. - * @access public - */ - function clickSubmitByName($name, $additional = false) { - return $this->failOnError( - $this->browser->clickSubmitByName($name, $additional)); - } - - /** - * Clicks the submit button by ID attribute. The owning - * form will be submitted by this. - * @param string $id ID attribute of button. - * @param hash $additional Additional form values. - * @return boolean/string Page on success. - * @access public - */ - function clickSubmitById($id, $additional = false) { - return $this->failOnError( - $this->browser->clickSubmitById($id, $additional)); - } - - /** - * Checks for a valid button label. - * @param string $label Visible text. - * @return boolean True if click target. - * @access public - */ - function assertSubmit($label, $message = '%s') { - return $this->assertTrue( - $this->browser->isSubmit($label), - sprintf($message, "Submit button [$label] should exist")); - } - - /** - * Clicks the submit image by some kind of label. Usually - * the alt tag or the nearest equivalent. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param string $label Alt attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form values. - * @return boolean/string Page on success. - * @access public - */ - function clickImage($label, $x = 1, $y = 1, $additional = false) { - return $this->failOnError( - $this->browser->clickImage($label, $x, $y, $additional)); - } - - /** - * Clicks the submit image by the name. Usually - * the alt tag or the nearest equivalent. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param string $name Name attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form values. - * @return boolean/string Page on success. - * @access public - */ - function clickImageByName($name, $x = 1, $y = 1, $additional = false) { - return $this->failOnError( - $this->browser->clickImageByName($name, $x, $y, $additional)); - } - - /** - * Clicks the submit image by ID attribute. The owning - * form will be submitted by this. Clicking outside of - * the boundary of the coordinates will result in - * a failure. - * @param integer/string $id ID attribute of button. - * @param integer $x X-coordinate of imaginary click. - * @param integer $y Y-coordinate of imaginary click. - * @param hash $additional Additional form values. - * @return boolean/string Page on success. - * @access public - */ - function clickImageById($id, $x = 1, $y = 1, $additional = false) { - return $this->failOnError( - $this->browser->clickImageById($id, $x, $y, $additional)); - } - - /** - * Checks for a valid image with atht alt text or title. - * @param string $label Visible text. - * @return boolean True if click target. - * @access public - */ - function assertImage($label, $message = '%s') { - return $this->assertTrue( - $this->browser->isImage($label), - sprintf($message, "Image with text [$label] should exist")); - } - - /** - * Submits a form by the ID. - * @param string $id Form ID. No button information - * is submitted this way. - * @return boolean/string Page on success. - * @access public - */ - function submitFormById($id, $additional = false) { - return $this->failOnError($this->browser->submitFormById($id, $additional)); - } - - /** - * Follows a link by name. Will click the first link - * found with this link text by default, or a later - * one if an index is given. Match is case insensitive - * with normalised space. - * @param string $label Text between the anchor tags. - * @param integer $index Link position counting from zero. - * @return boolean/string Page on success. - * @access public - */ - function clickLink($label, $index = 0) { - return $this->failOnError($this->browser->clickLink($label, $index)); - } - - /** - * Follows a link by id attribute. - * @param string $id ID attribute value. - * @return boolean/string Page on success. - * @access public - */ - function clickLinkById($id) { - return $this->failOnError($this->browser->clickLinkById($id)); - } - - /** - * Tests for the presence of a link label. Match is - * case insensitive with normalised space. - * @param string $label Text between the anchor tags. - * @param mixed $expected Expected URL or expectation object. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if link present. - * @access public - */ - function assertLink($label, $expected = true, $message = '%s') { - $url = $this->browser->getLink($label); - if ($expected === true || ($expected !== true && $url === false)) { - return $this->assertTrue($url !== false, sprintf($message, "Link [$label] should exist")); - } - if (! SimpleExpectation::isExpectation($expected)) { - $expected = new IdenticalExpectation($expected); - } - return $this->assert($expected, $url->asString(), sprintf($message, "Link [$label] should match")); - } - - /** - * Tests for the non-presence of a link label. Match is - * case insensitive with normalised space. - * @param string/integer $label Text between the anchor tags - * or ID attribute. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if link missing. - * @access public - */ - function assertNoLink($label, $message = '%s') { - return $this->assertTrue( - $this->browser->getLink($label) === false, - sprintf($message, "Link [$label] should not exist")); - } - - /** - * Tests for the presence of a link id attribute. - * @param string $id Id attribute value. - * @param mixed $expected Expected URL or expectation object. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if link present. - * @access public - */ - function assertLinkById($id, $expected = true, $message = '%s') { - $url = $this->browser->getLinkById($id); - if ($expected === true) { - return $this->assertTrue($url !== false, sprintf($message, "Link ID [$id] should exist")); - } - if (! SimpleExpectation::isExpectation($expected)) { - $expected = new IdenticalExpectation($expected); - } - return $this->assert($expected, $url->asString(), sprintf($message, "Link ID [$id] should match")); - } - - /** - * Tests for the non-presence of a link label. Match is - * case insensitive with normalised space. - * @param string $id Id attribute value. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if link missing. - * @access public - */ - function assertNoLinkById($id, $message = '%s') { - return $this->assertTrue( - $this->browser->getLinkById($id) === false, - sprintf($message, "Link ID [$id] should not exist")); - } - - /** - * Sets all form fields with that label, or name if there - * is no label attached. - * @param string $name Name of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setField($label, $value, $position=false) { - return $this->browser->setField($label, $value, $position); - } - - /** - * Sets all form fields with that name. - * @param string $name Name of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setFieldByName($name, $value, $position=false) { - return $this->browser->setFieldByName($name, $value, $position); - } - - /** - * Sets all form fields with that id. - * @param string/integer $id Id of field in forms. - * @param string $value New value of field. - * @return boolean True if field exists, otherwise false. - * @access public - */ - function setFieldById($id, $value) { - return $this->browser->setFieldById($id, $value); - } - - /** - * Confirms that the form element is currently set - * to the expected value. A missing form will always - * fail. If no value is given then only the existence - * of the field is checked. - * @param string $name Name of field in forms. - * @param mixed $expected Expected string/array value or - * false for unset fields. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if pass. - * @access public - */ - function assertField($label, $expected = true, $message = '%s') { - $value = $this->browser->getField($label); - return $this->assertFieldValue($label, $value, $expected, $message); - } - - /** - * Confirms that the form element is currently set - * to the expected value. A missing form element will always - * fail. If no value is given then only the existence - * of the field is checked. - * @param string $name Name of field in forms. - * @param mixed $expected Expected string/array value or - * false for unset fields. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if pass. - * @access public - */ - function assertFieldByName($name, $expected = true, $message = '%s') { - $value = $this->browser->getFieldByName($name); - return $this->assertFieldValue($name, $value, $expected, $message); - } - - /** - * Confirms that the form element is currently set - * to the expected value. A missing form will always - * fail. If no ID is given then only the existence - * of the field is checked. - * @param string/integer $id Name of field in forms. - * @param mixed $expected Expected string/array value or - * false for unset fields. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if pass. - * @access public - */ - function assertFieldById($id, $expected = true, $message = '%s') { - $value = $this->browser->getFieldById($id); - return $this->assertFieldValue($id, $value, $expected, $message); - } - - /** - * Tests the field value against the expectation. - * @param string $identifier Name, ID or label. - * @param mixed $value Current field value. - * @param mixed $expected Expected value to match. - * @param string $message Failure message. - * @return boolean True if pass - * @access protected - */ - protected function assertFieldValue($identifier, $value, $expected, $message) { - if ($expected === true) { - return $this->assertTrue( - isset($value), - sprintf($message, "Field [$identifier] should exist")); - } - if (! SimpleExpectation::isExpectation($expected)) { - $identifier = str_replace('%', '%%', $identifier); - $expected = new FieldExpectation( - $expected, - "Field [$identifier] should match with [%s]"); - } - return $this->assert($expected, $value, $message); - } - - /** - * Checks the response code against a list - * of possible values. - * @param array $responses Possible responses for a pass. - * @param string $message Message to display. Default - * can be embedded with %s. - * @return boolean True if pass. - * @access public - */ - function assertResponse($responses, $message = '%s') { - $responses = (is_array($responses) ? $responses : array($responses)); - $code = $this->browser->getResponseCode(); - $message = sprintf($message, "Expecting response in [" . - implode(", ", $responses) . "] got [$code]"); - return $this->assertTrue(in_array($code, $responses), $message); - } - - /** - * Checks the mime type against a list - * of possible values. - * @param array $types Possible mime types for a pass. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertMime($types, $message = '%s') { - $types = (is_array($types) ? $types : array($types)); - $type = $this->browser->getMimeType(); - $message = sprintf($message, "Expecting mime type in [" . - implode(", ", $types) . "] got [$type]"); - return $this->assertTrue(in_array($type, $types), $message); - } - - /** - * Attempt to match the authentication type within - * the security realm we are currently matching. - * @param string $authentication Usually basic. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertAuthentication($authentication = false, $message = '%s') { - if (! $authentication) { - $message = sprintf($message, "Expected any authentication type, got [" . - $this->browser->getAuthentication() . "]"); - return $this->assertTrue( - $this->browser->getAuthentication(), - $message); - } else { - $message = sprintf($message, "Expected authentication [$authentication] got [" . - $this->browser->getAuthentication() . "]"); - return $this->assertTrue( - strtolower($this->browser->getAuthentication()) == strtolower($authentication), - $message); - } - } - - /** - * Checks that no authentication is necessary to view - * the desired page. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoAuthentication($message = '%s') { - $message = sprintf($message, "Expected no authentication type, got [" . - $this->browser->getAuthentication() . "]"); - return $this->assertFalse($this->browser->getAuthentication(), $message); - } - - /** - * Attempts to match the current security realm. - * @param string $realm Name of security realm. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertRealm($realm, $message = '%s') { - if (! SimpleExpectation::isExpectation($realm)) { - $realm = new EqualExpectation($realm); - } - return $this->assert( - $realm, - $this->browser->getRealm(), - "Expected realm -> $message"); - } - - /** - * Checks each header line for the required value. If no - * value is given then only an existence check is made. - * @param string $header Case insensitive header name. - * @param mixed $value Case sensitive trimmed string to - * match against. An expectation object - * can be used for pattern matching. - * @return boolean True if pass. - * @access public - */ - function assertHeader($header, $value = false, $message = '%s') { - return $this->assert( - new HttpHeaderExpectation($header, $value), - $this->browser->getHeaders(), - $message); - } - - /** - * Confirms that the header type has not been received. - * Only the landing page is checked. If you want to check - * redirect pages, then you should limit redirects so - * as to capture the page you want. - * @param string $header Case insensitive header name. - * @return boolean True if pass. - * @access public - */ - function assertNoHeader($header, $message = '%s') { - return $this->assert( - new NoHttpHeaderExpectation($header), - $this->browser->getHeaders(), - $message); - } - - /** - * Tests the text between the title tags. - * @param string/SimpleExpectation $title Expected title. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertTitle($title = false, $message = '%s') { - if (! SimpleExpectation::isExpectation($title)) { - $title = new EqualExpectation($title); - } - return $this->assert($title, $this->browser->getTitle(), $message); - } - - /** - * Will trigger a pass if the text is found in the plain - * text form of the page. - * @param string $text Text to look for. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertText($text, $message = '%s') { - return $this->assert( - new TextExpectation($text), - $this->browser->getContentAsText(), - $message); - } - - /** - * Will trigger a pass if the text is not found in the plain - * text form of the page. - * @param string $text Text to look for. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoText($text, $message = '%s') { - return $this->assert( - new NoTextExpectation($text), - $this->browser->getContentAsText(), - $message); - } - - /** - * Will trigger a pass if the Perl regex pattern - * is found in the raw content. - * @param string $pattern Perl regex to look for including - * the regex delimiters. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertPattern($pattern, $message = '%s') { - return $this->assert( - new PatternExpectation($pattern), - $this->browser->getContent(), - $message); - } - - /** - * Will trigger a pass if the perl regex pattern - * is not present in raw content. - * @param string $pattern Perl regex to look for including - * the regex delimiters. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoPattern($pattern, $message = '%s') { - return $this->assert( - new NoPatternExpectation($pattern), - $this->browser->getContent(), - $message); - } - - /** - * Checks that a cookie is set for the current page - * and optionally checks the value. - * @param string $name Name of cookie to test. - * @param string $expected Expected value as a string or - * false if any value will do. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertCookie($name, $expected = false, $message = '%s') { - $value = $this->getCookie($name); - if (! $expected) { - return $this->assertTrue( - $value, - sprintf($message, "Expecting cookie [$name]")); - } - if (! SimpleExpectation::isExpectation($expected)) { - $expected = new EqualExpectation($expected); - } - return $this->assert($expected, $value, "Expecting cookie [$name] -> $message"); - } - - /** - * Checks that no cookie is present or that it has - * been successfully cleared. - * @param string $name Name of cookie to test. - * @param string $message Message to display. - * @return boolean True if pass. - * @access public - */ - function assertNoCookie($name, $message = '%s') { - return $this->assertTrue( - $this->getCookie($name) === null or $this->getCookie($name) === false, - sprintf($message, "Not expecting cookie [$name]")); - } - - /** - * Called from within the test methods to register - * passes and failures. - * @param boolean $result Pass on true. - * @param string $message Message to display describing - * the test state. - * @return boolean True on pass - * @access public - */ - function assertTrue($result, $message = '%s') { - return $this->assert(new TrueExpectation(), $result, $message); - } - - /** - * Will be true on false and vice versa. False - * is the PHP definition of false, so that null, - * empty strings, zero and an empty array all count - * as false. - * @param boolean $result Pass on false. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertFalse($result, $message = '%s') { - return $this->assert(new FalseExpectation(), $result, $message); - } - - /** - * Will trigger a pass if the two parameters have - * the same value only. Otherwise a fail. This - * is for testing hand extracted text, etc. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertEqual($first, $second, $message = '%s') { - return $this->assert( - new EqualExpectation($first), - $second, - $message); - } - - /** - * Will trigger a pass if the two parameters have - * a different value. Otherwise a fail. This - * is for testing hand extracted text, etc. - * @param mixed $first Value to compare. - * @param mixed $second Value to compare. - * @param string $message Message to display. - * @return boolean True on pass - * @access public - */ - function assertNotEqual($first, $second, $message = '%s') { - return $this->assert( - new NotEqualExpectation($first), - $second, - $message); - } - - /** - * Uses a stack trace to find the line of an assertion. - * @return string Line number of first assert* - * method embedded in format string. - * @access public - */ - function getAssertionLine() { - $trace = new SimpleStackTrace(array('assert', 'click', 'pass', 'fail')); - return $trace->traceMethod(); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/xml.php b/3rdparty/simpletest/xml.php deleted file mode 100755 index 54fb6f5b16dcf0d073ead2f7b5706e38898bea89..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/xml.php +++ /dev/null @@ -1,647 +0,0 @@ -<?php -/** - * base include file for SimpleTest - * @package SimpleTest - * @subpackage UnitTester - * @version $Id: xml.php 1787 2008-04-26 20:35:39Z pp11 $ - */ - -/**#@+ - * include other SimpleTest class files - */ -require_once(dirname(__FILE__) . '/scorer.php'); -/**#@-*/ - -/** - * Creates the XML needed for remote communication - * by SimpleTest. - * @package SimpleTest - * @subpackage UnitTester - */ -class XmlReporter extends SimpleReporter { - private $indent; - private $namespace; - - /** - * Sets up indentation and namespace. - * @param string $namespace Namespace to add to each tag. - * @param string $indent Indenting to add on each nesting. - * @access public - */ - function __construct($namespace = false, $indent = ' ') { - parent::__construct(); - $this->namespace = ($namespace ? $namespace . ':' : ''); - $this->indent = $indent; - } - - /** - * Calculates the pretty printing indent level - * from the current level of nesting. - * @param integer $offset Extra indenting level. - * @return string Leading space. - * @access protected - */ - protected function getIndent($offset = 0) { - return str_repeat( - $this->indent, - count($this->getTestList()) + $offset); - } - - /** - * Converts character string to parsed XML - * entities string. - * @param string text Unparsed character data. - * @return string Parsed character data. - * @access public - */ - function toParsedXml($text) { - return str_replace( - array('&', '<', '>', '"', '\''), - array('&', '<', '>', '"', '''), - $text); - } - - /** - * Paints the start of a group test. - * @param string $test_name Name of test that is starting. - * @param integer $size Number of test cases starting. - * @access public - */ - function paintGroupStart($test_name, $size) { - parent::paintGroupStart($test_name, $size); - print $this->getIndent(); - print "<" . $this->namespace . "group size=\"$size\">\n"; - print $this->getIndent(1); - print "<" . $this->namespace . "name>" . - $this->toParsedXml($test_name) . - "</" . $this->namespace . "name>\n"; - } - - /** - * Paints the end of a group test. - * @param string $test_name Name of test that is ending. - * @access public - */ - function paintGroupEnd($test_name) { - print $this->getIndent(); - print "</" . $this->namespace . "group>\n"; - parent::paintGroupEnd($test_name); - } - - /** - * Paints the start of a test case. - * @param string $test_name Name of test that is starting. - * @access public - */ - function paintCaseStart($test_name) { - parent::paintCaseStart($test_name); - print $this->getIndent(); - print "<" . $this->namespace . "case>\n"; - print $this->getIndent(1); - print "<" . $this->namespace . "name>" . - $this->toParsedXml($test_name) . - "</" . $this->namespace . "name>\n"; - } - - /** - * Paints the end of a test case. - * @param string $test_name Name of test that is ending. - * @access public - */ - function paintCaseEnd($test_name) { - print $this->getIndent(); - print "</" . $this->namespace . "case>\n"; - parent::paintCaseEnd($test_name); - } - - /** - * Paints the start of a test method. - * @param string $test_name Name of test that is starting. - * @access public - */ - function paintMethodStart($test_name) { - parent::paintMethodStart($test_name); - print $this->getIndent(); - print "<" . $this->namespace . "test>\n"; - print $this->getIndent(1); - print "<" . $this->namespace . "name>" . - $this->toParsedXml($test_name) . - "</" . $this->namespace . "name>\n"; - } - - /** - * Paints the end of a test method. - * @param string $test_name Name of test that is ending. - * @param integer $progress Number of test cases ending. - * @access public - */ - function paintMethodEnd($test_name) { - print $this->getIndent(); - print "</" . $this->namespace . "test>\n"; - parent::paintMethodEnd($test_name); - } - - /** - * Paints pass as XML. - * @param string $message Message to encode. - * @access public - */ - function paintPass($message) { - parent::paintPass($message); - print $this->getIndent(1); - print "<" . $this->namespace . "pass>"; - print $this->toParsedXml($message); - print "</" . $this->namespace . "pass>\n"; - } - - /** - * Paints failure as XML. - * @param string $message Message to encode. - * @access public - */ - function paintFail($message) { - parent::paintFail($message); - print $this->getIndent(1); - print "<" . $this->namespace . "fail>"; - print $this->toParsedXml($message); - print "</" . $this->namespace . "fail>\n"; - } - - /** - * Paints error as XML. - * @param string $message Message to encode. - * @access public - */ - function paintError($message) { - parent::paintError($message); - print $this->getIndent(1); - print "<" . $this->namespace . "exception>"; - print $this->toParsedXml($message); - print "</" . $this->namespace . "exception>\n"; - } - - /** - * Paints exception as XML. - * @param Exception $exception Exception to encode. - * @access public - */ - function paintException($exception) { - parent::paintException($exception); - print $this->getIndent(1); - print "<" . $this->namespace . "exception>"; - $message = 'Unexpected exception of type [' . get_class($exception) . - '] with message ['. $exception->getMessage() . - '] in ['. $exception->getFile() . - ' line ' . $exception->getLine() . ']'; - print $this->toParsedXml($message); - print "</" . $this->namespace . "exception>\n"; - } - - /** - * Paints the skipping message and tag. - * @param string $message Text to display in skip tag. - * @access public - */ - function paintSkip($message) { - parent::paintSkip($message); - print $this->getIndent(1); - print "<" . $this->namespace . "skip>"; - print $this->toParsedXml($message); - print "</" . $this->namespace . "skip>\n"; - } - - /** - * Paints a simple supplementary message. - * @param string $message Text to display. - * @access public - */ - function paintMessage($message) { - parent::paintMessage($message); - print $this->getIndent(1); - print "<" . $this->namespace . "message>"; - print $this->toParsedXml($message); - print "</" . $this->namespace . "message>\n"; - } - - /** - * Paints a formatted ASCII message such as a - * privateiable dump. - * @param string $message Text to display. - * @access public - */ - function paintFormattedMessage($message) { - parent::paintFormattedMessage($message); - print $this->getIndent(1); - print "<" . $this->namespace . "formatted>"; - print "<![CDATA[$message]]>"; - print "</" . $this->namespace . "formatted>\n"; - } - - /** - * Serialises the event object. - * @param string $type Event type as text. - * @param mixed $payload Message or object. - * @access public - */ - function paintSignal($type, $payload) { - parent::paintSignal($type, $payload); - print $this->getIndent(1); - print "<" . $this->namespace . "signal type=\"$type\">"; - print "<![CDATA[" . serialize($payload) . "]]>"; - print "</" . $this->namespace . "signal>\n"; - } - - /** - * Paints the test document header. - * @param string $test_name First test top level - * to start. - * @access public - * @abstract - */ - function paintHeader($test_name) { - if (! SimpleReporter::inCli()) { - header('Content-type: text/xml'); - } - print "<?xml version=\"1.0\""; - if ($this->namespace) { - print " xmlns:" . $this->namespace . - "=\"www.lastcraft.com/SimpleTest/Beta3/Report\""; - } - print "?>\n"; - print "<" . $this->namespace . "run>\n"; - } - - /** - * Paints the test document footer. - * @param string $test_name The top level test. - * @access public - * @abstract - */ - function paintFooter($test_name) { - print "</" . $this->namespace . "run>\n"; - } -} - -/** - * Accumulator for incoming tag. Holds the - * incoming test structure information for - * later dispatch to the reporter. - * @package SimpleTest - * @subpackage UnitTester - */ -class NestingXmlTag { - private $name; - private $attributes; - - /** - * Sets the basic test information except - * the name. - * @param hash $attributes Name value pairs. - * @access public - */ - function NestingXmlTag($attributes) { - $this->name = false; - $this->attributes = $attributes; - } - - /** - * Sets the test case/method name. - * @param string $name Name of test. - * @access public - */ - function setName($name) { - $this->name = $name; - } - - /** - * Accessor for name. - * @return string Name of test. - * @access public - */ - function getName() { - return $this->name; - } - - /** - * Accessor for attributes. - * @return hash All attributes. - * @access protected - */ - protected function getAttributes() { - return $this->attributes; - } -} - -/** - * Accumulator for incoming method tag. Holds the - * incoming test structure information for - * later dispatch to the reporter. - * @package SimpleTest - * @subpackage UnitTester - */ -class NestingMethodTag extends NestingXmlTag { - - /** - * Sets the basic test information except - * the name. - * @param hash $attributes Name value pairs. - * @access public - */ - function NestingMethodTag($attributes) { - $this->NestingXmlTag($attributes); - } - - /** - * Signals the appropriate start event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintStart(&$listener) { - $listener->paintMethodStart($this->getName()); - } - - /** - * Signals the appropriate end event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintEnd(&$listener) { - $listener->paintMethodEnd($this->getName()); - } -} - -/** - * Accumulator for incoming case tag. Holds the - * incoming test structure information for - * later dispatch to the reporter. - * @package SimpleTest - * @subpackage UnitTester - */ -class NestingCaseTag extends NestingXmlTag { - - /** - * Sets the basic test information except - * the name. - * @param hash $attributes Name value pairs. - * @access public - */ - function NestingCaseTag($attributes) { - $this->NestingXmlTag($attributes); - } - - /** - * Signals the appropriate start event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintStart(&$listener) { - $listener->paintCaseStart($this->getName()); - } - - /** - * Signals the appropriate end event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintEnd(&$listener) { - $listener->paintCaseEnd($this->getName()); - } -} - -/** - * Accumulator for incoming group tag. Holds the - * incoming test structure information for - * later dispatch to the reporter. - * @package SimpleTest - * @subpackage UnitTester - */ -class NestingGroupTag extends NestingXmlTag { - - /** - * Sets the basic test information except - * the name. - * @param hash $attributes Name value pairs. - * @access public - */ - function NestingGroupTag($attributes) { - $this->NestingXmlTag($attributes); - } - - /** - * Signals the appropriate start event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintStart(&$listener) { - $listener->paintGroupStart($this->getName(), $this->getSize()); - } - - /** - * Signals the appropriate end event on the - * listener. - * @param SimpleReporter $listener Target for events. - * @access public - */ - function paintEnd(&$listener) { - $listener->paintGroupEnd($this->getName()); - } - - /** - * The size in the attributes. - * @return integer Value of size attribute or zero. - * @access public - */ - function getSize() { - $attributes = $this->getAttributes(); - if (isset($attributes['SIZE'])) { - return (integer)$attributes['SIZE']; - } - return 0; - } -} - -/** - * Parser for importing the output of the XmlReporter. - * Dispatches that output to another reporter. - * @package SimpleTest - * @subpackage UnitTester - */ -class SimpleTestXmlParser { - private $listener; - private $expat; - private $tag_stack; - private $in_content_tag; - private $content; - private $attributes; - - /** - * Loads a listener with the SimpleReporter - * interface. - * @param SimpleReporter $listener Listener of tag events. - * @access public - */ - function SimpleTestXmlParser(&$listener) { - $this->listener = &$listener; - $this->expat = &$this->createParser(); - $this->tag_stack = array(); - $this->in_content_tag = false; - $this->content = ''; - $this->attributes = array(); - } - - /** - * Parses a block of XML sending the results to - * the listener. - * @param string $chunk Block of text to read. - * @return boolean True if valid XML. - * @access public - */ - function parse($chunk) { - if (! xml_parse($this->expat, $chunk)) { - trigger_error('XML parse error with ' . - xml_error_string(xml_get_error_code($this->expat))); - return false; - } - return true; - } - - /** - * Sets up expat as the XML parser. - * @return resource Expat handle. - * @access protected - */ - protected function &createParser() { - $expat = xml_parser_create(); - xml_set_object($expat, $this); - xml_set_element_handler($expat, 'startElement', 'endElement'); - xml_set_character_data_handler($expat, 'addContent'); - xml_set_default_handler($expat, 'defaultContent'); - return $expat; - } - - /** - * Opens a new test nesting level. - * @return NestedXmlTag The group, case or method tag - * to start. - * @access private - */ - protected function pushNestingTag($nested) { - array_unshift($this->tag_stack, $nested); - } - - /** - * Accessor for current test structure tag. - * @return NestedXmlTag The group, case or method tag - * being parsed. - * @access private - */ - protected function &getCurrentNestingTag() { - return $this->tag_stack[0]; - } - - /** - * Ends a nesting tag. - * @return NestedXmlTag The group, case or method tag - * just finished. - * @access private - */ - protected function popNestingTag() { - return array_shift($this->tag_stack); - } - - /** - * Test if tag is a leaf node with only text content. - * @param string $tag XML tag name. - * @return @boolean True if leaf, false if nesting. - * @private - */ - protected function isLeaf($tag) { - return in_array($tag, array( - 'NAME', 'PASS', 'FAIL', 'EXCEPTION', 'SKIP', 'MESSAGE', 'FORMATTED', 'SIGNAL')); - } - - /** - * Handler for start of event element. - * @param resource $expat Parser handle. - * @param string $tag Element name. - * @param hash $attributes Name value pairs. - * Attributes without content - * are marked as true. - * @access protected - */ - protected function startElement($expat, $tag, $attributes) { - $this->attributes = $attributes; - if ($tag == 'GROUP') { - $this->pushNestingTag(new NestingGroupTag($attributes)); - } elseif ($tag == 'CASE') { - $this->pushNestingTag(new NestingCaseTag($attributes)); - } elseif ($tag == 'TEST') { - $this->pushNestingTag(new NestingMethodTag($attributes)); - } elseif ($this->isLeaf($tag)) { - $this->in_content_tag = true; - $this->content = ''; - } - } - - /** - * End of element event. - * @param resource $expat Parser handle. - * @param string $tag Element name. - * @access protected - */ - protected function endElement($expat, $tag) { - $this->in_content_tag = false; - if (in_array($tag, array('GROUP', 'CASE', 'TEST'))) { - $nesting_tag = $this->popNestingTag(); - $nesting_tag->paintEnd($this->listener); - } elseif ($tag == 'NAME') { - $nesting_tag = &$this->getCurrentNestingTag(); - $nesting_tag->setName($this->content); - $nesting_tag->paintStart($this->listener); - } elseif ($tag == 'PASS') { - $this->listener->paintPass($this->content); - } elseif ($tag == 'FAIL') { - $this->listener->paintFail($this->content); - } elseif ($tag == 'EXCEPTION') { - $this->listener->paintError($this->content); - } elseif ($tag == 'SKIP') { - $this->listener->paintSkip($this->content); - } elseif ($tag == 'SIGNAL') { - $this->listener->paintSignal( - $this->attributes['TYPE'], - unserialize($this->content)); - } elseif ($tag == 'MESSAGE') { - $this->listener->paintMessage($this->content); - } elseif ($tag == 'FORMATTED') { - $this->listener->paintFormattedMessage($this->content); - } - } - - /** - * Content between start and end elements. - * @param resource $expat Parser handle. - * @param string $text Usually output messages. - * @access protected - */ - protected function addContent($expat, $text) { - if ($this->in_content_tag) { - $this->content .= $text; - } - return true; - } - - /** - * XML and Doctype handler. Discards all such content. - * @param resource $expat Parser handle. - * @param string $default Text of default content. - * @access protected - */ - protected function defaultContent($expat, $default) { - } -} -?> diff --git a/3rdparty/timepicker/GPL-LICENSE.txt b/3rdparty/timepicker/GPL-LICENSE.txt deleted file mode 100644 index 932f11115fe4e47e57f4e6b2723ac6a921d578fe..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/GPL-LICENSE.txt +++ /dev/null @@ -1,278 +0,0 @@ -GNU GENERAL PUBLIC LICENSE -Version 2, June 1991 - -Copyright (C) 1989, 1991 Free Software Foundation, Inc. -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -Everyone is permitted to copy and distribute verbatim copies -of this license document, but changing it is not allowed. - -Preamble - -The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by - the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - -When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for - this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - -To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - -For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - -We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, - distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain - that everyone understands that there is no warranty for this free - software. If the software is modified by someone else and passed on, we - want its recipients to know that what they have is not the original, so - that any problems introduced by others will not reflect on the original - authors' reputations. - - Finally, any free program is threatened constantly by software - patents. We wish to avoid the danger that redistributors of a free - program will individually obtain patent licenses, in effect making the - program proprietary. To prevent this, we have made it clear that any - patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and - modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains - a notice placed by the copyright holder saying it may be distributed - under the terms of this General Public License. The "Program", below, - refers to any such program or work, and a "work based on the Program" - means either the Program or any derivative work under copyright law: - that is to say, a work containing the Program or a portion of it, - either verbatim or with modifications and/or translated into another - language. (Hereinafter, translation is included without limitation in - the term "modification".) Each licensee is addressed as "you". - - Activities other than copying, distribution and modification are not - covered by this License; they are outside its scope. The act of - running the Program is not restricted, and the output from the Program - is covered only if its contents constitute a work based on the - Program (independent of having been made by running the Program). - Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's - source code as you receive it, in any medium, provided that you - conspicuously and appropriately publish on each copy an appropriate - copyright notice and disclaimer of warranty; keep intact all the - notices that refer to this License and to the absence of any warranty; - and give any other recipients of the Program a copy of this License - along with the Program. - - You may charge a fee for the physical act of transferring a copy, and - you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion - of it, thus forming a work based on the Program, and copy and - distribute such modifications or work under the terms of Section 1 - above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - - These requirements apply to the modified work as a whole. If - identifiable sections of that work are not derived from the Program, - and can be reasonably considered independent and separate works in - themselves, then this License, and its terms, do not apply to those - sections when you distribute them as separate works. But when you - distribute the same sections as part of a whole which is a work based - on the Program, the distribution of the whole must be on the terms of - this License, whose permissions for other licensees extend to the - entire whole, and thus to each and every part regardless of who wrote it. - - Thus, it is not the intent of this section to claim rights or contest - your rights to work written entirely by you; rather, the intent is to - exercise the right to control the distribution of derivative or - collective works based on the Program. - - In addition, mere aggregation of another work not based on the Program - with the Program (or with a work based on the Program) on a volume of - a storage or distribution medium does not bring the other work under - the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, - under Section 2) in object code or executable form under the terms of - Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - - The source code for a work means the preferred form of the work for - making modifications to it. For an executable work, complete source - code means all the source code for all modules it contains, plus any - associated interface definition files, plus the scripts used to - control compilation and installation of the executable. However, as a - special exception, the source code distributed need not include - anything that is normally distributed (in either source or binary - form) with the major components (compiler, kernel, and so on) of the - operating system on which the executable runs, unless that component - itself accompanies the executable. - - If distribution of executable or object code is made by offering - access to copy from a designated place, then offering equivalent - access to copy the source code from the same place counts as - distribution of the source code, even though third parties are not - compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program - except as expressly provided under this License. Any attempt - otherwise to copy, modify, sublicense or distribute the Program is - void, and will automatically terminate your rights under this License. - However, parties who have received copies, or rights, from you under - this License will not have their licenses terminated so long as such - parties remain in full compliance. - - 5. You are not required to accept this License, since you have not - signed it. However, nothing else grants you permission to modify or - distribute the Program or its derivative works. These actions are - prohibited by law if you do not accept this License. Therefore, by - modifying or distributing the Program (or any work based on the - Program), you indicate your acceptance of this License to do so, and - all its terms and conditions for copying, distributing or modifying - the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the - Program), the recipient automatically receives a license from the - original licensor to copy, distribute or modify the Program subject to - these terms and conditions. You may not impose any further - restrictions on the recipients' exercise of the rights granted herein. - You are not responsible for enforcing compliance by third parties to - this License. - - 7. If, as a consequence of a court judgment or allegation of patent - infringement or for any other reason (not limited to patent issues), - conditions are imposed on you (whether by court order, agreement or - otherwise) that contradict the conditions of this License, they do not - excuse you from the conditions of this License. If you cannot - distribute so as to satisfy simultaneously your obligations under this - License and any other pertinent obligations, then as a consequence you - may not distribute the Program at all. For example, if a patent - license would not permit royalty-free redistribution of the Program by - all those who receive copies directly or indirectly through you, then - the only way you could satisfy both it and this License would be to - refrain entirely from distribution of the Program. - - If any portion of this section is held invalid or unenforceable under - any particular circumstance, the balance of the section is intended to - apply and the section as a whole is intended to apply in other - circumstances. - - It is not the purpose of this section to induce you to infringe any - patents or other property right claims or to contest validity of any - such claims; this section has the sole purpose of protecting the - integrity of the free software distribution system, which is - implemented by public license practices. Many people have made - generous contributions to the wide range of software distributed - through that system in reliance on consistent application of that - system; it is up to the author/donor to decide if he or she is willing - to distribute software through any other system and a licensee cannot - impose that choice. - - This section is intended to make thoroughly clear what is believed to - be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in - certain countries either by patents or by copyrighted interfaces, the - original copyright holder who places the Program under this License - may add an explicit geographical distribution limitation excluding - those countries, so that distribution is permitted only in or among - countries not thus excluded. In such case, this License incorporates - the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions - of the General Public License from time to time. Such new versions will - be similar in spirit to the present version, but may differ in detail to - address new problems or concerns. - - Each version is given a distinguishing version number. If the Program - specifies a version number of this License which applies to it and "any - later version", you have the option of following the terms and conditions - either of that version or of any later version published by the Free - Software Foundation. If the Program does not specify a version number of - this License, you may choose any version ever published by the Free Software - Foundation. - - 10. If you wish to incorporate parts of the Program into other free - programs whose distribution conditions are different, write to the author - to ask for permission. For software which is copyrighted by the Free - Software Foundation, write to the Free Software Foundation; we sometimes - make exceptions for this. Our decision will be guided by the two goals - of preserving the free status of all derivatives of our free software and - of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY - FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN - OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES - PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED - OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS - TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE - PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, - REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING - WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR - REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, - INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING - OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED - TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY - YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER - PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE - POSSIBILITY OF SUCH DAMAGES.""'''''' diff --git a/3rdparty/timepicker/MIT-LICENSE.txt b/3rdparty/timepicker/MIT-LICENSE.txt deleted file mode 100644 index 532704636b730cba3b36bb35ad0945295b188597..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/MIT-LICENSE.txt +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2011 John Resig, http://jquery.com/ - -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. diff --git a/3rdparty/timepicker/css/include/images/ui-bg_diagonals-thick_18_b81900_40x40.png b/3rdparty/timepicker/css/include/images/ui-bg_diagonals-thick_18_b81900_40x40.png deleted file mode 100644 index 954e22dbd99e8c6dd7091335599abf2d10bf8003..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-bg_diagonals-thick_18_b81900_40x40.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-bg_diagonals-thick_20_666666_40x40.png b/3rdparty/timepicker/css/include/images/ui-bg_diagonals-thick_20_666666_40x40.png deleted file mode 100644 index 64ece5707d91a6edf9fad4bfcce0c4dbcafcf58d..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-bg_diagonals-thick_20_666666_40x40.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-bg_flat_10_000000_40x100.png b/3rdparty/timepicker/css/include/images/ui-bg_flat_10_000000_40x100.png deleted file mode 100644 index abdc01082bf3534eafecc5819d28c9574d44ea89..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-bg_flat_10_000000_40x100.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-bg_glass_100_f6f6f6_1x400.png b/3rdparty/timepicker/css/include/images/ui-bg_glass_100_f6f6f6_1x400.png deleted file mode 100644 index 9b383f4d2eab09c0f2a739d6b232c32934bc620b..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-bg_glass_100_f6f6f6_1x400.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-bg_glass_100_fdf5ce_1x400.png b/3rdparty/timepicker/css/include/images/ui-bg_glass_100_fdf5ce_1x400.png deleted file mode 100644 index a23baad25b1d1ff36e17361eab24271f2e9b7326..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-bg_glass_100_fdf5ce_1x400.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-bg_glass_65_ffffff_1x400.png b/3rdparty/timepicker/css/include/images/ui-bg_glass_65_ffffff_1x400.png deleted file mode 100644 index 42ccba269b6e91bef12ad0fa18be651b5ef0ee68..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-bg_glass_65_ffffff_1x400.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-bg_gloss-wave_35_f6a828_500x100.png b/3rdparty/timepicker/css/include/images/ui-bg_gloss-wave_35_f6a828_500x100.png deleted file mode 100644 index 39d5824d6af5456f1e89fc7847ea3599ea5fd815..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-bg_gloss-wave_35_f6a828_500x100.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-bg_highlight-soft_100_eeeeee_1x100.png b/3rdparty/timepicker/css/include/images/ui-bg_highlight-soft_100_eeeeee_1x100.png deleted file mode 100644 index f1273672d253263b7564e9e21d69d7d9d0b337d9..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-bg_highlight-soft_100_eeeeee_1x100.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-bg_highlight-soft_75_ffe45c_1x100.png b/3rdparty/timepicker/css/include/images/ui-bg_highlight-soft_75_ffe45c_1x100.png deleted file mode 100644 index 359397acffdd84bd102f0e8a951c9d744f278db5..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-bg_highlight-soft_75_ffe45c_1x100.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-icons_222222_256x240.png b/3rdparty/timepicker/css/include/images/ui-icons_222222_256x240.png deleted file mode 100644 index b273ff111d219c9b9a8b96d57683d0075fb7871a..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-icons_222222_256x240.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-icons_228ef1_256x240.png b/3rdparty/timepicker/css/include/images/ui-icons_228ef1_256x240.png deleted file mode 100644 index a641a371afa0fbb08ba599dc7ddf14b9bfc3c84f..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-icons_228ef1_256x240.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-icons_ef8c08_256x240.png b/3rdparty/timepicker/css/include/images/ui-icons_ef8c08_256x240.png deleted file mode 100644 index 85e63e9f604ce042d59eb06a8428eeb7cb7896c9..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-icons_ef8c08_256x240.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-icons_ffd27a_256x240.png b/3rdparty/timepicker/css/include/images/ui-icons_ffd27a_256x240.png deleted file mode 100644 index e117effa3dca24e7978cfc5f8b967f661e81044f..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-icons_ffd27a_256x240.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/images/ui-icons_ffffff_256x240.png b/3rdparty/timepicker/css/include/images/ui-icons_ffffff_256x240.png deleted file mode 100644 index 42f8f992c727ddaa617da224a522e463df690387..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/images/ui-icons_ffffff_256x240.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/jquery-1.5.1.min.js b/3rdparty/timepicker/css/include/jquery-1.5.1.min.js deleted file mode 100644 index 6437874c699e26d29813936d16586cbdee7b8382..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/css/include/jquery-1.5.1.min.js +++ /dev/null @@ -1,16 +0,0 @@ -/*! - * jQuery JavaScript Library v1.5.1 - * http://jquery.com/ - * - * Copyright 2011, John Resig - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * - * Date: Wed Feb 23 13:55:29 2011 -0500 - */ -(function(a,b){function cg(a){return d.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cd(a){if(!bZ[a]){var b=d("<"+a+">").appendTo("body"),c=b.css("display");b.remove();if(c==="none"||c==="")c="block";bZ[a]=c}return bZ[a]}function cc(a,b){var c={};d.each(cb.concat.apply([],cb.slice(0,b)),function(){c[this]=a});return c}function bY(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function bX(){try{return new a.XMLHttpRequest}catch(b){}}function bW(){d(a).unload(function(){for(var a in bU)bU[a](0,1)})}function bQ(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var e=a.dataTypes,f={},g,h,i=e.length,j,k=e[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h==="string"&&(f[h.toLowerCase()]=a.converters[h]);l=k,k=e[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=f[m]||f["* "+k];if(!n){p=b;for(o in f){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=f[j[1]+" "+k];if(p){o=f[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&d.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bP(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function bO(a,b,c,e){if(d.isArray(b)&&b.length)d.each(b,function(b,f){c||bq.test(a)?e(a,f):bO(a+"["+(typeof f==="object"||d.isArray(f)?b:"")+"]",f,c,e)});else if(c||b==null||typeof b!=="object")e(a,b);else if(d.isArray(b)||d.isEmptyObject(b))e(a,"");else for(var f in b)bO(a+"["+f+"]",b[f],c,e)}function bN(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bH,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l==="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bN(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bN(a,c,d,e,"*",g));return l}function bM(a){return function(b,c){typeof b!=="string"&&(c=b,b="*");if(d.isFunction(c)){var e=b.toLowerCase().split(bB),f=0,g=e.length,h,i,j;for(;f<g;f++)h=e[f],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bo(a,b,c){var e=b==="width"?bi:bj,f=b==="width"?a.offsetWidth:a.offsetHeight;if(c==="border")return f;d.each(e,function(){c||(f-=parseFloat(d.css(a,"padding"+this))||0),c==="margin"?f+=parseFloat(d.css(a,"margin"+this))||0:f-=parseFloat(d.css(a,"border"+this+"Width"))||0});return f}function ba(a,b){b.src?d.ajax({url:b.src,async:!1,dataType:"script"}):d.globalEval(b.text||b.textContent||b.innerHTML||""),b.parentNode&&b.parentNode.removeChild(b)}function _(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function $(a,b){if(b.nodeType===1){var c=b.nodeName.toLowerCase();b.clearAttributes(),b.mergeAttributes(a);if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(d.expando)}}function Z(a,b){if(b.nodeType===1&&d.hasData(a)){var c=d.expando,e=d.data(a),f=d.data(b,e);if(e=e[c]){var g=e.events;f=f[c]=d.extend({},e);if(g){delete f.handle,f.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)d.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function Y(a,b){return d.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function O(a,b,c){if(d.isFunction(b))return d.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return d.grep(a,function(a,d){return a===b===c});if(typeof b==="string"){var e=d.grep(a,function(a){return a.nodeType===1});if(J.test(b))return d.filter(b,e,!c);b=d.filter(b,e)}return d.grep(a,function(a,e){return d.inArray(a,b)>=0===c})}function N(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function F(a,b){return(a&&a!=="*"?a+".":"")+b.replace(r,"`").replace(s,"&")}function E(a){var b,c,e,f,g,h,i,j,k,l,m,n,o,q=[],r=[],s=d._data(this,"events");if(a.liveFired!==this&&s&&s.live&&!a.target.disabled&&(!a.button||a.type!=="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var t=s.live.slice(0);for(i=0;i<t.length;i++)g=t[i],g.origType.replace(p,"")===a.type?r.push(g.selector):t.splice(i--,1);f=d(a.target).closest(r,a.currentTarget);for(j=0,k=f.length;j<k;j++){m=f[j];for(i=0;i<t.length;i++){g=t[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,e=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,e=d(a.relatedTarget).closest(g.selector)[0];(!e||e!==h)&&q.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=q.length;j<k;j++){f=q[j];if(c&&f.level>c)break;a.currentTarget=f.elem,a.data=f.handleObj.data,a.handleObj=f.handleObj,o=f.handleObj.origHandler.apply(f.elem,arguments);if(o===!1||a.isPropagationStopped()){c=f.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function C(a,c,e){var f=d.extend({},e[0]);f.type=a,f.originalEvent={},f.liveFired=b,d.event.handle.call(c,f),f.isDefaultPrevented()&&e[0].preventDefault()}function w(){return!0}function v(){return!1}function g(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function f(a,c,f){if(f===b&&a.nodeType===1){f=a.getAttribute("data-"+c);if(typeof f==="string"){try{f=f==="true"?!0:f==="false"?!1:f==="null"?null:d.isNaN(f)?e.test(f)?d.parseJSON(f):f:parseFloat(f)}catch(g){}d.data(a,c,f)}else f=b}return f}var c=a.document,d=function(){function I(){if(!d.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(I,1);return}d.ready()}}var d=function(a,b){return new d.fn.init(a,b,g)},e=a.jQuery,f=a.$,g,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,i=/\S/,j=/^\s+/,k=/\s+$/,l=/\d/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=navigator.userAgent,w,x=!1,y,z="then done fail isResolved isRejected promise".split(" "),A,B=Object.prototype.toString,C=Object.prototype.hasOwnProperty,D=Array.prototype.push,E=Array.prototype.slice,F=String.prototype.trim,G=Array.prototype.indexOf,H={};d.fn=d.prototype={constructor:d,init:function(a,e,f){var g,i,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!e&&c.body){this.context=c,this[0]=c.body,this.selector="body",this.length=1;return this}if(typeof a==="string"){g=h.exec(a);if(!g||!g[1]&&e)return!e||e.jquery?(e||f).find(a):this.constructor(e).find(a);if(g[1]){e=e instanceof d?e[0]:e,k=e?e.ownerDocument||e:c,j=m.exec(a),j?d.isPlainObject(e)?(a=[c.createElement(j[1])],d.fn.attr.call(a,e,!0)):a=[k.createElement(j[1])]:(j=d.buildFragment([g[1]],[k]),a=(j.cacheable?d.clone(j.fragment):j.fragment).childNodes);return d.merge(this,a)}i=c.getElementById(g[2]);if(i&&i.parentNode){if(i.id!==g[2])return f.find(a);this.length=1,this[0]=i}this.context=c,this.selector=a;return this}if(d.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return d.makeArray(a,this)},selector:"",jquery:"1.5.1",length:0,size:function(){return this.length},toArray:function(){return E.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var e=this.constructor();d.isArray(a)?D.apply(e,a):d.merge(e,a),e.prevObject=this,e.context=this.context,b==="find"?e.selector=this.selector+(this.selector?" ":"")+c:b&&(e.selector=this.selector+"."+b+"("+c+")");return e},each:function(a,b){return d.each(this,a,b)},ready:function(a){d.bindReady(),y.done(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(E.apply(this,arguments),"slice",E.call(arguments).join(","))},map:function(a){return this.pushStack(d.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:D,sort:[].sort,splice:[].splice},d.fn.init.prototype=d.fn,d.extend=d.fn.extend=function(){var a,c,e,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i==="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!=="object"&&!d.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){e=i[c],f=a[c];if(i===f)continue;l&&f&&(d.isPlainObject(f)||(g=d.isArray(f)))?(g?(g=!1,h=e&&d.isArray(e)?e:[]):h=e&&d.isPlainObject(e)?e:{},i[c]=d.extend(l,h,f)):f!==b&&(i[c]=f)}return i},d.extend({noConflict:function(b){a.$=f,b&&(a.jQuery=e);return d},isReady:!1,readyWait:1,ready:function(a){a===!0&&d.readyWait--;if(!d.readyWait||a!==!0&&!d.isReady){if(!c.body)return setTimeout(d.ready,1);d.isReady=!0;if(a!==!0&&--d.readyWait>0)return;y.resolveWith(c,[d]),d.fn.trigger&&d(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!x){x=!0;if(c.readyState==="complete")return setTimeout(d.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",A,!1),a.addEventListener("load",d.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",A),a.attachEvent("onload",d.ready);var b=!1;try{b=a.frameElement==null}catch(e){}c.documentElement.doScroll&&b&&I()}}},isFunction:function(a){return d.type(a)==="function"},isArray:Array.isArray||function(a){return d.type(a)==="array"},isWindow:function(a){return a&&typeof a==="object"&&"setInterval"in a},isNaN:function(a){return a==null||!l.test(a)||isNaN(a)},type:function(a){return a==null?String(a):H[B.call(a)]||"object"},isPlainObject:function(a){if(!a||d.type(a)!=="object"||a.nodeType||d.isWindow(a))return!1;if(a.constructor&&!C.call(a,"constructor")&&!C.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a){}return c===b||C.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!=="string"||!b)return null;b=d.trim(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return a.JSON&&a.JSON.parse?a.JSON.parse(b):(new Function("return "+b))();d.error("Invalid JSON: "+b)},parseXML:function(b,c,e){a.DOMParser?(e=new DOMParser,c=e.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),e=c.documentElement,(!e||!e.nodeName||e.nodeName==="parsererror")&&d.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(a){if(a&&i.test(a)){var b=c.head||c.getElementsByTagName("head")[0]||c.documentElement,e=c.createElement("script");d.support.scriptEval()?e.appendChild(c.createTextNode(a)):e.text=a,b.insertBefore(e,b.firstChild),b.removeChild(e)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,e){var f,g=0,h=a.length,i=h===b||d.isFunction(a);if(e){if(i){for(f in a)if(c.apply(a[f],e)===!1)break}else for(;g<h;)if(c.apply(a[g++],e)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(var j=a[0];g<h&&c.call(j,g,j)!==!1;j=a[++g]){}return a},trim:F?function(a){return a==null?"":F.call(a)}:function(a){return a==null?"":(a+"").replace(j,"").replace(k,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var e=d.type(a);a.length==null||e==="string"||e==="function"||e==="regexp"||d.isWindow(a)?D.call(c,a):d.merge(c,a)}return c},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length==="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,b,c){var d=[],e;for(var f=0,g=a.length;f<g;f++)e=b(a[f],f,c),e!=null&&(d[d.length]=e);return d.concat.apply([],d)},guid:1,proxy:function(a,c,e){arguments.length===2&&(typeof c==="string"?(e=a,a=e[c],c=b):c&&!d.isFunction(c)&&(e=c,c=b)),!c&&a&&(c=function(){return a.apply(e||this,arguments)}),a&&(c.guid=a.guid=a.guid||c.guid||d.guid++);return c},access:function(a,c,e,f,g,h){var i=a.length;if(typeof c==="object"){for(var j in c)d.access(a,j,c[j],f,g,e);return a}if(e!==b){f=!h&&f&&d.isFunction(e);for(var k=0;k<i;k++)g(a[k],c,f?e.call(a[k],k,g(a[k],c)):e,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},_Deferred:function(){var a=[],b,c,e,f={done:function(){if(!e){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=d.type(i),j==="array"?f.done.apply(f,i):j==="function"&&a.push(i);k&&f.resolveWith(k[0],k[1])}return this},resolveWith:function(d,f){if(!e&&!b&&!c){c=1;try{while(a[0])a.shift().apply(d,f)}catch(g){throw g}finally{b=[d,f],c=0}}return this},resolve:function(){f.resolveWith(d.isFunction(this.promise)?this.promise():this,arguments);return this},isResolved:function(){return c||b},cancel:function(){e=1,a=[];return this}};return f},Deferred:function(a){var b=d._Deferred(),c=d._Deferred(),e;d.extend(b,{then:function(a,c){b.done(a).fail(c);return this},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,promise:function(a){if(a==null){if(e)return e;e=a={}}var c=z.length;while(c--)a[z[c]]=b[z[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){var b=arguments.length,c=b<=1&&a&&d.isFunction(a.promise)?a:d.Deferred(),e=c.promise();if(b>1){var f=E.call(arguments,0),g=b,h=function(a){return function(b){f[a]=arguments.length>1?E.call(arguments,0):b,--g||c.resolveWith(e,f)}};while(b--)a=f[b],a&&d.isFunction(a.promise)?a.promise().then(h(b),c.reject):--g;g||c.resolveWith(e,f)}else c!==a&&c.resolve(a);return e},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}d.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.subclass=this.subclass,a.fn.init=function b(b,c){c&&c instanceof d&&!(c instanceof a)&&(c=a(c));return d.fn.init.call(this,b,c,e)},a.fn.init.prototype=a.fn;var e=a(c);return a},browser:{}}),y=d._Deferred(),d.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){H["[object "+b+"]"]=b.toLowerCase()}),w=d.uaMatch(v),w.browser&&(d.browser[w.browser]=!0,d.browser.version=w.version),d.browser.webkit&&(d.browser.safari=!0),G&&(d.inArray=function(a,b){return G.call(b,a)}),i.test(" ")&&(j=/^[\s\xA0]+/,k=/[\s\xA0]+$/),g=d(c),c.addEventListener?A=function(){c.removeEventListener("DOMContentLoaded",A,!1),d.ready()}:c.attachEvent&&(A=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",A),d.ready())});return d}();(function(){d.support={};var b=c.createElement("div");b.style.display="none",b.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=b.getElementsByTagName("*"),f=b.getElementsByTagName("a")[0],g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=b.getElementsByTagName("input")[0];if(e&&e.length&&f){d.support={leadingWhitespace:b.firstChild.nodeType===3,tbody:!b.getElementsByTagName("tbody").length,htmlSerialize:!!b.getElementsByTagName("link").length,style:/red/.test(f.getAttribute("style")),hrefNormalized:f.getAttribute("href")==="/a",opacity:/^0.55$/.test(f.style.opacity),cssFloat:!!f.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,deleteExpando:!0,optDisabled:!1,checkClone:!1,noCloneEvent:!0,noCloneChecked:!0,boxModel:null,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableHiddenOffsets:!0},i.checked=!0,d.support.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,d.support.optDisabled=!h.disabled;var j=null;d.support.scriptEval=function(){if(j===null){var b=c.documentElement,e=c.createElement("script"),f="script"+d.now();try{e.appendChild(c.createTextNode("window."+f+"=1;"))}catch(g){}b.insertBefore(e,b.firstChild),a[f]?(j=!0,delete a[f]):j=!1,b.removeChild(e),b=e=f=null}return j};try{delete b.test}catch(k){d.support.deleteExpando=!1}!b.addEventListener&&b.attachEvent&&b.fireEvent&&(b.attachEvent("onclick",function l(){d.support.noCloneEvent=!1,b.detachEvent("onclick",l)}),b.cloneNode(!0).fireEvent("onclick")),b=c.createElement("div"),b.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";var m=c.createDocumentFragment();m.appendChild(b.firstChild),d.support.checkClone=m.cloneNode(!0).cloneNode(!0).lastChild.checked,d(function(){var a=c.createElement("div"),b=c.getElementsByTagName("body")[0];if(b){a.style.width=a.style.paddingLeft="1px",b.appendChild(a),d.boxModel=d.support.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,d.support.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",d.support.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";var e=a.getElementsByTagName("td");d.support.reliableHiddenOffsets=e[0].offsetHeight===0,e[0].style.display="",e[1].style.display="none",d.support.reliableHiddenOffsets=d.support.reliableHiddenOffsets&&e[0].offsetHeight===0,a.innerHTML="",b.removeChild(a).style.display="none",a=e=null}});var n=function(a){var b=c.createElement("div");a="on"+a;if(!b.attachEvent)return!0;var d=a in b;d||(b.setAttribute(a,"return;"),d=typeof b[a]==="function"),b=null;return d};d.support.submitBubbles=n("submit"),d.support.changeBubbles=n("change"),b=e=f=null}})();var e=/^(?:\{.*\}|\[.*\])$/;d.extend({cache:{},uuid:0,expando:"jQuery"+(d.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?d.cache[a[d.expando]]:a[d.expando];return!!a&&!g(a)},data:function(a,c,e,f){if(d.acceptData(a)){var g=d.expando,h=typeof c==="string",i,j=a.nodeType,k=j?d.cache:a,l=j?a[d.expando]:a[d.expando]&&d.expando;if((!l||f&&l&&!k[l][g])&&h&&e===b)return;l||(j?a[d.expando]=l=++d.uuid:l=d.expando),k[l]||(k[l]={},j||(k[l].toJSON=d.noop));if(typeof c==="object"||typeof c==="function")f?k[l][g]=d.extend(k[l][g],c):k[l]=d.extend(k[l],c);i=k[l],f&&(i[g]||(i[g]={}),i=i[g]),e!==b&&(i[c]=e);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[c]:i}},removeData:function(b,c,e){if(d.acceptData(b)){var f=d.expando,h=b.nodeType,i=h?d.cache:b,j=h?b[d.expando]:d.expando;if(!i[j])return;if(c){var k=e?i[j][f]:i[j];if(k){delete k[c];if(!g(k))return}}if(e){delete i[j][f];if(!g(i[j]))return}var l=i[j][f];d.support.deleteExpando||i!=a?delete i[j]:i[j]=null,l?(i[j]={},h||(i[j].toJSON=d.noop),i[j][f]=l):h&&(d.support.deleteExpando?delete b[d.expando]:b.removeAttribute?b.removeAttribute(d.expando):b[d.expando]=null)}},_data:function(a,b,c){return d.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=d.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),d.fn.extend({data:function(a,c){var e=null;if(typeof a==="undefined"){if(this.length){e=d.data(this[0]);if(this[0].nodeType===1){var g=this[0].attributes,h;for(var i=0,j=g.length;i<j;i++)h=g[i].name,h.indexOf("data-")===0&&(h=h.substr(5),f(this[0],h,e[h]))}}return e}if(typeof a==="object")return this.each(function(){d.data(this,a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(c===b){e=this.triggerHandler("getData"+k[1]+"!",[k[0]]),e===b&&this.length&&(e=d.data(this[0],a),e=f(this[0],a,e));return e===b&&k[1]?this.data(k[0]):e}return this.each(function(){var b=d(this),e=[k[0],c];b.triggerHandler("setData"+k[1]+"!",e),d.data(this,a,c),b.triggerHandler("changeData"+k[1]+"!",e)})},removeData:function(a){return this.each(function(){d.removeData(this,a)})}}),d.extend({queue:function(a,b,c){if(a){b=(b||"fx")+"queue";var e=d._data(a,b);if(!c)return e||[];!e||d.isArray(c)?e=d._data(a,b,d.makeArray(c)):e.push(c);return e}},dequeue:function(a,b){b=b||"fx";var c=d.queue(a,b),e=c.shift();e==="inprogress"&&(e=c.shift()),e&&(b==="fx"&&c.unshift("inprogress"),e.call(a,function(){d.dequeue(a,b)})),c.length||d.removeData(a,b+"queue",!0)}}),d.fn.extend({queue:function(a,c){typeof a!=="string"&&(c=a,a="fx");if(c===b)return d.queue(this[0],a);return this.each(function(b){var e=d.queue(this,a,c);a==="fx"&&e[0]!=="inprogress"&&d.dequeue(this,a)})},dequeue:function(a){return this.each(function(){d.dequeue(this,a)})},delay:function(a,b){a=d.fx?d.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){d.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var h=/[\n\t\r]/g,i=/\s+/,j=/\r/g,k=/^(?:href|src|style)$/,l=/^(?:button|input)$/i,m=/^(?:button|input|object|select|textarea)$/i,n=/^a(?:rea)?$/i,o=/^(?:radio|checkbox)$/i;d.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"},d.fn.extend({attr:function(a,b){return d.access(this,a,b,!0,d.attr)},removeAttr:function(a,b){return this.each(function(){d.attr(this,a,""),this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.addClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"){var b=(a||"").split(i);for(var c=0,e=this.length;c<e;c++){var f=this[c];if(f.nodeType===1)if(f.className){var g=" "+f.className+" ",h=f.className;for(var j=0,k=b.length;j<k;j++)g.indexOf(" "+b[j]+" ")<0&&(h+=" "+b[j]);f.className=d.trim(h)}else f.className=a}}return this},removeClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.removeClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"||a===b){var c=(a||"").split(i);for(var e=0,f=this.length;e<f;e++){var g=this[e];if(g.nodeType===1&&g.className)if(a){var j=(" "+g.className+" ").replace(h," ");for(var k=0,l=c.length;k<l;k++)j=j.replace(" "+c[k]+" "," ");g.className=d.trim(j)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,e=typeof b==="boolean";if(d.isFunction(a))return this.each(function(c){var e=d(this);e.toggleClass(a.call(this,c,e.attr("class"),b),b)});return this.each(function(){if(c==="string"){var f,g=0,h=d(this),j=b,k=a.split(i);while(f=k[g++])j=e?j:!h.hasClass(f),h[j?"addClass":"removeClass"](f)}else if(c==="undefined"||c==="boolean")this.className&&d._data(this,"__className__",this.className),this.className=this.className||a===!1?"":d._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(h," ").indexOf(b)>-1)return!0;return!1},val:function(a){if(!arguments.length){var c=this[0];if(c){if(d.nodeName(c,"option")){var e=c.attributes.value;return!e||e.specified?c.value:c.text}if(d.nodeName(c,"select")){var f=c.selectedIndex,g=[],h=c.options,i=c.type==="select-one";if(f<0)return null;for(var k=i?f:0,l=i?f+1:h.length;k<l;k++){var m=h[k];if(m.selected&&(d.support.optDisabled?!m.disabled:m.getAttribute("disabled")===null)&&(!m.parentNode.disabled||!d.nodeName(m.parentNode,"optgroup"))){a=d(m).val();if(i)return a;g.push(a)}}if(i&&!g.length&&h.length)return d(h[f]).val();return g}if(o.test(c.type)&&!d.support.checkOn)return c.getAttribute("value")===null?"on":c.value;return(c.value||"").replace(j,"")}return b}var n=d.isFunction(a);return this.each(function(b){var c=d(this),e=a;if(this.nodeType===1){n&&(e=a.call(this,b,c.val())),e==null?e="":typeof e==="number"?e+="":d.isArray(e)&&(e=d.map(e,function(a){return a==null?"":a+""}));if(d.isArray(e)&&o.test(this.type))this.checked=d.inArray(c.val(),e)>=0;else if(d.nodeName(this,"select")){var f=d.makeArray(e);d("option",this).each(function(){this.selected=d.inArray(d(this).val(),f)>=0}),f.length||(this.selectedIndex=-1)}else this.value=e}})}}),d.extend({attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,e,f){if(!a||a.nodeType===3||a.nodeType===8||a.nodeType===2)return b;if(f&&c in d.attrFn)return d(a)[c](e);var g=a.nodeType!==1||!d.isXMLDoc(a),h=e!==b;c=g&&d.props[c]||c;if(a.nodeType===1){var i=k.test(c);if(c==="selected"&&!d.support.optSelected){var j=a.parentNode;j&&(j.selectedIndex,j.parentNode&&j.parentNode.selectedIndex)}if((c in a||a[c]!==b)&&g&&!i){h&&(c==="type"&&l.test(a.nodeName)&&a.parentNode&&d.error("type property can't be changed"),e===null?a.nodeType===1&&a.removeAttribute(c):a[c]=e);if(d.nodeName(a,"form")&&a.getAttributeNode(c))return a.getAttributeNode(c).nodeValue;if(c==="tabIndex"){var o=a.getAttributeNode("tabIndex");return o&&o.specified?o.value:m.test(a.nodeName)||n.test(a.nodeName)&&a.href?0:b}return a[c]}if(!d.support.style&&g&&c==="style"){h&&(a.style.cssText=""+e);return a.style.cssText}h&&a.setAttribute(c,""+e);if(!a.attributes[c]&&(a.hasAttribute&&!a.hasAttribute(c)))return b;var p=!d.support.hrefNormalized&&g&&i?a.getAttribute(c,2):a.getAttribute(c);return p===null?b:p}h&&(a[c]=e);return a[c]}});var p=/\.(.*)$/,q=/^(?:textarea|input|select)$/i,r=/\./g,s=/ /g,t=/[^\w\s.|`]/g,u=function(a){return a.replace(t,"\\$&")};d.event={add:function(c,e,f,g){if(c.nodeType!==3&&c.nodeType!==8){try{d.isWindow(c)&&(c!==a&&!c.frameElement)&&(c=a)}catch(h){}if(f===!1)f=v;else if(!f)return;var i,j;f.handler&&(i=f,f=i.handler),f.guid||(f.guid=d.guid++);var k=d._data(c);if(!k)return;var l=k.events,m=k.handle;l||(k.events=l={}),m||(k.handle=m=function(){return typeof d!=="undefined"&&!d.event.triggered?d.event.handle.apply(m.elem,arguments):b}),m.elem=c,e=e.split(" ");var n,o=0,p;while(n=e[o++]){j=i?d.extend({},i):{handler:f,data:g},n.indexOf(".")>-1?(p=n.split("."),n=p.shift(),j.namespace=p.slice(0).sort().join(".")):(p=[],j.namespace=""),j.type=n,j.guid||(j.guid=f.guid);var q=l[n],r=d.event.special[n]||{};if(!q){q=l[n]=[];if(!r.setup||r.setup.call(c,g,p,m)===!1)c.addEventListener?c.addEventListener(n,m,!1):c.attachEvent&&c.attachEvent("on"+n,m)}r.add&&(r.add.call(c,j),j.handler.guid||(j.handler.guid=f.guid)),q.push(j),d.event.global[n]=!0}c=null}},global:{},remove:function(a,c,e,f){if(a.nodeType!==3&&a.nodeType!==8){e===!1&&(e=v);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=d.hasData(a)&&d._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(e=c.handler,c=c.type);if(!c||typeof c==="string"&&c.charAt(0)==="."){c=c||"";for(h in t)d.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+d.map(m.slice(0).sort(),u).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!e){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))d.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=d.event.special[h]||{};for(j=f||0;j<p.length;j++){q=p[j];if(e.guid===q.guid){if(l||n.test(q.namespace))f==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(f!=null)break}}if(p.length===0||f!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&d.removeEvent(a,h,s.handle),g=null,delete t[h]}if(d.isEmptyObject(t)){var w=s.handle;w&&(w.elem=null),delete s.events,delete s.handle,d.isEmptyObject(s)&&d.removeData(a,b,!0)}}},trigger:function(a,c,e){var f=a.type||a,g=arguments[3];if(!g){a=typeof a==="object"?a[d.expando]?a:d.extend(d.Event(f),a):d.Event(f),f.indexOf("!")>=0&&(a.type=f=f.slice(0,-1),a.exclusive=!0),e||(a.stopPropagation(),d.event.global[f]&&d.each(d.cache,function(){var b=d.expando,e=this[b];e&&e.events&&e.events[f]&&d.event.trigger(a,c,e.handle.elem)}));if(!e||e.nodeType===3||e.nodeType===8)return b;a.result=b,a.target=e,c=d.makeArray(c),c.unshift(a)}a.currentTarget=e;var h=d._data(e,"handle");h&&h.apply(e,c);var i=e.parentNode||e.ownerDocument;try{e&&e.nodeName&&d.noData[e.nodeName.toLowerCase()]||e["on"+f]&&e["on"+f].apply(e,c)===!1&&(a.result=!1,a.preventDefault())}catch(j){}if(!a.isPropagationStopped()&&i)d.event.trigger(a,c,i,!0);else if(!a.isDefaultPrevented()){var k,l=a.target,m=f.replace(p,""),n=d.nodeName(l,"a")&&m==="click",o=d.event.special[m]||{};if((!o._default||o._default.call(e,a)===!1)&&!n&&!(l&&l.nodeName&&d.noData[l.nodeName.toLowerCase()])){try{l[m]&&(k=l["on"+m],k&&(l["on"+m]=null),d.event.triggered=!0,l[m]())}catch(q){}k&&(l["on"+m]=k),d.event.triggered=!1}}},handle:function(c){var e,f,g,h,i,j=[],k=d.makeArray(arguments);c=k[0]=d.event.fix(c||a.event),c.currentTarget=this,e=c.type.indexOf(".")<0&&!c.exclusive,e||(g=c.type.split("."),c.type=g.shift(),j=g.slice(0).sort(),h=new RegExp("(^|\\.)"+j.join("\\.(?:.*\\.)?")+"(\\.|$)")),c.namespace=c.namespace||j.join("."),i=d._data(this,"events"),f=(i||{})[c.type];if(i&&f){f=f.slice(0);for(var l=0,m=f.length;l<m;l++){var n=f[l];if(e||h.test(n.namespace)){c.handler=n.handler,c.data=n.data,c.handleObj=n;var o=n.handler.apply(this,k);o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[d.expando])return a;var e=a;a=d.Event(e);for(var f=this.props.length,g;f;)g=this.props[--f],a[g]=e[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=c.documentElement,i=c.body;a.pageX=a.clientX+(h&&h.scrollLeft||i&&i.scrollLeft||0)-(h&&h.clientLeft||i&&i.clientLeft||0),a.pageY=a.clientY+(h&&h.scrollTop||i&&i.scrollTop||0)-(h&&h.clientTop||i&&i.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:d.proxy,special:{ready:{setup:d.bindReady,teardown:d.noop},live:{add:function(a){d.event.add(this,F(a.origType,a.selector),d.extend({},a,{handler:E,guid:a.handler.guid}))},remove:function(a){d.event.remove(this,F(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){d.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},d.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},d.Event=function(a){if(!this.preventDefault)return new d.Event(a);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?w:v):this.type=a,this.timeStamp=d.now(),this[d.expando]=!0},d.Event.prototype={preventDefault:function(){this.isDefaultPrevented=w;var a=this.originalEvent;a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=w;var a=this.originalEvent;a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=w,this.stopPropagation()},isDefaultPrevented:v,isPropagationStopped:v,isImmediatePropagationStopped:v};var x=function(a){var b=a.relatedTarget;try{if(b!==c&&!b.parentNode)return;while(b&&b!==this)b=b.parentNode;b!==this&&(a.type=a.data,d.event.handle.apply(this,arguments))}catch(e){}},y=function(a){a.type=a.data,d.event.handle.apply(this,arguments)};d.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){d.event.special[a]={setup:function(c){d.event.add(this,b,c&&c.selector?y:x,a)},teardown:function(a){d.event.remove(this,b,a&&a.selector?y:x)}}}),d.support.submitBubbles||(d.event.special.submit={setup:function(a,b){if(this.nodeName&&this.nodeName.toLowerCase()!=="form")d.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&d(b).closest("form").length&&C("submit",this,arguments)}),d.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&d(b).closest("form").length&&a.keyCode===13&&C("submit",this,arguments)});else return!1},teardown:function(a){d.event.remove(this,".specialSubmit")}});if(!d.support.changeBubbles){var z,A=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?d.map(a.options,function(a){return a.selected}).join("-"):"":a.nodeName.toLowerCase()==="select"&&(c=a.selectedIndex);return c},B=function B(a){var c=a.target,e,f;if(q.test(c.nodeName)&&!c.readOnly){e=d._data(c,"_change_data"),f=A(c),(a.type!=="focusout"||c.type!=="radio")&&d._data(c,"_change_data",f);if(e===b||f===e)return;if(e!=null||f)a.type="change",a.liveFired=b,d.event.trigger(a,arguments[1],c)}};d.event.special.change={filters:{focusout:B,beforedeactivate:B,click:function(a){var b=a.target,c=b.type;(c==="radio"||c==="checkbox"||b.nodeName.toLowerCase()==="select")&&B.call(this,a)},keydown:function(a){var b=a.target,c=b.type;(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&B.call(this,a)},beforeactivate:function(a){var b=a.target;d._data(b,"_change_data",A(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in z)d.event.add(this,c+".specialChange",z[c]);return q.test(this.nodeName)},teardown:function(a){d.event.remove(this,".specialChange");return q.test(this.nodeName)}},z=d.event.special.change.filters,z.focus=z.beforeactivate}c.addEventListener&&d.each({focus:"focusin",blur:"focusout"},function(a,b){function c(a){a=d.event.fix(a),a.type=b;return d.event.handle.call(this,a)}d.event.special[b]={setup:function(){this.addEventListener(a,c,!0)},teardown:function(){this.removeEventListener(a,c,!0)}}}),d.each(["bind","one"],function(a,c){d.fn[c]=function(a,e,f){if(typeof a==="object"){for(var g in a)this[c](g,e,a[g],f);return this}if(d.isFunction(e)||e===!1)f=e,e=b;var h=c==="one"?d.proxy(f,function(a){d(this).unbind(a,h);return f.apply(this,arguments)}):f;if(a==="unload"&&c!=="one")this.one(a,e,f);else for(var i=0,j=this.length;i<j;i++)d.event.add(this[i],a,h,e);return this}}),d.fn.extend({unbind:function(a,b){if(typeof a!=="object"||a.preventDefault)for(var e=0,f=this.length;e<f;e++)d.event.remove(this[e],a,b);else for(var c in a)this.unbind(c,a[c]);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){d.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var c=d.Event(a);c.preventDefault(),c.stopPropagation(),d.event.trigger(c,b,this[0]);return c.result}},toggle:function(a){var b=arguments,c=1;while(c<b.length)d.proxy(a,b[c++]);return this.click(d.proxy(a,function(e){var f=(d._data(this,"lastToggle"+a.guid)||0)%c;d._data(this,"lastToggle"+a.guid,f+1),e.preventDefault();return b[f].apply(this,arguments)||!1}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var D={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};d.each(["live","die"],function(a,c){d.fn[c]=function(a,e,f,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:d(this.context);if(typeof a==="object"&&!a.preventDefault){for(var o in a)n[c](o,e,a[o],m);return this}d.isFunction(e)&&(f=e,e=b),a=(a||"").split(" ");while((h=a[i++])!=null){j=p.exec(h),k="",j&&(k=j[0],h=h.replace(p,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,h==="focus"||h==="blur"?(a.push(D[h]+k),h=h+k):h=(D[h]||h)+k;if(c==="live")for(var q=0,r=n.length;q<r;q++)d.event.add(n[q],"live."+F(h,m),{data:e,selector:m,handler:f,origType:h,origHandler:f,preType:l});else n.unbind("live."+F(h,m),f)}return this}}),d.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){d.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},d.attrFn&&(d.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!=="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,e,g){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!=="string")return e;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(f.call(n)==="[object Array]")if(u)if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&e.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&e.push(j[t]);else e.push.apply(e,n);else p(n,e);o&&(k(o,h,e,g),k.uniqueSort(e));return e};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!=="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(f){if(f===!0)continue}else g=o=!0}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b==="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1){}a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b==="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!=="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!=="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!=="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){return"text"===a.getAttribute("type")},radio:function(a){return"radio"===a.type},checkbox:function(a){return"checkbox"===a.type},file:function(a){return"file"===a.type},password:function(a){return"password"===a.type},submit:function(a){return"submit"===a.type},image:function(a){return"image"===a.type},reset:function(a){return"reset"===a.type},button:function(a){return"button"===a.type||a.nodeName.toLowerCase()==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(f.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length==="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(a===b){g=!0;return 0}if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!=="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!=="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!=="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!=="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector,d=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(e){d=!0}b&&(k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(d||!l.match.PSEUDO.test(c)&&!/!=/.test(c))return b.call(a,c)}catch(e){}return k(c,null,null,[a]).length>0})}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!=="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};d.find=k,d.expr=k.selectors,d.expr[":"]=d.expr.filters,d.unique=k.uniqueSort,d.text=k.getText,d.isXMLDoc=k.isXML,d.contains=k.contains}();var G=/Until$/,H=/^(?:parents|prevUntil|prevAll)/,I=/,/,J=/^.[^:#\[\.,]*$/,K=Array.prototype.slice,L=d.expr.match.POS,M={children:!0,contents:!0,next:!0,prev:!0};d.fn.extend({find:function(a){var b=this.pushStack("","find",a),c=0;for(var e=0,f=this.length;e<f;e++){c=b.length,d.find(a,this[e],b);if(e>0)for(var g=c;g<b.length;g++)for(var h=0;h<c;h++)if(b[h]===b[g]){b.splice(g--,1);break}}return b},has:function(a){var b=d(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(d.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(O(this,a,!1),"not",a)},filter:function(a){return this.pushStack(O(this,a,!0),"filter",a)},is:function(a){return!!a&&d.filter(a,this).length>0},closest:function(a,b){var c=[],e,f,g=this[0];if(d.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(e=0,f=a.length;e<f;e++)i=a[e],j[i]||(j[i]=d.expr.match.POS.test(i)?d(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:d(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=L.test(a)?d(a,b||this.context):null;for(e=0,f=this.length;e<f;e++){g=this[e];while(g){if(l?l.index(g)>-1:d.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b)break}}c=c.length>1?d.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a||typeof a==="string")return d.inArray(this[0],a?d(a):this.parent().children());return d.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a==="string"?d(a,b):d.makeArray(a),e=d.merge(this.get(),c);return this.pushStack(N(c[0])||N(e[0])?e:d.unique(e))},andSelf:function(){return this.add(this.prevObject)}}),d.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return d.dir(a,"parentNode")},parentsUntil:function(a,b,c){return d.dir(a,"parentNode",c)},next:function(a){return d.nth(a,2,"nextSibling")},prev:function(a){return d.nth(a,2,"previousSibling")},nextAll:function(a){return d.dir(a,"nextSibling")},prevAll:function(a){return d.dir(a,"previousSibling")},nextUntil:function(a,b,c){return d.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return d.dir(a,"previousSibling",c)},siblings:function(a){return d.sibling(a.parentNode.firstChild,a)},children:function(a){return d.sibling(a.firstChild)},contents:function(a){return d.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:d.makeArray(a.childNodes)}},function(a,b){d.fn[a]=function(c,e){var f=d.map(this,b,c),g=K.call(arguments);G.test(a)||(e=c),e&&typeof e==="string"&&(f=d.filter(e,f)),f=this.length>1&&!M[a]?d.unique(f):f,(this.length>1||I.test(e))&&H.test(a)&&(f=f.reverse());return this.pushStack(f,a,g.join(","))}}),d.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?d.find.matchesSelector(b[0],a)?[b[0]]:[]:d.find.matches(a,b)},dir:function(a,c,e){var f=[],g=a[c];while(g&&g.nodeType!==9&&(e===b||g.nodeType!==1||!d(g).is(e)))g.nodeType===1&&f.push(g),g=g[c];return f},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var P=/ jQuery\d+="(?:\d+|null)"/g,Q=/^\s+/,R=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,S=/<([\w:]+)/,T=/<tbody/i,U=/<|&#?\w+;/,V=/<(?:script|object|embed|option|style)/i,W=/checked\s*(?:[^=]|=\s*.checked.)/i,X={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};X.optgroup=X.option,X.tbody=X.tfoot=X.colgroup=X.caption=X.thead,X.th=X.td,d.support.htmlSerialize||(X._default=[1,"div<div>","</div>"]),d.fn.extend({text:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.text(a.call(this,b,c.text()))});if(typeof a!=="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return d.text(this)},wrapAll:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapAll(a.call(this,b))});if(this[0]){var b=d(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapInner(a.call(this,b))});return this.each(function(){var b=d(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){d(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){d.nodeName(this,"body")||d(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=d(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,d(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,e;(e=this[c])!=null;c++)if(!a||d.filter(a,[e]).length)!b&&e.nodeType===1&&(d.cleanData(e.getElementsByTagName("*")),d.cleanData([e])),e.parentNode&&e.parentNode.removeChild(e);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&d.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return d.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(P,""):null;if(typeof a!=="string"||V.test(a)||!d.support.leadingWhitespace&&Q.test(a)||X[(S.exec(a)||["",""])[1].toLowerCase()])d.isFunction(a)?this.each(function(b){var c=d(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);else{a=a.replace(R,"<$1></$2>");try{for(var c=0,e=this.length;c<e;c++)this[c].nodeType===1&&(d.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(f){this.empty().append(a)}}return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(d.isFunction(a))return this.each(function(b){var c=d(this),e=c.html();c.replaceWith(a.call(this,b,e))});typeof a!=="string"&&(a=d(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;d(this).remove(),b?d(b).before(a):d(c).append(a)})}return this.pushStack(d(d.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,e){var f,g,h,i,j=a[0],k=[];if(!d.support.checkClone&&arguments.length===3&&typeof j==="string"&&W.test(j))return this.each(function(){d(this).domManip(a,c,e,!0)});if(d.isFunction(j))return this.each(function(f){var g=d(this);a[0]=j.call(this,f,c?g.html():b),g.domManip(a,c,e)});if(this[0]){i=j&&j.parentNode,d.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?f={fragment:i}:f=d.buildFragment(a,this,k),h=f.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&d.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)e.call(c?Y(this[l],g):this[l],f.cacheable||m>1&&l<n?d.clone(h,!0,!0):h)}k.length&&d.each(k,ba)}return this}}),d.buildFragment=function(a,b,e){var f,g,h,i=b&&b[0]?b[0].ownerDocument||b[0]:c;a.length===1&&typeof a[0]==="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!V.test(a[0])&&(d.support.checkClone||!W.test(a[0]))&&(g=!0,h=d.fragments[a[0]],h&&(h!==1&&(f=h))),f||(f=i.createDocumentFragment(),d.clean(a,i,f,e)),g&&(d.fragments[a[0]]=h?f:1);return{fragment:f,cacheable:g}},d.fragments={},d.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){d.fn[a]=function(c){var e=[],f=d(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&f.length===1){f[b](this[0]);return this}for(var h=0,i=f.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();d(f[h])[b](j),e=e.concat(j)}return this.pushStack(e,a,f.selector)}}),d.extend({clone:function(a,b,c){var e=a.cloneNode(!0),f,g,h;if((!d.support.noCloneEvent||!d.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!d.isXMLDoc(a)){$(a,e),f=_(a),g=_(e);for(h=0;f[h];++h)$(f[h],g[h])}if(b){Z(a,e);if(c){f=_(a),g=_(e);for(h=0;f[h];++h)Z(f[h],g[h])}}return e},clean:function(a,b,e,f){b=b||c,typeof b.createElement==="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var g=[];for(var h=0,i;(i=a[h])!=null;h++){typeof i==="number"&&(i+="");if(!i)continue;if(typeof i!=="string"||U.test(i)){if(typeof i==="string"){i=i.replace(R,"<$1></$2>");var j=(S.exec(i)||["",""])[1].toLowerCase(),k=X[j]||X._default,l=k[0],m=b.createElement("div");m.innerHTML=k[1]+i+k[2];while(l--)m=m.lastChild;if(!d.support.tbody){var n=T.test(i),o=j==="table"&&!n?m.firstChild&&m.firstChild.childNodes:k[1]==="<table>"&&!n?m.childNodes:[];for(var p=o.length-1;p>=0;--p)d.nodeName(o[p],"tbody")&&!o[p].childNodes.length&&o[p].parentNode.removeChild(o[p])}!d.support.leadingWhitespace&&Q.test(i)&&m.insertBefore(b.createTextNode(Q.exec(i)[0]),m.firstChild),i=m.childNodes}}else i=b.createTextNode(i);i.nodeType?g.push(i):g=d.merge(g,i)}if(e)for(h=0;g[h];h++)!f||!d.nodeName(g[h],"script")||g[h].type&&g[h].type.toLowerCase()!=="text/javascript"?(g[h].nodeType===1&&g.splice.apply(g,[h+1,0].concat(d.makeArray(g[h].getElementsByTagName("script")))),e.appendChild(g[h])):f.push(g[h].parentNode?g[h].parentNode.removeChild(g[h]):g[h]);return g},cleanData:function(a){var b,c,e=d.cache,f=d.expando,g=d.event.special,h=d.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&d.noData[j.nodeName.toLowerCase()])continue;c=j[d.expando];if(c){b=e[c]&&e[c][f];if(b&&b.events){for(var k in b.events)g[k]?d.event.remove(j,k):d.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[d.expando]:j.removeAttribute&&j.removeAttribute(d.expando),delete e[c]}}}});var bb=/alpha\([^)]*\)/i,bc=/opacity=([^)]*)/,bd=/-([a-z])/ig,be=/([A-Z])/g,bf=/^-?\d+(?:px)?$/i,bg=/^-?\d/,bh={position:"absolute",visibility:"hidden",display:"block"},bi=["Left","Right"],bj=["Top","Bottom"],bk,bl,bm,bn=function(a,b){return b.toUpperCase()};d.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return d.access(this,a,c,!0,function(a,c,e){return e!==b?d.style(a,c,e):d.css(a,c)})},d.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bk(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{zIndex:!0,fontWeight:!0,opacity:!0,zoom:!0,lineHeight:!0},cssProps:{"float":d.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,e,f){if(a&&a.nodeType!==3&&a.nodeType!==8&&a.style){var g,h=d.camelCase(c),i=a.style,j=d.cssHooks[h];c=d.cssProps[h]||h;if(e===b){if(j&&"get"in j&&(g=j.get(a,!1,f))!==b)return g;return i[c]}if(typeof e==="number"&&isNaN(e)||e==null)return;typeof e==="number"&&!d.cssNumber[h]&&(e+="px");if(!j||!("set"in j)||(e=j.set(a,e))!==b)try{i[c]=e}catch(k){}}},css:function(a,c,e){var f,g=d.camelCase(c),h=d.cssHooks[g];c=d.cssProps[g]||g;if(h&&"get"in h&&(f=h.get(a,!0,e))!==b)return f;if(bk)return bk(a,c,g)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]},camelCase:function(a){return a.replace(bd,bn)}}),d.curCSS=d.css,d.each(["height","width"],function(a,b){d.cssHooks[b]={get:function(a,c,e){var f;if(c){a.offsetWidth!==0?f=bo(a,b,e):d.swap(a,bh,function(){f=bo(a,b,e)});if(f<=0){f=bk(a,b,b),f==="0px"&&bm&&(f=bm(a,b,b));if(f!=null)return f===""||f==="auto"?"0px":f}if(f<0||f==null){f=a.style[b];return f===""||f==="auto"?"0px":f}return typeof f==="string"?f:f+"px"}},set:function(a,b){if(!bf.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),d.support.opacity||(d.cssHooks.opacity={get:function(a,b){return bc.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style;c.zoom=1;var e=d.isNaN(b)?"":"alpha(opacity="+b*100+")",f=c.filter||"";c.filter=bb.test(f)?f.replace(bb,e):c.filter+" "+e}}),c.defaultView&&c.defaultView.getComputedStyle&&(bl=function(a,c,e){var f,g,h;e=e.replace(be,"-$1").toLowerCase();if(!(g=a.ownerDocument.defaultView))return b;if(h=g.getComputedStyle(a,null))f=h.getPropertyValue(e),f===""&&!d.contains(a.ownerDocument.documentElement,a)&&(f=d.style(a,e));return f}),c.documentElement.currentStyle&&(bm=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bf.test(d)&&bg.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bk=bl||bm,d.expr&&d.expr.filters&&(d.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!d.support.reliableHiddenOffsets&&(a.style.display||d.css(a,"display"))==="none"},d.expr.filters.visible=function(a){return!d.expr.filters.hidden(a)});var bp=/%20/g,bq=/\[\]$/,br=/\r?\n/g,bs=/#.*$/,bt=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bu=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bv=/(?:^file|^widget|\-extension):$/,bw=/^(?:GET|HEAD)$/,bx=/^\/\//,by=/\?/,bz=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bA=/^(?:select|textarea)/i,bB=/\s+/,bC=/([?&])_=[^&]*/,bD=/(^|\-)([a-z])/g,bE=function(a,b,c){return b+c.toUpperCase()},bF=/^([\w\+\.\-]+:)\/\/([^\/?#:]*)(?::(\d+))?/,bG=d.fn.load,bH={},bI={},bJ,bK;try{bJ=c.location.href}catch(bL){bJ=c.createElement("a"),bJ.href="",bJ=bJ.href}bK=bF.exec(bJ.toLowerCase()),d.fn.extend({load:function(a,c,e){if(typeof a!=="string"&&bG)return bG.apply(this,arguments);if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var g=a.slice(f,a.length);a=a.slice(0,f)}var h="GET";c&&(d.isFunction(c)?(e=c,c=b):typeof c==="object"&&(c=d.param(c,d.ajaxSettings.traditional),h="POST"));var i=this;d.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?d("<div>").append(c.replace(bz,"")).find(g):c)),e&&i.each(e,[c,b,a])}});return this},serialize:function(){return d.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?d.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bA.test(this.nodeName)||bu.test(this.type))}).map(function(a,b){var c=d(this).val();return c==null?null:d.isArray(c)?d.map(c,function(a,c){return{name:b.name,value:a.replace(br,"\r\n")}}):{name:b.name,value:c.replace(br,"\r\n")}}).get()}}),d.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){d.fn[b]=function(a){return this.bind(b,a)}}),d.each(["get","post"],function(a,c){d[c]=function(a,e,f,g){d.isFunction(e)&&(g=g||f,f=e,e=b);return d.ajax({type:c,url:a,data:e,success:f,dataType:g})}}),d.extend({getScript:function(a,c){return d.get(a,b,c,"script")},getJSON:function(a,b,c){return d.get(a,b,c,"json")},ajaxSetup:function(a,b){b?d.extend(!0,a,d.ajaxSettings,b):(b=a,a=d.extend(!0,d.ajaxSettings,b));for(var c in {context:1,url:1})c in b?a[c]=b[c]:c in d.ajaxSettings&&(a[c]=d.ajaxSettings[c]);return a},ajaxSettings:{url:bJ,isLocal:bv.test(bK[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":d.parseJSON,"text xml":d.parseXML}},ajaxPrefilter:bM(bH),ajaxTransport:bM(bI),ajax:function(a,c){function v(a,c,l,n){if(r!==2){r=2,p&&clearTimeout(p),o=b,m=n||"",u.readyState=a?4:0;var q,t,v,w=l?bP(e,u,l):b,x,y;if(a>=200&&a<300||a===304){if(e.ifModified){if(x=u.getResponseHeader("Last-Modified"))d.lastModified[k]=x;if(y=u.getResponseHeader("Etag"))d.etag[k]=y}if(a===304)c="notmodified",q=!0;else try{t=bQ(e,w),c="success",q=!0}catch(z){c="parsererror",v=z}}else{v=c;if(!c||a)c="error",a<0&&(a=0)}u.status=a,u.statusText=c,q?h.resolveWith(f,[t,c,u]):h.rejectWith(f,[u,c,v]),u.statusCode(j),j=b,s&&g.trigger("ajax"+(q?"Success":"Error"),[u,e,q?t:v]),i.resolveWith(f,[u,c]),s&&(g.trigger("ajaxComplete",[u,e]),--d.active||d.event.trigger("ajaxStop"))}}typeof a==="object"&&(c=a,a=b),c=c||{};var e=d.ajaxSetup({},c),f=e.context||e,g=f!==e&&(f.nodeType||f instanceof d)?d(f):d.event,h=d.Deferred(),i=d._Deferred(),j=e.statusCode||{},k,l={},m,n,o,p,q,r=0,s,t,u={readyState:0,setRequestHeader:function(a,b){r||(l[a.toLowerCase().replace(bD,bE)]=b);return this},getAllResponseHeaders:function(){return r===2?m:null},getResponseHeader:function(a){var c;if(r===2){if(!n){n={};while(c=bt.exec(m))n[c[1].toLowerCase()]=c[2]}c=n[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){r||(e.mimeType=a);return this},abort:function(a){a=a||"abort",o&&o.abort(a),v(0,a);return this}};h.promise(u),u.success=u.done,u.error=u.fail,u.complete=i.done,u.statusCode=function(a){if(a){var b;if(r<2)for(b in a)j[b]=[j[b],a[b]];else b=a[u.status],u.then(b,b)}return this},e.url=((a||e.url)+"").replace(bs,"").replace(bx,bK[1]+"//"),e.dataTypes=d.trim(e.dataType||"*").toLowerCase().split(bB),e.crossDomain||(q=bF.exec(e.url.toLowerCase()),e.crossDomain=q&&(q[1]!=bK[1]||q[2]!=bK[2]||(q[3]||(q[1]==="http:"?80:443))!=(bK[3]||(bK[1]==="http:"?80:443)))),e.data&&e.processData&&typeof e.data!=="string"&&(e.data=d.param(e.data,e.traditional)),bN(bH,e,c,u);if(r===2)return!1;s=e.global,e.type=e.type.toUpperCase(),e.hasContent=!bw.test(e.type),s&&d.active++===0&&d.event.trigger("ajaxStart");if(!e.hasContent){e.data&&(e.url+=(by.test(e.url)?"&":"?")+e.data),k=e.url;if(e.cache===!1){var w=d.now(),x=e.url.replace(bC,"$1_="+w);e.url=x+(x===e.url?(by.test(e.url)?"&":"?")+"_="+w:"")}}if(e.data&&e.hasContent&&e.contentType!==!1||c.contentType)l["Content-Type"]=e.contentType;e.ifModified&&(k=k||e.url,d.lastModified[k]&&(l["If-Modified-Since"]=d.lastModified[k]),d.etag[k]&&(l["If-None-Match"]=d.etag[k])),l.Accept=e.dataTypes[0]&&e.accepts[e.dataTypes[0]]?e.accepts[e.dataTypes[0]]+(e.dataTypes[0]!=="*"?", */*; q=0.01":""):e.accepts["*"];for(t in e.headers)u.setRequestHeader(t,e.headers[t]);if(e.beforeSend&&(e.beforeSend.call(f,u,e)===!1||r===2)){u.abort();return!1}for(t in {success:1,error:1,complete:1})u[t](e[t]);o=bN(bI,e,c,u);if(o){u.readyState=1,s&&g.trigger("ajaxSend",[u,e]),e.async&&e.timeout>0&&(p=setTimeout(function(){u.abort("timeout")},e.timeout));try{r=1,o.send(l,v)}catch(y){status<2?v(-1,y):d.error(y)}}else v(-1,"No Transport");return u},param:function(a,c){var e=[],f=function(a,b){b=d.isFunction(b)?b():b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=d.ajaxSettings.traditional);if(d.isArray(a)||a.jquery&&!d.isPlainObject(a))d.each(a,function(){f(this.name,this.value)});else for(var g in a)bO(g,a[g],c,f);return e.join("&").replace(bp,"+")}}),d.extend({active:0,lastModified:{},etag:{}});var bR=d.now(),bS=/(\=)\?(&|$)|()\?\?()/i;d.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return d.expando+"_"+bR++}}),d.ajaxPrefilter("json jsonp",function(b,c,e){var f=typeof b.data==="string";if(b.dataTypes[0]==="jsonp"||c.jsonpCallback||c.jsonp!=null||b.jsonp!==!1&&(bS.test(b.url)||f&&bS.test(b.data))){var g,h=b.jsonpCallback=d.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2",m=function(){a[h]=i,g&&d.isFunction(i)&&a[h](g[0])};b.jsonp!==!1&&(j=j.replace(bS,l),b.url===j&&(f&&(k=k.replace(bS,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},e.then(m,m),b.converters["script json"]=function(){g||d.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),d.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){d.globalEval(a);return a}}}),d.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),d.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var bT=d.now(),bU,bV;d.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&bX()||bY()}:bX,bV=d.ajaxSettings.xhr(),d.support.ajax=!!bV,d.support.cors=bV&&"withCredentials"in bV,bV=b,d.support.ajax&&d.ajaxTransport(function(a){if(!a.crossDomain||d.support.cors){var c;return{send:function(e,f){var g=a.xhr(),h,i;a.username?g.open(a.type,a.url,a.async,a.username,a.password):g.open(a.type,a.url,a.async);if(a.xhrFields)for(i in a.xhrFields)g[i]=a.xhrFields[i];a.mimeType&&g.overrideMimeType&&g.overrideMimeType(a.mimeType),(!a.crossDomain||a.hasContent)&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(i in e)g.setRequestHeader(i,e[i])}catch(j){}g.send(a.hasContent&&a.data||null),c=function(e,i){var j,k,l,m,n;try{if(c&&(i||g.readyState===4)){c=b,h&&(g.onreadystatechange=d.noop,delete bU[h]);if(i)g.readyState!==4&&g.abort();else{j=g.status,l=g.getAllResponseHeaders(),m={},n=g.responseXML,n&&n.documentElement&&(m.xml=n),m.text=g.responseText;try{k=g.statusText}catch(o){k=""}j||!a.isLocal||a.crossDomain?j===1223&&(j=204):j=m.text?200:404}}}catch(p){i||f(-1,p)}m&&f(j,k,m,l)},a.async&&g.readyState!==4?(bU||(bU={},bW()),h=bT++,g.onreadystatechange=bU[h]=c):c()},abort:function(){c&&c(0,1)}}}});var bZ={},b$=/^(?:toggle|show|hide)$/,b_=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,ca,cb=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];d.fn.extend({show:function(a,b,c){var e,f;if(a||a===0)return this.animate(cc("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)e=this[g],f=e.style.display,!d._data(e,"olddisplay")&&f==="none"&&(f=e.style.display=""),f===""&&d.css(e,"display")==="none"&&d._data(e,"olddisplay",cd(e.nodeName));for(g=0;g<h;g++){e=this[g],f=e.style.display;if(f===""||f==="none")e.style.display=d._data(e,"olddisplay")||""}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cc("hide",3),a,b,c);for(var e=0,f=this.length;e<f;e++){var g=d.css(this[e],"display");g!=="none"&&!d._data(this[e],"olddisplay")&&d._data(this[e],"olddisplay",g)}for(e=0;e<f;e++)this[e].style.display="none";return this},_toggle:d.fn.toggle,toggle:function(a,b,c){var e=typeof a==="boolean";d.isFunction(a)&&d.isFunction(b)?this._toggle.apply(this,arguments):a==null||e?this.each(function(){var b=e?a:d(this).is(":hidden");d(this)[b?"show":"hide"]()}):this.animate(cc("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,e){var f=d.speed(b,c,e);if(d.isEmptyObject(a))return this.each(f.complete);return this[f.queue===!1?"each":"queue"](function(){var b=d.extend({},f),c,e=this.nodeType===1,g=e&&d(this).is(":hidden"),h=this;for(c in a){var i=d.camelCase(c);c!==i&&(a[i]=a[c],delete a[c],c=i);if(a[c]==="hide"&&g||a[c]==="show"&&!g)return b.complete.call(this);if(e&&(c==="height"||c==="width")){b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(d.css(this,"display")==="inline"&&d.css(this,"float")==="none")if(d.support.inlineBlockNeedsLayout){var j=cd(this.nodeName);j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)}else this.style.display="inline-block"}d.isArray(a[c])&&((b.specialEasing=b.specialEasing||{})[c]=a[c][1],a[c]=a[c][0])}b.overflow!=null&&(this.style.overflow="hidden"),b.curAnim=d.extend({},a),d.each(a,function(c,e){var f=new d.fx(h,b,c);if(b$.test(e))f[e==="toggle"?g?"show":"hide":e](a);else{var i=b_.exec(e),j=f.cur();if(i){var k=parseFloat(i[2]),l=i[3]||(d.cssNumber[c]?"":"px");l!=="px"&&(d.style(h,c,(k||1)+l),j=(k||1)/f.cur()*j,d.style(h,c,j+l)),i[1]&&(k=(i[1]==="-="?-1:1)*k+j),f.custom(j,k,l)}else f.custom(j,e,"")}});return!0})},stop:function(a,b){var c=d.timers;a&&this.queue([]),this.each(function(){for(var a=c.length-1;a>=0;a--)c[a].elem===this&&(b&&c[a](!0),c.splice(a,1))}),b||this.dequeue();return this}}),d.each({slideDown:cc("show",1),slideUp:cc("hide",1),slideToggle:cc("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){d.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),d.extend({speed:function(a,b,c){var e=a&&typeof a==="object"?d.extend({},a):{complete:c||!c&&b||d.isFunction(a)&&a,duration:a,easing:c&&b||b&&!d.isFunction(b)&&b};e.duration=d.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in d.fx.speeds?d.fx.speeds[e.duration]:d.fx.speeds._default,e.old=e.complete,e.complete=function(){e.queue!==!1&&d(this).dequeue(),d.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig||(b.orig={})}}),d.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(d.fx.step[this.prop]||d.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=d.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,b,c){function g(a){return e.step(a)}var e=this,f=d.fx;this.startTime=d.now(),this.start=a,this.end=b,this.unit=c||this.unit||(d.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,g.elem=this.elem,g()&&d.timers.push(g)&&!ca&&(ca=setInterval(f.tick,f.interval))},show:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),d(this.elem).show()},hide:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=d.now(),c=!0;if(a||b>=this.options.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),this.options.curAnim[this.prop]=!0;for(var e in this.options.curAnim)this.options.curAnim[e]!==!0&&(c=!1);if(c){if(this.options.overflow!=null&&!d.support.shrinkWrapBlocks){var f=this.elem,g=this.options;d.each(["","X","Y"],function(a,b){f.style["overflow"+b]=g.overflow[a]})}this.options.hide&&d(this.elem).hide();if(this.options.hide||this.options.show)for(var h in this.options.curAnim)d.style(this.elem,h,this.options.orig[h]);this.options.complete.call(this.elem)}return!1}var i=b-this.startTime;this.state=i/this.options.duration;var j=this.options.specialEasing&&this.options.specialEasing[this.prop],k=this.options.easing||(d.easing.swing?"swing":"linear");this.pos=d.easing[j||k](this.state,i,0,1,this.options.duration),this.now=this.start+(this.end-this.start)*this.pos,this.update();return!0}},d.extend(d.fx,{tick:function(){var a=d.timers;for(var b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||d.fx.stop()},interval:13,stop:function(){clearInterval(ca),ca=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){d.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=a.now}}}),d.expr&&d.expr.filters&&(d.expr.filters.animated=function(a){return d.grep(d.timers,function(b){return a===b.elem}).length});var ce=/^t(?:able|d|h)$/i,cf=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?d.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,g=f.documentElement;if(!c||!d.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=f.body,i=cg(f),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||d.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||d.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:d.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);d.offset.initialize();var c,e=b.offsetParent,f=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(d.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===e&&(l+=b.offsetTop,m+=b.offsetLeft,d.offset.doesNotAddBorder&&(!d.offset.doesAddBorderForTableAndCells||!ce.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),f=e,e=b.offsetParent),d.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;d.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},d.offset={initialize:function(){var a=c.body,b=c.createElement("div"),e,f,g,h,i=parseFloat(d.css(a,"marginTop"))||0,j="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";d.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),e=b.firstChild,f=e.firstChild,h=e.nextSibling.firstChild.firstChild,this.doesNotAddBorder=f.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,f.style.position="fixed",f.style.top="20px",this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15,f.style.position=f.style.top="",e.style.overflow="hidden",e.style.position="relative",this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),a=b=e=f=g=h=null,d.offset.initialize=d.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;d.offset.initialize(),d.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(d.css(a,"marginTop"))||0,c+=parseFloat(d.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var e=d.css(a,"position");e==="static"&&(a.style.position="relative");var f=d(a),g=f.offset(),h=d.css(a,"top"),i=d.css(a,"left"),j=e==="absolute"&&d.inArray("auto",[h,i])>-1,k={},l={},m,n;j&&(l=f.position()),m=j?l.top:parseInt(h,10)||0,n=j?l.left:parseInt(i,10)||0,d.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):f.css(k)}},d.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),e=cf.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(d.css(a,"marginTop"))||0,c.left-=parseFloat(d.css(a,"marginLeft"))||0,e.top+=parseFloat(d.css(b[0],"borderTopWidth"))||0,e.left+=parseFloat(d.css(b[0],"borderLeftWidth"))||0;return{top:c.top-e.top,left:c.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&(!cf.test(a.nodeName)&&d.css(a,"position")==="static"))a=a.offsetParent;return a})}}),d.each(["Left","Top"],function(a,c){var e="scroll"+c;d.fn[e]=function(c){var f=this[0],g;if(!f)return null;if(c!==b)return this.each(function(){g=cg(this),g?g.scrollTo(a?d(g).scrollLeft():c,a?c:d(g).scrollTop()):this[e]=c});g=cg(f);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:d.support.boxModel&&g.document.documentElement[e]||g.document.body[e]:f[e]}}),d.each(["Height","Width"],function(a,c){var e=c.toLowerCase();d.fn["inner"+c]=function(){return this[0]?parseFloat(d.css(this[0],e,"padding")):null},d.fn["outer"+c]=function(a){return this[0]?parseFloat(d.css(this[0],e,a?"margin":"border")):null},d.fn[e]=function(a){var f=this[0];if(!f)return a==null?null:this;if(d.isFunction(a))return this.each(function(b){var c=d(this);c[e](a.call(this,b,c[e]()))});if(d.isWindow(f)){var g=f.document.documentElement["client"+c];return f.document.compatMode==="CSS1Compat"&&g||f.document.body["client"+c]||g}if(f.nodeType===9)return Math.max(f.documentElement["client"+c],f.body["scroll"+c],f.documentElement["scroll"+c],f.body["offset"+c],f.documentElement["offset"+c]);if(a===b){var h=d.css(f,e),i=parseFloat(h);return d.isNaN(i)?h:i}return this.css(e,typeof a==="string"?a:a+"px")}}),a.jQuery=a.$=d})(window); \ No newline at end of file diff --git a/3rdparty/timepicker/css/include/jquery-ui-1.8.14.custom.css b/3rdparty/timepicker/css/include/jquery-ui-1.8.14.custom.css deleted file mode 100644 index fe310705756befa7e6c0e28fc7edd0d2e4323275..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/css/include/jquery-ui-1.8.14.custom.css +++ /dev/null @@ -1,568 +0,0 @@ -/* - * jQuery UI CSS Framework 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Theming/API - */ - -/* Layout helpers -----------------------------------*/ -.ui-helper-hidden { display: none; } -.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); } -.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } -.ui-helper-clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } -.ui-helper-clearfix { display: inline-block; } -/* required comment for clearfix to work in Opera \*/ -* html .ui-helper-clearfix { height:1%; } -.ui-helper-clearfix { display:block; } -/* end clearfix */ -.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); } - - -/* Interaction Cues -----------------------------------*/ -.ui-state-disabled { cursor: default !important; } - - -/* Icons -----------------------------------*/ - -/* states and images */ -.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } - - -/* Misc visuals -----------------------------------*/ - -/* Overlays */ -.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } - - -/* - * jQuery UI CSS Framework 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Theming/API - * - * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Trebuchet%20MS,%20Tahoma,%20Verdana,%20Arial,%20sans-serif&fwDefault=bold&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=f6a828&bgTextureHeader=12_gloss_wave.png&bgImgOpacityHeader=35&borderColorHeader=e78f08&fcHeader=ffffff&iconColorHeader=ffffff&bgColorContent=eeeeee&bgTextureContent=03_highlight_soft.png&bgImgOpacityContent=100&borderColorContent=dddddd&fcContent=333333&iconColorContent=222222&bgColorDefault=f6f6f6&bgTextureDefault=02_glass.png&bgImgOpacityDefault=100&borderColorDefault=cccccc&fcDefault=1c94c4&iconColorDefault=ef8c08&bgColorHover=fdf5ce&bgTextureHover=02_glass.png&bgImgOpacityHover=100&borderColorHover=fbcb09&fcHover=c77405&iconColorHover=ef8c08&bgColorActive=ffffff&bgTextureActive=02_glass.png&bgImgOpacityActive=65&borderColorActive=fbd850&fcActive=eb8f00&iconColorActive=ef8c08&bgColorHighlight=ffe45c&bgTextureHighlight=03_highlight_soft.png&bgImgOpacityHighlight=75&borderColorHighlight=fed22f&fcHighlight=363636&iconColorHighlight=228ef1&bgColorError=b81900&bgTextureError=08_diagonals_thick.png&bgImgOpacityError=18&borderColorError=cd0a0a&fcError=ffffff&iconColorError=ffd27a&bgColorOverlay=666666&bgTextureOverlay=08_diagonals_thick.png&bgImgOpacityOverlay=20&opacityOverlay=50&bgColorShadow=000000&bgTextureShadow=01_flat.png&bgImgOpacityShadow=10&opacityShadow=20&thicknessShadow=5px&offsetTopShadow=-5px&offsetLeftShadow=-5px&cornerRadiusShadow=5px - */ - - -/* Component containers -----------------------------------*/ -.ui-widget { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1.1em; } -.ui-widget .ui-widget { font-size: 1em; } -.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1em; } -.ui-widget-content { border: 1px solid #dddddd; background: #eeeeee url(images/ui-bg_highlight-soft_100_eeeeee_1x100.png) 50% top repeat-x; color: #333333; } -.ui-widget-content a { color: #333333; } -.ui-widget-header { border: 1px solid #e78f08; background: #f6a828 url(images/ui-bg_gloss-wave_35_f6a828_500x100.png) 50% 50% repeat-x; color: #ffffff; font-weight: bold; } -.ui-widget-header a { color: #ffffff; } - -/* Interaction states -----------------------------------*/ -.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; background: #f6f6f6 url(images/ui-bg_glass_100_f6f6f6_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #1c94c4; } -.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #1c94c4; text-decoration: none; } -.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #fbcb09; background: #fdf5ce url(images/ui-bg_glass_100_fdf5ce_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #c77405; } -.ui-state-hover a, .ui-state-hover a:hover { color: #c77405; text-decoration: none; } -.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #fbd850; background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #eb8f00; } -.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #eb8f00; text-decoration: none; } -.ui-widget :active { outline: none; } - -/* Interaction Cues -----------------------------------*/ -.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #fed22f; background: #ffe45c url(images/ui-bg_highlight-soft_75_ffe45c_1x100.png) 50% top repeat-x; color: #363636; } -.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636; } -.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #b81900 url(images/ui-bg_diagonals-thick_18_b81900_40x40.png) 50% 50% repeat; color: #ffffff; } -.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #ffffff; } -.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #ffffff; } -.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; } -.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; } -.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; } - -/* Icons -----------------------------------*/ - -/* states and images */ -.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_222222_256x240.png); } -.ui-widget-content .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); } -.ui-widget-header .ui-icon {background-image: url(images/ui-icons_ffffff_256x240.png); } -.ui-state-default .ui-icon { background-image: url(images/ui-icons_ef8c08_256x240.png); } -.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_ef8c08_256x240.png); } -.ui-state-active .ui-icon {background-image: url(images/ui-icons_ef8c08_256x240.png); } -.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_228ef1_256x240.png); } -.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_ffd27a_256x240.png); } - -/* positioning */ -.ui-icon-carat-1-n { background-position: 0 0; } -.ui-icon-carat-1-ne { background-position: -16px 0; } -.ui-icon-carat-1-e { background-position: -32px 0; } -.ui-icon-carat-1-se { background-position: -48px 0; } -.ui-icon-carat-1-s { background-position: -64px 0; } -.ui-icon-carat-1-sw { background-position: -80px 0; } -.ui-icon-carat-1-w { background-position: -96px 0; } -.ui-icon-carat-1-nw { background-position: -112px 0; } -.ui-icon-carat-2-n-s { background-position: -128px 0; } -.ui-icon-carat-2-e-w { background-position: -144px 0; } -.ui-icon-triangle-1-n { background-position: 0 -16px; } -.ui-icon-triangle-1-ne { background-position: -16px -16px; } -.ui-icon-triangle-1-e { background-position: -32px -16px; } -.ui-icon-triangle-1-se { background-position: -48px -16px; } -.ui-icon-triangle-1-s { background-position: -64px -16px; } -.ui-icon-triangle-1-sw { background-position: -80px -16px; } -.ui-icon-triangle-1-w { background-position: -96px -16px; } -.ui-icon-triangle-1-nw { background-position: -112px -16px; } -.ui-icon-triangle-2-n-s { background-position: -128px -16px; } -.ui-icon-triangle-2-e-w { background-position: -144px -16px; } -.ui-icon-arrow-1-n { background-position: 0 -32px; } -.ui-icon-arrow-1-ne { background-position: -16px -32px; } -.ui-icon-arrow-1-e { background-position: -32px -32px; } -.ui-icon-arrow-1-se { background-position: -48px -32px; } -.ui-icon-arrow-1-s { background-position: -64px -32px; } -.ui-icon-arrow-1-sw { background-position: -80px -32px; } -.ui-icon-arrow-1-w { background-position: -96px -32px; } -.ui-icon-arrow-1-nw { background-position: -112px -32px; } -.ui-icon-arrow-2-n-s { background-position: -128px -32px; } -.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } -.ui-icon-arrow-2-e-w { background-position: -160px -32px; } -.ui-icon-arrow-2-se-nw { background-position: -176px -32px; } -.ui-icon-arrowstop-1-n { background-position: -192px -32px; } -.ui-icon-arrowstop-1-e { background-position: -208px -32px; } -.ui-icon-arrowstop-1-s { background-position: -224px -32px; } -.ui-icon-arrowstop-1-w { background-position: -240px -32px; } -.ui-icon-arrowthick-1-n { background-position: 0 -48px; } -.ui-icon-arrowthick-1-ne { background-position: -16px -48px; } -.ui-icon-arrowthick-1-e { background-position: -32px -48px; } -.ui-icon-arrowthick-1-se { background-position: -48px -48px; } -.ui-icon-arrowthick-1-s { background-position: -64px -48px; } -.ui-icon-arrowthick-1-sw { background-position: -80px -48px; } -.ui-icon-arrowthick-1-w { background-position: -96px -48px; } -.ui-icon-arrowthick-1-nw { background-position: -112px -48px; } -.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } -.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } -.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } -.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } -.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } -.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } -.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } -.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } -.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } -.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } -.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } -.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } -.ui-icon-arrowreturn-1-w { background-position: -64px -64px; } -.ui-icon-arrowreturn-1-n { background-position: -80px -64px; } -.ui-icon-arrowreturn-1-e { background-position: -96px -64px; } -.ui-icon-arrowreturn-1-s { background-position: -112px -64px; } -.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } -.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } -.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } -.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } -.ui-icon-arrow-4 { background-position: 0 -80px; } -.ui-icon-arrow-4-diag { background-position: -16px -80px; } -.ui-icon-extlink { background-position: -32px -80px; } -.ui-icon-newwin { background-position: -48px -80px; } -.ui-icon-refresh { background-position: -64px -80px; } -.ui-icon-shuffle { background-position: -80px -80px; } -.ui-icon-transfer-e-w { background-position: -96px -80px; } -.ui-icon-transferthick-e-w { background-position: -112px -80px; } -.ui-icon-folder-collapsed { background-position: 0 -96px; } -.ui-icon-folder-open { background-position: -16px -96px; } -.ui-icon-document { background-position: -32px -96px; } -.ui-icon-document-b { background-position: -48px -96px; } -.ui-icon-note { background-position: -64px -96px; } -.ui-icon-mail-closed { background-position: -80px -96px; } -.ui-icon-mail-open { background-position: -96px -96px; } -.ui-icon-suitcase { background-position: -112px -96px; } -.ui-icon-comment { background-position: -128px -96px; } -.ui-icon-person { background-position: -144px -96px; } -.ui-icon-print { background-position: -160px -96px; } -.ui-icon-trash { background-position: -176px -96px; } -.ui-icon-locked { background-position: -192px -96px; } -.ui-icon-unlocked { background-position: -208px -96px; } -.ui-icon-bookmark { background-position: -224px -96px; } -.ui-icon-tag { background-position: -240px -96px; } -.ui-icon-home { background-position: 0 -112px; } -.ui-icon-flag { background-position: -16px -112px; } -.ui-icon-calendar { background-position: -32px -112px; } -.ui-icon-cart { background-position: -48px -112px; } -.ui-icon-pencil { background-position: -64px -112px; } -.ui-icon-clock { background-position: -80px -112px; } -.ui-icon-disk { background-position: -96px -112px; } -.ui-icon-calculator { background-position: -112px -112px; } -.ui-icon-zoomin { background-position: -128px -112px; } -.ui-icon-zoomout { background-position: -144px -112px; } -.ui-icon-search { background-position: -160px -112px; } -.ui-icon-wrench { background-position: -176px -112px; } -.ui-icon-gear { background-position: -192px -112px; } -.ui-icon-heart { background-position: -208px -112px; } -.ui-icon-star { background-position: -224px -112px; } -.ui-icon-link { background-position: -240px -112px; } -.ui-icon-cancel { background-position: 0 -128px; } -.ui-icon-plus { background-position: -16px -128px; } -.ui-icon-plusthick { background-position: -32px -128px; } -.ui-icon-minus { background-position: -48px -128px; } -.ui-icon-minusthick { background-position: -64px -128px; } -.ui-icon-close { background-position: -80px -128px; } -.ui-icon-closethick { background-position: -96px -128px; } -.ui-icon-key { background-position: -112px -128px; } -.ui-icon-lightbulb { background-position: -128px -128px; } -.ui-icon-scissors { background-position: -144px -128px; } -.ui-icon-clipboard { background-position: -160px -128px; } -.ui-icon-copy { background-position: -176px -128px; } -.ui-icon-contact { background-position: -192px -128px; } -.ui-icon-image { background-position: -208px -128px; } -.ui-icon-video { background-position: -224px -128px; } -.ui-icon-script { background-position: -240px -128px; } -.ui-icon-alert { background-position: 0 -144px; } -.ui-icon-info { background-position: -16px -144px; } -.ui-icon-notice { background-position: -32px -144px; } -.ui-icon-help { background-position: -48px -144px; } -.ui-icon-check { background-position: -64px -144px; } -.ui-icon-bullet { background-position: -80px -144px; } -.ui-icon-radio-off { background-position: -96px -144px; } -.ui-icon-radio-on { background-position: -112px -144px; } -.ui-icon-pin-w { background-position: -128px -144px; } -.ui-icon-pin-s { background-position: -144px -144px; } -.ui-icon-play { background-position: 0 -160px; } -.ui-icon-pause { background-position: -16px -160px; } -.ui-icon-seek-next { background-position: -32px -160px; } -.ui-icon-seek-prev { background-position: -48px -160px; } -.ui-icon-seek-end { background-position: -64px -160px; } -.ui-icon-seek-start { background-position: -80px -160px; } -/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ -.ui-icon-seek-first { background-position: -80px -160px; } -.ui-icon-stop { background-position: -96px -160px; } -.ui-icon-eject { background-position: -112px -160px; } -.ui-icon-volume-off { background-position: -128px -160px; } -.ui-icon-volume-on { background-position: -144px -160px; } -.ui-icon-power { background-position: 0 -176px; } -.ui-icon-signal-diag { background-position: -16px -176px; } -.ui-icon-signal { background-position: -32px -176px; } -.ui-icon-battery-0 { background-position: -48px -176px; } -.ui-icon-battery-1 { background-position: -64px -176px; } -.ui-icon-battery-2 { background-position: -80px -176px; } -.ui-icon-battery-3 { background-position: -96px -176px; } -.ui-icon-circle-plus { background-position: 0 -192px; } -.ui-icon-circle-minus { background-position: -16px -192px; } -.ui-icon-circle-close { background-position: -32px -192px; } -.ui-icon-circle-triangle-e { background-position: -48px -192px; } -.ui-icon-circle-triangle-s { background-position: -64px -192px; } -.ui-icon-circle-triangle-w { background-position: -80px -192px; } -.ui-icon-circle-triangle-n { background-position: -96px -192px; } -.ui-icon-circle-arrow-e { background-position: -112px -192px; } -.ui-icon-circle-arrow-s { background-position: -128px -192px; } -.ui-icon-circle-arrow-w { background-position: -144px -192px; } -.ui-icon-circle-arrow-n { background-position: -160px -192px; } -.ui-icon-circle-zoomin { background-position: -176px -192px; } -.ui-icon-circle-zoomout { background-position: -192px -192px; } -.ui-icon-circle-check { background-position: -208px -192px; } -.ui-icon-circlesmall-plus { background-position: 0 -208px; } -.ui-icon-circlesmall-minus { background-position: -16px -208px; } -.ui-icon-circlesmall-close { background-position: -32px -208px; } -.ui-icon-squaresmall-plus { background-position: -48px -208px; } -.ui-icon-squaresmall-minus { background-position: -64px -208px; } -.ui-icon-squaresmall-close { background-position: -80px -208px; } -.ui-icon-grip-dotted-vertical { background-position: 0 -224px; } -.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } -.ui-icon-grip-solid-vertical { background-position: -32px -224px; } -.ui-icon-grip-solid-horizontal { background-position: -48px -224px; } -.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } -.ui-icon-grip-diagonal-se { background-position: -80px -224px; } - - -/* Misc visuals -----------------------------------*/ - -/* Corner radius */ -.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -khtml-border-top-left-radius: 4px; border-top-left-radius: 4px; } -.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; -khtml-border-top-right-radius: 4px; border-top-right-radius: 4px; } -.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; -khtml-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; } -.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; -khtml-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; } - -/* Overlays */ -.ui-widget-overlay { background: #666666 url(images/ui-bg_diagonals-thick_20_666666_40x40.png) 50% 50% repeat; opacity: .50;filter:Alpha(Opacity=50); } -.ui-widget-shadow { margin: -5px 0 0 -5px; padding: 5px; background: #000000 url(images/ui-bg_flat_10_000000_40x100.png) 50% 50% repeat-x; opacity: .20;filter:Alpha(Opacity=20); -moz-border-radius: 5px; -khtml-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; }/* - * jQuery UI Resizable 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Resizable#theming - */ -.ui-resizable { position: relative;} -.ui-resizable-handle { position: absolute;font-size: 0.1px;z-index: 99999; display: block; } -.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; } -.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; } -.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; } -.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; } -.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; } -.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; } -.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; } -.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; } -.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}/* - * jQuery UI Selectable 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Selectable#theming - */ -.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; } -/* - * jQuery UI Accordion 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Accordion#theming - */ -/* IE/Win - Fix animation bug - #4615 */ -.ui-accordion { width: 100%; } -.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; } -.ui-accordion .ui-accordion-li-fix { display: inline; } -.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; } -.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: .5em .5em .5em .7em; } -.ui-accordion-icons .ui-accordion-header a { padding-left: 2.2em; } -.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; } -.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; zoom: 1; } -.ui-accordion .ui-accordion-content-active { display: block; } -/* - * jQuery UI Autocomplete 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Autocomplete#theming - */ -.ui-autocomplete { position: absolute; cursor: default; } - -/* workarounds */ -* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */ - -/* - * jQuery UI Menu 1.8.14 - * - * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Menu#theming - */ -.ui-menu { - list-style:none; - padding: 2px; - margin: 0; - display:block; - float: left; -} -.ui-menu .ui-menu { - margin-top: -3px; -} -.ui-menu .ui-menu-item { - margin:0; - padding: 0; - zoom: 1; - float: left; - clear: left; - width: 100%; -} -.ui-menu .ui-menu-item a { - text-decoration:none; - display:block; - padding:.2em .4em; - line-height:1.5; - zoom:1; -} -.ui-menu .ui-menu-item a.ui-state-hover, -.ui-menu .ui-menu-item a.ui-state-active { - font-weight: normal; - margin: -1px; -} -/* - * jQuery UI Button 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Button#theming - */ -.ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; text-decoration: none !important; cursor: pointer; text-align: center; zoom: 1; overflow: visible; } /* the overflow property removes extra width in IE */ -.ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */ -button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */ -.ui-button-icons-only { width: 3.4em; } -button.ui-button-icons-only { width: 3.7em; } - -/*button text element */ -.ui-button .ui-button-text { display: block; line-height: 1.4; } -.ui-button-text-only .ui-button-text { padding: .4em 1em; } -.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; } -.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; } -.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; } -.ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; } -/* no icon support for input elements, provide padding by default */ -input.ui-button { padding: .4em 1em; } - -/*button icon element(s) */ -.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; } -.ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; } -.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; } -.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } -.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } - -/*button sets*/ -.ui-buttonset { margin-right: 7px; } -.ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; } - -/* workarounds */ -button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */ -/* - * jQuery UI Dialog 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Dialog#theming - */ -.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; } -.ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative; } -.ui-dialog .ui-dialog-title { float: left; margin: .1em 16px .1em 0; } -.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; } -.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; } -.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; } -.ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; } -.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; } -.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; } -.ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; } -.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; } -.ui-draggable .ui-dialog-titlebar { cursor: move; } -/* - * jQuery UI Slider 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Slider#theming - */ -.ui-slider { position: relative; text-align: left; } -.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; } -.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; } - -.ui-slider-horizontal { height: .8em; } -.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; } -.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; } -.ui-slider-horizontal .ui-slider-range-min { left: 0; } -.ui-slider-horizontal .ui-slider-range-max { right: 0; } - -.ui-slider-vertical { width: .8em; height: 100px; } -.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; } -.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; } -.ui-slider-vertical .ui-slider-range-min { bottom: 0; } -.ui-slider-vertical .ui-slider-range-max { top: 0; }/* - * jQuery UI Tabs 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Tabs#theming - */ -.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ -.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; } -.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 1px; margin: 0 .2em 1px 0; border-bottom: 0 !important; padding: 0; white-space: nowrap; } -.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; } -.ui-tabs .ui-tabs-nav li.ui-tabs-selected { margin-bottom: 0; padding-bottom: 1px; } -.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; } -.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ -.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; } -.ui-tabs .ui-tabs-hide { display: none !important; } -/* - * jQuery UI Datepicker 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Datepicker#theming - */ -.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; } -.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; } -.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; } -.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; } -.ui-datepicker .ui-datepicker-prev { left:2px; } -.ui-datepicker .ui-datepicker-next { right:2px; } -.ui-datepicker .ui-datepicker-prev-hover { left:1px; } -.ui-datepicker .ui-datepicker-next-hover { right:1px; } -.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; } -.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; } -.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; } -.ui-datepicker select.ui-datepicker-month-year {width: 100%;} -.ui-datepicker select.ui-datepicker-month, -.ui-datepicker select.ui-datepicker-year { width: 49%;} -.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; } -.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; } -.ui-datepicker td { border: 0; padding: 1px; } -.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; } -.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; } -.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; } -.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; } - -/* with multiple calendars */ -.ui-datepicker.ui-datepicker-multi { width:auto; } -.ui-datepicker-multi .ui-datepicker-group { float:left; } -.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; } -.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; } -.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; } -.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; } -.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; } -.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; } -.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; } -.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; } - -/* RTL support */ -.ui-datepicker-rtl { direction: rtl; } -.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; } -.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; } -.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; } -.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; } -.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; } -.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; } -.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; } -.ui-datepicker-rtl .ui-datepicker-group { float:right; } -.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; } -.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; } - -/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ -.ui-datepicker-cover { - display: none; /*sorry for IE5*/ - display/**/: block; /*sorry for IE5*/ - position: absolute; /*must have*/ - z-index: -1; /*must have*/ - filter: mask(); /*must have*/ - top: -4px; /*must have*/ - left: -4px; /*must have*/ - width: 200px; /*must have*/ - height: 200px; /*must have*/ -}/* - * jQuery UI Progressbar 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Progressbar#theming - */ -.ui-progressbar { height:2em; text-align: left; } -.ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; } \ No newline at end of file diff --git a/3rdparty/timepicker/css/include/jquery.ui.core.min.js b/3rdparty/timepicker/css/include/jquery.ui.core.min.js deleted file mode 100644 index 577548e7882e81794897cb6cb8f7dacd369c592f..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/css/include/jquery.ui.core.min.js +++ /dev/null @@ -1,17 +0,0 @@ -/*! - * jQuery UI 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI - */ -(function(c,j){function k(a,b){var d=a.nodeName.toLowerCase();if("area"===d){b=a.parentNode;d=b.name;if(!a.href||!d||b.nodeName.toLowerCase()!=="map")return false;a=c("img[usemap=#"+d+"]")[0];return!!a&&l(a)}return(/input|select|textarea|button|object/.test(d)?!a.disabled:"a"==d?a.href||b:b)&&l(a)}function l(a){return!c(a).parents().andSelf().filter(function(){return c.curCSS(this,"visibility")==="hidden"||c.expr.filters.hidden(this)}).length}c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.14", -keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus(); -b&&b.call(d)},a)}):this._focus.apply(this,arguments)},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this, -"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==j)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b==="absolute"||b==="relative"||b==="fixed"){b=parseInt(a.css("zIndex"),10);if(!isNaN(b)&&b!==0)return b}a=a.parent()}}return 0},disableSelection:function(){return this.bind((c.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection", -function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});c.each(["Width","Height"],function(a,b){function d(f,g,m,n){c.each(e,function(){g-=parseFloat(c.curCSS(f,"padding"+this,true))||0;if(m)g-=parseFloat(c.curCSS(f,"border"+this+"Width",true))||0;if(n)g-=parseFloat(c.curCSS(f,"margin"+this,true))||0});return g}var e=b==="Width"?["Left","Right"]:["Top","Bottom"],h=b.toLowerCase(),i={innerWidth:c.fn.innerWidth,innerHeight:c.fn.innerHeight,outerWidth:c.fn.outerWidth, -outerHeight:c.fn.outerHeight};c.fn["inner"+b]=function(f){if(f===j)return i["inner"+b].call(this);return this.each(function(){c(this).css(h,d(this,f)+"px")})};c.fn["outer"+b]=function(f,g){if(typeof f!=="number")return i["outer"+b].call(this,f);return this.each(function(){c(this).css(h,d(this,f,true,g)+"px")})}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){return k(a,!isNaN(c.attr(a,"tabindex")))},tabbable:function(a){var b=c.attr(a,"tabindex"),d=isNaN(b); -return(d||b>=0)&&k(a,!d)}});c(function(){var a=document.body,b=a.appendChild(b=document.createElement("div"));c.extend(b.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});c.support.minHeight=b.offsetHeight===100;c.support.selectstart="onselectstart"in b;a.removeChild(b).style.display="none"});c.extend(c.ui,{plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e= -0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element,d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")==="hidden")return false;b=b&&b==="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,h,i){return c.ui.isOverAxis(a,d,h)&&c.ui.isOverAxis(b,e,i)}})}})(jQuery); diff --git a/3rdparty/timepicker/css/include/jquery.ui.position.min.js b/3rdparty/timepicker/css/include/jquery.ui.position.min.js deleted file mode 100644 index 9f550be8e21e6e3e10e042013a6ed347fa425261..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/css/include/jquery.ui.position.min.js +++ /dev/null @@ -1,16 +0,0 @@ -/* - * jQuery UI Position 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Position - */ -(function(c){c.ui=c.ui||{};var n=/left|center|right/,o=/top|center|bottom/,t=c.fn.position,u=c.fn.offset;c.fn.position=function(b){if(!b||!b.of)return t.apply(this,arguments);b=c.extend({},b);var a=c(b.of),d=a[0],g=(b.collision||"flip").split(" "),e=b.offset?b.offset.split(" "):[0,0],h,k,j;if(d.nodeType===9){h=a.width();k=a.height();j={top:0,left:0}}else if(d.setTimeout){h=a.width();k=a.height();j={top:a.scrollTop(),left:a.scrollLeft()}}else if(d.preventDefault){b.at="left top";h=k=0;j={top:b.of.pageY, -left:b.of.pageX}}else{h=a.outerWidth();k=a.outerHeight();j=a.offset()}c.each(["my","at"],function(){var f=(b[this]||"").split(" ");if(f.length===1)f=n.test(f[0])?f.concat(["center"]):o.test(f[0])?["center"].concat(f):["center","center"];f[0]=n.test(f[0])?f[0]:"center";f[1]=o.test(f[1])?f[1]:"center";b[this]=f});if(g.length===1)g[1]=g[0];e[0]=parseInt(e[0],10)||0;if(e.length===1)e[1]=e[0];e[1]=parseInt(e[1],10)||0;if(b.at[0]==="right")j.left+=h;else if(b.at[0]==="center")j.left+=h/2;if(b.at[1]==="bottom")j.top+= -k;else if(b.at[1]==="center")j.top+=k/2;j.left+=e[0];j.top+=e[1];return this.each(function(){var f=c(this),l=f.outerWidth(),m=f.outerHeight(),p=parseInt(c.curCSS(this,"marginLeft",true))||0,q=parseInt(c.curCSS(this,"marginTop",true))||0,v=l+p+(parseInt(c.curCSS(this,"marginRight",true))||0),w=m+q+(parseInt(c.curCSS(this,"marginBottom",true))||0),i=c.extend({},j),r;if(b.my[0]==="right")i.left-=l;else if(b.my[0]==="center")i.left-=l/2;if(b.my[1]==="bottom")i.top-=m;else if(b.my[1]==="center")i.top-= -m/2;i.left=Math.round(i.left);i.top=Math.round(i.top);r={left:i.left-p,top:i.top-q};c.each(["left","top"],function(s,x){c.ui.position[g[s]]&&c.ui.position[g[s]][x](i,{targetWidth:h,targetHeight:k,elemWidth:l,elemHeight:m,collisionPosition:r,collisionWidth:v,collisionHeight:w,offset:e,my:b.my,at:b.at})});c.fn.bgiframe&&f.bgiframe();f.offset(c.extend(i,{using:b.using}))})};c.ui.position={fit:{left:function(b,a){var d=c(window);d=a.collisionPosition.left+a.collisionWidth-d.width()-d.scrollLeft();b.left= -d>0?b.left-d:Math.max(b.left-a.collisionPosition.left,b.left)},top:function(b,a){var d=c(window);d=a.collisionPosition.top+a.collisionHeight-d.height()-d.scrollTop();b.top=d>0?b.top-d:Math.max(b.top-a.collisionPosition.top,b.top)}},flip:{left:function(b,a){if(a.at[0]!=="center"){var d=c(window);d=a.collisionPosition.left+a.collisionWidth-d.width()-d.scrollLeft();var g=a.my[0]==="left"?-a.elemWidth:a.my[0]==="right"?a.elemWidth:0,e=a.at[0]==="left"?a.targetWidth:-a.targetWidth,h=-2*a.offset[0];b.left+= -a.collisionPosition.left<0?g+e+h:d>0?g+e+h:0}},top:function(b,a){if(a.at[1]!=="center"){var d=c(window);d=a.collisionPosition.top+a.collisionHeight-d.height()-d.scrollTop();var g=a.my[1]==="top"?-a.elemHeight:a.my[1]==="bottom"?a.elemHeight:0,e=a.at[1]==="top"?a.targetHeight:-a.targetHeight,h=-2*a.offset[1];b.top+=a.collisionPosition.top<0?g+e+h:d>0?g+e+h:0}}}};if(!c.offset.setOffset){c.offset.setOffset=function(b,a){if(/static/.test(c.curCSS(b,"position")))b.style.position="relative";var d=c(b), -g=d.offset(),e=parseInt(c.curCSS(b,"top",true),10)||0,h=parseInt(c.curCSS(b,"left",true),10)||0;g={top:a.top-g.top+e,left:a.left-g.left+h};"using"in a?a.using.call(b,g):d.css(g)};c.fn.offset=function(b){var a=this[0];if(!a||!a.ownerDocument)return null;if(b)return this.each(function(){c.offset.setOffset(this,b)});return u.call(this)}}})(jQuery); diff --git a/3rdparty/timepicker/css/include/jquery.ui.tabs.min.js b/3rdparty/timepicker/css/include/jquery.ui.tabs.min.js deleted file mode 100644 index 11a67c144a6a2166663a41f185c3e97359bc4d25..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/css/include/jquery.ui.tabs.min.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * jQuery UI Tabs 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Tabs - * - * Depends: - * jquery.ui.core.js - * jquery.ui.widget.js - */ -(function(d,p){function u(){return++v}function w(){return++x}var v=0,x=0;d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading…</em>",tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},_create:function(){this._tabify(true)},_setOption:function(b,e){if(b=="selected")this.options.collapsible&& -e==this.options.selected||this.select(e);else{this.options[b]=e;this._tabify()}},_tabId:function(b){return b.title&&b.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+u()},_sanitizeSelector:function(b){return b.replace(/:/g,"\\:")},_cookie:function(){var b=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+w());return d.cookie.apply(null,[b].concat(d.makeArray(arguments)))},_ui:function(b,e){return{tab:b,panel:e,index:this.anchors.index(b)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var b= -d(this);b.html(b.data("label.tabs")).removeData("label.tabs")})},_tabify:function(b){function e(g,f){g.css("display","");!d.support.opacity&&f.opacity&&g[0].style.removeAttribute("filter")}var a=this,c=this.options,h=/^#.+/;this.list=this.element.find("ol,ul").eq(0);this.lis=d(" > li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0]});this.panels=d([]);this.anchors.each(function(g,f){var i=d(f).attr("href"),l=i.split("#")[0],q;if(l&&(l===location.toString().split("#")[0]|| -(q=d("base")[0])&&l===q.href)){i=f.hash;f.href=i}if(h.test(i))a.panels=a.panels.add(a.element.find(a._sanitizeSelector(i)));else if(i&&i!=="#"){d.data(f,"href.tabs",i);d.data(f,"load.tabs",i.replace(/#.*$/,""));i=a._tabId(f);f.href="#"+i;f=a.element.find("#"+i);if(!f.length){f=d(c.panelTemplate).attr("id",i).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(a.panels[g-1]||a.list);f.data("destroy.tabs",true)}a.panels=a.panels.add(f)}else c.disabled.push(g)});if(b){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all"); -this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(c.selected===p){location.hash&&this.anchors.each(function(g,f){if(f.hash==location.hash){c.selected=g;return false}});if(typeof c.selected!=="number"&&c.cookie)c.selected=parseInt(a._cookie(),10);if(typeof c.selected!=="number"&&this.lis.filter(".ui-tabs-selected").length)c.selected= -this.lis.index(this.lis.filter(".ui-tabs-selected"));c.selected=c.selected||(this.lis.length?0:-1)}else if(c.selected===null)c.selected=-1;c.selected=c.selected>=0&&this.anchors[c.selected]||c.selected<0?c.selected:0;c.disabled=d.unique(c.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(g){return a.lis.index(g)}))).sort();d.inArray(c.selected,c.disabled)!=-1&&c.disabled.splice(d.inArray(c.selected,c.disabled),1);this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active"); -if(c.selected>=0&&this.anchors.length){a.element.find(a._sanitizeSelector(a.anchors[c.selected].hash)).removeClass("ui-tabs-hide");this.lis.eq(c.selected).addClass("ui-tabs-selected ui-state-active");a.element.queue("tabs",function(){a._trigger("show",null,a._ui(a.anchors[c.selected],a.element.find(a._sanitizeSelector(a.anchors[c.selected].hash))[0]))});this.load(c.selected)}d(window).bind("unload",function(){a.lis.add(a.anchors).unbind(".tabs");a.lis=a.anchors=a.panels=null})}else c.selected=this.lis.index(this.lis.filter(".ui-tabs-selected")); -this.element[c.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible");c.cookie&&this._cookie(c.selected,c.cookie);b=0;for(var j;j=this.lis[b];b++)d(j)[d.inArray(b,c.disabled)!=-1&&!d(j).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");c.cache===false&&this.anchors.removeData("cache.tabs");this.lis.add(this.anchors).unbind(".tabs");if(c.event!=="mouseover"){var k=function(g,f){f.is(":not(.ui-state-disabled)")&&f.addClass("ui-state-"+g)},n=function(g,f){f.removeClass("ui-state-"+ -g)};this.lis.bind("mouseover.tabs",function(){k("hover",d(this))});this.lis.bind("mouseout.tabs",function(){n("hover",d(this))});this.anchors.bind("focus.tabs",function(){k("focus",d(this).closest("li"))});this.anchors.bind("blur.tabs",function(){n("focus",d(this).closest("li"))})}var m,o;if(c.fx)if(d.isArray(c.fx)){m=c.fx[0];o=c.fx[1]}else m=o=c.fx;var r=o?function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.hide().removeClass("ui-tabs-hide").animate(o,o.duration||"normal", -function(){e(f,o);a._trigger("show",null,a._ui(g,f[0]))})}:function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");a._trigger("show",null,a._ui(g,f[0]))},s=m?function(g,f){f.animate(m,m.duration||"normal",function(){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");e(f,m);a.element.dequeue("tabs")})}:function(g,f){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");a.element.dequeue("tabs")}; -this.anchors.bind(c.event+".tabs",function(){var g=this,f=d(g).closest("li"),i=a.panels.filter(":not(.ui-tabs-hide)"),l=a.element.find(a._sanitizeSelector(g.hash));if(f.hasClass("ui-tabs-selected")&&!c.collapsible||f.hasClass("ui-state-disabled")||f.hasClass("ui-state-processing")||a.panels.filter(":animated").length||a._trigger("select",null,a._ui(this,l[0]))===false){this.blur();return false}c.selected=a.anchors.index(this);a.abort();if(c.collapsible)if(f.hasClass("ui-tabs-selected")){c.selected= --1;c.cookie&&a._cookie(c.selected,c.cookie);a.element.queue("tabs",function(){s(g,i)}).dequeue("tabs");this.blur();return false}else if(!i.length){c.cookie&&a._cookie(c.selected,c.cookie);a.element.queue("tabs",function(){r(g,l)});a.load(a.anchors.index(this));this.blur();return false}c.cookie&&a._cookie(c.selected,c.cookie);if(l.length){i.length&&a.element.queue("tabs",function(){s(g,i)});a.element.queue("tabs",function(){r(g,l)});a.load(a.anchors.index(this))}else throw"jQuery UI Tabs: Mismatching fragment identifier."; -d.browser.msie&&this.blur()});this.anchors.bind("click.tabs",function(){return false})},_getIndex:function(b){if(typeof b=="string")b=this.anchors.index(this.anchors.filter("[href$="+b+"]"));return b},destroy:function(){var b=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var e= -d.data(this,"href.tabs");if(e)this.href=e;var a=d(this).unbind(".tabs");d.each(["href","load","cache"],function(c,h){a.removeData(h+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){d.data(this,"destroy.tabs")?d(this).remove():d(this).removeClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-hover ui-state-focus ui-state-disabled ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide")});b.cookie&&this._cookie(null,b.cookie);return this},add:function(b, -e,a){if(a===p)a=this.anchors.length;var c=this,h=this.options;e=d(h.tabTemplate.replace(/#\{href\}/g,b).replace(/#\{label\}/g,e));b=!b.indexOf("#")?b.replace("#",""):this._tabId(d("a",e)[0]);e.addClass("ui-state-default ui-corner-top").data("destroy.tabs",true);var j=c.element.find("#"+b);j.length||(j=d(h.panelTemplate).attr("id",b).data("destroy.tabs",true));j.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(a>=this.lis.length){e.appendTo(this.list);j.appendTo(this.list[0].parentNode)}else{e.insertBefore(this.lis[a]); -j.insertBefore(this.panels[a])}h.disabled=d.map(h.disabled,function(k){return k>=a?++k:k});this._tabify();if(this.anchors.length==1){h.selected=0;e.addClass("ui-tabs-selected ui-state-active");j.removeClass("ui-tabs-hide");this.element.queue("tabs",function(){c._trigger("show",null,c._ui(c.anchors[0],c.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[a],this.panels[a]));return this},remove:function(b){b=this._getIndex(b);var e=this.options,a=this.lis.eq(b).remove(),c=this.panels.eq(b).remove(); -if(a.hasClass("ui-tabs-selected")&&this.anchors.length>1)this.select(b+(b+1<this.anchors.length?1:-1));e.disabled=d.map(d.grep(e.disabled,function(h){return h!=b}),function(h){return h>=b?--h:h});this._tabify();this._trigger("remove",null,this._ui(a.find("a")[0],c[0]));return this},enable:function(b){b=this._getIndex(b);var e=this.options;if(d.inArray(b,e.disabled)!=-1){this.lis.eq(b).removeClass("ui-state-disabled");e.disabled=d.grep(e.disabled,function(a){return a!=b});this._trigger("enable",null, -this._ui(this.anchors[b],this.panels[b]));return this}},disable:function(b){b=this._getIndex(b);var e=this.options;if(b!=e.selected){this.lis.eq(b).addClass("ui-state-disabled");e.disabled.push(b);e.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[b],this.panels[b]))}return this},select:function(b){b=this._getIndex(b);if(b==-1)if(this.options.collapsible&&this.options.selected!=-1)b=this.options.selected;else return this;this.anchors.eq(b).trigger(this.options.event+".tabs");return this}, -load:function(b){b=this._getIndex(b);var e=this,a=this.options,c=this.anchors.eq(b)[0],h=d.data(c,"load.tabs");this.abort();if(!h||this.element.queue("tabs").length!==0&&d.data(c,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(b).addClass("ui-state-processing");if(a.spinner){var j=d("span",c);j.data("label.tabs",j.html()).html(a.spinner)}this.xhr=d.ajax(d.extend({},a.ajaxOptions,{url:h,success:function(k,n){e.element.find(e._sanitizeSelector(c.hash)).html(k);e._cleanup();a.cache&&d.data(c, -"cache.tabs",true);e._trigger("load",null,e._ui(e.anchors[b],e.panels[b]));try{a.ajaxOptions.success(k,n)}catch(m){}},error:function(k,n){e._cleanup();e._trigger("load",null,e._ui(e.anchors[b],e.panels[b]));try{a.ajaxOptions.error(k,n,b,c)}catch(m){}}}));e.element.dequeue("tabs");return this}},abort:function(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup();return this}, -url:function(b,e){this.anchors.eq(b).removeData("cache.tabs").data("load.tabs",e);return this},length:function(){return this.anchors.length}});d.extend(d.ui.tabs,{version:"1.8.14"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function(b,e){var a=this,c=this.options,h=a._rotate||(a._rotate=function(j){clearTimeout(a.rotation);a.rotation=setTimeout(function(){var k=c.selected;a.select(++k<a.anchors.length?k:0)},b);j&&j.stopPropagation()});e=a._unrotate||(a._unrotate=!e?function(j){j.clientX&& -a.rotate(null)}:function(){t=c.selected;h()});if(b){this.element.bind("tabsshow",h);this.anchors.bind(c.event+".tabs",e);h()}else{clearTimeout(a.rotation);this.element.unbind("tabsshow",h);this.anchors.unbind(c.event+".tabs",e);delete this._rotate;delete this._unrotate}return this}})})(jQuery); diff --git a/3rdparty/timepicker/css/include/jquery.ui.widget.min.js b/3rdparty/timepicker/css/include/jquery.ui.widget.min.js deleted file mode 100644 index 39ab91a0963e9e4740d75f606f07f62fc6821b48..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/css/include/jquery.ui.widget.min.js +++ /dev/null @@ -1,15 +0,0 @@ -/*! - * jQuery UI Widget 1.8.14 - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ -(function(b,j){if(b.cleanData){var k=b.cleanData;b.cleanData=function(a){for(var c=0,d;(d=a[c])!=null;c++)b(d).triggerHandler("remove");k(a)}}else{var l=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add([this]).each(function(){b(this).triggerHandler("remove")});return l.call(b(this),a,c)})}}b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h, -a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend(true,{},c.options);b[e][a].prototype=b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.charAt(0)==="_")return h; -e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==j){h=i;return false}}):this.each(function(){var g=b.data(this,a);g?g.option(d||{})._init():b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){b.data(c,this.widgetName,this);this.element=b(c);this.options=b.extend(true,{},this.options, -this._getCreateOptions(),a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return b.metadata&&b.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")}, -widget:function(){return this.element},option:function(a,c){var d=a;if(arguments.length===0)return b.extend({},this.options);if(typeof a==="string"){if(c===j)return this.options[a];d={};d[a]=c}this._setOptions(d);return this},_setOptions:function(a){var c=this;b.each(a,function(d,e){c._setOption(d,e)});return this},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this}, -enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery); diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_diagonals-thick_18_b81900_40x40.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_diagonals-thick_18_b81900_40x40.png deleted file mode 100644 index 954e22dbd99e8c6dd7091335599abf2d10bf8003..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_diagonals-thick_18_b81900_40x40.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_diagonals-thick_20_666666_40x40.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_diagonals-thick_20_666666_40x40.png deleted file mode 100644 index 64ece5707d91a6edf9fad4bfcce0c4dbcafcf58d..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_diagonals-thick_20_666666_40x40.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_flat_10_000000_40x100.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_flat_10_000000_40x100.png deleted file mode 100644 index abdc01082bf3534eafecc5819d28c9574d44ea89..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_flat_10_000000_40x100.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_100_f6f6f6_1x400.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_100_f6f6f6_1x400.png deleted file mode 100644 index 9b383f4d2eab09c0f2a739d6b232c32934bc620b..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_100_f6f6f6_1x400.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_100_fdf5ce_1x400.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_100_fdf5ce_1x400.png deleted file mode 100644 index a23baad25b1d1ff36e17361eab24271f2e9b7326..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_100_fdf5ce_1x400.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_65_ffffff_1x400.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_65_ffffff_1x400.png deleted file mode 100644 index 42ccba269b6e91bef12ad0fa18be651b5ef0ee68..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_65_ffffff_1x400.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_gloss-wave_35_f6a828_500x100.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_gloss-wave_35_f6a828_500x100.png deleted file mode 100644 index 39d5824d6af5456f1e89fc7847ea3599ea5fd815..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_gloss-wave_35_f6a828_500x100.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_highlight-soft_100_eeeeee_1x100.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_highlight-soft_100_eeeeee_1x100.png deleted file mode 100644 index f1273672d253263b7564e9e21d69d7d9d0b337d9..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_highlight-soft_100_eeeeee_1x100.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_highlight-soft_75_ffe45c_1x100.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_highlight-soft_75_ffe45c_1x100.png deleted file mode 100644 index 359397acffdd84bd102f0e8a951c9d744f278db5..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_highlight-soft_75_ffe45c_1x100.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_222222_256x240.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_222222_256x240.png deleted file mode 100644 index b273ff111d219c9b9a8b96d57683d0075fb7871a..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_222222_256x240.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_228ef1_256x240.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_228ef1_256x240.png deleted file mode 100644 index a641a371afa0fbb08ba599dc7ddf14b9bfc3c84f..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_228ef1_256x240.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ef8c08_256x240.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ef8c08_256x240.png deleted file mode 100644 index 85e63e9f604ce042d59eb06a8428eeb7cb7896c9..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ef8c08_256x240.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ffd27a_256x240.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ffd27a_256x240.png deleted file mode 100644 index e117effa3dca24e7978cfc5f8b967f661e81044f..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ffd27a_256x240.png and /dev/null differ diff --git a/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ffffff_256x240.png b/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ffffff_256x240.png deleted file mode 100644 index 42f8f992c727ddaa617da224a522e463df690387..0000000000000000000000000000000000000000 Binary files a/3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ffffff_256x240.png and /dev/null differ diff --git a/3rdparty/timepicker/css/jquery.ui.timepicker.css b/3rdparty/timepicker/css/jquery.ui.timepicker.css deleted file mode 100644 index 08b442a7e53212578a43951761d20da81012fbb1..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/css/jquery.ui.timepicker.css +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Timepicker stylesheet - * Highly inspired from datepicker - * FG - Nov 2010 - Web3R - * - * version 0.0.3 : Fixed some settings, more dynamic - * version 0.0.4 : Removed width:100% on tables - * version 0.1.1 : set width 0 on tables to fix an ie6 bug - */ - -.ui-timepicker-inline { display: inline; } - -#ui-timepicker-div { padding: 0.2em } -.ui-timepicker-table { display: inline-table; width: 0; } -.ui-timepicker-table table { margin:0.15em 0 0 0; border-collapse: collapse; } - -.ui-timepicker-hours, .ui-timepicker-minutes { padding: 0.2em; } - -.ui-timepicker-table .ui-timepicker-title { line-height: 1.8em; text-align: center; } -.ui-timepicker-table td { padding: 0.1em; width: 2.2em; } -.ui-timepicker-table th.periods { padding: 0.1em; width: 2.2em; } - -/* span for disabled cells */ -.ui-timepicker-table td span { - display:block; - padding:0.2em 0.3em 0.2em 0.5em; - width: 1.2em; - - text-align:right; - text-decoration:none; -} -/* anchors for clickable cells */ -.ui-timepicker-table td a { - display:block; - padding:0.2em 0.3em 0.2em 0.5em; - width: 1.2em; - cursor: pointer; - text-align:right; - text-decoration:none; -} - - -/* buttons and button pane styling */ -.ui-timepicker .ui-timepicker-buttonpane { - background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; -} -.ui-timepicker .ui-timepicker-buttonpane button { margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; } -/* The close button */ -.ui-timepicker .ui-timepicker-close { float: right } - -/* the now button */ -.ui-timepicker .ui-timepicker-now { float: left; } - -/* the deselect button */ -.ui-timepicker .ui-timepicker-deselect { float: left; } - - -/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ -.ui-timepicker-cover { - display: none; /*sorry for IE5*/ - display/**/: block; /*sorry for IE5*/ - position: absolute; /*must have*/ - z-index: -1; /*must have*/ - filter: mask(); /*must have*/ - top: -4px; /*must have*/ - left: -4px; /*must have*/ - width: 200px; /*must have*/ - height: 200px; /*must have*/ -} \ No newline at end of file diff --git a/3rdparty/timepicker/js/i18n/i18n.html b/3rdparty/timepicker/js/i18n/i18n.html deleted file mode 100644 index 83cb5e3f30c8587f75a0087de1b4ff8e6279672b..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/js/i18n/i18n.html +++ /dev/null @@ -1,73 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head> - <meta charset="utf-8"> - <title>Internationalisation page for the jquery ui timepicker</title> - - <script src="../include/jquery-1.5.1.min.js"></script> - <script src="../include/jquery.ui.core.min.js"></script> - <script src="../include/jquery.ui.widget.min.js"></script> - <script src="../jquery.ui.timepicker.js"></script> - - <link rel="stylesheet" href="../include/jquery-ui-1.8.14.custom.css" /> - <link rel="stylesheet" href="../jquery.ui.timepicker.css" /> - <style> - #timepicker { font-size: 10px } - </style> - - <script src='jquery.ui.timepicker-de.js'></script> - <script src='jquery.ui.timepicker-fr.js'></script> - <script src='jquery.ui.timepicker-ja.js'></script> -</head> -<body> - - <script type="text/javascript"> - $(document).ready(function() { - - $.timepicker.setDefaults( $.timepicker.regional[ "" ] ); - - $('#timepicker').timepicker({ - showCloseButton: true, - showNowButton: true, - showDeselectButton: true - }); - - $('#locale').change(function() { - $('#timepicker').timepicker( "option", - $.timepicker.regional[ $( this ).val() ] ); - }); - }); - </script> - - Select a localisation : - <select id='locale'> - <option value='fr'>Français</option> - <option value='de'>Deutsch</option> - <option value='ja'>Japanese</option> - </select> - - <br> - - <div id="timepicker"> - - </div> - - <br> - - List of localisations : -<ul> - <li> - <a href="jquery.ui.timepicker-de.js">Deutsch (jquery.ui.timepicker-de.js</a> - </li> - - <li> - <a href="jquery.ui.timepicker-fr.js">Français (jquery.ui.timepicker-fr.js</a> - </li> - - <li> - <a href="jquery.ui.timepicker-ja.js">Japanese (jquery.ui.timepicker-ja.js</a> - </li> - -</ul> - -</body> \ No newline at end of file diff --git a/3rdparty/timepicker/js/i18n/jquery.ui.timepicker-de.js b/3rdparty/timepicker/js/i18n/jquery.ui.timepicker-de.js deleted file mode 100644 index c010a498e15d9fd45f28cdf57f768e64c9b53402..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/js/i18n/jquery.ui.timepicker-de.js +++ /dev/null @@ -1,9 +0,0 @@ -/* Deutsch initialisation for the timepicker plugin */ -/* Written by Bernd Plagge (bplagge@choicenet.ne.jp). */ -jQuery(function($){ - $.timepicker.regional['de'] = { - hourText: 'Stunde', - minuteText: 'Minuten', - amPmText: ['AM', 'PM'] } - $.timepicker.setDefaults($.timepicker.regional['de']); -}); \ No newline at end of file diff --git a/3rdparty/timepicker/js/i18n/jquery.ui.timepicker-fr.js b/3rdparty/timepicker/js/i18n/jquery.ui.timepicker-fr.js deleted file mode 100644 index bd37d731c8d4f68d1d49dbddef0754c272e9b713..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/js/i18n/jquery.ui.timepicker-fr.js +++ /dev/null @@ -1,13 +0,0 @@ -/* French initialisation for the jQuery time picker plugin. */ -/* Written by Bernd Plagge (bplagge@choicenet.ne.jp), - Francois Gelinas (frank@fgelinas.com) */ -jQuery(function($){ - $.timepicker.regional['fr'] = { - hourText: 'Heures', - minuteText: 'Minutes', - amPmText: ['AM', 'PM'], - closeButtonText: 'Fermer', - nowButtonText: 'Maintenant', - deselectButtonText: 'Désélectionner' } - $.timepicker.setDefaults($.timepicker.regional['fr']); -}); \ No newline at end of file diff --git a/3rdparty/timepicker/js/i18n/jquery.ui.timepicker-ja.js b/3rdparty/timepicker/js/i18n/jquery.ui.timepicker-ja.js deleted file mode 100644 index 01b2c8a3de5b09f84c6db20c063e9cffae7888ab..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/js/i18n/jquery.ui.timepicker-ja.js +++ /dev/null @@ -1,9 +0,0 @@ -/* Japanese initialisation for the jQuery time picker plugin. */ -/* Written by Bernd Plagge (bplagge@choicenet.ne.jp). */ -jQuery(function($){ - $.timepicker.regional['ja'] = { - hourText: '時間', - minuteText: '分', - amPmText: ['午前', '午後'] } - $.timepicker.setDefaults($.timepicker.regional['ja']); -}); diff --git a/3rdparty/timepicker/js/jquery.ui.timepicker.js b/3rdparty/timepicker/js/jquery.ui.timepicker.js deleted file mode 100644 index d086b674b7b2f9428f16b162535533e9a6ed1521..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/js/jquery.ui.timepicker.js +++ /dev/null @@ -1,1345 +0,0 @@ -/* - * jQuery UI Timepicker 0.2.9 - * - * Copyright 2010-2011, Francois Gelinas - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://fgelinas.com/code/timepicker - * - * Depends: - * jquery.ui.core.js - * jquery.ui.position.js (only if position settngs are used) - * - * Change version 0.1.0 - moved the t-rex up here - * - ____ - ___ .-~. /_"-._ - `-._~-. / /_ "~o\ :Y - \ \ / : \~x. ` ') - ] Y / | Y< ~-.__j - / ! _.--~T : l l< /.-~ - / / ____.--~ . ` l /~\ \<|Y - / / .-~~" /| . ',-~\ \L| - / / / .^ \ Y~Y \.^>/l_ "--' - / Y .-"( . l__ j_j l_/ /~_.-~ . - Y l / \ ) ~~~." / `/"~ / \.__/l_ - | \ _.-" ~-{__ l : l._Z~-.___.--~ - | ~---~ / ~~"---\_ ' __[> - l . _.^ ___ _>-y~ - \ \ . .-~ .-~ ~>--" / - \ ~---" / ./ _.-' - "-.,_____.,_ _.--~\ _.-~ - ~~ ( _} -Row - `. ~( - ) \ - /,`--'~\--'~\ - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ->T-Rex<- -*/ - -(function ($, undefined) { - - $.extend($.ui, { timepicker: { version: "0.2.9"} }); - - var PROP_NAME = 'timepicker'; - var tpuuid = new Date().getTime(); - - /* Time picker manager. - Use the singleton instance of this class, $.timepicker, to interact with the time picker. - Settings for (groups of) time pickers are maintained in an instance object, - allowing multiple different settings on the same page. */ - - function Timepicker() { - this.debug = true; // Change this to true to start debugging - this._curInst = null; // The current instance in use - this._isInline = false; // true if the instance is displayed inline - this._disabledInputs = []; // List of time picker inputs that have been disabled - this._timepickerShowing = false; // True if the popup picker is showing , false if not - this._inDialog = false; // True if showing within a "dialog", false if not - this._dialogClass = 'ui-timepicker-dialog'; // The name of the dialog marker class - this._mainDivId = 'ui-timepicker-div'; // The ID of the main timepicker division - this._inlineClass = 'ui-timepicker-inline'; // The name of the inline marker class - this._currentClass = 'ui-timepicker-current'; // The name of the current hour / minutes marker class - this._dayOverClass = 'ui-timepicker-days-cell-over'; // The name of the day hover marker class - - this.regional = []; // Available regional settings, indexed by language code - this.regional[''] = { // Default regional settings - hourText: 'Hour', // Display text for hours section - minuteText: 'Minute', // Display text for minutes link - amPmText: ['AM', 'PM'], // Display text for AM PM - closeButtonText: 'Done', // Text for the confirmation button (ok button) - nowButtonText: 'Now', // Text for the now button - deselectButtonText: 'Deselect' // Text for the deselect button - }; - this._defaults = { // Global defaults for all the time picker instances - showOn: 'focus', // 'focus' for popup on focus, - // 'button' for trigger button, or 'both' for either (not yet implemented) - button: null, // 'button' element that will trigger the timepicker - showAnim: 'fadeIn', // Name of jQuery animation for popup - showOptions: {}, // Options for enhanced animations - appendText: '', // Display text following the input box, e.g. showing the format - - beforeShow: null, // Define a callback function executed before the timepicker is shown - onSelect: null, // Define a callback function when a hour / minutes is selected - onClose: null, // Define a callback function when the timepicker is closed - - timeSeparator: ':', // The character to use to separate hours and minutes. - periodSeparator: ' ', // The character to use to separate the time from the time period. - showPeriod: false, // Define whether or not to show AM/PM with selected time - showPeriodLabels: true, // Show the AM/PM labels on the left of the time picker - showLeadingZero: true, // Define whether or not to show a leading zero for hours < 10. [true/false] - showMinutesLeadingZero: true, // Define whether or not to show a leading zero for minutes < 10. - altField: '', // Selector for an alternate field to store selected time into - defaultTime: 'now', // Used as default time when input field is empty or for inline timePicker - // (set to 'now' for the current time, '' for no highlighted time) - myPosition: 'left top', // Position of the dialog relative to the input. - // see the position utility for more info : http://jqueryui.com/demos/position/ - atPosition: 'left bottom', // Position of the input element to match - // Note : if the position utility is not loaded, the timepicker will attach left top to left bottom - //NEW: 2011-02-03 - onHourShow: null, // callback for enabling / disabling on selectable hours ex : function(hour) { return true; } - onMinuteShow: null, // callback for enabling / disabling on time selection ex : function(hour,minute) { return true; } - - hours: { - starts: 0, // first displayed hour - ends: 23 // last displayed hour - }, - minutes: { - starts: 0, // first displayed minute - ends: 55, // last displayed minute - interval: 5 // interval of displayed minutes - }, - rows: 4, // number of rows for the input tables, minimum 2, makes more sense if you use multiple of 2 - // 2011-08-05 0.2.4 - showHours: true, // display the hours section of the dialog - showMinutes: true, // display the minute section of the dialog - optionalMinutes: false, // optionally parse inputs of whole hours with minutes omitted - - // buttons - showCloseButton: false, // shows an OK button to confirm the edit - showNowButton: false, // Shows the 'now' button - showDeselectButton: false // Shows the deselect time button - - }; - $.extend(this._defaults, this.regional['']); - - this.tpDiv = $('<div id="' + this._mainDivId + '" class="ui-timepicker ui-widget ui-helper-clearfix ui-corner-all " style="display: none"></div>'); - } - - $.extend(Timepicker.prototype, { - /* Class name added to elements to indicate already configured with a time picker. */ - markerClassName: 'hasTimepicker', - - /* Debug logging (if enabled). */ - log: function () { - if (this.debug) - console.log.apply('', arguments); - }, - - _widgetTimepicker: function () { - return this.tpDiv; - }, - - /* Override the default settings for all instances of the time picker. - @param settings object - the new settings to use as defaults (anonymous object) - @return the manager object */ - setDefaults: function (settings) { - extendRemove(this._defaults, settings || {}); - return this; - }, - - /* Attach the time picker to a jQuery selection. - @param target element - the target input field or division or span - @param settings object - the new settings to use for this time picker instance (anonymous) */ - _attachTimepicker: function (target, settings) { - // check for settings on the control itself - in namespace 'time:' - var inlineSettings = null; - for (var attrName in this._defaults) { - var attrValue = target.getAttribute('time:' + attrName); - if (attrValue) { - inlineSettings = inlineSettings || {}; - try { - inlineSettings[attrName] = eval(attrValue); - } catch (err) { - inlineSettings[attrName] = attrValue; - } - } - } - var nodeName = target.nodeName.toLowerCase(); - var inline = (nodeName == 'div' || nodeName == 'span'); - - if (!target.id) { - this.uuid += 1; - target.id = 'tp' + this.uuid; - } - var inst = this._newInst($(target), inline); - inst.settings = $.extend({}, settings || {}, inlineSettings || {}); - if (nodeName == 'input') { - this._connectTimepicker(target, inst); - // init inst.hours and inst.minutes from the input value - this._setTimeFromField(inst); - } else if (inline) { - this._inlineTimepicker(target, inst); - } - - - }, - - /* Create a new instance object. */ - _newInst: function (target, inline) { - var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars - return { - id: id, input: target, // associated target - inline: inline, // is timepicker inline or not : - tpDiv: (!inline ? this.tpDiv : // presentation div - $('<div class="' + this._inlineClass + ' ui-timepicker ui-widget ui-helper-clearfix"></div>')) - }; - }, - - /* Attach the time picker to an input field. */ - _connectTimepicker: function (target, inst) { - var input = $(target); - inst.append = $([]); - inst.trigger = $([]); - if (input.hasClass(this.markerClassName)) { return; } - this._attachments(input, inst); - input.addClass(this.markerClassName). - keydown(this._doKeyDown). - keyup(this._doKeyUp). - bind("setData.timepicker", function (event, key, value) { - inst.settings[key] = value; - }). - bind("getData.timepicker", function (event, key) { - return this._get(inst, key); - }); - $.data(target, PROP_NAME, inst); - }, - - /* Handle keystrokes. */ - _doKeyDown: function (event) { - var inst = $.timepicker._getInst(event.target); - var handled = true; - inst._keyEvent = true; - if ($.timepicker._timepickerShowing) { - switch (event.keyCode) { - case 9: $.timepicker._hideTimepicker(); - handled = false; - break; // hide on tab out - case 13: - $.timepicker._updateSelectedValue(inst); - $.timepicker._hideTimepicker(); - - return false; // don't submit the form - break; // select the value on enter - case 27: $.timepicker._hideTimepicker(); - break; // hide on escape - default: handled = false; - } - } - else if (event.keyCode == 36 && event.ctrlKey) { // display the time picker on ctrl+home - $.timepicker._showTimepicker(this); - } - else { - handled = false; - } - if (handled) { - event.preventDefault(); - event.stopPropagation(); - } - }, - - /* Update selected time on keyUp */ - /* Added verion 0.0.5 */ - _doKeyUp: function (event) { - var inst = $.timepicker._getInst(event.target); - $.timepicker._setTimeFromField(inst); - $.timepicker._updateTimepicker(inst); - }, - - /* Make attachments based on settings. */ - _attachments: function (input, inst) { - var appendText = this._get(inst, 'appendText'); - var isRTL = this._get(inst, 'isRTL'); - if (inst.append) { inst.append.remove(); } - if (appendText) { - inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>'); - input[isRTL ? 'before' : 'after'](inst.append); - } - input.unbind('focus.timepicker', this._showTimepicker); - if (inst.trigger) { inst.trigger.remove(); } - - var showOn = this._get(inst, 'showOn'); - if (showOn == 'focus' || showOn == 'both') { // pop-up time picker when in the marked field - input.bind("focus.timepicker", this._showTimepicker); - } - if (showOn == 'button' || showOn == 'both') { // pop-up time picker when 'button' element is clicked - var button = this._get(inst, 'button'); - $(button).bind("click.timepicker", function () { - if ($.timepicker._timepickerShowing && $.timepicker._lastInput == input[0]) { $.timepicker._hideTimepicker(); } - else { $.timepicker._showTimepicker(input[0]); } - return false; - }); - - } - }, - - - /* Attach an inline time picker to a div. */ - _inlineTimepicker: function(target, inst) { - var divSpan = $(target); - if (divSpan.hasClass(this.markerClassName)) - return; - divSpan.addClass(this.markerClassName).append(inst.tpDiv). - bind("setData.timepicker", function(event, key, value){ - inst.settings[key] = value; - }).bind("getData.timepicker", function(event, key){ - return this._get(inst, key); - }); - $.data(target, PROP_NAME, inst); - - this._setTimeFromField(inst); - this._updateTimepicker(inst); - inst.tpDiv.show(); - }, - - /* Pop-up the time picker for a given input field. - @param input element - the input field attached to the time picker or - event - if triggered by focus */ - _showTimepicker: function (input) { - input = input.target || input; - if (input.nodeName.toLowerCase() != 'input') { input = $('input', input.parentNode)[0]; } // find from button/image trigger - if ($.timepicker._isDisabledTimepicker(input) || $.timepicker._lastInput == input) { return; } // already here - - // fix v 0.0.8 - close current timepicker before showing another one - $.timepicker._hideTimepicker(); - - var inst = $.timepicker._getInst(input); - if ($.timepicker._curInst && $.timepicker._curInst != inst) { - $.timepicker._curInst.tpDiv.stop(true, true); - } - var beforeShow = $.timepicker._get(inst, 'beforeShow'); - extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {})); - inst.lastVal = null; - $.timepicker._lastInput = input; - - $.timepicker._setTimeFromField(inst); - - // calculate default position - if ($.timepicker._inDialog) { input.value = ''; } // hide cursor - if (!$.timepicker._pos) { // position below input - $.timepicker._pos = $.timepicker._findPos(input); - $.timepicker._pos[1] += input.offsetHeight; // add the height - } - var isFixed = false; - $(input).parents().each(function () { - isFixed |= $(this).css('position') == 'fixed'; - return !isFixed; - }); - if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled - $.timepicker._pos[0] -= document.documentElement.scrollLeft; - $.timepicker._pos[1] -= document.documentElement.scrollTop; - } - - var offset = { left: $.timepicker._pos[0], top: $.timepicker._pos[1] }; - - $.timepicker._pos = null; - // determine sizing offscreen - inst.tpDiv.css({ position: 'absolute', display: 'block', top: '-1000px' }); - $.timepicker._updateTimepicker(inst); - - - // position with the ui position utility, if loaded - if ( ( ! inst.inline ) && ( typeof $.ui.position == 'object' ) ) { - inst.tpDiv.position({ - of: inst.input, - my: $.timepicker._get( inst, 'myPosition' ), - at: $.timepicker._get( inst, 'atPosition' ), - // offset: $( "#offset" ).val(), - // using: using, - collision: 'flip' - }); - var offset = inst.tpDiv.offset(); - $.timepicker._pos = [offset.top, offset.left]; - } - - - // reset clicked state - inst._hoursClicked = false; - inst._minutesClicked = false; - - // fix width for dynamic number of time pickers - // and adjust position before showing - offset = $.timepicker._checkOffset(inst, offset, isFixed); - inst.tpDiv.css({ position: ($.timepicker._inDialog && $.blockUI ? - 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none', - left: offset.left + 'px', top: offset.top + 'px' - }); - if ( ! inst.inline ) { - var showAnim = $.timepicker._get(inst, 'showAnim'); - var duration = $.timepicker._get(inst, 'duration'); - - var postProcess = function () { - $.timepicker._timepickerShowing = true; - var borders = $.timepicker._getBorders(inst.tpDiv); - inst.tpDiv.find('iframe.ui-timepicker-cover'). // IE6- only - css({ left: -borders[0], top: -borders[1], - width: inst.tpDiv.outerWidth(), height: inst.tpDiv.outerHeight() - }); - }; - - // Fixed the zIndex problem for real (I hope) - FG - v 0.2.9 - inst.tpDiv.css('zIndex', $.timepicker._getZIndex(input) +1); - - if ($.effects && $.effects[showAnim]) { - inst.tpDiv.show(showAnim, $.timepicker._get(inst, 'showOptions'), duration, postProcess); - } - else { - inst.tpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess); - } - if (!showAnim || !duration) { postProcess(); } - if (inst.input.is(':visible') && !inst.input.is(':disabled')) { inst.input.focus(); } - $.timepicker._curInst = inst; - } - }, - - // This is a copy of the zIndex function of UI core 1.8.?? - // Copied in the timepicker to stay backward compatible. - _getZIndex: function (target) { - var elem = $( target ), position, value; - while ( elem.length && elem[ 0 ] !== document ) { - position = elem.css( "position" ); - if ( position === "absolute" || position === "relative" || position === "fixed" ) { - value = parseInt( elem.css( "zIndex" ), 10 ); - if ( !isNaN( value ) && value !== 0 ) { - return value; - } - } - elem = elem.parent(); - } - }, - - /* Generate the time picker content. */ - _updateTimepicker: function (inst) { - inst.tpDiv.empty().append(this._generateHTML(inst)); - this._rebindDialogEvents(inst); - - }, - - _rebindDialogEvents: function (inst) { - var borders = $.timepicker._getBorders(inst.tpDiv), - self = this; - inst.tpDiv - .find('iframe.ui-timepicker-cover') // IE6- only - .css({ left: -borders[0], top: -borders[1], - width: inst.tpDiv.outerWidth(), height: inst.tpDiv.outerHeight() - }) - .end() - // after the picker html is appended bind the click & double click events (faster in IE this way - // then letting the browser interpret the inline events) - // the binding for the minute cells also exists in _updateMinuteDisplay - .find('.ui-timepicker-minute-cell') - .unbind() - .bind("click", { fromDoubleClick:false }, $.proxy($.timepicker.selectMinutes, this)) - .bind("dblclick", { fromDoubleClick:true }, $.proxy($.timepicker.selectMinutes, this)) - .end() - .find('.ui-timepicker-hour-cell') - .unbind() - .bind("click", { fromDoubleClick:false }, $.proxy($.timepicker.selectHours, this)) - .bind("dblclick", { fromDoubleClick:true }, $.proxy($.timepicker.selectHours, this)) - .end() - .find('.ui-timepicker td a') - .unbind() - .bind('mouseout', function () { - $(this).removeClass('ui-state-hover'); - if (this.className.indexOf('ui-timepicker-prev') != -1) $(this).removeClass('ui-timepicker-prev-hover'); - if (this.className.indexOf('ui-timepicker-next') != -1) $(this).removeClass('ui-timepicker-next-hover'); - }) - .bind('mouseover', function () { - if ( ! self._isDisabledTimepicker(inst.inline ? inst.tpDiv.parent()[0] : inst.input[0])) { - $(this).parents('.ui-timepicker-calendar').find('a').removeClass('ui-state-hover'); - $(this).addClass('ui-state-hover'); - if (this.className.indexOf('ui-timepicker-prev') != -1) $(this).addClass('ui-timepicker-prev-hover'); - if (this.className.indexOf('ui-timepicker-next') != -1) $(this).addClass('ui-timepicker-next-hover'); - } - }) - .end() - .find('.' + this._dayOverClass + ' a') - .trigger('mouseover') - .end() - .find('.ui-timepicker-now').bind("click",function(e) { - $.timepicker.selectNow(e); - }).end() - .find('.ui-timepicker-deselect').bind("click",function(e) { - $.timepicker.deselectTime(e); - }).end() - .find('.ui-timepicker-close').bind("click",function(e) { - $.timepicker._hideTimepicker(); - }).end(); - }, - - /* Generate the HTML for the current state of the time picker. */ - _generateHTML: function (inst) { - - var h, m, row, col, html, hoursHtml, minutesHtml = '', - showPeriod = (this._get(inst, 'showPeriod') == true), - showPeriodLabels = (this._get(inst, 'showPeriodLabels') == true), - showLeadingZero = (this._get(inst, 'showLeadingZero') == true), - showHours = (this._get(inst, 'showHours') == true), - showMinutes = (this._get(inst, 'showMinutes') == true), - amPmText = this._get(inst, 'amPmText'), - rows = this._get(inst, 'rows'), - amRows = 0, - pmRows = 0, - amItems = 0, - pmItems = 0, - amFirstRow = 0, - pmFirstRow = 0, - hours = Array(), - hours_options = this._get(inst, 'hours'), - hoursPerRow = null, - hourCounter = 0, - hourLabel = this._get(inst, 'hourText'), - showCloseButton = this._get(inst, 'showCloseButton'), - closeButtonText = this._get(inst, 'closeButtonText'), - showNowButton = this._get(inst, 'showNowButton'), - nowButtonText = this._get(inst, 'nowButtonText'), - showDeselectButton = this._get(inst, 'showDeselectButton'), - deselectButtonText = this._get(inst, 'deselectButtonText'), - showButtonPanel = showCloseButton || showNowButton || showDeselectButton; - - - - // prepare all hours and minutes, makes it easier to distribute by rows - for (h = hours_options.starts; h <= hours_options.ends; h++) { - hours.push (h); - } - hoursPerRow = Math.ceil(hours.length / rows); // always round up - - if (showPeriodLabels) { - for (hourCounter = 0; hourCounter < hours.length; hourCounter++) { - if (hours[hourCounter] < 12) { - amItems++; - } - else { - pmItems++; - } - } - hourCounter = 0; - - amRows = Math.floor(amItems / hours.length * rows); - pmRows = Math.floor(pmItems / hours.length * rows); - - // assign the extra row to the period that is more densly populated - if (rows != amRows + pmRows) { - // Make sure: AM Has Items and either PM Does Not, AM has no rows yet, or AM is more dense - if (amItems && (!pmItems || !amRows || (pmRows && amItems / amRows >= pmItems / pmRows))) { - amRows++; - } else { - pmRows++; - } - } - amFirstRow = Math.min(amRows, 1); - pmFirstRow = amRows + 1; - hoursPerRow = Math.ceil(Math.max(amItems / amRows, pmItems / pmRows)); - } - - - html = '<table class="ui-timepicker-table ui-widget-content ui-corner-all"><tr>'; - - if (showHours) { - - html += '<td class="ui-timepicker-hours">' + - '<div class="ui-timepicker-title ui-widget-header ui-helper-clearfix ui-corner-all">' + - hourLabel + - '</div>' + - '<table class="ui-timepicker">'; - - for (row = 1; row <= rows; row++) { - html += '<tr>'; - // AM - if (row == amFirstRow && showPeriodLabels) { - html += '<th rowspan="' + amRows.toString() + '" class="periods" scope="row">' + amPmText[0] + '</th>'; - } - // PM - if (row == pmFirstRow && showPeriodLabels) { - html += '<th rowspan="' + pmRows.toString() + '" class="periods" scope="row">' + amPmText[1] + '</th>'; - } - for (col = 1; col <= hoursPerRow; col++) { - if (showPeriodLabels && row < pmFirstRow && hours[hourCounter] >= 12) { - html += this._generateHTMLHourCell(inst, undefined, showPeriod, showLeadingZero); - } else { - html += this._generateHTMLHourCell(inst, hours[hourCounter], showPeriod, showLeadingZero); - hourCounter++; - } - } - html += '</tr>'; - } - html += '</tr></table>' + // Close the hours cells table - '</td>'; // Close the Hour td - } - - if (showMinutes) { - html += '<td class="ui-timepicker-minutes">'; - html += this._generateHTMLMinutes(inst); - html += '</td>'; - } - - html += '</tr>'; - - - if (showButtonPanel) { - var buttonPanel = '<tr><td colspan="3"><div class="ui-timepicker-buttonpane ui-widget-content">'; - if (showNowButton) { - buttonPanel += '<button type="button" class="ui-timepicker-now ui-state-default ui-corner-all" ' - + ' data-timepicker-instance-id="#' + inst.id.replace(/\\\\/g,"\\") + '" >' - + nowButtonText + '</button>'; - } - if (showDeselectButton) { - buttonPanel += '<button type="button" class="ui-timepicker-deselect ui-state-default ui-corner-all" ' - + ' data-timepicker-instance-id="#' + inst.id.replace(/\\\\/g,"\\") + '" >' - + deselectButtonText + '</button>'; - } - if (showCloseButton) { - buttonPanel += '<button type="button" class="ui-timepicker-close ui-state-default ui-corner-all" ' - + ' data-timepicker-instance-id="#' + inst.id.replace(/\\\\/g,"\\") + '" >' - + closeButtonText + '</button>'; - } - - html += buttonPanel + '</div></td></tr>'; - } - html += '</table>'; - - /* IE6 IFRAME FIX (taken from datepicker 1.5.3, fixed in 0.1.2 */ - html += ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ? - '<iframe src="javascript:false;" class="ui-timepicker-cover" frameborder="0"></iframe>' : ''); - - return html; - }, - - /* Special function that update the minutes selection in currently visible timepicker - * called on hour selection when onMinuteShow is defined */ - _updateMinuteDisplay: function (inst) { - var newHtml = this._generateHTMLMinutes(inst); - inst.tpDiv.find('td.ui-timepicker-minutes').html(newHtml); - this._rebindDialogEvents(inst); - // after the picker html is appended bind the click & double click events (faster in IE this way - // then letting the browser interpret the inline events) - // yes I know, duplicate code, sorry -/* .find('.ui-timepicker-minute-cell') - .bind("click", { fromDoubleClick:false }, $.proxy($.timepicker.selectMinutes, this)) - .bind("dblclick", { fromDoubleClick:true }, $.proxy($.timepicker.selectMinutes, this)); -*/ - - }, - - /* - * Generate the minutes table - * This is separated from the _generateHTML function because is can be called separately (when hours changes) - */ - _generateHTMLMinutes: function (inst) { - - var m, row, html = '', - rows = this._get(inst, 'rows'), - minutes = Array(), - minutes_options = this._get(inst, 'minutes'), - minutesPerRow = null, - minuteCounter = 0, - showMinutesLeadingZero = (this._get(inst, 'showMinutesLeadingZero') == true), - onMinuteShow = this._get(inst, 'onMinuteShow'), - minuteLabel = this._get(inst, 'minuteText'); - - if ( ! minutes_options.starts) { - minutes_options.starts = 0; - } - if ( ! minutes_options.ends) { - minutes_options.ends = 59; - } - for (m = minutes_options.starts; m <= minutes_options.ends; m += minutes_options.interval) { - minutes.push(m); - } - minutesPerRow = Math.round(minutes.length / rows + 0.49); // always round up - - /* - * The minutes table - */ - // if currently selected minute is not enabled, we have a problem and need to select a new minute. - if (onMinuteShow && - (onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours , inst.minutes]) == false) ) { - // loop minutes and select first available - for (minuteCounter = 0; minuteCounter < minutes.length; minuteCounter += 1) { - m = minutes[minuteCounter]; - if (onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours, m])) { - inst.minutes = m; - break; - } - } - } - - - - html += '<div class="ui-timepicker-title ui-widget-header ui-helper-clearfix ui-corner-all">' + - minuteLabel + - '</div>' + - '<table class="ui-timepicker">'; - - minuteCounter = 0; - for (row = 1; row <= rows; row++) { - html += '<tr>'; - while (minuteCounter < row * minutesPerRow) { - var m = minutes[minuteCounter]; - var displayText = ''; - if (m !== undefined ) { - displayText = (m < 10) && showMinutesLeadingZero ? "0" + m.toString() : m.toString(); - } - html += this._generateHTMLMinuteCell(inst, m, displayText); - minuteCounter++; - } - html += '</tr>'; - } - - html += '</table>'; - - return html; - }, - - /* Generate the content of a "Hour" cell */ - _generateHTMLHourCell: function (inst, hour, showPeriod, showLeadingZero) { - - var displayHour = hour; - if ((hour > 12) && showPeriod) { - displayHour = hour - 12; - } - if ((displayHour == 0) && showPeriod) { - displayHour = 12; - } - if ((displayHour < 10) && showLeadingZero) { - displayHour = '0' + displayHour; - } - - var html = ""; - var enabled = true; - var onHourShow = this._get(inst, 'onHourShow'); //custom callback - - if (hour == undefined) { - html = '<td><span class="ui-state-default ui-state-disabled"> </span></td>'; - return html; - } - - if (onHourShow) { - enabled = onHourShow.apply((inst.input ? inst.input[0] : null), [hour]); - } - - if (enabled) { - html = '<td class="ui-timepicker-hour-cell" data-timepicker-instance-id="#' + inst.id.replace(/\\\\/g,"\\") + '" data-hour="' + hour.toString() + '">' + - '<a class="ui-state-default ' + - (hour == inst.hours ? 'ui-state-active' : '') + - '">' + - displayHour.toString() + - '</a></td>'; - } - else { - html = - '<td>' + - '<span class="ui-state-default ui-state-disabled ' + - (hour == inst.hours ? ' ui-state-active ' : ' ') + - '">' + - displayHour.toString() + - '</span>' + - '</td>'; - } - return html; - }, - - /* Generate the content of a "Hour" cell */ - _generateHTMLMinuteCell: function (inst, minute, displayText) { - var html = ""; - var enabled = true; - var onMinuteShow = this._get(inst, 'onMinuteShow'); //custom callback - if (onMinuteShow) { - //NEW: 2011-02-03 we should give the hour as a parameter as well! - enabled = onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours,minute]); //trigger callback - } - - if (minute == undefined) { - html = '<td><span class="ui-state-default ui-state-disabled"> </span></td>'; - return html; - } - - if (enabled) { - html = '<td class="ui-timepicker-minute-cell" data-timepicker-instance-id="#' + inst.id.replace(/\\\\/g,"\\") + '" data-minute="' + minute.toString() + '" >' + - '<a class="ui-state-default ' + - (minute == inst.minutes ? 'ui-state-active' : '') + - '" >' + - displayText + - '</a></td>'; - } - else { - - html = '<td>' + - '<span class="ui-state-default ui-state-disabled" >' + - displayText + - '</span>' + - '</td>'; - } - return html; - }, - - - /* Enable the date picker to a jQuery selection. - @param target element - the target input field or division or span */ - _enableTimepicker: function(target) { - var $target = $(target), - target_id = $target.attr('id'), - inst = $.data(target, PROP_NAME); - - if (!$target.hasClass(this.markerClassName)) { - return; - } - var nodeName = target.nodeName.toLowerCase(); - if (nodeName == 'input') { - target.disabled = false; - inst.trigger.filter('button'). - each(function() { this.disabled = false; }).end(); - } - else if (nodeName == 'div' || nodeName == 'span') { - var inline = $target.children('.' + this._inlineClass); - inline.children().removeClass('ui-state-disabled'); - } - this._disabledInputs = $.map(this._disabledInputs, - function(value) { return (value == target_id ? null : value); }); // delete entry - }, - - /* Disable the time picker to a jQuery selection. - @param target element - the target input field or division or span */ - _disableTimepicker: function(target) { - var $target = $(target); - var inst = $.data(target, PROP_NAME); - if (!$target.hasClass(this.markerClassName)) { - return; - } - var nodeName = target.nodeName.toLowerCase(); - if (nodeName == 'input') { - target.disabled = true; - - inst.trigger.filter('button'). - each(function() { this.disabled = true; }).end(); - - } - else if (nodeName == 'div' || nodeName == 'span') { - var inline = $target.children('.' + this._inlineClass); - inline.children().addClass('ui-state-disabled'); - } - this._disabledInputs = $.map(this._disabledInputs, - function(value) { return (value == target ? null : value); }); // delete entry - this._disabledInputs[this._disabledInputs.length] = $target.attr('id'); - }, - - /* Is the first field in a jQuery collection disabled as a timepicker? - @param target_id element - the target input field or division or span - @return boolean - true if disabled, false if enabled */ - _isDisabledTimepicker: function (target_id) { - if ( ! target_id) { return false; } - for (var i = 0; i < this._disabledInputs.length; i++) { - if (this._disabledInputs[i] == target_id) { return true; } - } - return false; - }, - - /* Check positioning to remain on screen. */ - _checkOffset: function (inst, offset, isFixed) { - var tpWidth = inst.tpDiv.outerWidth(); - var tpHeight = inst.tpDiv.outerHeight(); - var inputWidth = inst.input ? inst.input.outerWidth() : 0; - var inputHeight = inst.input ? inst.input.outerHeight() : 0; - var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft(); - var viewHeight = document.documentElement.clientHeight + $(document).scrollTop(); - - offset.left -= (this._get(inst, 'isRTL') ? (tpWidth - inputWidth) : 0); - offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0; - offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; - - // now check if datepicker is showing outside window viewport - move to a better place if so. - offset.left -= Math.min(offset.left, (offset.left + tpWidth > viewWidth && viewWidth > tpWidth) ? - Math.abs(offset.left + tpWidth - viewWidth) : 0); - offset.top -= Math.min(offset.top, (offset.top + tpHeight > viewHeight && viewHeight > tpHeight) ? - Math.abs(tpHeight + inputHeight) : 0); - - return offset; - }, - - /* Find an object's position on the screen. */ - _findPos: function (obj) { - var inst = this._getInst(obj); - var isRTL = this._get(inst, 'isRTL'); - while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) { - obj = obj[isRTL ? 'previousSibling' : 'nextSibling']; - } - var position = $(obj).offset(); - return [position.left, position.top]; - }, - - /* Retrieve the size of left and top borders for an element. - @param elem (jQuery object) the element of interest - @return (number[2]) the left and top borders */ - _getBorders: function (elem) { - var convert = function (value) { - return { thin: 1, medium: 2, thick: 3}[value] || value; - }; - return [parseFloat(convert(elem.css('border-left-width'))), - parseFloat(convert(elem.css('border-top-width')))]; - }, - - - /* Close time picker if clicked elsewhere. */ - _checkExternalClick: function (event) { - if (!$.timepicker._curInst) { return; } - var $target = $(event.target); - if ($target[0].id != $.timepicker._mainDivId && - $target.parents('#' + $.timepicker._mainDivId).length == 0 && - !$target.hasClass($.timepicker.markerClassName) && - !$target.hasClass($.timepicker._triggerClass) && - $.timepicker._timepickerShowing && !($.timepicker._inDialog && $.blockUI)) - $.timepicker._hideTimepicker(); - }, - - /* Hide the time picker from view. - @param input element - the input field attached to the time picker */ - _hideTimepicker: function (input) { - var inst = this._curInst; - if (!inst || (input && inst != $.data(input, PROP_NAME))) { return; } - if (this._timepickerShowing) { - var showAnim = this._get(inst, 'showAnim'); - var duration = this._get(inst, 'duration'); - var postProcess = function () { - $.timepicker._tidyDialog(inst); - this._curInst = null; - }; - if ($.effects && $.effects[showAnim]) { - inst.tpDiv.hide(showAnim, $.timepicker._get(inst, 'showOptions'), duration, postProcess); - } - else { - inst.tpDiv[(showAnim == 'slideDown' ? 'slideUp' : - (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess); - } - if (!showAnim) { postProcess(); } - var onClose = this._get(inst, 'onClose'); - if (onClose) { - onClose.apply( - (inst.input ? inst.input[0] : null), - [(inst.input ? inst.input.val() : ''), inst]); // trigger custom callback - } - this._timepickerShowing = false; - this._lastInput = null; - if (this._inDialog) { - this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' }); - if ($.blockUI) { - $.unblockUI(); - $('body').append(this.tpDiv); - } - } - this._inDialog = false; - } - }, - - - - /* Tidy up after a dialog display. */ - _tidyDialog: function (inst) { - inst.tpDiv.removeClass(this._dialogClass).unbind('.ui-timepicker'); - }, - - /* Retrieve the instance data for the target control. - @param target element - the target input field or division or span - @return object - the associated instance data - @throws error if a jQuery problem getting data */ - _getInst: function (target) { - try { - return $.data(target, PROP_NAME); - } - catch (err) { - throw 'Missing instance data for this timepicker'; - } - }, - - /* Get a setting value, defaulting if necessary. */ - _get: function (inst, name) { - return inst.settings[name] !== undefined ? - inst.settings[name] : this._defaults[name]; - }, - - /* Parse existing time and initialise time picker. */ - _setTimeFromField: function (inst) { - if (inst.input.val() == inst.lastVal) { return; } - var defaultTime = this._get(inst, 'defaultTime'); - - var timeToParse = defaultTime == 'now' ? this._getCurrentTimeRounded(inst) : defaultTime; - if ((inst.inline == false) && (inst.input.val() != '')) { timeToParse = inst.input.val() } - - if (timeToParse instanceof Date) { - inst.hours = timeToParse.getHours(); - inst.minutes = timeToParse.getMinutes(); - } else { - var timeVal = inst.lastVal = timeToParse; - if (timeToParse == '') { - inst.hours = -1; - inst.minutes = -1; - } else { - var time = this.parseTime(inst, timeVal); - inst.hours = time.hours; - inst.minutes = time.minutes; - } - } - - - $.timepicker._updateTimepicker(inst); - }, - - /* Update or retrieve the settings for an existing time picker. - @param target element - the target input field or division or span - @param name object - the new settings to update or - string - the name of the setting to change or retrieve, - when retrieving also 'all' for all instance settings or - 'defaults' for all global defaults - @param value any - the new value for the setting - (omit if above is an object or to retrieve a value) */ - _optionTimepicker: function(target, name, value) { - var inst = this._getInst(target); - if (arguments.length == 2 && typeof name == 'string') { - return (name == 'defaults' ? $.extend({}, $.timepicker._defaults) : - (inst ? (name == 'all' ? $.extend({}, inst.settings) : - this._get(inst, name)) : null)); - } - var settings = name || {}; - if (typeof name == 'string') { - settings = {}; - settings[name] = value; - } - if (inst) { - if (this._curInst == inst) { - this._hideTimepicker(); - } - extendRemove(inst.settings, settings); - this._updateTimepicker(inst); - } - }, - - - /* Set the time for a jQuery selection. - @param target element - the target input field or division or span - @param time String - the new time */ - _setTimeTimepicker: function(target, time) { - var inst = this._getInst(target); - if (inst) { - this._setTime(inst, time); - this._updateTimepicker(inst); - this._updateAlternate(inst, time); - } - }, - - /* Set the time directly. */ - _setTime: function(inst, time, noChange) { - var origHours = inst.hours; - var origMinutes = inst.minutes; - var time = this.parseTime(inst, time); - inst.hours = time.hours; - inst.minutes = time.minutes; - - if ((origHours != inst.hours || origMinutes != inst.minuts) && !noChange) { - inst.input.trigger('change'); - } - this._updateTimepicker(inst); - this._updateSelectedValue(inst); - }, - - /* Return the current time, ready to be parsed, rounded to the closest 5 minute */ - _getCurrentTimeRounded: function (inst) { - var currentTime = new Date(), - currentMinutes = currentTime.getMinutes(), - // round to closest 5 - adjustedMinutes = Math.round( currentMinutes / 5 ) * 5; - currentTime.setMinutes(adjustedMinutes); - return currentTime; - }, - - /* - * Parse a time string into hours and minutes - */ - parseTime: function (inst, timeVal) { - var retVal = new Object(); - retVal.hours = -1; - retVal.minutes = -1; - - var timeSeparator = this._get(inst, 'timeSeparator'), - amPmText = this._get(inst, 'amPmText'), - showHours = this._get(inst, 'showHours'), - showMinutes = this._get(inst, 'showMinutes'), - optionalMinutes = this._get(inst, 'optionalMinutes'), - showPeriod = (this._get(inst, 'showPeriod') == true), - p = timeVal.indexOf(timeSeparator); - - // check if time separator found - if (p != -1) { - retVal.hours = parseInt(timeVal.substr(0, p), 10); - retVal.minutes = parseInt(timeVal.substr(p + 1), 10); - } - // check for hours only - else if ( (showHours) && ( !showMinutes || optionalMinutes ) ) { - retVal.hours = parseInt(timeVal, 10); - } - // check for minutes only - else if ( ( ! showHours) && (showMinutes) ) { - retVal.minutes = parseInt(timeVal, 10); - } - - if (showHours) { - var timeValUpper = timeVal.toUpperCase(); - if ((retVal.hours < 12) && (showPeriod) && (timeValUpper.indexOf(amPmText[1].toUpperCase()) != -1)) { - retVal.hours += 12; - } - // fix for 12 AM - if ((retVal.hours == 12) && (showPeriod) && (timeValUpper.indexOf(amPmText[0].toUpperCase()) != -1)) { - retVal.hours = 0; - } - } - - return retVal; - }, - - selectNow: function(e) { - - var id = $(e.target).attr("data-timepicker-instance-id"), - $target = $(id), - inst = this._getInst($target[0]); - - //if (!inst || (input && inst != $.data(input, PROP_NAME))) { return; } - var currentTime = new Date(); - inst.hours = currentTime.getHours(); - inst.minutes = currentTime.getMinutes(); - this._updateSelectedValue(inst); - this._updateTimepicker(inst); - this._hideTimepicker(); - }, - - deselectTime: function(e) { - var id = $(e.target).attr("data-timepicker-instance-id"), - $target = $(id), - inst = this._getInst($target[0]); - inst.hours = -1; - inst.minutes = -1; - this._updateSelectedValue(inst); - this._hideTimepicker(); - }, - - - selectHours: function (event) { - var $td = $(event.currentTarget), - id = $td.attr("data-timepicker-instance-id"), - newHours = $td.attr("data-hour"), - fromDoubleClick = event.data.fromDoubleClick, - $target = $(id), - inst = this._getInst($target[0]), - showMinutes = (this._get(inst, 'showMinutes') == true); - - // don't select if disabled - if ( $.timepicker._isDisabledTimepicker($target.attr('id')) ) { return false } - - $td.parents('.ui-timepicker-hours:first').find('a').removeClass('ui-state-active'); - $td.children('a').addClass('ui-state-active'); - inst.hours = newHours; - - // added for onMinuteShow callback - var onMinuteShow = this._get(inst, 'onMinuteShow'); - if (onMinuteShow) { - // this will trigger a callback on selected hour to make sure selected minute is allowed. - this._updateMinuteDisplay(inst); - } - - this._updateSelectedValue(inst); - - inst._hoursClicked = true; - if ((inst._minutesClicked) || (fromDoubleClick) || (showMinutes == false)) { - $.timepicker._hideTimepicker(); - } - // return false because if used inline, prevent the url to change to a hashtag - return false; - }, - - selectMinutes: function (event) { - var $td = $(event.currentTarget), - id = $td.attr("data-timepicker-instance-id"), - newMinutes = $td.attr("data-minute"), - fromDoubleClick = event.data.fromDoubleClick, - $target = $(id), - inst = this._getInst($target[0]), - showHours = (this._get(inst, 'showHours') == true); - - // don't select if disabled - if ( $.timepicker._isDisabledTimepicker($target.attr('id')) ) { return false } - - $td.parents('.ui-timepicker-minutes:first').find('a').removeClass('ui-state-active'); - $td.children('a').addClass('ui-state-active'); - - inst.minutes = newMinutes; - this._updateSelectedValue(inst); - - inst._minutesClicked = true; - if ((inst._hoursClicked) || (fromDoubleClick) || (showHours == false)) { - $.timepicker._hideTimepicker(); - // return false because if used inline, prevent the url to change to a hashtag - return false; - } - - // return false because if used inline, prevent the url to change to a hashtag - return false; - }, - - _updateSelectedValue: function (inst) { - var newTime = this._getParsedTime(inst); - if (inst.input) { - inst.input.val(newTime); - inst.input.trigger('change'); - } - var onSelect = this._get(inst, 'onSelect'); - if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [newTime, inst]); } // trigger custom callback - this._updateAlternate(inst, newTime); - return newTime; - }, - - /* this function process selected time and return it parsed according to instance options */ - _getParsedTime: function(inst) { - - if (inst.hours == -1 && inst.minutes == -1) { - return ''; - } - - if ((inst.hours < 0) || (inst.hours > 23)) { inst.hours = 12; } - if ((inst.minutes < 0) || (inst.minutes > 59)) { inst.minutes = 0; } - - var period = "", - showPeriod = (this._get(inst, 'showPeriod') == true), - showLeadingZero = (this._get(inst, 'showLeadingZero') == true), - showHours = (this._get(inst, 'showHours') == true), - showMinutes = (this._get(inst, 'showMinutes') == true), - optionalMinutes = (this._get(inst, 'optionalMinutes') == true), - amPmText = this._get(inst, 'amPmText'), - selectedHours = inst.hours ? inst.hours : 0, - selectedMinutes = inst.minutes ? inst.minutes : 0, - displayHours = selectedHours ? selectedHours : 0, - parsedTime = ''; - - if (showPeriod) { - if (inst.hours == 0) { - displayHours = 12; - } - if (inst.hours < 12) { - period = amPmText[0]; - } - else { - period = amPmText[1]; - if (displayHours > 12) { - displayHours -= 12; - } - } - } - - var h = displayHours.toString(); - if (showLeadingZero && (displayHours < 10)) { h = '0' + h; } - - var m = selectedMinutes.toString(); - if (selectedMinutes < 10) { m = '0' + m; } - - if (showHours) { - parsedTime += h; - } - if (showHours && showMinutes && (!optionalMinutes || m != 0)) { - parsedTime += this._get(inst, 'timeSeparator'); - } - if (showMinutes && (!optionalMinutes || m != 0)) { - parsedTime += m; - } - if (showHours) { - if (period.length > 0) { parsedTime += this._get(inst, 'periodSeparator') + period; } - } - - return parsedTime; - }, - - /* Update any alternate field to synchronise with the main field. */ - _updateAlternate: function(inst, newTime) { - var altField = this._get(inst, 'altField'); - if (altField) { // update alternate field too - $(altField).each(function(i,e) { - $(e).val(newTime); - }); - } - }, - - /* This might look unused but it's called by the $.fn.timepicker function with param getTime */ - /* added v 0.2.3 - gitHub issue #5 - Thanks edanuff */ - _getTimeTimepicker : function(input) { - var inst = this._getInst(input); - return this._getParsedTime(inst); - }, - _getHourTimepicker: function(input) { - var inst = this._getInst(input); - if ( inst == undefined) { return -1; } - return inst.hours; - }, - _getMinuteTimepicker: function(input) { - var inst= this._getInst(input); - if ( inst == undefined) { return -1; } - return inst.minutes; - } - - }); - - - - /* Invoke the timepicker functionality. - @param options string - a command, optionally followed by additional parameters or - Object - settings for attaching new timepicker functionality - @return jQuery object */ - $.fn.timepicker = function (options) { - - /* Initialise the time picker. */ - if (!$.timepicker.initialized) { - $(document).mousedown($.timepicker._checkExternalClick). - find('body').append($.timepicker.tpDiv); - $.timepicker.initialized = true; - } - - var otherArgs = Array.prototype.slice.call(arguments, 1); - if (typeof options == 'string' && (options == 'getTime' || options == 'getHour' || options == 'getMinute' )) - return $.timepicker['_' + options + 'Timepicker']. - apply($.timepicker, [this[0]].concat(otherArgs)); - if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') - return $.timepicker['_' + options + 'Timepicker']. - apply($.timepicker, [this[0]].concat(otherArgs)); - return this.each(function () { - typeof options == 'string' ? - $.timepicker['_' + options + 'Timepicker']. - apply($.timepicker, [this].concat(otherArgs)) : - $.timepicker._attachTimepicker(this, options); - }); - }; - - /* jQuery extend now ignores nulls! */ - function extendRemove(target, props) { - $.extend(target, props); - for (var name in props) - if (props[name] == null || props[name] == undefined) - target[name] = props[name]; - return target; - }; - - $.timepicker = new Timepicker(); // singleton instance - $.timepicker.initialized = false; - $.timepicker.uuid = new Date().getTime(); - $.timepicker.version = "0.2.9"; - - // Workaround for #4055 - // Add another global to avoid noConflict issues with inline event handlers - window['TP_jQuery_' + tpuuid] = $; - -})(jQuery); diff --git a/3rdparty/timepicker/releases.txt b/3rdparty/timepicker/releases.txt deleted file mode 100644 index 64622d4942986472a2781e1c544974647f40de12..0000000000000000000000000000000000000000 --- a/3rdparty/timepicker/releases.txt +++ /dev/null @@ -1,105 +0,0 @@ -Release 0.2.9 - November 13, 2011 -Fixed the zIndex problem and removed the zIndex option (Thanks everyone who reported the problem) -Fix a bug where repeatedly clicking on hour cells made the timepicker very slow. -Added Italian translation, thanks to Serge Margarita. - -Release 0.2.8 - November 5, 2011 -Updated "defaultTime" to allow for Date object (github issue #26) -Fixed the now and deselect buttons in IE - -Release 0.2.7 - October 19, 2011 -Added option to omit minutes in parsed time when user select 0 for minutes. (Thanks tribalvibes, Github issue #23) -Added support for internationalisation (fr, de and ja, Thanks Bernd Plagge). - -Release 0.2.6 - October 12, 2011 -Fixed a bug when input ID have more then one special char. (Thamks Jacqueline Krijnen) -Fixed a bug when parsing hours only or minutes only time. (Thanks protron, <a href="https://github.com/fgelinas/timepicker/issues/20">github issue #20</a>) -Added 'Now', 'Deselect' and 'Close' buttons. (Thanks Christian Grobmeier for the close button code, <a href="https://github.com/fgelinas/timepicker/issues/20">github issue #22</a>) - -Release 0.2.5 - September 13, 2011 -Added support for disable and enable. (Suggested by danielrex, github issue #17) -Added an example for 2 timepicker to behave as a period selector (start time and end time). (Thanks Bill Pellowe) -Renamed the stylesheet to jquery.ui.timepicker.css to be more consistent with jQuery UI file name convention. - -Release 0.2.4 - August 5, 2011 -Fixed the hand cursor in the css file. (Thanks Mike Neumegen) -Added position option to use with the jquery ui position utility. -Added option to display only hours or only minutes. - -Release 0.2.3 - July 11, 2011 -Fix github issue #3 : Bug when hours or minutes choices does not divide by number of rows (thanks wukimus) -Changed default behavior of the defaultTime option, if set to '' and input is empty, there will be no highlighted time in the popup (Thanks Rasmus Schultz) -Fix github issue #4 : Error when generating empty minute cell. (Thanks 123Haynes) -Fix github issue #5 : Add functionality for "getTime" option. (Thanks edanuff) -Added the periodSeparator option. (thanks jrchamp) -Fixed "getTime" for inline timepickers. (thanks Mike Neumegen) -Added "getHour" and "getMinute" to get individual values. - -Release 0.2.2 - June 16, 2011 -Fixed a "console.log" line that I forgot to remove before release 0.2.1 - -Release 0.2.1 - June 12, 2011 -Timepicker does not give the focus back to the input any more after time selection. This is similar to the datepicker behaviour and is more natural to the user because it shows the dialog again when the user click on the input again, as expected. -Added options to customize the hours and minutes ranges and interval for more customization. - -Release 0.2 - May 28, 2011 -So in the previous release I mixed up versions and lost some changes, I guess that's what happen when you drink and code. - -Release 0.1.2 - May 26, 2011 -Fixed a bug with inline timepickers that would append a #timepickr hashtag when selecting hours and minutes. -Fixed z-index problem with IE6 (Thanks Graham Bentley) -Added selection of highlighted text when enter is pressed on the input field (Thanks Glen Chiacchieri) -Adjusted some focus problems, now the input gets the focus back when the used click on hours / minutes. - -Release 0.1.something aka the lost release - around April 11 -Fixed a bug for when input Id had a dot in it, it was getting double escaped when it should not. (Thanks Zdenek Machac) -So in 0.1.1 I created a bug that made timepicker changes the location hash, well now it's fixed. (Thanks Lucas Falk) - -Release 0.1.1 - April 6, 2011 -Changed the cells click and dblclick binding for faster rendering in IE6/7 (Thanks Blair Parsons) -Fixed a class naming bug created in 0.1.0 (Thanks Morlion Peter) - -Release 0.1.0 - March 23, 2011 -Fixed some bugs with release 0.0.9 - -Release 0.0.9 - March 22, 2011 -Added zIndex option (Thanks Frank Enderle) -Added option showPeriodLabels that defines if the AM/PM labels are displayed on the left (Thanks Frank Enderle) -Added showOn ['focus'|'button'|'both'] and button options for alternate trigger method - -Release 0.0.8 - Fev 17, 2011 -Fixed close event not triggered when switching to another input with time picker (thanks Stuart Gregg) - -Release 0.0.7 - Fev 10, 2011 -Added function to set time after initialisation :$('#timepicker').timepicker('setTime',newTime); -Added support for disabled period of time : onHourShow and onMinuteShow (thanks Rene Felgentr�ger) - -Release 0.0.6 - Jan 19, 2011 -Added standard "change" event being triggered on the input when the content changes. (Thanks Rasmus Schultz) -Added support for inline timePicker, attached to div or span -Added altField that receive the parsed time value when selected time changes -Added defaultTime value to use when input field is missing (inline) or input value is empty - if defaultTime is missing, current time is used - -Release 0.0.5 - Jan 18, 2011 -Now updating time picker selected value when manually typing in the text field (thanks Rasmus Schultz) -Fixed : with showPeriod: true and showLeadingZero: true, PM hours did not show leading zeros (thanks Chandler May) -Fixed : with showPeriod: true and showLeadingZero: true, Selecting 12 AM shows as 00 AM in the input field, also parsing 12AM did not work correctly (thanks Rasmus Schultz) - -Release 0.0.4 - jan 10, 2011 -changed showLeadingZero to affect only hours, added showMinutesLeadingZero for minutes display -Removed width:100% for tables in css - -Release 0.0.3 - Jan 8, 2011 -Re-added a display:none on the main div (fix a small empty div visible at the bottom of the page before timepicker is called) (Thanks Gertjan van Roekel) -Fixed a problem where the timepicker was never displayed with jquery ui 1.8.7 css, - the problem was the class ui-helper-hidden-accessible, witch I removed. - Thanks Alexander Fietz and StackOverflow : http://stackoverflow.com/questions/4522274/jquery-timepicker-and-jqueryui-1-8-7-conflict - -Release 0.0.2 - Jan 6, 2011 -Updated to include common display options for USA users -Stephen Commisso - Jan 2011 - -As it is a timepicker, I inspired most of the code from the datepicker -Francois Gelinas - Nov 2010 - diff --git a/3rdparty/when/MIT-LICENSE.txt b/3rdparty/when/MIT-LICENSE.txt deleted file mode 100644 index b4429c89ac108d61d2b3de16362ef4704003997e..0000000000000000000000000000000000000000 --- a/3rdparty/when/MIT-LICENSE.txt +++ /dev/null @@ -1,9 +0,0 @@ -License - -Copyright (c) 2010 Thomas Planer - -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. \ No newline at end of file diff --git a/3rdparty/when/When.php b/3rdparty/when/When.php deleted file mode 100755 index d54f296ed610b997c15ab7196ddff857d66ce462..0000000000000000000000000000000000000000 --- a/3rdparty/when/When.php +++ /dev/null @@ -1,731 +0,0 @@ -<?php -/** - * Name: When - * Author: Thomas Planer <tplaner@gmail.com> - * Location: http://github.com/tplaner/When - * Created: September 2010 - * Description: Determines the next date of recursion given an iCalendar "rrule" like pattern. - * Requirements: PHP 5.3+ - makes extensive use of the Date and Time library (http://us2.php.net/manual/en/book.datetime.php) - */ -class When -{ - protected $frequency; - - protected $start_date; - protected $try_date; - - protected $end_date; - - protected $gobymonth; - protected $bymonth; - - protected $gobyweekno; - protected $byweekno; - - protected $gobyyearday; - protected $byyearday; - - protected $gobymonthday; - protected $bymonthday; - - protected $gobyday; - protected $byday; - - protected $gobysetpos; - protected $bysetpos; - - protected $suggestions; - - protected $count; - protected $counter; - - protected $goenddate; - - protected $interval; - - protected $wkst; - - protected $valid_week_days; - protected $valid_frequency; - - /** - * __construct - */ - public function __construct() - { - $this->frequency = null; - - $this->gobymonth = false; - $this->bymonth = range(1,12); - - $this->gobymonthday = false; - $this->bymonthday = range(1,31); - - $this->gobyday = false; - // setup the valid week days (0 = sunday) - $this->byday = range(0,6); - - $this->gobyyearday = false; - $this->byyearday = range(0,366); - - $this->gobysetpos = false; - $this->bysetpos = range(1,366); - - $this->gobyweekno = false; - // setup the range for valid weeks - $this->byweekno = range(0,54); - - $this->suggestions = array(); - - // this will be set if a count() is specified - $this->count = 0; - // how many *valid* results we returned - $this->counter = 0; - - // max date we'll return - $this->end_date = new DateTime('9999-12-31'); - - // the interval to increase the pattern by - $this->interval = 1; - - // what day does the week start on? (0 = sunday) - $this->wkst = 0; - - $this->valid_week_days = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); - - $this->valid_frequency = array('SECONDLY', 'MINUTELY', 'HOURLY', 'DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'); - } - - /** - * @param DateTime|string $start_date of the recursion - also is the first return value. - * @param string $frequency of the recrusion, valid frequencies: secondly, minutely, hourly, daily, weekly, monthly, yearly - */ - public function recur($start_date, $frequency = "daily") - { - try - { - if(is_object($start_date)) - { - $this->start_date = clone $start_date; - } - else - { - // timestamps within the RFC have a 'Z' at the end of them, remove this. - $start_date = trim($start_date, 'Z'); - $this->start_date = new DateTime($start_date); - } - - $this->try_date = clone $this->start_date; - } - catch(Exception $e) - { - throw new InvalidArgumentException('Invalid start date DateTime: ' . $e); - } - - $this->freq($frequency); - - return $this; - } - - public function freq($frequency) - { - if(in_array(strtoupper($frequency), $this->valid_frequency)) - { - $this->frequency = strtoupper($frequency); - } - else - { - throw new InvalidArgumentException('Invalid frequency type.'); - } - - return $this; - } - - // accepts an rrule directly - public function rrule($rrule) - { - // strip off a trailing semi-colon - $rrule = trim($rrule, ";"); - - $parts = explode(";", $rrule); - - foreach($parts as $part) - { - list($rule, $param) = explode("=", $part); - - $rule = strtoupper($rule); - $param = strtoupper($param); - - switch($rule) - { - case "FREQ": - $this->frequency = $param; - break; - case "UNTIL": - $this->until($param); - break; - case "COUNT": - $this->count($param); - break; - case "INTERVAL": - $this->interval($param); - break; - case "BYDAY": - $params = explode(",", $param); - $this->byday($params); - break; - case "BYMONTHDAY": - $params = explode(",", $param); - $this->bymonthday($params); - break; - case "BYYEARDAY": - $params = explode(",", $param); - $this->byyearday($params); - break; - case "BYWEEKNO": - $params = explode(",", $param); - $this->byweekno($params); - break; - case "BYMONTH": - $params = explode(",", $param); - $this->bymonth($params); - break; - case "BYSETPOS": - $params = explode(",", $param); - $this->bysetpos($params); - break; - case "WKST": - $this->wkst($param); - break; - } - } - - return $this; - } - - //max number of items to return based on the pattern - public function count($count) - { - $this->count = (int)$count; - - return $this; - } - - // how often the recurrence rule repeats - public function interval($interval) - { - $this->interval = (int)$interval; - - return $this; - } - - // starting day of the week - public function wkst($day) - { - switch($day) - { - case 'SU': - $this->wkst = 0; - break; - case 'MO': - $this->wkst = 1; - break; - case 'TU': - $this->wkst = 2; - break; - case 'WE': - $this->wkst = 3; - break; - case 'TH': - $this->wkst = 4; - break; - case 'FR': - $this->wkst = 5; - break; - case 'SA': - $this->wkst = 6; - break; - } - - return $this; - } - - // max date - public function until($end_date) - { - try - { - if(is_object($end_date)) - { - $this->end_date = clone $end_date; - } - else - { - // timestamps within the RFC have a 'Z' at the end of them, remove this. - $end_date = trim($end_date, 'Z'); - $this->end_date = new DateTime($end_date); - } - } - catch(Exception $e) - { - throw new InvalidArgumentException('Invalid end date DateTime: ' . $e); - } - - return $this; - } - - public function bymonth($months) - { - if(is_array($months)) - { - $this->gobymonth = true; - $this->bymonth = $months; - } - - return $this; - } - - public function bymonthday($days) - { - if(is_array($days)) - { - $this->gobymonthday = true; - $this->bymonthday = $days; - } - - return $this; - } - - public function byweekno($weeks) - { - $this->gobyweekno = true; - - if(is_array($weeks)) - { - $this->byweekno = $weeks; - } - - return $this; - } - - public function bysetpos($days) - { - $this->gobysetpos = true; - - if(is_array($days)) - { - $this->bysetpos = $days; - } - - return $this; - } - - public function byday($days) - { - $this->gobyday = true; - - if(is_array($days)) - { - $this->byday = array(); - foreach($days as $day) - { - $len = strlen($day); - - $as = '+'; - - // 0 mean no occurence is set - $occ = 0; - - if($len == 3) - { - $occ = substr($day, 0, 1); - } - if($len == 4) - { - $as = substr($day, 0, 1); - $occ = substr($day, 1, 1); - } - - if($as == '-') - { - $occ = '-' . $occ; - } - else - { - $occ = '+' . $occ; - } - - $day = substr($day, -2, 2); - switch($day) - { - case 'SU': - $this->byday[] = $occ . 'SU'; - break; - case 'MO': - $this->byday[] = $occ . 'MO'; - break; - case 'TU': - $this->byday[] = $occ . 'TU'; - break; - case 'WE': - $this->byday[] = $occ . 'WE'; - break; - case 'TH': - $this->byday[] = $occ . 'TH'; - break; - case 'FR': - $this->byday[] = $occ . 'FR'; - break; - case 'SA': - $this->byday[] = $occ . 'SA'; - break; - } - } - } - - return $this; - } - - public function byyearday($days) - { - $this->gobyyearday = true; - - if(is_array($days)) - { - $this->byyearday = $days; - } - - return $this; - } - - // this creates a basic list of dates to "try" - protected function create_suggestions() - { - switch($this->frequency) - { - case "YEARLY": - $interval = 'year'; - break; - case "MONTHLY": - $interval = 'month'; - break; - case "WEEKLY": - $interval = 'week'; - break; - case "DAILY": - $interval = 'day'; - break; - case "HOURLY": - $interval = 'hour'; - break; - case "MINUTELY": - $interval = 'minute'; - break; - case "SECONDLY": - $interval = 'second'; - break; - } - - $month_day = $this->try_date->format('j'); - $month = $this->try_date->format('n'); - $year = $this->try_date->format('Y'); - - $timestamp = $this->try_date->format('H:i:s'); - - if($this->gobysetpos) - { - if($this->try_date == $this->start_date) - { - $this->suggestions[] = clone $this->try_date; - } - else - { - if($this->gobyday) - { - foreach($this->bysetpos as $_pos) - { - $tmp_array = array(); - $_mdays = range(1, date('t',mktime(0,0,0,$month,1,$year))); - foreach($_mdays as $_mday) - { - $date_time = new DateTime($year . '-' . $month . '-' . $_mday . ' ' . $timestamp); - - $occur = ceil($_mday / 7); - - $day_of_week = $date_time->format('l'); - $dow_abr = strtoupper(substr($day_of_week, 0, 2)); - - // set the day of the month + (positive) - $occur = '+' . $occur . $dow_abr; - $occur_zero = '+0' . $dow_abr; - - // set the day of the month - (negative) - $total_days = $date_time->format('t') - $date_time->format('j'); - $occur_neg = '-' . ceil(($total_days + 1)/7) . $dow_abr; - - $day_from_end_of_month = $date_time->format('t') + 1 - $_mday; - - if(in_array($occur, $this->byday) || in_array($occur_zero, $this->byday) || in_array($occur_neg, $this->byday)) - { - $tmp_array[] = clone $date_time; - } - } - - if($_pos > 0) - { - $this->suggestions[] = clone $tmp_array[$_pos - 1]; - } - else - { - $this->suggestions[] = clone $tmp_array[count($tmp_array) + $_pos]; - } - - } - } - } - } - elseif($this->gobyyearday) - { - foreach($this->byyearday as $_day) - { - if($_day >= 0) - { - $_day--; - - $_time = strtotime('+' . $_day . ' days', mktime(0, 0, 0, 1, 1, $year)); - $this->suggestions[] = new Datetime(date('Y-m-d', $_time) . ' ' . $timestamp); - } - else - { - $year_day_neg = 365 + $_day; - $leap_year = $this->try_date->format('L'); - if($leap_year == 1) - { - $year_day_neg = 366 + $_day; - } - - $_time = strtotime('+' . $year_day_neg . ' days', mktime(0, 0, 0, 1, 1, $year)); - $this->suggestions[] = new Datetime(date('Y-m-d', $_time) . ' ' . $timestamp); - } - } - } - // special case because for years you need to loop through the months too - elseif($this->gobyday && $interval == "year") - { - foreach($this->bymonth as $_month) - { - // this creates an array of days of the month - $_mdays = range(1, date('t',mktime(0,0,0,$_month,1,$year))); - foreach($_mdays as $_mday) - { - $date_time = new DateTime($year . '-' . $_month . '-' . $_mday . ' ' . $timestamp); - - // get the week of the month (1, 2, 3, 4, 5, etc) - $week = $date_time->format('W'); - - if($date_time >= $this->start_date && in_array($week, $this->byweekno)) - { - $this->suggestions[] = clone $date_time; - } - } - } - } - elseif($interval == "day") - { - $this->suggestions[] = clone $this->try_date; - } - elseif($interval == "week") - { - $this->suggestions[] = clone $this->try_date; - - if($this->gobyday) - { - $week_day = $this->try_date->format('w'); - - $days_in_month = $this->try_date->format('t'); - - $overflow_count = 1; - $_day = $month_day; - - $run = true; - while($run) - { - $_day++; - if($_day <= $days_in_month) - { - $tmp_date = new DateTime($year . '-' . $month . '-' . $_day . ' ' . $timestamp); - } - else - { - //$tmp_month = $month+1; - $tmp_date = new DateTime($year . '-' . $month . '-' . $overflow_count . ' ' . $timestamp); - $tmp_date->modify('+1 month'); - $overflow_count++; - } - - $week_day = $tmp_date->format('w'); - - if($this->try_date == $this->start_date) - { - if($week_day == $this->wkst) - { - $this->try_date = clone $tmp_date; - $this->try_date->modify('-7 days'); - $run = false; - } - } - - if($week_day != $this->wkst) - { - $this->suggestions[] = clone $tmp_date; - } - else - { - $run = false; - } - } - } - } - elseif($this->gobyday && $interval == "month") - { - $_mdays = range(1, date('t',mktime(0,0,0,$month,1,$year))); - foreach($_mdays as $_mday) - { - $date_time = new DateTime($year . '-' . $month . '-' . $_mday . ' ' . $timestamp); - - // get the week of the month (1, 2, 3, 4, 5, etc) - $week = $date_time->format('W'); - - if($date_time >= $this->start_date && in_array($week, $this->byweekno)) - { - $this->suggestions[] = clone $date_time; - } - } - } - elseif($this->gobymonth) - { - foreach($this->bymonth as $_month) - { - $date_time = new DateTime($year . '-' . $_month . '-' . $month_day . ' ' . $timestamp); - - if($date_time >= $this->start_date) - { - $this->suggestions[] = clone $date_time; - } - } - } - else - { - $this->suggestions[] = clone $this->try_date; - } - - if($interval == "month") - { - - $this->try_date->modify('first day of next month'); - if((int) date('t', $this->try_date->format('U')) > (int) $this->start_date->format('j')){ - $this->try_date->modify('+' . (int) $this->start_date->format('j') - 1 . ' day'); - }else{ - $this->try_date->modify('+' . (int) date('t', $this->try_date->format('U')) - 1 . ' day'); - } - } - else - { - $this->try_date->modify($this->interval . ' ' . $interval); - } - } - - protected function valid_date($date) - { - $year = $date->format('Y'); - $month = $date->format('n'); - $day = $date->format('j'); - - $year_day = $date->format('z') + 1; - - $year_day_neg = -366 + $year_day; - $leap_year = $date->format('L'); - if($leap_year == 1) - { - $year_day_neg = -367 + $year_day; - } - - // this is the nth occurence of the date - $occur = ceil($day / 7); - - $week = $date->format('W'); - - $day_of_week = $date->format('l'); - $dow_abr = strtoupper(substr($day_of_week, 0, 2)); - - // set the day of the month + (positive) - $occur = '+' . $occur . $dow_abr; - $occur_zero = '+0' . $dow_abr; - - // set the day of the month - (negative) - $total_days = $date->format('t') - $date->format('j'); - $occur_neg = '-' . ceil(($total_days + 1)/7) . $dow_abr; - - $day_from_end_of_month = $date->format('t') + 1 - $day; - - if(in_array($month, $this->bymonth) && - (in_array($occur, $this->byday) || in_array($occur_zero, $this->byday) || in_array($occur_neg, $this->byday)) && - in_array($week, $this->byweekno) && - (in_array($day, $this->bymonthday) || in_array(-$day_from_end_of_month, $this->bymonthday)) && - (in_array($year_day, $this->byyearday) || in_array($year_day_neg, $this->byyearday))) - { - return true; - } - else - { - return false; - } - } - - // return the next valid DateTime object which matches the pattern and follows the rules - public function next() - { - // check the counter is set - if($this->count !== 0) - { - if($this->counter >= $this->count) - { - return false; - } - } - - // create initial set of suggested dates - if(count($this->suggestions) === 0) - { - $this->create_suggestions(); - } - - // loop through the suggested dates - while(count($this->suggestions) > 0) - { - // get the first one on the array - $try_date = array_shift($this->suggestions); - - // make sure the date doesn't exceed the max date - if($try_date > $this->end_date) - { - return false; - } - - // make sure it falls within the allowed days - if($this->valid_date($try_date) === true) - { - $this->counter++; - return $try_date; - } - else - { - // we might be out of suggested days, so load some more - if(count($this->suggestions) === 0) - { - $this->create_suggestions(); - } - } - } - } -}