Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • 4.0_templates
  • 4.1_templates-symlink
  • develop
  • git-fixes
  • master
5 results

Target

Select target project
  • tneumann9/PlanetRed
  • JSTUREK8/PlanetRed
  • smccoy12/PlanetRed
  • dkuzelka2/PlanetRed
  • s-cwiedel5/PlanetRed
  • dxg/PlanetRed
6 results
Select Git revision
  • 4.0_templates
  • 4.1_templates-symlink
  • develop
  • git-fixes
  • master
5 results
Show changes
Showing
with 10221 additions and 0 deletions
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* File::CSV
*
* PHP versions 4 and 5
*
* Copyright (c) 1997-2008,
* Vincent Blavet <vincent@phpconcept.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* @category File_Formats
* @package Archive_Tar
* @author Vincent Blavet <vincent@phpconcept.net>
* @copyright 1997-2008 The Authors
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id: Tar.php,v 1.43 2008/10/30 17:58:42 dufuz Exp $
* @link http://pear.php.net/package/Archive_Tar
*/
require_once 'PEAR.php';
define ('ARCHIVE_TAR_ATT_SEPARATOR', 90001);
define ('ARCHIVE_TAR_END_BLOCK', pack("a512", ''));
/**
* Creates a (compressed) Tar archive
*
* @author Vincent Blavet <vincent@phpconcept.net>
* @version $Revision: 1.43 $
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @package Archive_Tar
*/
class Archive_Tar extends PEAR
{
/**
* @var string Name of the Tar
*/
var $_tarname='';
/**
* @var boolean if true, the Tar file will be gzipped
*/
var $_compress=false;
/**
* @var string Type of compression : 'none', 'gz' or 'bz2'
*/
var $_compress_type='none';
/**
* @var string Explode separator
*/
var $_separator=' ';
/**
* @var file descriptor
*/
var $_file=0;
/**
* @var string Local Tar name of a remote Tar (http:// or ftp://)
*/
var $_temp_tarname='';
// {{{ constructor
/**
* Archive_Tar Class constructor. This flavour of the constructor only
* declare a new Archive_Tar object, identifying it by the name of the
* tar file.
* If the compress argument is set the tar will be read or created as a
* gzip or bz2 compressed TAR file.
*
* @param string $p_tarname The name of the tar archive to create
* @param string $p_compress can be null, 'gz' or 'bz2'. This
* parameter indicates if gzip or bz2 compression
* is required. For compatibility reason the
* boolean value 'true' means 'gz'.
* @access public
*/
function Archive_Tar($p_tarname, $p_compress = null)
{
$this->PEAR();
$this->_compress = false;
$this->_compress_type = 'none';
if (($p_compress === null) || ($p_compress == '')) {
if (@file_exists($p_tarname)) {
if ($fp = @fopen($p_tarname, "rb")) {
// look for gzip magic cookie
$data = fread($fp, 2);
fclose($fp);
if ($data == "\37\213") {
$this->_compress = true;
$this->_compress_type = 'gz';
// No sure it's enought for a magic code ....
} elseif ($data == "BZ") {
$this->_compress = true;
$this->_compress_type = 'bz2';
}
}
} else {
// probably a remote file or some file accessible
// through a stream interface
if (substr($p_tarname, -2) == 'gz') {
$this->_compress = true;
$this->_compress_type = 'gz';
} elseif ((substr($p_tarname, -3) == 'bz2') ||
(substr($p_tarname, -2) == 'bz')) {
$this->_compress = true;
$this->_compress_type = 'bz2';
}
}
} else {
if (($p_compress === true) || ($p_compress == 'gz')) {
$this->_compress = true;
$this->_compress_type = 'gz';
} else if ($p_compress == 'bz2') {
$this->_compress = true;
$this->_compress_type = 'bz2';
} else {
die("Unsupported compression type '$p_compress'\n".
"Supported types are 'gz' and 'bz2'.\n");
return false;
}
}
$this->_tarname = $p_tarname;
if ($this->_compress) { // assert zlib or bz2 extension support
if ($this->_compress_type == 'gz')
$extname = 'zlib';
else if ($this->_compress_type == 'bz2')
$extname = 'bz2';
if (!extension_loaded($extname)) {
PEAR::loadExtension($extname);
}
if (!extension_loaded($extname)) {
die("The extension '$extname' couldn't be found.\n".
"Please make sure your version of PHP was built ".
"with '$extname' support.\n");
return false;
}
}
}
// }}}
// {{{ destructor
function _Archive_Tar()
{
$this->_close();
// ----- Look for a local copy to delete
if ($this->_temp_tarname != '')
@unlink($this->_temp_tarname);
$this->_PEAR();
}
// }}}
// {{{ create()
/**
* This method creates the archive file and add the files / directories
* that are listed in $p_filelist.
* If a file with the same name exist and is writable, it is replaced
* by the new tar.
* The method return false and a PEAR error text.
* The $p_filelist parameter can be an array of string, each string
* representing a filename or a directory name with their path if
* needed. It can also be a single string with names separated by a
* single blank.
* For each directory added in the archive, the files and
* sub-directories are also added.
* See also createModify() method for more details.
*
* @param array $p_filelist An array of filenames and directory names, or a
* single string with names separated by a single
* blank space.
* @return true on success, false on error.
* @see createModify()
* @access public
*/
function create($p_filelist)
{
return $this->createModify($p_filelist, '', '');
}
// }}}
// {{{ add()
/**
* This method add the files / directories that are listed in $p_filelist in
* the archive. If the archive does not exist it is created.
* The method return false and a PEAR error text.
* The files and directories listed are only added at the end of the archive,
* even if a file with the same name is already archived.
* See also createModify() method for more details.
*
* @param array $p_filelist An array of filenames and directory names, or a
* single string with names separated by a single
* blank space.
* @return true on success, false on error.
* @see createModify()
* @access public
*/
function add($p_filelist)
{
return $this->addModify($p_filelist, '', '');
}
// }}}
// {{{ extract()
function extract($p_path='')
{
return $this->extractModify($p_path, '');
}
// }}}
// {{{ listContent()
function listContent()
{
$v_list_detail = array();
if ($this->_openRead()) {
if (!$this->_extractList('', $v_list_detail, "list", '', '')) {
unset($v_list_detail);
$v_list_detail = 0;
}
$this->_close();
}
return $v_list_detail;
}
// }}}
// {{{ createModify()
/**
* This method creates the archive file and add the files / directories
* that are listed in $p_filelist.
* If the file already exists and is writable, it is replaced by the
* new tar. It is a create and not an add. If the file exists and is
* read-only or is a directory it is not replaced. The method return
* false and a PEAR error text.
* The $p_filelist parameter can be an array of string, each string
* representing a filename or a directory name with their path if
* needed. It can also be a single string with names separated by a
* single blank.
* The path indicated in $p_remove_dir will be removed from the
* memorized path of each file / directory listed when this path
* exists. By default nothing is removed (empty path '')
* The path indicated in $p_add_dir will be added at the beginning of
* the memorized path of each file / directory listed. However it can
* be set to empty ''. The adding of a path is done after the removing
* of path.
* The path add/remove ability enables the user to prepare an archive
* for extraction in a different path than the origin files are.
* See also addModify() method for file adding properties.
*
* @param array $p_filelist An array of filenames and directory names,
* or a single string with names separated by
* a single blank space.
* @param string $p_add_dir A string which contains a path to be added
* to the memorized path of each element in
* the list.
* @param string $p_remove_dir A string which contains a path to be
* removed from the memorized path of each
* element in the list, when relevant.
* @return boolean true on success, false on error.
* @access public
* @see addModify()
*/
function createModify($p_filelist, $p_add_dir, $p_remove_dir='')
{
$v_result = true;
if (!$this->_openWrite())
return false;
if ($p_filelist != '') {
if (is_array($p_filelist))
$v_list = $p_filelist;
elseif (is_string($p_filelist))
$v_list = explode($this->_separator, $p_filelist);
else {
$this->_cleanFile();
$this->_error('Invalid file list');
return false;
}
$v_result = $this->_addList($v_list, $p_add_dir, $p_remove_dir);
}
if ($v_result) {
$this->_writeFooter();
$this->_close();
} else
$this->_cleanFile();
return $v_result;
}
// }}}
// {{{ addModify()
/**
* This method add the files / directories listed in $p_filelist at the
* end of the existing archive. If the archive does not yet exists it
* is created.
* The $p_filelist parameter can be an array of string, each string
* representing a filename or a directory name with their path if
* needed. It can also be a single string with names separated by a
* single blank.
* The path indicated in $p_remove_dir will be removed from the
* memorized path of each file / directory listed when this path
* exists. By default nothing is removed (empty path '')
* The path indicated in $p_add_dir will be added at the beginning of
* the memorized path of each file / directory listed. However it can
* be set to empty ''. The adding of a path is done after the removing
* of path.
* The path add/remove ability enables the user to prepare an archive
* for extraction in a different path than the origin files are.
* If a file/dir is already in the archive it will only be added at the
* end of the archive. There is no update of the existing archived
* file/dir. However while extracting the archive, the last file will
* replace the first one. This results in a none optimization of the
* archive size.
* If a file/dir does not exist the file/dir is ignored. However an
* error text is send to PEAR error.
* If a file/dir is not readable the file/dir is ignored. However an
* error text is send to PEAR error.
*
* @param array $p_filelist An array of filenames and directory
* names, or a single string with names
* separated by a single blank space.
* @param string $p_add_dir A string which contains a path to be
* added to the memorized path of each
* element in the list.
* @param string $p_remove_dir A string which contains a path to be
* removed from the memorized path of
* each element in the list, when
* relevant.
* @return true on success, false on error.
* @access public
*/
function addModify($p_filelist, $p_add_dir, $p_remove_dir='')
{
$v_result = true;
if (!$this->_isArchive())
$v_result = $this->createModify($p_filelist, $p_add_dir,
$p_remove_dir);
else {
if (is_array($p_filelist))
$v_list = $p_filelist;
elseif (is_string($p_filelist))
$v_list = explode($this->_separator, $p_filelist);
else {
$this->_error('Invalid file list');
return false;
}
$v_result = $this->_append($v_list, $p_add_dir, $p_remove_dir);
}
return $v_result;
}
// }}}
// {{{ addString()
/**
* This method add a single string as a file at the
* end of the existing archive. If the archive does not yet exists it
* is created.
*
* @param string $p_filename A string which contains the full
* filename path that will be associated
* with the string.
* @param string $p_string The content of the file added in
* the archive.
* @return true on success, false on error.
* @access public
*/
function addString($p_filename, $p_string)
{
$v_result = true;
if (!$this->_isArchive()) {
if (!$this->_openWrite()) {
return false;
}
$this->_close();
}
if (!$this->_openAppend())
return false;
// Need to check the get back to the temporary file ? ....
$v_result = $this->_addString($p_filename, $p_string);
$this->_writeFooter();
$this->_close();
return $v_result;
}
// }}}
// {{{ extractModify()
/**
* This method extract all the content of the archive in the directory
* indicated by $p_path. When relevant the memorized path of the
* files/dir can be modified by removing the $p_remove_path path at the
* beginning of the file/dir path.
* While extracting a file, if the directory path does not exists it is
* created.
* While extracting a file, if the file already exists it is replaced
* without looking for last modification date.
* While extracting a file, if the file already exists and is write
* protected, the extraction is aborted.
* While extracting a file, if a directory with the same name already
* exists, the extraction is aborted.
* While extracting a directory, if a file with the same name already
* exists, the extraction is aborted.
* While extracting a file/directory if the destination directory exist
* and is write protected, or does not exist but can not be created,
* the extraction is aborted.
* If after extraction an extracted file does not show the correct
* stored file size, the extraction is aborted.
* When the extraction is aborted, a PEAR error text is set and false
* is returned. However the result can be a partial extraction that may
* need to be manually cleaned.
*
* @param string $p_path The path of the directory where the
* files/dir need to by extracted.
* @param string $p_remove_path Part of the memorized path that can be
* removed if present at the beginning of
* the file/dir path.
* @return boolean true on success, false on error.
* @access public
* @see extractList()
*/
function extractModify($p_path, $p_remove_path)
{
$v_result = true;
$v_list_detail = array();
if ($v_result = $this->_openRead()) {
$v_result = $this->_extractList($p_path, $v_list_detail,
"complete", 0, $p_remove_path);
$this->_close();
}
return $v_result;
}
// }}}
// {{{ extractInString()
/**
* This method extract from the archive one file identified by $p_filename.
* The return value is a string with the file content, or NULL on error.
* @param string $p_filename The path of the file to extract in a string.
* @return a string with the file content or NULL.
* @access public
*/
function extractInString($p_filename)
{
if ($this->_openRead()) {
$v_result = $this->_extractInString($p_filename);
$this->_close();
} else {
$v_result = NULL;
}
return $v_result;
}
// }}}
// {{{ extractList()
/**
* This method extract from the archive only the files indicated in the
* $p_filelist. These files are extracted in the current directory or
* in the directory indicated by the optional $p_path parameter.
* If indicated the $p_remove_path can be used in the same way as it is
* used in extractModify() method.
* @param array $p_filelist An array of filenames and directory names,
* or a single string with names separated
* by a single blank space.
* @param string $p_path The path of the directory where the
* files/dir need to by extracted.
* @param string $p_remove_path Part of the memorized path that can be
* removed if present at the beginning of
* the file/dir path.
* @return true on success, false on error.
* @access public
* @see extractModify()
*/
function extractList($p_filelist, $p_path='', $p_remove_path='')
{
$v_result = true;
$v_list_detail = array();
if (is_array($p_filelist))
$v_list = $p_filelist;
elseif (is_string($p_filelist))
$v_list = explode($this->_separator, $p_filelist);
else {
$this->_error('Invalid string list');
return false;
}
if ($v_result = $this->_openRead()) {
$v_result = $this->_extractList($p_path, $v_list_detail, "partial",
$v_list, $p_remove_path);
$this->_close();
}
return $v_result;
}
// }}}
// {{{ setAttribute()
/**
* This method set specific attributes of the archive. It uses a variable
* list of parameters, in the format attribute code + attribute values :
* $arch->setAttribute(ARCHIVE_TAR_ATT_SEPARATOR, ',');
* @param mixed $argv variable list of attributes and values
* @return true on success, false on error.
* @access public
*/
function setAttribute()
{
$v_result = true;
// ----- Get the number of variable list of arguments
if (($v_size = func_num_args()) == 0) {
return true;
}
// ----- Get the arguments
$v_att_list = &func_get_args();
// ----- Read the attributes
$i=0;
while ($i<$v_size) {
// ----- Look for next option
switch ($v_att_list[$i]) {
// ----- Look for options that request a string value
case ARCHIVE_TAR_ATT_SEPARATOR :
// ----- Check the number of parameters
if (($i+1) >= $v_size) {
$this->_error('Invalid number of parameters for '
.'attribute ARCHIVE_TAR_ATT_SEPARATOR');
return false;
}
// ----- Get the value
$this->_separator = $v_att_list[$i+1];
$i++;
break;
default :
$this->_error('Unknow attribute code '.$v_att_list[$i].'');
return false;
}
// ----- Next attribute
$i++;
}
return $v_result;
}
// }}}
// {{{ _error()
function _error($p_message)
{
// ----- To be completed
$this->raiseError($p_message);
}
// }}}
// {{{ _warning()
function _warning($p_message)
{
// ----- To be completed
$this->raiseError($p_message);
}
// }}}
// {{{ _isArchive()
function _isArchive($p_filename=NULL)
{
if ($p_filename == NULL) {
$p_filename = $this->_tarname;
}
clearstatcache();
return @is_file($p_filename) && !@is_link($p_filename);
}
// }}}
// {{{ _openWrite()
function _openWrite()
{
if ($this->_compress_type == 'gz')
$this->_file = @gzopen($this->_tarname, "wb9");
else if ($this->_compress_type == 'bz2')
$this->_file = @bzopen($this->_tarname, "w");
else if ($this->_compress_type == 'none')
$this->_file = @fopen($this->_tarname, "wb");
else
$this->_error('Unknown or missing compression type ('
.$this->_compress_type.')');
if ($this->_file == 0) {
$this->_error('Unable to open in write mode \''
.$this->_tarname.'\'');
return false;
}
return true;
}
// }}}
// {{{ _openRead()
function _openRead()
{
if (strtolower(substr($this->_tarname, 0, 7)) == 'http://') {
// ----- Look if a local copy need to be done
if ($this->_temp_tarname == '') {
$this->_temp_tarname = uniqid('tar').'.tmp';
if (!$v_file_from = @fopen($this->_tarname, 'rb')) {
$this->_error('Unable to open in read mode \''
.$this->_tarname.'\'');
$this->_temp_tarname = '';
return false;
}
if (!$v_file_to = @fopen($this->_temp_tarname, 'wb')) {
$this->_error('Unable to open in write mode \''
.$this->_temp_tarname.'\'');
$this->_temp_tarname = '';
return false;
}
while ($v_data = @fread($v_file_from, 1024))
@fwrite($v_file_to, $v_data);
@fclose($v_file_from);
@fclose($v_file_to);
}
// ----- File to open if the local copy
$v_filename = $this->_temp_tarname;
} else
// ----- File to open if the normal Tar file
$v_filename = $this->_tarname;
if ($this->_compress_type == 'gz')
$this->_file = @gzopen($v_filename, "rb");
else if ($this->_compress_type == 'bz2')
$this->_file = @bzopen($v_filename, "r");
else if ($this->_compress_type == 'none')
$this->_file = @fopen($v_filename, "rb");
else
$this->_error('Unknown or missing compression type ('
.$this->_compress_type.')');
if ($this->_file == 0) {
$this->_error('Unable to open in read mode \''.$v_filename.'\'');
return false;
}
return true;
}
// }}}
// {{{ _openReadWrite()
function _openReadWrite()
{
if ($this->_compress_type == 'gz')
$this->_file = @gzopen($this->_tarname, "r+b");
else if ($this->_compress_type == 'bz2') {
$this->_error('Unable to open bz2 in read/write mode \''
.$this->_tarname.'\' (limitation of bz2 extension)');
return false;
} else if ($this->_compress_type == 'none')
$this->_file = @fopen($this->_tarname, "r+b");
else
$this->_error('Unknown or missing compression type ('
.$this->_compress_type.')');
if ($this->_file == 0) {
$this->_error('Unable to open in read/write mode \''
.$this->_tarname.'\'');
return false;
}
return true;
}
// }}}
// {{{ _close()
function _close()
{
//if (isset($this->_file)) {
if (is_resource($this->_file)) {
if ($this->_compress_type == 'gz')
@gzclose($this->_file);
else if ($this->_compress_type == 'bz2')
@bzclose($this->_file);
else if ($this->_compress_type == 'none')
@fclose($this->_file);
else
$this->_error('Unknown or missing compression type ('
.$this->_compress_type.')');
$this->_file = 0;
}
// ----- Look if a local copy need to be erase
// Note that it might be interesting to keep the url for a time : ToDo
if ($this->_temp_tarname != '') {
@unlink($this->_temp_tarname);
$this->_temp_tarname = '';
}
return true;
}
// }}}
// {{{ _cleanFile()
function _cleanFile()
{
$this->_close();
// ----- Look for a local copy
if ($this->_temp_tarname != '') {
// ----- Remove the local copy but not the remote tarname
@unlink($this->_temp_tarname);
$this->_temp_tarname = '';
} else {
// ----- Remove the local tarname file
@unlink($this->_tarname);
}
$this->_tarname = '';
return true;
}
// }}}
// {{{ _writeBlock()
function _writeBlock($p_binary_data, $p_len=null)
{
if (is_resource($this->_file)) {
if ($p_len === null) {
if ($this->_compress_type == 'gz')
@gzputs($this->_file, $p_binary_data);
else if ($this->_compress_type == 'bz2')
@bzwrite($this->_file, $p_binary_data);
else if ($this->_compress_type == 'none')
@fputs($this->_file, $p_binary_data);
else
$this->_error('Unknown or missing compression type ('
.$this->_compress_type.')');
} else {
if ($this->_compress_type == 'gz')
@gzputs($this->_file, $p_binary_data, $p_len);
else if ($this->_compress_type == 'bz2')
@bzwrite($this->_file, $p_binary_data, $p_len);
else if ($this->_compress_type == 'none')
@fputs($this->_file, $p_binary_data, $p_len);
else
$this->_error('Unknown or missing compression type ('
.$this->_compress_type.')');
}
}
return true;
}
// }}}
// {{{ _readBlock()
function _readBlock()
{
$v_block = null;
if (is_resource($this->_file)) {
if ($this->_compress_type == 'gz')
$v_block = @gzread($this->_file, 512);
else if ($this->_compress_type == 'bz2')
$v_block = @bzread($this->_file, 512);
else if ($this->_compress_type == 'none')
$v_block = @fread($this->_file, 512);
else
$this->_error('Unknown or missing compression type ('
.$this->_compress_type.')');
}
return $v_block;
}
// }}}
// {{{ _jumpBlock()
function _jumpBlock($p_len=null)
{
if (is_resource($this->_file)) {
if ($p_len === null)
$p_len = 1;
if ($this->_compress_type == 'gz') {
@gzseek($this->_file, gztell($this->_file)+($p_len*512));
}
else if ($this->_compress_type == 'bz2') {
// ----- Replace missing bztell() and bzseek()
for ($i=0; $i<$p_len; $i++)
$this->_readBlock();
} else if ($this->_compress_type == 'none')
@fseek($this->_file, ftell($this->_file)+($p_len*512));
else
$this->_error('Unknown or missing compression type ('
.$this->_compress_type.')');
}
return true;
}
// }}}
// {{{ _writeFooter()
function _writeFooter()
{
if (is_resource($this->_file)) {
// ----- Write the last 0 filled block for end of archive
$v_binary_data = pack('a1024', '');
$this->_writeBlock($v_binary_data);
}
return true;
}
// }}}
// {{{ _addList()
function _addList($p_list, $p_add_dir, $p_remove_dir)
{
$v_result=true;
$v_header = array();
// ----- Remove potential windows directory separator
$p_add_dir = $this->_translateWinPath($p_add_dir);
$p_remove_dir = $this->_translateWinPath($p_remove_dir, false);
if (!$this->_file) {
$this->_error('Invalid file descriptor');
return false;
}
if (sizeof($p_list) == 0)
return true;
foreach ($p_list as $v_filename) {
if (!$v_result) {
break;
}
// ----- Skip the current tar name
if ($v_filename == $this->_tarname)
continue;
if ($v_filename == '')
continue;
if (!file_exists($v_filename)) {
$this->_warning("File '$v_filename' does not exist");
continue;
}
// ----- Add the file or directory header
if (!$this->_addFile($v_filename, $v_header, $p_add_dir, $p_remove_dir))
return false;
if (@is_dir($v_filename) && !@is_link($v_filename)) {
if (!($p_hdir = opendir($v_filename))) {
$this->_warning("Directory '$v_filename' can not be read");
continue;
}
while (false !== ($p_hitem = readdir($p_hdir))) {
if (($p_hitem != '.') && ($p_hitem != '..')) {
if ($v_filename != ".")
$p_temp_list[0] = $v_filename.'/'.$p_hitem;
else
$p_temp_list[0] = $p_hitem;
$v_result = $this->_addList($p_temp_list,
$p_add_dir,
$p_remove_dir);
}
}
unset($p_temp_list);
unset($p_hdir);
unset($p_hitem);
}
}
return $v_result;
}
// }}}
// {{{ _addFile()
function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir)
{
if (!$this->_file) {
$this->_error('Invalid file descriptor');
return false;
}
if ($p_filename == '') {
$this->_error('Invalid file name');
return false;
}
// ----- Calculate the stored filename
$p_filename = $this->_translateWinPath($p_filename, false);;
$v_stored_filename = $p_filename;
if (strcmp($p_filename, $p_remove_dir) == 0) {
return true;
}
if ($p_remove_dir != '') {
if (substr($p_remove_dir, -1) != '/')
$p_remove_dir .= '/';
if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir)
$v_stored_filename = substr($p_filename, strlen($p_remove_dir));
}
$v_stored_filename = $this->_translateWinPath($v_stored_filename);
if ($p_add_dir != '') {
if (substr($p_add_dir, -1) == '/')
$v_stored_filename = $p_add_dir.$v_stored_filename;
else
$v_stored_filename = $p_add_dir.'/'.$v_stored_filename;
}
$v_stored_filename = $this->_pathReduction($v_stored_filename);
if ($this->_isArchive($p_filename)) {
if (($v_file = @fopen($p_filename, "rb")) == 0) {
$this->_warning("Unable to open file '".$p_filename
."' in binary read mode");
return true;
}
if (!$this->_writeHeader($p_filename, $v_stored_filename))
return false;
while (($v_buffer = fread($v_file, 512)) != '') {
$v_binary_data = pack("a512", "$v_buffer");
$this->_writeBlock($v_binary_data);
}
fclose($v_file);
} else {
// ----- Only header for dir
if (!$this->_writeHeader($p_filename, $v_stored_filename))
return false;
}
return true;
}
// }}}
// {{{ _addString()
function _addString($p_filename, $p_string)
{
if (!$this->_file) {
$this->_error('Invalid file descriptor');
return false;
}
if ($p_filename == '') {
$this->_error('Invalid file name');
return false;
}
// ----- Calculate the stored filename
$p_filename = $this->_translateWinPath($p_filename, false);;
if (!$this->_writeHeaderBlock($p_filename, strlen($p_string),
time(), 384, "", 0, 0))
return false;
$i=0;
while (($v_buffer = substr($p_string, (($i++)*512), 512)) != '') {
$v_binary_data = pack("a512", $v_buffer);
$this->_writeBlock($v_binary_data);
}
return true;
}
// }}}
// {{{ _writeHeader()
function _writeHeader($p_filename, $p_stored_filename)
{
if ($p_stored_filename == '')
$p_stored_filename = $p_filename;
$v_reduce_filename = $this->_pathReduction($p_stored_filename);
if (strlen($v_reduce_filename) > 99) {
if (!$this->_writeLongHeader($v_reduce_filename))
return false;
}
$v_info = lstat($p_filename);
$v_uid = sprintf("%6s ", DecOct($v_info[4]));
$v_gid = sprintf("%6s ", DecOct($v_info[5]));
$v_perms = sprintf("%6s ", DecOct($v_info['mode']));
$v_mtime = sprintf("%11s", DecOct($v_info['mode']));
$v_linkname = '';
if (@is_link($p_filename)) {
$v_typeflag = '2';
$v_linkname = readlink($p_filename);
$v_size = sprintf("%11s ", DecOct(0));
} elseif (@is_dir($p_filename)) {
$v_typeflag = "5";
$v_size = sprintf("%11s ", DecOct(0));
} else {
$v_typeflag = '';
clearstatcache();
$v_size = sprintf("%11s ", DecOct($v_info['size']));
}
$v_magic = '';
$v_version = '';
$v_uname = '';
$v_gname = '';
$v_devmajor = '';
$v_devminor = '';
$v_prefix = '';
$v_binary_data_first = pack("a100a8a8a8a12A12",
$v_reduce_filename, $v_perms, $v_uid,
$v_gid, $v_size, $v_mtime);
$v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
$v_typeflag, $v_linkname, $v_magic,
$v_version, $v_uname, $v_gname,
$v_devmajor, $v_devminor, $v_prefix, '');
// ----- Calculate the checksum
$v_checksum = 0;
// ..... First part of the header
for ($i=0; $i<148; $i++)
$v_checksum += ord(substr($v_binary_data_first,$i,1));
// ..... Ignore the checksum value and replace it by ' ' (space)
for ($i=148; $i<156; $i++)
$v_checksum += ord(' ');
// ..... Last part of the header
for ($i=156, $j=0; $i<512; $i++, $j++)
$v_checksum += ord(substr($v_binary_data_last,$j,1));
// ----- Write the first 148 bytes of the header in the archive
$this->_writeBlock($v_binary_data_first, 148);
// ----- Write the calculated checksum
$v_checksum = sprintf("%6s ", DecOct($v_checksum));
$v_binary_data = pack("a8", $v_checksum);
$this->_writeBlock($v_binary_data, 8);
// ----- Write the last 356 bytes of the header in the archive
$this->_writeBlock($v_binary_data_last, 356);
return true;
}
// }}}
// {{{ _writeHeaderBlock()
function _writeHeaderBlock($p_filename, $p_size, $p_mtime=0, $p_perms=0,
$p_type='', $p_uid=0, $p_gid=0)
{
$p_filename = $this->_pathReduction($p_filename);
if (strlen($p_filename) > 99) {
if (!$this->_writeLongHeader($p_filename))
return false;
}
if ($p_type == "5") {
$v_size = sprintf("%11s ", DecOct(0));
} else {
$v_size = sprintf("%11s ", DecOct($p_size));
}
$v_uid = sprintf("%6s ", DecOct($p_uid));
$v_gid = sprintf("%6s ", DecOct($p_gid));
$v_perms = sprintf("%6s ", DecOct($p_perms));
$v_mtime = sprintf("%11s", DecOct($p_mtime));
$v_linkname = '';
$v_magic = '';
$v_version = '';
$v_uname = '';
$v_gname = '';
$v_devmajor = '';
$v_devminor = '';
$v_prefix = '';
$v_binary_data_first = pack("a100a8a8a8a12A12",
$p_filename, $v_perms, $v_uid, $v_gid,
$v_size, $v_mtime);
$v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
$p_type, $v_linkname, $v_magic,
$v_version, $v_uname, $v_gname,
$v_devmajor, $v_devminor, $v_prefix, '');
// ----- Calculate the checksum
$v_checksum = 0;
// ..... First part of the header
for ($i=0; $i<148; $i++)
$v_checksum += ord(substr($v_binary_data_first,$i,1));
// ..... Ignore the checksum value and replace it by ' ' (space)
for ($i=148; $i<156; $i++)
$v_checksum += ord(' ');
// ..... Last part of the header
for ($i=156, $j=0; $i<512; $i++, $j++)
$v_checksum += ord(substr($v_binary_data_last,$j,1));
// ----- Write the first 148 bytes of the header in the archive
$this->_writeBlock($v_binary_data_first, 148);
// ----- Write the calculated checksum
$v_checksum = sprintf("%6s ", DecOct($v_checksum));
$v_binary_data = pack("a8", $v_checksum);
$this->_writeBlock($v_binary_data, 8);
// ----- Write the last 356 bytes of the header in the archive
$this->_writeBlock($v_binary_data_last, 356);
return true;
}
// }}}
// {{{ _writeLongHeader()
function _writeLongHeader($p_filename)
{
$v_size = sprintf("%11s ", DecOct(strlen($p_filename)));
$v_typeflag = 'L';
$v_linkname = '';
$v_magic = '';
$v_version = '';
$v_uname = '';
$v_gname = '';
$v_devmajor = '';
$v_devminor = '';
$v_prefix = '';
$v_binary_data_first = pack("a100a8a8a8a12A12",
'././@LongLink', 0, 0, 0, $v_size, 0);
$v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
$v_typeflag, $v_linkname, $v_magic,
$v_version, $v_uname, $v_gname,
$v_devmajor, $v_devminor, $v_prefix, '');
// ----- Calculate the checksum
$v_checksum = 0;
// ..... First part of the header
for ($i=0; $i<148; $i++)
$v_checksum += ord(substr($v_binary_data_first,$i,1));
// ..... Ignore the checksum value and replace it by ' ' (space)
for ($i=148; $i<156; $i++)
$v_checksum += ord(' ');
// ..... Last part of the header
for ($i=156, $j=0; $i<512; $i++, $j++)
$v_checksum += ord(substr($v_binary_data_last,$j,1));
// ----- Write the first 148 bytes of the header in the archive
$this->_writeBlock($v_binary_data_first, 148);
// ----- Write the calculated checksum
$v_checksum = sprintf("%6s ", DecOct($v_checksum));
$v_binary_data = pack("a8", $v_checksum);
$this->_writeBlock($v_binary_data, 8);
// ----- Write the last 356 bytes of the header in the archive
$this->_writeBlock($v_binary_data_last, 356);
// ----- Write the filename as content of the block
$i=0;
while (($v_buffer = substr($p_filename, (($i++)*512), 512)) != '') {
$v_binary_data = pack("a512", "$v_buffer");
$this->_writeBlock($v_binary_data);
}
return true;
}
// }}}
// {{{ _readHeader()
function _readHeader($v_binary_data, &$v_header)
{
if (strlen($v_binary_data)==0) {
$v_header['filename'] = '';
return true;
}
if (strlen($v_binary_data) != 512) {
$v_header['filename'] = '';
$this->_error('Invalid block size : '.strlen($v_binary_data));
return false;
}
if (!is_array($v_header)) {
$v_header = array();
}
// ----- Calculate the checksum
$v_checksum = 0;
// ..... First part of the header
for ($i=0; $i<148; $i++)
$v_checksum+=ord(substr($v_binary_data,$i,1));
// ..... Ignore the checksum value and replace it by ' ' (space)
for ($i=148; $i<156; $i++)
$v_checksum += ord(' ');
// ..... Last part of the header
for ($i=156; $i<512; $i++)
$v_checksum+=ord(substr($v_binary_data,$i,1));
$v_data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/"
."a8checksum/a1typeflag/a100link/a6magic/a2version/"
."a32uname/a32gname/a8devmajor/a8devminor",
$v_binary_data);
// ----- Extract the checksum
$v_header['checksum'] = OctDec(trim($v_data['checksum']));
if ($v_header['checksum'] != $v_checksum) {
$v_header['filename'] = '';
// ----- Look for last block (empty block)
if (($v_checksum == 256) && ($v_header['checksum'] == 0))
return true;
$this->_error('Invalid checksum for file "'.$v_data['filename']
.'" : '.$v_checksum.' calculated, '
.$v_header['checksum'].' expected');
return false;
}
// ----- Extract the properties
$v_header['filename'] = trim($v_data['filename']);
if ($this->_maliciousFilename($v_header['filename'])) {
$this->_error('Malicious .tar detected, file "' . $v_header['filename'] .
'" will not install in desired directory tree');
return false;
}
$v_header['mode'] = OctDec(trim($v_data['mode']));
$v_header['uid'] = OctDec(trim($v_data['uid']));
$v_header['gid'] = OctDec(trim($v_data['gid']));
$v_header['size'] = OctDec(trim($v_data['size']));
$v_header['mtime'] = OctDec(trim($v_data['mtime']));
if (($v_header['typeflag'] = $v_data['typeflag']) == "5") {
$v_header['size'] = 0;
}
$v_header['link'] = trim($v_data['link']);
/* ----- All these fields are removed form the header because
they do not carry interesting info
$v_header[magic] = trim($v_data[magic]);
$v_header[version] = trim($v_data[version]);
$v_header[uname] = trim($v_data[uname]);
$v_header[gname] = trim($v_data[gname]);
$v_header[devmajor] = trim($v_data[devmajor]);
$v_header[devminor] = trim($v_data[devminor]);
*/
return true;
}
// }}}
// {{{ _maliciousFilename()
/**
* Detect and report a malicious file name
*
* @param string $file
* @return bool
* @access private
*/
function _maliciousFilename($file)
{
if (strpos($file, '/../') !== false) {
return true;
}
if (strpos($file, '../') === 0) {
return true;
}
return false;
}
// }}}
// {{{ _readLongHeader()
function _readLongHeader(&$v_header)
{
$v_filename = '';
$n = floor($v_header['size']/512);
for ($i=0; $i<$n; $i++) {
$v_content = $this->_readBlock();
$v_filename .= $v_content;
}
if (($v_header['size'] % 512) != 0) {
$v_content = $this->_readBlock();
$v_filename .= $v_content;
}
// ----- Read the next header
$v_binary_data = $this->_readBlock();
if (!$this->_readHeader($v_binary_data, $v_header))
return false;
$v_filename = trim($v_filename);
$v_header['filename'] = $v_filename;
if ($this->_maliciousFilename($v_filename)) {
$this->_error('Malicious .tar detected, file "' . $v_filename .
'" will not install in desired directory tree');
return false;
}
return true;
}
// }}}
// {{{ _extractInString()
/**
* This method extract from the archive one file identified by $p_filename.
* The return value is a string with the file content, or NULL on error.
* @param string $p_filename The path of the file to extract in a string.
* @return a string with the file content or NULL.
* @access private
*/
function _extractInString($p_filename)
{
$v_result_str = "";
While (strlen($v_binary_data = $this->_readBlock()) != 0)
{
if (!$this->_readHeader($v_binary_data, $v_header))
return NULL;
if ($v_header['filename'] == '')
continue;
// ----- Look for long filename
if ($v_header['typeflag'] == 'L') {
if (!$this->_readLongHeader($v_header))
return NULL;
}
if ($v_header['filename'] == $p_filename) {
if ($v_header['typeflag'] == "5") {
$this->_error('Unable to extract in string a directory '
.'entry {'.$v_header['filename'].'}');
return NULL;
} else {
$n = floor($v_header['size']/512);
for ($i=0; $i<$n; $i++) {
$v_result_str .= $this->_readBlock();
}
if (($v_header['size'] % 512) != 0) {
$v_content = $this->_readBlock();
$v_result_str .= substr($v_content, 0,
($v_header['size'] % 512));
}
return $v_result_str;
}
} else {
$this->_jumpBlock(ceil(($v_header['size']/512)));
}
}
return NULL;
}
// }}}
// {{{ _extractList()
function _extractList($p_path, &$p_list_detail, $p_mode,
$p_file_list, $p_remove_path)
{
$v_result=true;
$v_nb = 0;
$v_extract_all = true;
$v_listing = false;
$p_path = $this->_translateWinPath($p_path, false);
if ($p_path == '' || (substr($p_path, 0, 1) != '/'
&& substr($p_path, 0, 3) != "../" && !strpos($p_path, ':'))) {
$p_path = "./".$p_path;
}
$p_remove_path = $this->_translateWinPath($p_remove_path);
// ----- Look for path to remove format (should end by /)
if (($p_remove_path != '') && (substr($p_remove_path, -1) != '/'))
$p_remove_path .= '/';
$p_remove_path_size = strlen($p_remove_path);
switch ($p_mode) {
case "complete" :
$v_extract_all = TRUE;
$v_listing = FALSE;
break;
case "partial" :
$v_extract_all = FALSE;
$v_listing = FALSE;
break;
case "list" :
$v_extract_all = FALSE;
$v_listing = TRUE;
break;
default :
$this->_error('Invalid extract mode ('.$p_mode.')');
return false;
}
clearstatcache();
while (strlen($v_binary_data = $this->_readBlock()) != 0)
{
$v_extract_file = FALSE;
$v_extraction_stopped = 0;
if (!$this->_readHeader($v_binary_data, $v_header))
return false;
if ($v_header['filename'] == '') {
continue;
}
// ----- Look for long filename
if ($v_header['typeflag'] == 'L') {
if (!$this->_readLongHeader($v_header))
return false;
}
if ((!$v_extract_all) && (is_array($p_file_list))) {
// ----- By default no unzip if the file is not found
$v_extract_file = false;
for ($i=0; $i<sizeof($p_file_list); $i++) {
// ----- Look if it is a directory
if (substr($p_file_list[$i], -1) == '/') {
// ----- Look if the directory is in the filename path
if ((strlen($v_header['filename']) > strlen($p_file_list[$i]))
&& (substr($v_header['filename'], 0, strlen($p_file_list[$i]))
== $p_file_list[$i])) {
$v_extract_file = TRUE;
break;
}
}
// ----- It is a file, so compare the file names
elseif ($p_file_list[$i] == $v_header['filename']) {
$v_extract_file = TRUE;
break;
}
}
} else {
$v_extract_file = TRUE;
}
// ----- Look if this file need to be extracted
if (($v_extract_file) && (!$v_listing))
{
if (($p_remove_path != '')
&& (substr($v_header['filename'], 0, $p_remove_path_size)
== $p_remove_path))
$v_header['filename'] = substr($v_header['filename'],
$p_remove_path_size);
if (($p_path != './') && ($p_path != '/')) {
while (substr($p_path, -1) == '/')
$p_path = substr($p_path, 0, strlen($p_path)-1);
if (substr($v_header['filename'], 0, 1) == '/')
$v_header['filename'] = $p_path.$v_header['filename'];
else
$v_header['filename'] = $p_path.'/'.$v_header['filename'];
}
if (file_exists($v_header['filename'])) {
if ( (@is_dir($v_header['filename']))
&& ($v_header['typeflag'] == '')) {
$this->_error('File '.$v_header['filename']
.' already exists as a directory');
return false;
}
if ( ($this->_isArchive($v_header['filename']))
&& ($v_header['typeflag'] == "5")) {
$this->_error('Directory '.$v_header['filename']
.' already exists as a file');
return false;
}
if (!is_writeable($v_header['filename'])) {
$this->_error('File '.$v_header['filename']
.' already exists and is write protected');
return false;
}
if (filemtime($v_header['filename']) > $v_header['mtime']) {
// To be completed : An error or silent no replace ?
}
}
// ----- Check the directory availability and create it if necessary
elseif (($v_result
= $this->_dirCheck(($v_header['typeflag'] == "5"
?$v_header['filename']
:dirname($v_header['filename'])))) != 1) {
$this->_error('Unable to create path for '.$v_header['filename']);
return false;
}
if ($v_extract_file) {
if ($v_header['typeflag'] == "5") {
if (!@file_exists($v_header['filename'])) {
if (!@mkdir($v_header['filename'], 0777)) {
$this->_error('Unable to create directory {'
.$v_header['filename'].'}');
return false;
}
}
} elseif ($v_header['typeflag'] == "2") {
if (@file_exists($v_header['filename'])) {
@unlink($v_header['filename']);
}
if (!@symlink($v_header['link'], $v_header['filename'])) {
$this->_error('Unable to extract symbolic link {'
.$v_header['filename'].'}');
return false;
}
} else {
if (($v_dest_file = @fopen($v_header['filename'], "wb")) == 0) {
$this->_error('Error while opening {'.$v_header['filename']
.'} in write binary mode');
return false;
} else {
$n = floor($v_header['size']/512);
for ($i=0; $i<$n; $i++) {
$v_content = $this->_readBlock();
fwrite($v_dest_file, $v_content, 512);
}
if (($v_header['size'] % 512) != 0) {
$v_content = $this->_readBlock();
fwrite($v_dest_file, $v_content, ($v_header['size'] % 512));
}
@fclose($v_dest_file);
// ----- Change the file mode, mtime
@touch($v_header['filename'], $v_header['mtime']);
if ($v_header['mode'] & 0111) {
// make file executable, obey umask
$mode = fileperms($v_header['filename']) | (~umask() & 0111);
@chmod($v_header['filename'], $mode);
}
}
// ----- Check the file size
clearstatcache();
if (filesize($v_header['filename']) != $v_header['size']) {
$this->_error('Extracted file '.$v_header['filename']
.' does not have the correct file size \''
.filesize($v_header['filename'])
.'\' ('.$v_header['size']
.' expected). Archive may be corrupted.');
return false;
}
}
} else {
$this->_jumpBlock(ceil(($v_header['size']/512)));
}
} else {
$this->_jumpBlock(ceil(($v_header['size']/512)));
}
/* TBC : Seems to be unused ...
if ($this->_compress)
$v_end_of_file = @gzeof($this->_file);
else
$v_end_of_file = @feof($this->_file);
*/
if ($v_listing || $v_extract_file || $v_extraction_stopped) {
// ----- Log extracted files
if (($v_file_dir = dirname($v_header['filename']))
== $v_header['filename'])
$v_file_dir = '';
if ((substr($v_header['filename'], 0, 1) == '/') && ($v_file_dir == ''))
$v_file_dir = '/';
$p_list_detail[$v_nb++] = $v_header;
if (is_array($p_file_list) && (count($p_list_detail) == count($p_file_list))) {
return true;
}
}
}
return true;
}
// }}}
// {{{ _openAppend()
function _openAppend()
{
if (filesize($this->_tarname) == 0)
return $this->_openWrite();
if ($this->_compress) {
$this->_close();
if (!@rename($this->_tarname, $this->_tarname.".tmp")) {
$this->_error('Error while renaming \''.$this->_tarname
.'\' to temporary file \''.$this->_tarname
.'.tmp\'');
return false;
}
if ($this->_compress_type == 'gz')
$v_temp_tar = @gzopen($this->_tarname.".tmp", "rb");
elseif ($this->_compress_type == 'bz2')
$v_temp_tar = @bzopen($this->_tarname.".tmp", "r");
if ($v_temp_tar == 0) {
$this->_error('Unable to open file \''.$this->_tarname
.'.tmp\' in binary read mode');
@rename($this->_tarname.".tmp", $this->_tarname);
return false;
}
if (!$this->_openWrite()) {
@rename($this->_tarname.".tmp", $this->_tarname);
return false;
}
if ($this->_compress_type == 'gz') {
while (!@gzeof($v_temp_tar)) {
$v_buffer = @gzread($v_temp_tar, 512);
if ($v_buffer == ARCHIVE_TAR_END_BLOCK) {
// do not copy end blocks, we will re-make them
// after appending
continue;
}
$v_binary_data = pack("a512", $v_buffer);
$this->_writeBlock($v_binary_data);
}
@gzclose($v_temp_tar);
}
elseif ($this->_compress_type == 'bz2') {
while (strlen($v_buffer = @bzread($v_temp_tar, 512)) > 0) {
if ($v_buffer == ARCHIVE_TAR_END_BLOCK) {
continue;
}
$v_binary_data = pack("a512", $v_buffer);
$this->_writeBlock($v_binary_data);
}
@bzclose($v_temp_tar);
}
if (!@unlink($this->_tarname.".tmp")) {
$this->_error('Error while deleting temporary file \''
.$this->_tarname.'.tmp\'');
}
} else {
// ----- For not compressed tar, just add files before the last
// one or two 512 bytes block
if (!$this->_openReadWrite())
return false;
clearstatcache();
$v_size = filesize($this->_tarname);
// We might have zero, one or two end blocks.
// The standard is two, but we should try to handle
// other cases.
fseek($this->_file, $v_size - 1024);
if (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) {
fseek($this->_file, $v_size - 1024);
}
elseif (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) {
fseek($this->_file, $v_size - 512);
}
}
return true;
}
// }}}
// {{{ _append()
function _append($p_filelist, $p_add_dir='', $p_remove_dir='')
{
if (!$this->_openAppend())
return false;
if ($this->_addList($p_filelist, $p_add_dir, $p_remove_dir))
$this->_writeFooter();
$this->_close();
return true;
}
// }}}
// {{{ _dirCheck()
/**
* Check if a directory exists and create it (including parent
* dirs) if not.
*
* @param string $p_dir directory to check
*
* @return bool TRUE if the directory exists or was created
*/
function _dirCheck($p_dir)
{
clearstatcache();
if ((@is_dir($p_dir)) || ($p_dir == ''))
return true;
$p_parent_dir = dirname($p_dir);
if (($p_parent_dir != $p_dir) &&
($p_parent_dir != '') &&
(!$this->_dirCheck($p_parent_dir)))
return false;
if (!@mkdir($p_dir, 0777)) {
$this->_error("Unable to create directory '$p_dir'");
return false;
}
return true;
}
// }}}
// {{{ _pathReduction()
/**
* Compress path by changing for example "/dir/foo/../bar" to "/dir/bar",
* rand emove double slashes.
*
* @param string $p_dir path to reduce
*
* @return string reduced path
*
* @access private
*
*/
function _pathReduction($p_dir)
{
$v_result = '';
// ----- Look for not empty path
if ($p_dir != '') {
// ----- Explode path by directory names
$v_list = explode('/', $p_dir);
// ----- Study directories from last to first
for ($i=sizeof($v_list)-1; $i>=0; $i--) {
// ----- Look for current path
if ($v_list[$i] == ".") {
// ----- Ignore this directory
// Should be the first $i=0, but no check is done
}
else if ($v_list[$i] == "..") {
// ----- Ignore it and ignore the $i-1
$i--;
}
else if ( ($v_list[$i] == '')
&& ($i!=(sizeof($v_list)-1))
&& ($i!=0)) {
// ----- Ignore only the double '//' in path,
// but not the first and last /
} else {
$v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?'/'
.$v_result:'');
}
}
}
$v_result = strtr($v_result, '\\', '/');
return $v_result;
}
// }}}
// {{{ _translateWinPath()
function _translateWinPath($p_path, $p_remove_disk_letter=true)
{
if (defined('OS_WINDOWS') && OS_WINDOWS) {
// ----- Look for potential disk letter
if ( ($p_remove_disk_letter)
&& (($v_position = strpos($p_path, ':')) != false)) {
$p_path = substr($p_path, $v_position+1);
}
// ----- Change potential windows directory separator
if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
$p_path = strtr($p_path, '\\', '/');
}
}
return $p_path;
}
// }}}
}
?>
<?php
/**
* Fast, light and safe Cache Class
*
* Cache_Lite is a fast, light and safe cache system. It's optimized
* for file containers. It is fast and safe (because it uses file
* locking and/or anti-corruption tests).
*
* There are some examples in the 'docs/examples' file
* Technical choices are described in the 'docs/technical' file
*
* Memory Caching is from an original idea of
* Mike BENOIT <ipso@snappymail.ca>
*
* Nota : A chinese documentation (thanks to RainX <china_1982@163.com>) is
* available at :
* http://rainx.phpmore.com/manual/cache_lite.html
*
* @package Cache_Lite
* @category Caching
* @version $Id: Lite.php,v 1.54 2009/07/07 05:34:37 tacker Exp $
* @author Fabien MARTY <fab@php.net>
*/
define('CACHE_LITE_ERROR_RETURN', 1);
define('CACHE_LITE_ERROR_DIE', 8);
class Cache_Lite
{
// --- Private properties ---
/**
* Directory where to put the cache files
* (make sure to add a trailing slash)
*
* @var string $_cacheDir
*/
var $_cacheDir = '/tmp/';
/**
* Enable / disable caching
*
* (can be very usefull for the debug of cached scripts)
*
* @var boolean $_caching
*/
var $_caching = true;
/**
* Cache lifetime (in seconds)
*
* If null, the cache is valid forever.
*
* @var int $_lifeTime
*/
var $_lifeTime = 3600;
/**
* Enable / disable fileLocking
*
* (can avoid cache corruption under bad circumstances)
*
* @var boolean $_fileLocking
*/
var $_fileLocking = true;
/**
* Timestamp of the last valid cache
*
* @var int $_refreshTime
*/
var $_refreshTime;
/**
* File name (with path)
*
* @var string $_file
*/
var $_file;
/**
* File name (without path)
*
* @var string $_fileName
*/
var $_fileName;
/**
* Enable / disable write control (the cache is read just after writing to detect corrupt entries)
*
* Enable write control will lightly slow the cache writing but not the cache reading
* Write control can detect some corrupt cache files but maybe it's not a perfect control
*
* @var boolean $_writeControl
*/
var $_writeControl = true;
/**
* Enable / disable read control
*
* If enabled, a control key is embeded in cache file and this key is compared with the one
* calculated after the reading.
*
* @var boolean $_writeControl
*/
var $_readControl = true;
/**
* Type of read control (only if read control is enabled)
*
* Available values are :
* 'md5' for a md5 hash control (best but slowest)
* 'crc32' for a crc32 hash control (lightly less safe but faster, better choice)
* 'strlen' for a length only test (fastest)
*
* @var boolean $_readControlType
*/
var $_readControlType = 'crc32';
/**
* Pear error mode (when raiseError is called)
*
* (see PEAR doc)
*
* @see setToDebug()
* @var int $_pearErrorMode
*/
var $_pearErrorMode = CACHE_LITE_ERROR_RETURN;
/**
* Current cache id
*
* @var string $_id
*/
var $_id;
/**
* Current cache group
*
* @var string $_group
*/
var $_group;
/**
* Enable / Disable "Memory Caching"
*
* NB : There is no lifetime for memory caching !
*
* @var boolean $_memoryCaching
*/
var $_memoryCaching = false;
/**
* Enable / Disable "Only Memory Caching"
* (be carefull, memory caching is "beta quality")
*
* @var boolean $_onlyMemoryCaching
*/
var $_onlyMemoryCaching = false;
/**
* Memory caching array
*
* @var array $_memoryCachingArray
*/
var $_memoryCachingArray = array();
/**
* Memory caching counter
*
* @var int $memoryCachingCounter
*/
var $_memoryCachingCounter = 0;
/**
* Memory caching limit
*
* @var int $memoryCachingLimit
*/
var $_memoryCachingLimit = 1000;
/**
* File Name protection
*
* if set to true, you can use any cache id or group name
* if set to false, it can be faster but cache ids and group names
* will be used directly in cache file names so be carefull with
* special characters...
*
* @var boolean $fileNameProtection
*/
var $_fileNameProtection = true;
/**
* Enable / disable automatic serialization
*
* it can be used to save directly datas which aren't strings
* (but it's slower)
*
* @var boolean $_serialize
*/
var $_automaticSerialization = false;
/**
* Disable / Tune the automatic cleaning process
*
* The automatic cleaning process destroy too old (for the given life time)
* cache files when a new cache file is written.
* 0 => no automatic cache cleaning
* 1 => systematic cache cleaning
* x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
*
* @var int $_automaticCleaning
*/
var $_automaticCleaningFactor = 0;
/**
* Nested directory level
*
* Set the hashed directory structure level. 0 means "no hashed directory
* structure", 1 means "one level of directory", 2 means "two levels"...
* This option can speed up Cache_Lite only when you have many thousands of
* cache file. Only specific benchs can help you to choose the perfect value
* for you. Maybe, 1 or 2 is a good start.
*
* @var int $_hashedDirectoryLevel
*/
var $_hashedDirectoryLevel = 0;
/**
* Umask for hashed directory structure
*
* @var int $_hashedDirectoryUmask
*/
var $_hashedDirectoryUmask = 0700;
/**
* API break for error handling in CACHE_LITE_ERROR_RETURN mode
*
* In CACHE_LITE_ERROR_RETURN mode, error handling was not good because
* for example save() method always returned a boolean (a PEAR_Error object
* would be better in CACHE_LITE_ERROR_RETURN mode). To correct this without
* breaking the API, this option (false by default) can change this handling.
*
* @var boolean
*/
var $_errorHandlingAPIBreak = false;
// --- Public methods ---
/**
* Constructor
*
* $options is an assoc. Available options are :
* $options = array(
* 'cacheDir' => directory where to put the cache files (string),
* 'caching' => enable / disable caching (boolean),
* 'lifeTime' => cache lifetime in seconds (int),
* 'fileLocking' => enable / disable fileLocking (boolean),
* 'writeControl' => enable / disable write control (boolean),
* 'readControl' => enable / disable read control (boolean),
* 'readControlType' => type of read control 'crc32', 'md5', 'strlen' (string),
* 'pearErrorMode' => pear error mode (when raiseError is called) (cf PEAR doc) (int),
* 'memoryCaching' => enable / disable memory caching (boolean),
* 'onlyMemoryCaching' => enable / disable only memory caching (boolean),
* 'memoryCachingLimit' => max nbr of records to store into memory caching (int),
* 'fileNameProtection' => enable / disable automatic file name protection (boolean),
* 'automaticSerialization' => enable / disable automatic serialization (boolean),
* 'automaticCleaningFactor' => distable / tune automatic cleaning process (int),
* 'hashedDirectoryLevel' => level of the hashed directory system (int),
* 'hashedDirectoryUmask' => umask for hashed directory structure (int),
* 'errorHandlingAPIBreak' => API break for better error handling ? (boolean)
* );
*
* @param array $options options
* @access public
*/
function Cache_Lite($options = array(NULL))
{
foreach($options as $key => $value) {
$this->setOption($key, $value);
}
}
/**
* Generic way to set a Cache_Lite option
*
* see Cache_Lite constructor for available options
*
* @var string $name name of the option
* @var mixed $value value of the option
* @access public
*/
function setOption($name, $value)
{
$availableOptions = array('errorHandlingAPIBreak', 'hashedDirectoryUmask', 'hashedDirectoryLevel', 'automaticCleaningFactor', 'automaticSerialization', 'fileNameProtection', 'memoryCaching', 'onlyMemoryCaching', 'memoryCachingLimit', 'cacheDir', 'caching', 'lifeTime', 'fileLocking', 'writeControl', 'readControl', 'readControlType', 'pearErrorMode');
if (in_array($name, $availableOptions)) {
$property = '_'.$name;
$this->$property = $value;
}
}
/**
* Test if a cache is available and (if yes) return it
*
* @param string $id cache id
* @param string $group name of the cache group
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string data of the cache (else : false)
* @access public
*/
function get($id, $group = 'default', $doNotTestCacheValidity = false)
{
$this->_id = $id;
$this->_group = $group;
$data = false;
if ($this->_caching) {
$this->_setRefreshTime();
$this->_setFileName($id, $group);
clearstatcache();
if ($this->_memoryCaching) {
if (isset($this->_memoryCachingArray[$this->_file])) {
if ($this->_automaticSerialization) {
return unserialize($this->_memoryCachingArray[$this->_file]);
}
return $this->_memoryCachingArray[$this->_file];
}
if ($this->_onlyMemoryCaching) {
return false;
}
}
if (($doNotTestCacheValidity) || (is_null($this->_refreshTime))) {
if (file_exists($this->_file)) {
$data = $this->_read();
}
} else {
if ((file_exists($this->_file)) && (@filemtime($this->_file) > $this->_refreshTime)) {
$data = $this->_read();
}
}
if (($data) and ($this->_memoryCaching)) {
$this->_memoryCacheAdd($data);
}
if (($this->_automaticSerialization) and (is_string($data))) {
$data = unserialize($data);
}
return $data;
}
return false;
}
/**
* Save some data in a cache file
*
* @param string $data data to put in cache (can be another type than strings if automaticSerialization is on)
* @param string $id cache id
* @param string $group name of the cache group
* @return boolean true if no problem (else : false or a PEAR_Error object)
* @access public
*/
function save($data, $id = NULL, $group = 'default')
{
if ($this->_caching) {
if ($this->_automaticSerialization) {
$data = serialize($data);
}
if (isset($id)) {
$this->_setFileName($id, $group);
}
if ($this->_memoryCaching) {
$this->_memoryCacheAdd($data);
if ($this->_onlyMemoryCaching) {
return true;
}
}
if ($this->_automaticCleaningFactor>0 && ($this->_automaticCleaningFactor==1 || mt_rand(1, $this->_automaticCleaningFactor)==1)) {
$this->clean(false, 'old');
}
if ($this->_writeControl) {
$res = $this->_writeAndControl($data);
if (is_bool($res)) {
if ($res) {
return true;
}
// if $res if false, we need to invalidate the cache
@touch($this->_file, time() - 2*abs($this->_lifeTime));
return false;
}
} else {
$res = $this->_write($data);
}
if (is_object($res)) {
// $res is a PEAR_Error object
if (!($this->_errorHandlingAPIBreak)) {
return false; // we return false (old API)
}
}
return $res;
}
return false;
}
/**
* Remove a cache file
*
* @param string $id cache id
* @param string $group name of the cache group
* @param boolean $checkbeforeunlink check if file exists before removing it
* @return boolean true if no problem
* @access public
*/
function remove($id, $group = 'default', $checkbeforeunlink = false)
{
$this->_setFileName($id, $group);
if ($this->_memoryCaching) {
if (isset($this->_memoryCachingArray[$this->_file])) {
unset($this->_memoryCachingArray[$this->_file]);
$this->_memoryCachingCounter = $this->_memoryCachingCounter - 1;
}
if ($this->_onlyMemoryCaching) {
return true;
}
}
if ( $checkbeforeunlink ) {
if (!file_exists($this->_file)) return true;
}
return $this->_unlink($this->_file);
}
/**
* Clean the cache
*
* if no group is specified all cache files will be destroyed
* else only cache files of the specified group will be destroyed
*
* @param string $group name of the cache group
* @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
* 'callback_myFunction'
* @return boolean true if no problem
* @access public
*/
function clean($group = false, $mode = 'ingroup')
{
return $this->_cleanDir($this->_cacheDir, $group, $mode);
}
/**
* Set to debug mode
*
* When an error is found, the script will stop and the message will be displayed
* (in debug mode only).
*
* @access public
*/
function setToDebug()
{
$this->setOption('pearErrorMode', CACHE_LITE_ERROR_DIE);
}
/**
* Set a new life time
*
* @param int $newLifeTime new life time (in seconds)
* @access public
*/
function setLifeTime($newLifeTime)
{
$this->_lifeTime = $newLifeTime;
$this->_setRefreshTime();
}
/**
* Save the state of the caching memory array into a cache file cache
*
* @param string $id cache id
* @param string $group name of the cache group
* @access public
*/
function saveMemoryCachingState($id, $group = 'default')
{
if ($this->_caching) {
$array = array(
'counter' => $this->_memoryCachingCounter,
'array' => $this->_memoryCachingArray
);
$data = serialize($array);
$this->save($data, $id, $group);
}
}
/**
* Load the state of the caching memory array from a given cache file cache
*
* @param string $id cache id
* @param string $group name of the cache group
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @access public
*/
function getMemoryCachingState($id, $group = 'default', $doNotTestCacheValidity = false)
{
if ($this->_caching) {
if ($data = $this->get($id, $group, $doNotTestCacheValidity)) {
$array = unserialize($data);
$this->_memoryCachingCounter = $array['counter'];
$this->_memoryCachingArray = $array['array'];
}
}
}
/**
* Return the cache last modification time
*
* BE CAREFUL : THIS METHOD IS FOR HACKING ONLY !
*
* @return int last modification time
*/
function lastModified()
{
return @filemtime($this->_file);
}
/**
* Trigger a PEAR error
*
* To improve performances, the PEAR.php file is included dynamically.
* The file is so included only when an error is triggered. So, in most
* cases, the file isn't included and perfs are much better.
*
* @param string $msg error message
* @param int $code error code
* @access public
*/
function raiseError($msg, $code)
{
include_once('PEAR.php');
return PEAR::raiseError($msg, $code, $this->_pearErrorMode);
}
/**
* Extend the life of a valid cache file
*
* see http://pear.php.net/bugs/bug.php?id=6681
*
* @access public
*/
function extendLife()
{
@touch($this->_file);
}
// --- Private methods ---
/**
* Compute & set the refresh time
*
* @access private
*/
function _setRefreshTime()
{
if (is_null($this->_lifeTime)) {
$this->_refreshTime = null;
} else {
$this->_refreshTime = time() - $this->_lifeTime;
}
}
/**
* Remove a file
*
* @param string $file complete file path and name
* @return boolean true if no problem
* @access private
*/
function _unlink($file)
{
if (!@unlink($file)) {
return $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
}
return true;
}
/**
* Recursive function for cleaning cache file in the given directory
*
* @param string $dir directory complete path (with a trailing slash)
* @param string $group name of the cache group
* @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
'callback_myFunction'
* @return boolean true if no problem
* @access private
*/
function _cleanDir($dir, $group = false, $mode = 'ingroup')
{
if ($this->_fileNameProtection) {
$motif = ($group) ? 'cache_'.md5($group).'_' : 'cache_';
} else {
$motif = ($group) ? 'cache_'.$group.'_' : 'cache_';
}
if ($this->_memoryCaching) {
foreach($this->_memoryCachingArray as $key => $v) {
if (strpos($key, $motif) !== false) {
unset($this->_memoryCachingArray[$key]);
$this->_memoryCachingCounter = $this->_memoryCachingCounter - 1;
}
}
if ($this->_onlyMemoryCaching) {
return true;
}
}
if (!($dh = opendir($dir))) {
return $this->raiseError('Cache_Lite : Unable to open cache directory !', -4);
}
$result = true;
while ($file = readdir($dh)) {
if (($file != '.') && ($file != '..')) {
if (substr($file, 0, 6)=='cache_') {
$file2 = $dir . $file;
if (is_file($file2)) {
switch (substr($mode, 0, 9)) {
case 'old':
// files older than lifeTime get deleted from cache
if (!is_null($this->_lifeTime)) {
if ((time() - @filemtime($file2)) > $this->_lifeTime) {
$result = ($result and ($this->_unlink($file2)));
}
}
break;
case 'notingrou':
if (strpos($file2, $motif) === false) {
$result = ($result and ($this->_unlink($file2)));
}
break;
case 'callback_':
$func = substr($mode, 9, strlen($mode) - 9);
if ($func($file2, $group)) {
$result = ($result and ($this->_unlink($file2)));
}
break;
case 'ingroup':
default:
if (strpos($file2, $motif) !== false) {
$result = ($result and ($this->_unlink($file2)));
}
break;
}
}
if ((is_dir($file2)) and ($this->_hashedDirectoryLevel>0)) {
$result = ($result and ($this->_cleanDir($file2 . '/', $group, $mode)));
}
}
}
}
return $result;
}
/**
* Add some date in the memory caching array
*
* @param string $data data to cache
* @access private
*/
function _memoryCacheAdd($data)
{
$this->_memoryCachingArray[$this->_file] = $data;
if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {
list($key, ) = each($this->_memoryCachingArray);
unset($this->_memoryCachingArray[$key]);
} else {
$this->_memoryCachingCounter = $this->_memoryCachingCounter + 1;
}
}
/**
* Make a file name (with path)
*
* @param string $id cache id
* @param string $group name of the group
* @access private
*/
function _setFileName($id, $group)
{
if ($this->_fileNameProtection) {
$suffix = 'cache_'.md5($group).'_'.md5($id);
} else {
$suffix = 'cache_'.$group.'_'.$id;
}
$root = $this->_cacheDir;
if ($this->_hashedDirectoryLevel>0) {
$hash = md5($suffix);
for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
$root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
}
}
$this->_fileName = $suffix;
$this->_file = $root.$suffix;
}
/**
* Read the cache file and return the content
*
* @return string content of the cache file (else : false or a PEAR_Error object)
* @access private
*/
function _read()
{
$fp = @fopen($this->_file, "rb");
if ($this->_fileLocking) @flock($fp, LOCK_SH);
if ($fp) {
clearstatcache();
$length = @filesize($this->_file);
$mqr = get_magic_quotes_runtime();
if ($mqr) {
set_magic_quotes_runtime(0);
}
if ($this->_readControl) {
$hashControl = @fread($fp, 32);
$length = $length - 32;
}
if ($length) {
$data = @fread($fp, $length);
} else {
$data = '';
}
if ($mqr) {
set_magic_quotes_runtime($mqr);
}
if ($this->_fileLocking) @flock($fp, LOCK_UN);
@fclose($fp);
if ($this->_readControl) {
$hashData = $this->_hash($data, $this->_readControlType);
if ($hashData != $hashControl) {
if (!(is_null($this->_lifeTime))) {
@touch($this->_file, time() - 2*abs($this->_lifeTime));
} else {
@unlink($this->_file);
}
return false;
}
}
return $data;
}
return $this->raiseError('Cache_Lite : Unable to read cache !', -2);
}
/**
* Write the given data in the cache file
*
* @param string $data data to put in cache
* @return boolean true if ok (a PEAR_Error object else)
* @access private
*/
function _write($data)
{
if ($this->_hashedDirectoryLevel > 0) {
$hash = md5($this->_fileName);
$root = $this->_cacheDir;
for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
$root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
if (!(@is_dir($root))) {
@mkdir($root, $this->_hashedDirectoryUmask);
}
}
}
$fp = @fopen($this->_file, "wb");
if ($fp) {
if ($this->_fileLocking) @flock($fp, LOCK_EX);
if ($this->_readControl) {
@fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
}
$mqr = get_magic_quotes_runtime();
if ($mqr) {
set_magic_quotes_runtime(0);
}
@fwrite($fp, $data);
if ($mqr) {
set_magic_quotes_runtime($mqr);
}
if ($this->_fileLocking) @flock($fp, LOCK_UN);
@fclose($fp);
return true;
}
return $this->raiseError('Cache_Lite : Unable to write cache file : '.$this->_file, -1);
}
/**
* Write the given data in the cache file and control it just after to avoir corrupted cache entries
*
* @param string $data data to put in cache
* @return boolean true if the test is ok (else : false or a PEAR_Error object)
* @access private
*/
function _writeAndControl($data)
{
$result = $this->_write($data);
if (is_object($result)) {
return $result; # We return the PEAR_Error object
}
$dataRead = $this->_read();
if (is_object($dataRead)) {
return $dataRead; # We return the PEAR_Error object
}
if ((is_bool($dataRead)) && (!$dataRead)) {
return false;
}
return ($dataRead==$data);
}
/**
* Make a control key with the string containing datas
*
* @param string $data data
* @param string $controlType type of control 'md5', 'crc32' or 'strlen'
* @return string control key
* @access private
*/
function _hash($data, $controlType)
{
switch ($controlType) {
case 'md5':
return md5($data);
case 'crc32':
return sprintf('% 32d', crc32($data));
case 'strlen':
return sprintf('% 32d', strlen($data));
default:
return $this->raiseError('Unknown controlType ! (available values are only \'md5\', \'crc32\', \'strlen\')', -5);
}
}
}
?>
<?php
/**
* This class extends Cache_Lite and offers a cache system driven by a master file
*
* With this class, cache validity is only dependent of a given file. Cache files
* are valid only if they are older than the master file. It's a perfect way for
* caching templates results (if the template file is newer than the cache, cache
* must be rebuild...) or for config classes...
* There are some examples in the 'docs/examples' file
* Technical choices are described in the 'docs/technical' file
*
* @package Cache_Lite
* @version $Id: File.php,v 1.4 2009/03/07 12:55:39 tacker Exp $
* @author Fabien MARTY <fab@php.net>
*/
require_once('Cache/Lite.php');
class Cache_Lite_File extends Cache_Lite
{
// --- Private properties ---
/**
* Complete path of the file used for controlling the cache lifetime
*
* @var string $_masterFile
*/
var $_masterFile = '';
/**
* Masterfile mtime
*
* @var int $_masterFile_mtime
*/
var $_masterFile_mtime = 0;
// --- Public methods ----
/**
* Constructor
*
* $options is an assoc. To have a look at availables options,
* see the constructor of the Cache_Lite class in 'Cache_Lite.php'
*
* Comparing to Cache_Lite constructor, there is another option :
* $options = array(
* (...) see Cache_Lite constructor
* 'masterFile' => complete path of the file used for controlling the cache lifetime(string)
* );
*
* @param array $options options
* @access public
*/
function Cache_Lite_File($options = array(NULL))
{
$options['lifetime'] = 0;
$this->Cache_Lite($options);
if (isset($options['masterFile'])) {
$this->_masterFile = $options['masterFile'];
} else {
return $this->raiseError('Cache_Lite_File : masterFile option must be set !');
}
if (!($this->_masterFile_mtime = @filemtime($this->_masterFile))) {
return $this->raiseError('Cache_Lite_File : Unable to read masterFile : '.$this->_masterFile, -3);
}
}
/**
* Test if a cache is available and (if yes) return it
*
* @param string $id cache id
* @param string $group name of the cache group
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string data of the cache (else : false)
* @access public
*/
function get($id, $group = 'default', $doNotTestCacheValidity = false)
{
if ($data = parent::get($id, $group, true)) {
if ($filemtime = $this->lastModified()) {
if ($filemtime > $this->_masterFile_mtime) {
return $data;
}
}
}
return false;
}
}
?>
<?php
/**
* This class extends Cache_Lite and can be used to cache the result and output of functions/methods
*
* This class is completly inspired from Sebastian Bergmann's
* PEAR/Cache_Function class. This is only an adaptation to
* Cache_Lite
*
* There are some examples in the 'docs/examples' file
* Technical choices are described in the 'docs/technical' file
*
* @package Cache_Lite
* @version $Id: Function.php,v 1.11 2006/12/14 12:59:43 cweiske Exp $
* @author Sebastian BERGMANN <sb@sebastian-bergmann.de>
* @author Fabien MARTY <fab@php.net>
*/
require_once('Cache/Lite.php');
class Cache_Lite_Function extends Cache_Lite
{
// --- Private properties ---
/**
* Default cache group for function caching
*
* @var string $_defaultGroup
*/
var $_defaultGroup = 'Cache_Lite_Function';
/**
* Don't cache the method call when its output contains the string "NOCACHE"
*
* if set to true, the output of the method will never be displayed (because the output is used
* to control the cache)
*
* @var boolean $_dontCacheWhenTheOutputContainsNOCACHE
*/
var $_dontCacheWhenTheOutputContainsNOCACHE = false;
/**
* Don't cache the method call when its result is false
*
* @var boolean $_dontCacheWhenTheResultIsFalse
*/
var $_dontCacheWhenTheResultIsFalse = false;
/**
* Don't cache the method call when its result is null
*
* @var boolean $_dontCacheWhenTheResultIsNull
*/
var $_dontCacheWhenTheResultIsNull = false;
/**
* Debug the Cache_Lite_Function caching process
*
* @var boolean $_debugCacheLiteFunction
*/
var $_debugCacheLiteFunction = false;
// --- Public methods ----
/**
* Constructor
*
* $options is an assoc. To have a look at availables options,
* see the constructor of the Cache_Lite class in 'Cache_Lite.php'
*
* Comparing to Cache_Lite constructor, there is another option :
* $options = array(
* (...) see Cache_Lite constructor
* 'debugCacheLiteFunction' => (bool) debug the caching process,
* 'defaultGroup' => default cache group for function caching (string),
* 'dontCacheWhenTheOutputContainsNOCACHE' => (bool) don't cache when the function output contains "NOCACHE",
* 'dontCacheWhenTheResultIsFalse' => (bool) don't cache when the function result is false,
* 'dontCacheWhenTheResultIsNull' => (bool don't cache when the function result is null
* );
*
* @param array $options options
* @access public
*/
function Cache_Lite_Function($options = array(NULL))
{
$availableOptions = array('debugCacheLiteFunction', 'defaultGroup', 'dontCacheWhenTheOutputContainsNOCACHE', 'dontCacheWhenTheResultIsFalse', 'dontCacheWhenTheResultIsNull');
while (list($name, $value) = each($options)) {
if (in_array($name, $availableOptions)) {
$property = '_'.$name;
$this->$property = $value;
}
}
reset($options);
$this->Cache_Lite($options);
}
/**
* Calls a cacheable function or method (or not if there is already a cache for it)
*
* Arguments of this method are read with func_get_args. So it doesn't appear
* in the function definition. Synopsis :
* call('functionName', $arg1, $arg2, ...)
* (arg1, arg2... are arguments of 'functionName')
*
* @return mixed result of the function/method
* @access public
*/
function call()
{
$arguments = func_get_args();
$id = $this->_makeId($arguments);
$data = $this->get($id, $this->_defaultGroup);
if ($data !== false) {
if ($this->_debugCacheLiteFunction) {
echo "Cache hit !\n";
}
$array = unserialize($data);
$output = $array['output'];
$result = $array['result'];
} else {
if ($this->_debugCacheLiteFunction) {
echo "Cache missed !\n";
}
ob_start();
ob_implicit_flush(false);
$target = array_shift($arguments);
if (is_array($target)) {
// in this case, $target is for example array($obj, 'method')
$object = $target[0];
$method = $target[1];
$result = call_user_func_array(array(&$object, $method), $arguments);
} else {
if (strstr($target, '::')) { // classname::staticMethod
list($class, $method) = explode('::', $target);
$result = call_user_func_array(array($class, $method), $arguments);
} else if (strstr($target, '->')) { // object->method
// use a stupid name ($objet_123456789 because) of problems where the object
// name is the same as this var name
list($object_123456789, $method) = explode('->', $target);
global $$object_123456789;
$result = call_user_func_array(array($$object_123456789, $method), $arguments);
} else { // function
$result = call_user_func_array($target, $arguments);
}
}
$output = ob_get_contents();
ob_end_clean();
if ($this->_dontCacheWhenTheResultIsFalse) {
if ((is_bool($result)) && (!($result))) {
echo($output);
return $result;
}
}
if ($this->_dontCacheWhenTheResultIsNull) {
if (is_null($result)) {
echo($output);
return $result;
}
}
if ($this->_dontCacheWhenTheOutputContainsNOCACHE) {
if (strpos($output, 'NOCACHE') > -1) {
return $result;
}
}
$array['output'] = $output;
$array['result'] = $result;
$this->save(serialize($array), $id, $this->_defaultGroup);
}
echo($output);
return $result;
}
/**
* Drop a cache file
*
* Arguments of this method are read with func_get_args. So it doesn't appear
* in the function definition. Synopsis :
* remove('functionName', $arg1, $arg2, ...)
* (arg1, arg2... are arguments of 'functionName')
*
* @return boolean true if no problem
* @access public
*/
function drop()
{
$id = $this->_makeId(func_get_args());
return $this->remove($id, $this->_defaultGroup);
}
/**
* Make an id for the cache
*
* @var array result of func_get_args for the call() or the remove() method
* @return string id
* @access private
*/
function _makeId($arguments)
{
$id = serialize($arguments); // Generate a cache id
if (!$this->_fileNameProtection) {
$id = md5($id);
// if fileNameProtection is set to false, then the id has to be hashed
// because it's a very bad file name in most cases
}
return $id;
}
}
?>
<?php
/**
* This class extends Cache_Lite and uses output buffering to get the data to cache.
*
* There are some examples in the 'docs/examples' file
* Technical choices are described in the 'docs/technical' file
*
* @package Cache_Lite
* @version $Id: Output.php,v 1.4 2006/01/29 00:22:07 fab Exp $
* @author Fabien MARTY <fab@php.net>
*/
require_once('Cache/Lite.php');
class Cache_Lite_Output extends Cache_Lite
{
// --- Public methods ---
/**
* Constructor
*
* $options is an assoc. To have a look at availables options,
* see the constructor of the Cache_Lite class in 'Cache_Lite.php'
*
* @param array $options options
* @access public
*/
function Cache_Lite_Output($options)
{
$this->Cache_Lite($options);
}
/**
* Start the cache
*
* @param string $id cache id
* @param string $group name of the cache group
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return boolean true if the cache is hit (false else)
* @access public
*/
function start($id, $group = 'default', $doNotTestCacheValidity = false)
{
$data = $this->get($id, $group, $doNotTestCacheValidity);
if ($data !== false) {
echo($data);
return true;
}
ob_start();
ob_implicit_flush(false);
return false;
}
/**
* Stop the cache
*
* @access public
*/
function end()
{
$data = ob_get_contents();
ob_end_clean();
$this->save($data, $this->_id, $this->_group);
echo($data);
}
}
?>
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP Version 5 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at the following url: |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Andrei Zmievski <andrei@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: Getopt.php,v 1.4 2007/06/12 14:58:56 cellog Exp $
require_once 'PEAR.php';
/**
* Command-line options parsing class.
*
* @author Andrei Zmievski <andrei@php.net>
*
*/
class Console_Getopt {
/**
* Parses the command-line options.
*
* The first parameter to this function should be the list of command-line
* arguments without the leading reference to the running program.
*
* The second parameter is a string of allowed short options. Each of the
* option letters can be followed by a colon ':' to specify that the option
* requires an argument, or a double colon '::' to specify that the option
* takes an optional argument.
*
* The third argument is an optional array of allowed long options. The
* leading '--' should not be included in the option name. Options that
* require an argument should be followed by '=', and options that take an
* option argument should be followed by '=='.
*
* The return value is an array of two elements: the list of parsed
* options and the list of non-option command-line arguments. Each entry in
* the list of parsed options is a pair of elements - the first one
* specifies the option, and the second one specifies the option argument,
* if there was one.
*
* Long and short options can be mixed.
*
* Most of the semantics of this function are based on GNU getopt_long().
*
* @param array $args an array of command-line arguments
* @param string $short_options specifies the list of allowed short options
* @param array $long_options specifies the list of allowed long options
*
* @return array two-element array containing the list of parsed options and
* the non-option arguments
*
* @access public
*
*/
function getopt2($args, $short_options, $long_options = null)
{
return Console_Getopt::doGetopt(2, $args, $short_options, $long_options);
}
/**
* This function expects $args to start with the script name (POSIX-style).
* Preserved for backwards compatibility.
* @see getopt2()
*/
function getopt($args, $short_options, $long_options = null)
{
return Console_Getopt::doGetopt(1, $args, $short_options, $long_options);
}
/**
* The actual implementation of the argument parsing code.
*/
function doGetopt($version, $args, $short_options, $long_options = null)
{
// in case you pass directly readPHPArgv() as the first arg
if (PEAR::isError($args)) {
return $args;
}
if (empty($args)) {
return array(array(), array());
}
$opts = array();
$non_opts = array();
settype($args, 'array');
if ($long_options) {
sort($long_options);
}
/*
* Preserve backwards compatibility with callers that relied on
* erroneous POSIX fix.
*/
if ($version < 2) {
if (isset($args[0]{0}) && $args[0]{0} != '-') {
array_shift($args);
}
}
reset($args);
while (list($i, $arg) = each($args)) {
/* The special element '--' means explicit end of
options. Treat the rest of the arguments as non-options
and end the loop. */
if ($arg == '--') {
$non_opts = array_merge($non_opts, array_slice($args, $i + 1));
break;
}
if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) {
$non_opts = array_merge($non_opts, array_slice($args, $i));
break;
} elseif (strlen($arg) > 1 && $arg{1} == '-') {
$error = Console_Getopt::_parseLongOption(substr($arg, 2), $long_options, $opts, $args);
if (PEAR::isError($error))
return $error;
} elseif ($arg == '-') {
// - is stdin
$non_opts = array_merge($non_opts, array_slice($args, $i));
break;
} else {
$error = Console_Getopt::_parseShortOption(substr($arg, 1), $short_options, $opts, $args);
if (PEAR::isError($error))
return $error;
}
}
return array($opts, $non_opts);
}
/**
* @access private
*
*/
function _parseShortOption($arg, $short_options, &$opts, &$args)
{
for ($i = 0; $i < strlen($arg); $i++) {
$opt = $arg{$i};
$opt_arg = null;
/* Try to find the short option in the specifier string. */
if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':')
{
return PEAR::raiseError("Console_Getopt: unrecognized option -- $opt");
}
if (strlen($spec) > 1 && $spec{1} == ':') {
if (strlen($spec) > 2 && $spec{2} == ':') {
if ($i + 1 < strlen($arg)) {
/* Option takes an optional argument. Use the remainder of
the arg string if there is anything left. */
$opts[] = array($opt, substr($arg, $i + 1));
break;
}
} else {
/* Option requires an argument. Use the remainder of the arg
string if there is anything left. */
if ($i + 1 < strlen($arg)) {
$opts[] = array($opt, substr($arg, $i + 1));
break;
} else if (list(, $opt_arg) = each($args)) {
/* Else use the next argument. */;
if (Console_Getopt::_isShortOpt($opt_arg) || Console_Getopt::_isLongOpt($opt_arg)) {
return PEAR::raiseError("Console_Getopt: option requires an argument -- $opt");
}
} else {
return PEAR::raiseError("Console_Getopt: option requires an argument -- $opt");
}
}
}
$opts[] = array($opt, $opt_arg);
}
}
/**
* @access private
*
*/
function _isShortOpt($arg)
{
return strlen($arg) == 2 && $arg[0] == '-' && preg_match('/[a-zA-Z]/', $arg[1]);
}
/**
* @access private
*
*/
function _isLongOpt($arg)
{
return strlen($arg) > 2 && $arg[0] == '-' && $arg[1] == '-' &&
preg_match('/[a-zA-Z]+$/', substr($arg, 2));
}
/**
* @access private
*
*/
function _parseLongOption($arg, $long_options, &$opts, &$args)
{
@list($opt, $opt_arg) = explode('=', $arg, 2);
$opt_len = strlen($opt);
for ($i = 0; $i < count($long_options); $i++) {
$long_opt = $long_options[$i];
$opt_start = substr($long_opt, 0, $opt_len);
$long_opt_name = str_replace('=', '', $long_opt);
/* Option doesn't match. Go on to the next one. */
if ($long_opt_name != $opt) {
continue;
}
$opt_rest = substr($long_opt, $opt_len);
/* Check that the options uniquely matches one of the allowed
options. */
if ($i + 1 < count($long_options)) {
$next_option_rest = substr($long_options[$i + 1], $opt_len);
} else {
$next_option_rest = '';
}
if ($opt_rest != '' && $opt{0} != '=' &&
$i + 1 < count($long_options) &&
$opt == substr($long_options[$i+1], 0, $opt_len) &&
$next_option_rest != '' &&
$next_option_rest{0} != '=') {
return PEAR::raiseError("Console_Getopt: option --$opt is ambiguous");
}
if (substr($long_opt, -1) == '=') {
if (substr($long_opt, -2) != '==') {
/* Long option requires an argument.
Take the next argument if one wasn't specified. */;
if (!strlen($opt_arg) && !(list(, $opt_arg) = each($args))) {
return PEAR::raiseError("Console_Getopt: option --$opt requires an argument");
}
if (Console_Getopt::_isShortOpt($opt_arg) || Console_Getopt::_isLongOpt($opt_arg)) {
return PEAR::raiseError("Console_Getopt: option requires an argument --$opt");
}
}
} else if ($opt_arg) {
return PEAR::raiseError("Console_Getopt: option --$opt doesn't allow an argument");
}
$opts[] = array('--' . $opt, $opt_arg);
return;
}
return PEAR::raiseError("Console_Getopt: unrecognized option --$opt");
}
/**
* Safely read the $argv PHP array across different PHP configurations.
* Will take care on register_globals and register_argc_argv ini directives
*
* @access public
* @return mixed the $argv PHP array or PEAR error if not registered
*/
function readPHPArgv()
{
global $argv;
if (!is_array($argv)) {
if (!@is_array($_SERVER['argv'])) {
if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) {
return PEAR::raiseError("Console_Getopt: Could not read cmd args (register_argc_argv=Off?)");
}
return $GLOBALS['HTTP_SERVER_VARS']['argv'];
}
return $_SERVER['argv'];
}
return $argv;
}
}
?>
<?php
/**
* Class representing a HTTP request message
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: Request2.php 290921 2009-11-18 17:31:58Z avb $
* @link http://pear.php.net/package/HTTP_Request2
*/
/**
* A class representing an URL as per RFC 3986.
*/
require_once 'Net/URL2.php';
/**
* Exception class for HTTP_Request2 package
*/
require_once 'HTTP/Request2/Exception.php';
/**
* Class representing a HTTP request message
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @version Release: 0.5.1
* @link http://tools.ietf.org/html/rfc2616#section-5
*/
class HTTP_Request2 implements SplSubject
{
/**#@+
* Constants for HTTP request methods
*
* @link http://tools.ietf.org/html/rfc2616#section-5.1.1
*/
const METHOD_OPTIONS = 'OPTIONS';
const METHOD_GET = 'GET';
const METHOD_HEAD = 'HEAD';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_DELETE = 'DELETE';
const METHOD_TRACE = 'TRACE';
const METHOD_CONNECT = 'CONNECT';
/**#@-*/
/**#@+
* Constants for HTTP authentication schemes
*
* @link http://tools.ietf.org/html/rfc2617
*/
const AUTH_BASIC = 'basic';
const AUTH_DIGEST = 'digest';
/**#@-*/
/**
* Regular expression used to check for invalid symbols in RFC 2616 tokens
* @link http://pear.php.net/bugs/bug.php?id=15630
*/
const REGEXP_INVALID_TOKEN = '![\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]!';
/**
* Regular expression used to check for invalid symbols in cookie strings
* @link http://pear.php.net/bugs/bug.php?id=15630
* @link http://web.archive.org/web/20080331104521/http://cgi.netscape.com/newsref/std/cookie_spec.html
*/
const REGEXP_INVALID_COOKIE = '/[\s,;]/';
/**
* Fileinfo magic database resource
* @var resource
* @see detectMimeType()
*/
private static $_fileinfoDb;
/**
* Observers attached to the request (instances of SplObserver)
* @var array
*/
protected $observers = array();
/**
* Request URL
* @var Net_URL2
*/
protected $url;
/**
* Request method
* @var string
*/
protected $method = self::METHOD_GET;
/**
* Authentication data
* @var array
* @see getAuth()
*/
protected $auth;
/**
* Request headers
* @var array
*/
protected $headers = array();
/**
* Configuration parameters
* @var array
* @see setConfig()
*/
protected $config = array(
'adapter' => 'HTTP_Request2_Adapter_Socket',
'connect_timeout' => 10,
'timeout' => 0,
'use_brackets' => true,
'protocol_version' => '1.1',
'buffer_size' => 16384,
'store_body' => true,
'proxy_host' => '',
'proxy_port' => '',
'proxy_user' => '',
'proxy_password' => '',
'proxy_auth_scheme' => self::AUTH_BASIC,
'ssl_verify_peer' => true,
'ssl_verify_host' => true,
'ssl_cafile' => null,
'ssl_capath' => null,
'ssl_local_cert' => null,
'ssl_passphrase' => null,
'digest_compat_ie' => false,
'follow_redirects' => false,
'max_redirects' => 5,
'strict_redirects' => false
);
/**
* Last event in request / response handling, intended for observers
* @var array
* @see getLastEvent()
*/
protected $lastEvent = array(
'name' => 'start',
'data' => null
);
/**
* Request body
* @var string|resource
* @see setBody()
*/
protected $body = '';
/**
* Array of POST parameters
* @var array
*/
protected $postParams = array();
/**
* Array of file uploads (for multipart/form-data POST requests)
* @var array
*/
protected $uploads = array();
/**
* Adapter used to perform actual HTTP request
* @var HTTP_Request2_Adapter
*/
protected $adapter;
/**
* Constructor. Can set request URL, method and configuration array.
*
* Also sets a default value for User-Agent header.
*
* @param string|Net_Url2 Request URL
* @param string Request method
* @param array Configuration for this Request instance
*/
public function __construct($url = null, $method = self::METHOD_GET, array $config = array())
{
$this->setConfig($config);
if (!empty($url)) {
$this->setUrl($url);
}
if (!empty($method)) {
$this->setMethod($method);
}
$this->setHeader('user-agent', 'HTTP_Request2/0.5.1 ' .
'(http://pear.php.net/package/http_request2) ' .
'PHP/' . phpversion());
}
/**
* Sets the URL for this request
*
* If the URL has userinfo part (username & password) these will be removed
* and converted to auth data. If the URL does not have a path component,
* that will be set to '/'.
*
* @param string|Net_URL2 Request URL
* @return HTTP_Request2
* @throws HTTP_Request2_Exception
*/
public function setUrl($url)
{
if (is_string($url)) {
$url = new Net_URL2(
$url, array(Net_URL2::OPTION_USE_BRACKETS => $this->config['use_brackets'])
);
}
if (!$url instanceof Net_URL2) {
throw new HTTP_Request2_Exception('Parameter is not a valid HTTP URL');
}
// URL contains username / password?
if ($url->getUserinfo()) {
$username = $url->getUser();
$password = $url->getPassword();
$this->setAuth(rawurldecode($username), $password? rawurldecode($password): '');
$url->setUserinfo('');
}
if ('' == $url->getPath()) {
$url->setPath('/');
}
$this->url = $url;
return $this;
}
/**
* Returns the request URL
*
* @return Net_URL2
*/
public function getUrl()
{
return $this->url;
}
/**
* Sets the request method
*
* @param string
* @return HTTP_Request2
* @throws HTTP_Request2_Exception if the method name is invalid
*/
public function setMethod($method)
{
// Method name should be a token: http://tools.ietf.org/html/rfc2616#section-5.1.1
if (preg_match(self::REGEXP_INVALID_TOKEN, $method)) {
throw new HTTP_Request2_Exception("Invalid request method '{$method}'");
}
$this->method = $method;
return $this;
}
/**
* Returns the request method
*
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* Sets the configuration parameter(s)
*
* The following parameters are available:
* <ul>
* <li> 'adapter' - adapter to use (string)</li>
* <li> 'connect_timeout' - Connection timeout in seconds (integer)</li>
* <li> 'timeout' - Total number of seconds a request can take.
* Use 0 for no limit, should be greater than
* 'connect_timeout' if set (integer)</li>
* <li> 'use_brackets' - Whether to append [] to array variable names (bool)</li>
* <li> 'protocol_version' - HTTP Version to use, '1.0' or '1.1' (string)</li>
* <li> 'buffer_size' - Buffer size to use for reading and writing (int)</li>
* <li> 'store_body' - Whether to store response body in response object.
* Set to false if receiving a huge response and
* using an Observer to save it (boolean)</li>
* <li> 'proxy_host' - Proxy server host (string)</li>
* <li> 'proxy_port' - Proxy server port (integer)</li>
* <li> 'proxy_user' - Proxy auth username (string)</li>
* <li> 'proxy_password' - Proxy auth password (string)</li>
* <li> 'proxy_auth_scheme' - Proxy auth scheme, one of HTTP_Request2::AUTH_* constants (string)</li>
* <li> 'ssl_verify_peer' - Whether to verify peer's SSL certificate (bool)</li>
* <li> 'ssl_verify_host' - Whether to check that Common Name in SSL
* certificate matches host name (bool)</li>
* <li> 'ssl_cafile' - Cerificate Authority file to verify the peer
* with (use with 'ssl_verify_peer') (string)</li>
* <li> 'ssl_capath' - Directory holding multiple Certificate
* Authority files (string)</li>
* <li> 'ssl_local_cert' - Name of a file containing local cerificate (string)</li>
* <li> 'ssl_passphrase' - Passphrase with which local certificate
* was encoded (string)</li>
* <li> 'digest_compat_ie' - Whether to imitate behaviour of MSIE 5 and 6
* in using URL without query string in digest
* authentication (boolean)</li>
* <li> 'follow_redirects' - Whether to automatically follow HTTP Redirects (boolean)</li>
* <li> 'max_redirects' - Maximum number of redirects to follow (integer)</li>
* <li> 'strict_redirects' - Whether to keep request method on redirects via status 301 and
* 302 (true, needed for compatibility with RFC 2616)
* or switch to GET (false, needed for compatibility with most
* browsers) (boolean)</li>
* </ul>
*
* @param string|array configuration parameter name or array
* ('parameter name' => 'parameter value')
* @param mixed parameter value if $nameOrConfig is not an array
* @return HTTP_Request2
* @throws HTTP_Request2_Exception If the parameter is unknown
*/
public function setConfig($nameOrConfig, $value = null)
{
if (is_array($nameOrConfig)) {
foreach ($nameOrConfig as $name => $value) {
$this->setConfig($name, $value);
}
} else {
if (!array_key_exists($nameOrConfig, $this->config)) {
throw new HTTP_Request2_Exception(
"Unknown configuration parameter '{$nameOrConfig}'"
);
}
$this->config[$nameOrConfig] = $value;
}
return $this;
}
/**
* Returns the value(s) of the configuration parameter(s)
*
* @param string parameter name
* @return mixed value of $name parameter, array of all configuration
* parameters if $name is not given
* @throws HTTP_Request2_Exception If the parameter is unknown
*/
public function getConfig($name = null)
{
if (null === $name) {
return $this->config;
} elseif (!array_key_exists($name, $this->config)) {
throw new HTTP_Request2_Exception(
"Unknown configuration parameter '{$name}'"
);
}
return $this->config[$name];
}
/**
* Sets the autentification data
*
* @param string user name
* @param string password
* @param string authentication scheme
* @return HTTP_Request2
*/
public function setAuth($user, $password = '', $scheme = self::AUTH_BASIC)
{
if (empty($user)) {
$this->auth = null;
} else {
$this->auth = array(
'user' => (string)$user,
'password' => (string)$password,
'scheme' => $scheme
);
}
return $this;
}
/**
* Returns the authentication data
*
* The array has the keys 'user', 'password' and 'scheme', where 'scheme'
* is one of the HTTP_Request2::AUTH_* constants.
*
* @return array
*/
public function getAuth()
{
return $this->auth;
}
/**
* Sets request header(s)
*
* The first parameter may be either a full header string 'header: value' or
* header name. In the former case $value parameter is ignored, in the latter
* the header's value will either be set to $value or the header will be
* removed if $value is null. The first parameter can also be an array of
* headers, in that case method will be called recursively.
*
* Note that headers are treated case insensitively as per RFC 2616.
*
* <code>
* $req->setHeader('Foo: Bar'); // sets the value of 'Foo' header to 'Bar'
* $req->setHeader('FoO', 'Baz'); // sets the value of 'Foo' header to 'Baz'
* $req->setHeader(array('foo' => 'Quux')); // sets the value of 'Foo' header to 'Quux'
* $req->setHeader('FOO'); // removes 'Foo' header from request
* </code>
*
* @param string|array header name, header string ('Header: value')
* or an array of headers
* @param string|null header value, header will be removed if null
* @return HTTP_Request2
* @throws HTTP_Request2_Exception
*/
public function setHeader($name, $value = null)
{
if (is_array($name)) {
foreach ($name as $k => $v) {
if (is_string($k)) {
$this->setHeader($k, $v);
} else {
$this->setHeader($v);
}
}
} else {
if (null === $value && strpos($name, ':')) {
list($name, $value) = array_map('trim', explode(':', $name, 2));
}
// Header name should be a token: http://tools.ietf.org/html/rfc2616#section-4.2
if (preg_match(self::REGEXP_INVALID_TOKEN, $name)) {
throw new HTTP_Request2_Exception("Invalid header name '{$name}'");
}
// Header names are case insensitive anyway
$name = strtolower($name);
if (null === $value) {
unset($this->headers[$name]);
} else {
$this->headers[$name] = $value;
}
}
return $this;
}
/**
* Returns the request headers
*
* The array is of the form ('header name' => 'header value'), header names
* are lowercased
*
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Appends a cookie to "Cookie:" header
*
* @param string cookie name
* @param string cookie value
* @return HTTP_Request2
* @throws HTTP_Request2_Exception
*/
public function addCookie($name, $value)
{
$cookie = $name . '=' . $value;
if (preg_match(self::REGEXP_INVALID_COOKIE, $cookie)) {
throw new HTTP_Request2_Exception("Invalid cookie: '{$cookie}'");
}
$cookies = empty($this->headers['cookie'])? '': $this->headers['cookie'] . '; ';
$this->setHeader('cookie', $cookies . $cookie);
return $this;
}
/**
* Sets the request body
*
* @param string Either a string with the body or filename containing body
* @param bool Whether first parameter is a filename
* @return HTTP_Request2
* @throws HTTP_Request2_Exception
*/
public function setBody($body, $isFilename = false)
{
if (!$isFilename) {
if (!$body instanceof HTTP_Request2_MultipartBody) {
$this->body = (string)$body;
} else {
$this->body = $body;
}
} else {
if (!($fp = @fopen($body, 'rb'))) {
throw new HTTP_Request2_Exception("Cannot open file {$body}");
}
$this->body = $fp;
if (empty($this->headers['content-type'])) {
$this->setHeader('content-type', self::detectMimeType($body));
}
}
$this->postParams = $this->uploads = array();
return $this;
}
/**
* Returns the request body
*
* @return string|resource|HTTP_Request2_MultipartBody
*/
public function getBody()
{
if (self::METHOD_POST == $this->method &&
(!empty($this->postParams) || !empty($this->uploads))
) {
if ('application/x-www-form-urlencoded' == $this->headers['content-type']) {
$body = http_build_query($this->postParams, '', '&');
if (!$this->getConfig('use_brackets')) {
$body = preg_replace('/%5B\d+%5D=/', '=', $body);
}
// support RFC 3986 by not encoding '~' symbol (request #15368)
return str_replace('%7E', '~', $body);
} elseif ('multipart/form-data' == $this->headers['content-type']) {
require_once 'HTTP/Request2/MultipartBody.php';
return new HTTP_Request2_MultipartBody(
$this->postParams, $this->uploads, $this->getConfig('use_brackets')
);
}
}
return $this->body;
}
/**
* Adds a file to form-based file upload
*
* Used to emulate file upload via a HTML form. The method also sets
* Content-Type of HTTP request to 'multipart/form-data'.
*
* If you just want to send the contents of a file as the body of HTTP
* request you should use setBody() method.
*
* @param string name of file-upload field
* @param mixed full name of local file
* @param string filename to send in the request
* @param string content-type of file being uploaded
* @return HTTP_Request2
* @throws HTTP_Request2_Exception
*/
public function addUpload($fieldName, $filename, $sendFilename = null,
$contentType = null)
{
if (!is_array($filename)) {
if (!($fp = @fopen($filename, 'rb'))) {
throw new HTTP_Request2_Exception("Cannot open file {$filename}");
}
$this->uploads[$fieldName] = array(
'fp' => $fp,
'filename' => empty($sendFilename)? basename($filename): $sendFilename,
'size' => filesize($filename),
'type' => empty($contentType)? self::detectMimeType($filename): $contentType
);
} else {
$fps = $names = $sizes = $types = array();
foreach ($filename as $f) {
if (!is_array($f)) {
$f = array($f);
}
if (!($fp = @fopen($f[0], 'rb'))) {
throw new HTTP_Request2_Exception("Cannot open file {$f[0]}");
}
$fps[] = $fp;
$names[] = empty($f[1])? basename($f[0]): $f[1];
$sizes[] = filesize($f[0]);
$types[] = empty($f[2])? self::detectMimeType($f[0]): $f[2];
}
$this->uploads[$fieldName] = array(
'fp' => $fps, 'filename' => $names, 'size' => $sizes, 'type' => $types
);
}
if (empty($this->headers['content-type']) ||
'application/x-www-form-urlencoded' == $this->headers['content-type']
) {
$this->setHeader('content-type', 'multipart/form-data');
}
return $this;
}
/**
* Adds POST parameter(s) to the request.
*
* @param string|array parameter name or array ('name' => 'value')
* @param mixed parameter value (can be an array)
* @return HTTP_Request2
*/
public function addPostParameter($name, $value = null)
{
if (!is_array($name)) {
$this->postParams[$name] = $value;
} else {
foreach ($name as $k => $v) {
$this->addPostParameter($k, $v);
}
}
if (empty($this->headers['content-type'])) {
$this->setHeader('content-type', 'application/x-www-form-urlencoded');
}
return $this;
}
/**
* Attaches a new observer
*
* @param SplObserver
*/
public function attach(SplObserver $observer)
{
foreach ($this->observers as $attached) {
if ($attached === $observer) {
return;
}
}
$this->observers[] = $observer;
}
/**
* Detaches an existing observer
*
* @param SplObserver
*/
public function detach(SplObserver $observer)
{
foreach ($this->observers as $key => $attached) {
if ($attached === $observer) {
unset($this->observers[$key]);
return;
}
}
}
/**
* Notifies all observers
*/
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
/**
* Sets the last event
*
* Adapters should use this method to set the current state of the request
* and notify the observers.
*
* @param string event name
* @param mixed event data
*/
public function setLastEvent($name, $data = null)
{
$this->lastEvent = array(
'name' => $name,
'data' => $data
);
$this->notify();
}
/**
* Returns the last event
*
* Observers should use this method to access the last change in request.
* The following event names are possible:
* <ul>
* <li>'connect' - after connection to remote server,
* data is the destination (string)</li>
* <li>'disconnect' - after disconnection from server</li>
* <li>'sentHeaders' - after sending the request headers,
* data is the headers sent (string)</li>
* <li>'sentBodyPart' - after sending a part of the request body,
* data is the length of that part (int)</li>
* <li>'receivedHeaders' - after receiving the response headers,
* data is HTTP_Request2_Response object</li>
* <li>'receivedBodyPart' - after receiving a part of the response
* body, data is that part (string)</li>
* <li>'receivedEncodedBodyPart' - as 'receivedBodyPart', but data is still
* encoded by Content-Encoding</li>
* <li>'receivedBody' - after receiving the complete response
* body, data is HTTP_Request2_Response object</li>
* </ul>
* Different adapters may not send all the event types. Mock adapter does
* not send any events to the observers.
*
* @return array The array has two keys: 'name' and 'data'
*/
public function getLastEvent()
{
return $this->lastEvent;
}
/**
* Sets the adapter used to actually perform the request
*
* You can pass either an instance of a class implementing HTTP_Request2_Adapter
* or a class name. The method will only try to include a file if the class
* name starts with HTTP_Request2_Adapter_, it will also try to prepend this
* prefix to the class name if it doesn't contain any underscores, so that
* <code>
* $request->setAdapter('curl');
* </code>
* will work.
*
* @param string|HTTP_Request2_Adapter
* @return HTTP_Request2
* @throws HTTP_Request2_Exception
*/
public function setAdapter($adapter)
{
if (is_string($adapter)) {
if (!class_exists($adapter, false)) {
if (false === strpos($adapter, '_')) {
$adapter = 'HTTP_Request2_Adapter_' . ucfirst($adapter);
}
if (preg_match('/^HTTP_Request2_Adapter_([a-zA-Z0-9]+)$/', $adapter)) {
include_once str_replace('_', DIRECTORY_SEPARATOR, $adapter) . '.php';
}
if (!class_exists($adapter, false)) {
throw new HTTP_Request2_Exception("Class {$adapter} not found");
}
}
$adapter = new $adapter;
}
if (!$adapter instanceof HTTP_Request2_Adapter) {
throw new HTTP_Request2_Exception('Parameter is not a HTTP request adapter');
}
$this->adapter = $adapter;
return $this;
}
/**
* Sends the request and returns the response
*
* @throws HTTP_Request2_Exception
* @return HTTP_Request2_Response
*/
public function send()
{
// Sanity check for URL
if (!$this->url instanceof Net_URL2) {
throw new HTTP_Request2_Exception('No URL given');
} elseif (!$this->url->isAbsolute()) {
throw new HTTP_Request2_Exception('Absolute URL required');
} elseif (!in_array(strtolower($this->url->getScheme()), array('https', 'http'))) {
throw new HTTP_Request2_Exception('Not a HTTP URL');
}
if (empty($this->adapter)) {
$this->setAdapter($this->getConfig('adapter'));
}
// magic_quotes_runtime may break file uploads and chunked response
// processing; see bug #4543
if ($magicQuotes = ini_get('magic_quotes_runtime')) {
ini_set('magic_quotes_runtime', false);
}
// force using single byte encoding if mbstring extension overloads
// strlen() and substr(); see bug #1781, bug #10605
if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {
$oldEncoding = mb_internal_encoding();
mb_internal_encoding('iso-8859-1');
}
try {
$response = $this->adapter->sendRequest($this);
} catch (Exception $e) {
}
// cleanup in either case (poor man's "finally" clause)
if ($magicQuotes) {
ini_set('magic_quotes_runtime', true);
}
if (!empty($oldEncoding)) {
mb_internal_encoding($oldEncoding);
}
// rethrow the exception
if (!empty($e)) {
throw $e;
}
return $response;
}
/**
* Tries to detect MIME type of a file
*
* The method will try to use fileinfo extension if it is available,
* deprecated mime_content_type() function in the other case. If neither
* works, default 'application/octet-stream' MIME type is returned
*
* @param string filename
* @return string file MIME type
*/
protected static function detectMimeType($filename)
{
// finfo extension from PECL available
if (function_exists('finfo_open')) {
if (!isset(self::$_fileinfoDb)) {
self::$_fileinfoDb = @finfo_open(FILEINFO_MIME);
}
if (self::$_fileinfoDb) {
$info = finfo_file(self::$_fileinfoDb, $filename);
}
}
// (deprecated) mime_content_type function available
if (empty($info) && function_exists('mime_content_type')) {
return mime_content_type($filename);
}
return empty($info)? 'application/octet-stream': $info;
}
}
?>
\ No newline at end of file
<?php
/**
* Base class for HTTP_Request2 adapters
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: Adapter.php 291118 2009-11-21 17:58:23Z avb $
* @link http://pear.php.net/package/HTTP_Request2
*/
/**
* Class representing a HTTP response
*/
require_once 'HTTP/Request2/Response.php';
/**
* Base class for HTTP_Request2 adapters
*
* HTTP_Request2 class itself only defines methods for aggregating the request
* data, all actual work of sending the request to the remote server and
* receiving its response is performed by adapters.
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @version Release: 0.5.1
*/
abstract class HTTP_Request2_Adapter
{
/**
* A list of methods that MUST NOT have a request body, per RFC 2616
* @var array
*/
protected static $bodyDisallowed = array('TRACE');
/**
* Methods having defined semantics for request body
*
* Content-Length header (indicating that the body follows, section 4.3 of
* RFC 2616) will be sent for these methods even if no body was added
*
* @var array
* @link http://pear.php.net/bugs/bug.php?id=12900
* @link http://pear.php.net/bugs/bug.php?id=14740
*/
protected static $bodyRequired = array('POST', 'PUT');
/**
* Request being sent
* @var HTTP_Request2
*/
protected $request;
/**
* Request body
* @var string|resource|HTTP_Request2_MultipartBody
* @see HTTP_Request2::getBody()
*/
protected $requestBody;
/**
* Length of the request body
* @var integer
*/
protected $contentLength;
/**
* Sends request to the remote server and returns its response
*
* @param HTTP_Request2
* @return HTTP_Request2_Response
* @throws HTTP_Request2_Exception
*/
abstract public function sendRequest(HTTP_Request2 $request);
/**
* Calculates length of the request body, adds proper headers
*
* @param array associative array of request headers, this method will
* add proper 'Content-Length' and 'Content-Type' headers
* to this array (or remove them if not needed)
*/
protected function calculateRequestLength(&$headers)
{
$this->requestBody = $this->request->getBody();
if (is_string($this->requestBody)) {
$this->contentLength = strlen($this->requestBody);
} elseif (is_resource($this->requestBody)) {
$stat = fstat($this->requestBody);
$this->contentLength = $stat['size'];
rewind($this->requestBody);
} else {
$this->contentLength = $this->requestBody->getLength();
$headers['content-type'] = 'multipart/form-data; boundary=' .
$this->requestBody->getBoundary();
$this->requestBody->rewind();
}
if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||
0 == $this->contentLength
) {
// No body: send a Content-Length header nonetheless (request #12900),
// but do that only for methods that require a body (bug #14740)
if (in_array($this->request->getMethod(), self::$bodyRequired)) {
$headers['content-length'] = 0;
} else {
unset($headers['content-length']);
// if the method doesn't require a body and doesn't have a
// body, don't send a Content-Type header. (request #16799)
unset($headers['content-type']);
}
} else {
if (empty($headers['content-type'])) {
$headers['content-type'] = 'application/x-www-form-urlencoded';
}
$headers['content-length'] = $this->contentLength;
}
}
}
?>
<?php
/**
* Adapter for HTTP_Request2 wrapping around cURL extension
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: Curl.php 291118 2009-11-21 17:58:23Z avb $
* @link http://pear.php.net/package/HTTP_Request2
*/
/**
* Base class for HTTP_Request2 adapters
*/
require_once 'HTTP/Request2/Adapter.php';
/**
* Adapter for HTTP_Request2 wrapping around cURL extension
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @version Release: 0.5.1
*/
class HTTP_Request2_Adapter_Curl extends HTTP_Request2_Adapter
{
/**
* Mapping of header names to cURL options
* @var array
*/
protected static $headerMap = array(
'accept-encoding' => CURLOPT_ENCODING,
'cookie' => CURLOPT_COOKIE,
'referer' => CURLOPT_REFERER,
'user-agent' => CURLOPT_USERAGENT
);
/**
* Mapping of SSL context options to cURL options
* @var array
*/
protected static $sslContextMap = array(
'ssl_verify_peer' => CURLOPT_SSL_VERIFYPEER,
'ssl_cafile' => CURLOPT_CAINFO,
'ssl_capath' => CURLOPT_CAPATH,
'ssl_local_cert' => CURLOPT_SSLCERT,
'ssl_passphrase' => CURLOPT_SSLCERTPASSWD
);
/**
* Response being received
* @var HTTP_Request2_Response
*/
protected $response;
/**
* Whether 'sentHeaders' event was sent to observers
* @var boolean
*/
protected $eventSentHeaders = false;
/**
* Whether 'receivedHeaders' event was sent to observers
* @var boolean
*/
protected $eventReceivedHeaders = false;
/**
* Position within request body
* @var integer
* @see callbackReadBody()
*/
protected $position = 0;
/**
* Information about last transfer, as returned by curl_getinfo()
* @var array
*/
protected $lastInfo;
/**
* Sends request to the remote server and returns its response
*
* @param HTTP_Request2
* @return HTTP_Request2_Response
* @throws HTTP_Request2_Exception
*/
public function sendRequest(HTTP_Request2 $request)
{
if (!extension_loaded('curl')) {
throw new HTTP_Request2_Exception('cURL extension not available');
}
$this->request = $request;
$this->response = null;
$this->position = 0;
$this->eventSentHeaders = false;
$this->eventReceivedHeaders = false;
try {
if (false === curl_exec($ch = $this->createCurlHandle())) {
$errorMessage = 'Error sending request: #' . curl_errno($ch) .
' ' . curl_error($ch);
}
} catch (Exception $e) {
}
$this->lastInfo = curl_getinfo($ch);
curl_close($ch);
$response = $this->response;
unset($this->request, $this->requestBody, $this->response);
if (!empty($e)) {
throw $e;
} elseif (!empty($errorMessage)) {
throw new HTTP_Request2_Exception($errorMessage);
}
if (0 < $this->lastInfo['size_download']) {
$request->setLastEvent('receivedBody', $response);
}
return $response;
}
/**
* Returns information about last transfer
*
* @return array associative array as returned by curl_getinfo()
*/
public function getInfo()
{
return $this->lastInfo;
}
/**
* Creates a new cURL handle and populates it with data from the request
*
* @return resource a cURL handle, as created by curl_init()
* @throws HTTP_Request2_Exception
*/
protected function createCurlHandle()
{
$ch = curl_init();
curl_setopt_array($ch, array(
// setup write callbacks
CURLOPT_HEADERFUNCTION => array($this, 'callbackWriteHeader'),
CURLOPT_WRITEFUNCTION => array($this, 'callbackWriteBody'),
// buffer size
CURLOPT_BUFFERSIZE => $this->request->getConfig('buffer_size'),
// connection timeout
CURLOPT_CONNECTTIMEOUT => $this->request->getConfig('connect_timeout'),
// save full outgoing headers, in case someone is interested
CURLINFO_HEADER_OUT => true,
// request url
CURLOPT_URL => $this->request->getUrl()->getUrl()
));
// set up redirects
if (!$this->request->getConfig('follow_redirects')) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
} else {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, $this->request->getConfig('max_redirects'));
// limit redirects to http(s), works in 5.2.10+
if (defined('CURLOPT_REDIR_PROTOCOLS')) {
curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
}
// works sometime after 5.3.0, http://bugs.php.net/bug.php?id=49571
if ($this->request->getConfig('strict_redirects') && defined('CURLOPT_POSTREDIR ')) {
curl_setopt($ch, CURLOPT_POSTREDIR, 3);
}
}
// request timeout
if ($timeout = $this->request->getConfig('timeout')) {
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
}
// set HTTP version
switch ($this->request->getConfig('protocol_version')) {
case '1.0':
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
break;
case '1.1':
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
}
// set request method
switch ($this->request->getMethod()) {
case HTTP_Request2::METHOD_GET:
curl_setopt($ch, CURLOPT_HTTPGET, true);
break;
case HTTP_Request2::METHOD_POST:
curl_setopt($ch, CURLOPT_POST, true);
break;
case HTTP_Request2::METHOD_HEAD:
curl_setopt($ch, CURLOPT_NOBODY, true);
break;
default:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->request->getMethod());
}
// set proxy, if needed
if ($host = $this->request->getConfig('proxy_host')) {
if (!($port = $this->request->getConfig('proxy_port'))) {
throw new HTTP_Request2_Exception('Proxy port not provided');
}
curl_setopt($ch, CURLOPT_PROXY, $host . ':' . $port);
if ($user = $this->request->getConfig('proxy_user')) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $user . ':' .
$this->request->getConfig('proxy_password'));
switch ($this->request->getConfig('proxy_auth_scheme')) {
case HTTP_Request2::AUTH_BASIC:
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
break;
case HTTP_Request2::AUTH_DIGEST:
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_DIGEST);
}
}
}
// set authentication data
if ($auth = $this->request->getAuth()) {
curl_setopt($ch, CURLOPT_USERPWD, $auth['user'] . ':' . $auth['password']);
switch ($auth['scheme']) {
case HTTP_Request2::AUTH_BASIC:
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
break;
case HTTP_Request2::AUTH_DIGEST:
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
}
}
// set SSL options
if (0 == strcasecmp($this->request->getUrl()->getScheme(), 'https')) {
foreach ($this->request->getConfig() as $name => $value) {
if ('ssl_verify_host' == $name && null !== $value) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $value? 2: 0);
} elseif (isset(self::$sslContextMap[$name]) && null !== $value) {
curl_setopt($ch, self::$sslContextMap[$name], $value);
}
}
}
$headers = $this->request->getHeaders();
// make cURL automagically send proper header
if (!isset($headers['accept-encoding'])) {
$headers['accept-encoding'] = '';
}
// set headers having special cURL keys
foreach (self::$headerMap as $name => $option) {
if (isset($headers[$name])) {
curl_setopt($ch, $option, $headers[$name]);
unset($headers[$name]);
}
}
$this->calculateRequestLength($headers);
if (isset($headers['content-length'])) {
$this->workaroundPhpBug47204($ch, $headers);
}
// set headers not having special keys
$headersFmt = array();
foreach ($headers as $name => $value) {
$canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
$headersFmt[] = $canonicalName . ': ' . $value;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headersFmt);
return $ch;
}
/**
* Workaround for PHP bug #47204 that prevents rewinding request body
*
* The workaround consists of reading the entire request body into memory
* and setting it as CURLOPT_POSTFIELDS, so it isn't recommended for large
* file uploads, use Socket adapter instead.
*
* @param resource cURL handle
* @param array Request headers
*/
protected function workaroundPhpBug47204($ch, &$headers)
{
// no redirects, no digest auth -> probably no rewind needed
if (!$this->request->getConfig('follow_redirects')
&& (!($auth = $this->request->getAuth())
|| HTTP_Request2::AUTH_DIGEST != $auth['scheme'])
) {
curl_setopt($ch, CURLOPT_READFUNCTION, array($this, 'callbackReadBody'));
// rewind may be needed, read the whole body into memory
} else {
if ($this->requestBody instanceof HTTP_Request2_MultipartBody) {
$this->requestBody = $this->requestBody->__toString();
} elseif (is_resource($this->requestBody)) {
$fp = $this->requestBody;
$this->requestBody = '';
while (!feof($fp)) {
$this->requestBody .= fread($fp, 16384);
}
}
// curl hangs up if content-length is present
unset($headers['content-length']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestBody);
}
}
/**
* Callback function called by cURL for reading the request body
*
* @param resource cURL handle
* @param resource file descriptor (not used)
* @param integer maximum length of data to return
* @return string part of the request body, up to $length bytes
*/
protected function callbackReadBody($ch, $fd, $length)
{
if (!$this->eventSentHeaders) {
$this->request->setLastEvent(
'sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT)
);
$this->eventSentHeaders = true;
}
if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||
0 == $this->contentLength || $this->position >= $this->contentLength
) {
return '';
}
if (is_string($this->requestBody)) {
$string = substr($this->requestBody, $this->position, $length);
} elseif (is_resource($this->requestBody)) {
$string = fread($this->requestBody, $length);
} else {
$string = $this->requestBody->read($length);
}
$this->request->setLastEvent('sentBodyPart', strlen($string));
$this->position += strlen($string);
return $string;
}
/**
* Callback function called by cURL for saving the response headers
*
* @param resource cURL handle
* @param string response header (with trailing CRLF)
* @return integer number of bytes saved
* @see HTTP_Request2_Response::parseHeaderLine()
*/
protected function callbackWriteHeader($ch, $string)
{
// we may receive a second set of headers if doing e.g. digest auth
if ($this->eventReceivedHeaders || !$this->eventSentHeaders) {
// don't bother with 100-Continue responses (bug #15785)
if (!$this->eventSentHeaders ||
$this->response->getStatus() >= 200
) {
$this->request->setLastEvent(
'sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT)
);
}
$upload = curl_getinfo($ch, CURLINFO_SIZE_UPLOAD);
// if body wasn't read by a callback, send event with total body size
if ($upload > $this->position) {
$this->request->setLastEvent(
'sentBodyPart', $upload - $this->position
);
$this->position = $upload;
}
$this->eventSentHeaders = true;
// we'll need a new response object
if ($this->eventReceivedHeaders) {
$this->eventReceivedHeaders = false;
$this->response = null;
}
}
if (empty($this->response)) {
$this->response = new HTTP_Request2_Response($string, false);
} else {
$this->response->parseHeaderLine($string);
if ('' == trim($string)) {
// don't bother with 100-Continue responses (bug #15785)
if (200 <= $this->response->getStatus()) {
$this->request->setLastEvent('receivedHeaders', $this->response);
}
// for versions lower than 5.2.10, check the redirection URL protocol
if ($this->request->getConfig('follow_redirects') && !defined('CURLOPT_REDIR_PROTOCOLS')
&& $this->response->isRedirect()
) {
$redirectUrl = new Net_URL2($this->response->getHeader('location'));
if ($redirectUrl->isAbsolute()
&& !in_array($redirectUrl->getScheme(), array('http', 'https'))
) {
return -1;
}
}
$this->eventReceivedHeaders = true;
}
}
return strlen($string);
}
/**
* Callback function called by cURL for saving the response body
*
* @param resource cURL handle (not used)
* @param string part of the response body
* @return integer number of bytes saved
* @see HTTP_Request2_Response::appendBody()
*/
protected function callbackWriteBody($ch, $string)
{
// cURL calls WRITEFUNCTION callback without calling HEADERFUNCTION if
// response doesn't start with proper HTTP status line (see bug #15716)
if (empty($this->response)) {
throw new HTTP_Request2_Exception("Malformed response: {$string}");
}
if ($this->request->getConfig('store_body')) {
$this->response->appendBody($string);
}
$this->request->setLastEvent('receivedBodyPart', $string);
return strlen($string);
}
}
?>
<?php
/**
* Mock adapter intended for testing
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: Mock.php 290192 2009-11-03 21:29:32Z avb $
* @link http://pear.php.net/package/HTTP_Request2
*/
/**
* Base class for HTTP_Request2 adapters
*/
require_once 'HTTP/Request2/Adapter.php';
/**
* Mock adapter intended for testing
*
* Can be used to test applications depending on HTTP_Request2 package without
* actually performing any HTTP requests. This adapter will return responses
* previously added via addResponse()
* <code>
* $mock = new HTTP_Request2_Adapter_Mock();
* $mock->addResponse("HTTP/1.1 ... ");
*
* $request = new HTTP_Request2();
* $request->setAdapter($mock);
*
* // This will return the response set above
* $response = $req->send();
* </code>
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @version Release: 0.5.1
*/
class HTTP_Request2_Adapter_Mock extends HTTP_Request2_Adapter
{
/**
* A queue of responses to be returned by sendRequest()
* @var array
*/
protected $responses = array();
/**
* Returns the next response from the queue built by addResponse()
*
* If the queue is empty it will return default empty response with status 400,
* if an Exception object was added to the queue it will be thrown.
*
* @param HTTP_Request2
* @return HTTP_Request2_Response
* @throws Exception
*/
public function sendRequest(HTTP_Request2 $request)
{
if (count($this->responses) > 0) {
$response = array_shift($this->responses);
if ($response instanceof HTTP_Request2_Response) {
return $response;
} else {
// rethrow the exception
$class = get_class($response);
$message = $response->getMessage();
$code = $response->getCode();
throw new $class($message, $code);
}
} else {
return self::createResponseFromString("HTTP/1.1 400 Bad Request\r\n\r\n");
}
}
/**
* Adds response to the queue
*
* @param mixed either a string, a pointer to an open file,
* an instance of HTTP_Request2_Response or Exception
* @throws HTTP_Request2_Exception
*/
public function addResponse($response)
{
if (is_string($response)) {
$response = self::createResponseFromString($response);
} elseif (is_resource($response)) {
$response = self::createResponseFromFile($response);
} elseif (!$response instanceof HTTP_Request2_Response &&
!$response instanceof Exception
) {
throw new HTTP_Request2_Exception('Parameter is not a valid response');
}
$this->responses[] = $response;
}
/**
* Creates a new HTTP_Request2_Response object from a string
*
* @param string
* @return HTTP_Request2_Response
* @throws HTTP_Request2_Exception
*/
public static function createResponseFromString($str)
{
$parts = preg_split('!(\r?\n){2}!m', $str, 2);
$headerLines = explode("\n", $parts[0]);
$response = new HTTP_Request2_Response(array_shift($headerLines));
foreach ($headerLines as $headerLine) {
$response->parseHeaderLine($headerLine);
}
$response->parseHeaderLine('');
if (isset($parts[1])) {
$response->appendBody($parts[1]);
}
return $response;
}
/**
* Creates a new HTTP_Request2_Response object from a file
*
* @param resource file pointer returned by fopen()
* @return HTTP_Request2_Response
* @throws HTTP_Request2_Exception
*/
public static function createResponseFromFile($fp)
{
$response = new HTTP_Request2_Response(fgets($fp));
do {
$headerLine = fgets($fp);
$response->parseHeaderLine($headerLine);
} while ('' != trim($headerLine));
while (!feof($fp)) {
$response->appendBody(fread($fp, 8192));
}
return $response;
}
}
?>
\ No newline at end of file
<?php
/**
* Socket-based adapter for HTTP_Request2
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: Socket.php 290921 2009-11-18 17:31:58Z avb $
* @link http://pear.php.net/package/HTTP_Request2
*/
/**
* Base class for HTTP_Request2 adapters
*/
require_once 'HTTP/Request2/Adapter.php';
/**
* Socket-based adapter for HTTP_Request2
*
* This adapter uses only PHP sockets and will work on almost any PHP
* environment. Code is based on original HTTP_Request PEAR package.
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @version Release: 0.5.1
*/
class HTTP_Request2_Adapter_Socket extends HTTP_Request2_Adapter
{
/**
* Regular expression for 'token' rule from RFC 2616
*/
const REGEXP_TOKEN = '[^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+';
/**
* Regular expression for 'quoted-string' rule from RFC 2616
*/
const REGEXP_QUOTED_STRING = '"(?:\\\\.|[^\\\\"])*"';
/**
* Connected sockets, needed for Keep-Alive support
* @var array
* @see connect()
*/
protected static $sockets = array();
/**
* Data for digest authentication scheme
*
* The keys for the array are URL prefixes.
*
* The values are associative arrays with data (realm, nonce, nonce-count,
* opaque...) needed for digest authentication. Stored here to prevent making
* duplicate requests to digest-protected resources after we have already
* received the challenge.
*
* @var array
*/
protected static $challenges = array();
/**
* Connected socket
* @var resource
* @see connect()
*/
protected $socket;
/**
* Challenge used for server digest authentication
* @var array
*/
protected $serverChallenge;
/**
* Challenge used for proxy digest authentication
* @var array
*/
protected $proxyChallenge;
/**
* Sum of start time and global timeout, exception will be thrown if request continues past this time
* @var integer
*/
protected $deadline = null;
/**
* Remaining length of the current chunk, when reading chunked response
* @var integer
* @see readChunked()
*/
protected $chunkLength = 0;
/**
* Remaining amount of redirections to follow
*
* Starts at 'max_redirects' configuration parameter and is reduced on each
* subsequent redirect. An Exception will be thrown once it reaches zero.
*
* @var integer
*/
protected $redirectCountdown = null;
/**
* Sends request to the remote server and returns its response
*
* @param HTTP_Request2
* @return HTTP_Request2_Response
* @throws HTTP_Request2_Exception
*/
public function sendRequest(HTTP_Request2 $request)
{
$this->request = $request;
// Use global request timeout if given, see feature requests #5735, #8964
if ($timeout = $request->getConfig('timeout')) {
$this->deadline = time() + $timeout;
} else {
$this->deadline = null;
}
try {
$keepAlive = $this->connect();
$headers = $this->prepareHeaders();
if (false === @fwrite($this->socket, $headers, strlen($headers))) {
throw new HTTP_Request2_Exception('Error writing request');
}
// provide request headers to the observer, see request #7633
$this->request->setLastEvent('sentHeaders', $headers);
$this->writeBody();
if ($this->deadline && time() > $this->deadline) {
throw new HTTP_Request2_Exception(
'Request timed out after ' .
$request->getConfig('timeout') . ' second(s)'
);
}
$response = $this->readResponse();
if (!$this->canKeepAlive($keepAlive, $response)) {
$this->disconnect();
}
if ($this->shouldUseProxyDigestAuth($response)) {
return $this->sendRequest($request);
}
if ($this->shouldUseServerDigestAuth($response)) {
return $this->sendRequest($request);
}
if ($authInfo = $response->getHeader('authentication-info')) {
$this->updateChallenge($this->serverChallenge, $authInfo);
}
if ($proxyInfo = $response->getHeader('proxy-authentication-info')) {
$this->updateChallenge($this->proxyChallenge, $proxyInfo);
}
} catch (Exception $e) {
$this->disconnect();
}
unset($this->request, $this->requestBody);
if (!empty($e)) {
throw $e;
}
if (!$request->getConfig('follow_redirects') || !$response->isRedirect()) {
return $response;
} else {
return $this->handleRedirect($request, $response);
}
}
/**
* Connects to the remote server
*
* @return bool whether the connection can be persistent
* @throws HTTP_Request2_Exception
*/
protected function connect()
{
$secure = 0 == strcasecmp($this->request->getUrl()->getScheme(), 'https');
$tunnel = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
$headers = $this->request->getHeaders();
$reqHost = $this->request->getUrl()->getHost();
if (!($reqPort = $this->request->getUrl()->getPort())) {
$reqPort = $secure? 443: 80;
}
if ($host = $this->request->getConfig('proxy_host')) {
if (!($port = $this->request->getConfig('proxy_port'))) {
throw new HTTP_Request2_Exception('Proxy port not provided');
}
$proxy = true;
} else {
$host = $reqHost;
$port = $reqPort;
$proxy = false;
}
if ($tunnel && !$proxy) {
throw new HTTP_Request2_Exception(
"Trying to perform CONNECT request without proxy"
);
}
if ($secure && !in_array('ssl', stream_get_transports())) {
throw new HTTP_Request2_Exception(
'Need OpenSSL support for https:// requests'
);
}
// RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
// connection token to a proxy server...
if ($proxy && !$secure &&
!empty($headers['connection']) && 'Keep-Alive' == $headers['connection']
) {
$this->request->setHeader('connection');
}
$keepAlive = ('1.1' == $this->request->getConfig('protocol_version') &&
empty($headers['connection'])) ||
(!empty($headers['connection']) &&
'Keep-Alive' == $headers['connection']);
$host = ((!$secure || $proxy)? 'tcp://': 'ssl://') . $host;
$options = array();
if ($secure || $tunnel) {
foreach ($this->request->getConfig() as $name => $value) {
if ('ssl_' == substr($name, 0, 4) && null !== $value) {
if ('ssl_verify_host' == $name) {
if ($value) {
$options['CN_match'] = $reqHost;
}
} else {
$options[substr($name, 4)] = $value;
}
}
}
ksort($options);
}
// Changing SSL context options after connection is established does *not*
// work, we need a new connection if options change
$remote = $host . ':' . $port;
$socketKey = $remote . (($secure && $proxy)? "->{$reqHost}:{$reqPort}": '') .
(empty($options)? '': ':' . serialize($options));
unset($this->socket);
// We use persistent connections and have a connected socket?
// Ensure that the socket is still connected, see bug #16149
if ($keepAlive && !empty(self::$sockets[$socketKey]) &&
!feof(self::$sockets[$socketKey])
) {
$this->socket =& self::$sockets[$socketKey];
} elseif ($secure && $proxy && !$tunnel) {
$this->establishTunnel();
$this->request->setLastEvent(
'connect', "ssl://{$reqHost}:{$reqPort} via {$host}:{$port}"
);
self::$sockets[$socketKey] =& $this->socket;
} else {
// Set SSL context options if doing HTTPS request or creating a tunnel
$context = stream_context_create();
foreach ($options as $name => $value) {
if (!stream_context_set_option($context, 'ssl', $name, $value)) {
throw new HTTP_Request2_Exception(
"Error setting SSL context option '{$name}'"
);
}
}
$this->socket = @stream_socket_client(
$remote, $errno, $errstr,
$this->request->getConfig('connect_timeout'),
STREAM_CLIENT_CONNECT, $context
);
if (!$this->socket) {
throw new HTTP_Request2_Exception(
"Unable to connect to {$remote}. Error #{$errno}: {$errstr}"
);
}
$this->request->setLastEvent('connect', $remote);
self::$sockets[$socketKey] =& $this->socket;
}
return $keepAlive;
}
/**
* Establishes a tunnel to a secure remote server via HTTP CONNECT request
*
* This method will fail if 'ssl_verify_peer' is enabled. Probably because PHP
* sees that we are connected to a proxy server (duh!) rather than the server
* that presents its certificate.
*
* @link http://tools.ietf.org/html/rfc2817#section-5.2
* @throws HTTP_Request2_Exception
*/
protected function establishTunnel()
{
$donor = new self;
$connect = new HTTP_Request2(
$this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,
array_merge($this->request->getConfig(),
array('adapter' => $donor))
);
$response = $connect->send();
// Need any successful (2XX) response
if (200 > $response->getStatus() || 300 <= $response->getStatus()) {
throw new HTTP_Request2_Exception(
'Failed to connect via HTTPS proxy. Proxy response: ' .
$response->getStatus() . ' ' . $response->getReasonPhrase()
);
}
$this->socket = $donor->socket;
$modes = array(
STREAM_CRYPTO_METHOD_TLS_CLIENT,
STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
STREAM_CRYPTO_METHOD_SSLv2_CLIENT
);
foreach ($modes as $mode) {
if (stream_socket_enable_crypto($this->socket, true, $mode)) {
return;
}
}
throw new HTTP_Request2_Exception(
'Failed to enable secure connection when connecting through proxy'
);
}
/**
* Checks whether current connection may be reused or should be closed
*
* @param boolean whether connection could be persistent
* in the first place
* @param HTTP_Request2_Response response object to check
* @return boolean
*/
protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)
{
// Do not close socket on successful CONNECT request
if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&
200 <= $response->getStatus() && 300 > $response->getStatus()
) {
return true;
}
$lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding')) ||
null !== $response->getHeader('content-length');
$persistent = 'keep-alive' == strtolower($response->getHeader('connection')) ||
(null === $response->getHeader('connection') &&
'1.1' == $response->getVersion());
return $requestKeepAlive && $lengthKnown && $persistent;
}
/**
* Disconnects from the remote server
*/
protected function disconnect()
{
if (is_resource($this->socket)) {
fclose($this->socket);
$this->socket = null;
$this->request->setLastEvent('disconnect');
}
}
/**
* Handles HTTP redirection
*
* This method will throw an Exception if redirect to a non-HTTP(S) location
* is attempted, also if number of redirects performed already is equal to
* 'max_redirects' configuration parameter.
*
* @param HTTP_Request2 Original request
* @param HTTP_Request2_Response Response containing redirect
* @return HTTP_Request2_Response Response from a new location
* @throws HTTP_Request2_Exception
*/
protected function handleRedirect(HTTP_Request2 $request,
HTTP_Request2_Response $response)
{
if (is_null($this->redirectCountdown)) {
$this->redirectCountdown = $request->getConfig('max_redirects');
}
if (0 == $this->redirectCountdown) {
// Copying cURL behaviour
throw new HTTP_Request2_Exception(
'Maximum (' . $request->getConfig('max_redirects') . ') redirects followed'
);
}
$redirectUrl = new Net_URL2(
$response->getHeader('location'),
array(Net_URL2::OPTION_USE_BRACKETS => $request->getConfig('use_brackets'))
);
// refuse non-HTTP redirect
if ($redirectUrl->isAbsolute()
&& !in_array($redirectUrl->getScheme(), array('http', 'https'))
) {
throw new HTTP_Request2_Exception(
'Refusing to redirect to a non-HTTP URL ' . $redirectUrl->__toString()
);
}
// Theoretically URL should be absolute (see http://tools.ietf.org/html/rfc2616#section-14.30),
// but in practice it is often not
if (!$redirectUrl->isAbsolute()) {
$redirectUrl = $request->getUrl()->resolve($redirectUrl);
}
$redirect = clone $request;
$redirect->setUrl($redirectUrl);
if (303 == $response->getStatus() || (!$request->getConfig('strict_redirects')
&& in_array($response->getStatus(), array(301, 302)))
) {
$redirect->setMethod(HTTP_Request2::METHOD_GET);
$redirect->setBody('');
}
if (0 < $this->redirectCountdown) {
$this->redirectCountdown--;
}
return $this->sendRequest($redirect);
}
/**
* Checks whether another request should be performed with server digest auth
*
* Several conditions should be satisfied for it to return true:
* - response status should be 401
* - auth credentials should be set in the request object
* - response should contain WWW-Authenticate header with digest challenge
* - there is either no challenge stored for this URL or new challenge
* contains stale=true parameter (in other case we probably just failed
* due to invalid username / password)
*
* The method stores challenge values in $challenges static property
*
* @param HTTP_Request2_Response response to check
* @return boolean whether another request should be performed
* @throws HTTP_Request2_Exception in case of unsupported challenge parameters
*/
protected function shouldUseServerDigestAuth(HTTP_Request2_Response $response)
{
// no sense repeating a request if we don't have credentials
if (401 != $response->getStatus() || !$this->request->getAuth()) {
return false;
}
if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {
return false;
}
$url = $this->request->getUrl();
$scheme = $url->getScheme();
$host = $scheme . '://' . $url->getHost();
if ($port = $url->getPort()) {
if ((0 == strcasecmp($scheme, 'http') && 80 != $port) ||
(0 == strcasecmp($scheme, 'https') && 443 != $port)
) {
$host .= ':' . $port;
}
}
if (!empty($challenge['domain'])) {
$prefixes = array();
foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {
// don't bother with different servers
if ('/' == substr($prefix, 0, 1)) {
$prefixes[] = $host . $prefix;
}
}
}
if (empty($prefixes)) {
$prefixes = array($host . '/');
}
$ret = true;
foreach ($prefixes as $prefix) {
if (!empty(self::$challenges[$prefix]) &&
(empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
) {
// probably credentials are invalid
$ret = false;
}
self::$challenges[$prefix] =& $challenge;
}
return $ret;
}
/**
* Checks whether another request should be performed with proxy digest auth
*
* Several conditions should be satisfied for it to return true:
* - response status should be 407
* - proxy auth credentials should be set in the request object
* - response should contain Proxy-Authenticate header with digest challenge
* - there is either no challenge stored for this proxy or new challenge
* contains stale=true parameter (in other case we probably just failed
* due to invalid username / password)
*
* The method stores challenge values in $challenges static property
*
* @param HTTP_Request2_Response response to check
* @return boolean whether another request should be performed
* @throws HTTP_Request2_Exception in case of unsupported challenge parameters
*/
protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)
{
if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {
return false;
}
if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {
return false;
}
$key = 'proxy://' . $this->request->getConfig('proxy_host') .
':' . $this->request->getConfig('proxy_port');
if (!empty(self::$challenges[$key]) &&
(empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
) {
$ret = false;
} else {
$ret = true;
}
self::$challenges[$key] = $challenge;
return $ret;
}
/**
* Extracts digest method challenge from (WWW|Proxy)-Authenticate header value
*
* There is a problem with implementation of RFC 2617: several of the parameters
* are defined as quoted-string there and thus may contain backslash escaped
* double quotes (RFC 2616, section 2.2). However, RFC 2617 defines unq(X) as
* just value of quoted-string X without surrounding quotes, it doesn't speak
* about removing backslash escaping.
*
* Now realm parameter is user-defined and human-readable, strange things
* happen when it contains quotes:
* - Apache allows quotes in realm, but apparently uses realm value without
* backslashes for digest computation
* - Squid allows (manually escaped) quotes there, but it is impossible to
* authorize with either escaped or unescaped quotes used in digest,
* probably it can't parse the response (?)
* - Both IE and Firefox display realm value with backslashes in
* the password popup and apparently use the same value for digest
*
* HTTP_Request2 follows IE and Firefox (and hopefully RFC 2617) in
* quoted-string handling, unfortunately that means failure to authorize
* sometimes
*
* @param string value of WWW-Authenticate or Proxy-Authenticate header
* @return mixed associative array with challenge parameters, false if
* no challenge is present in header value
* @throws HTTP_Request2_Exception in case of unsupported challenge parameters
*/
protected function parseDigestChallenge($headerValue)
{
$authParam = '(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')';
$challenge = "!(?<=^|\\s|,)Digest ({$authParam}\\s*(,\\s*|$))+!";
if (!preg_match($challenge, $headerValue, $matches)) {
return false;
}
preg_match_all('!' . $authParam . '!', $matches[0], $params);
$paramsAry = array();
$knownParams = array('realm', 'domain', 'nonce', 'opaque', 'stale',
'algorithm', 'qop');
for ($i = 0; $i < count($params[0]); $i++) {
// section 3.2.1: Any unrecognized directive MUST be ignored.
if (in_array($params[1][$i], $knownParams)) {
if ('"' == substr($params[2][$i], 0, 1)) {
$paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
} else {
$paramsAry[$params[1][$i]] = $params[2][$i];
}
}
}
// we only support qop=auth
if (!empty($paramsAry['qop']) &&
!in_array('auth', array_map('trim', explode(',', $paramsAry['qop'])))
) {
throw new HTTP_Request2_Exception(
"Only 'auth' qop is currently supported in digest authentication, " .
"server requested '{$paramsAry['qop']}'"
);
}
// we only support algorithm=MD5
if (!empty($paramsAry['algorithm']) && 'MD5' != $paramsAry['algorithm']) {
throw new HTTP_Request2_Exception(
"Only 'MD5' algorithm is currently supported in digest authentication, " .
"server requested '{$paramsAry['algorithm']}'"
);
}
return $paramsAry;
}
/**
* Parses [Proxy-]Authentication-Info header value and updates challenge
*
* @param array challenge to update
* @param string value of [Proxy-]Authentication-Info header
* @todo validate server rspauth response
*/
protected function updateChallenge(&$challenge, $headerValue)
{
$authParam = '!(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')!';
$paramsAry = array();
preg_match_all($authParam, $headerValue, $params);
for ($i = 0; $i < count($params[0]); $i++) {
if ('"' == substr($params[2][$i], 0, 1)) {
$paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
} else {
$paramsAry[$params[1][$i]] = $params[2][$i];
}
}
// for now, just update the nonce value
if (!empty($paramsAry['nextnonce'])) {
$challenge['nonce'] = $paramsAry['nextnonce'];
$challenge['nc'] = 1;
}
}
/**
* Creates a value for [Proxy-]Authorization header when using digest authentication
*
* @param string user name
* @param string password
* @param string request URL
* @param array digest challenge parameters
* @return string value of [Proxy-]Authorization request header
* @link http://tools.ietf.org/html/rfc2617#section-3.2.2
*/
protected function createDigestResponse($user, $password, $url, &$challenge)
{
if (false !== ($q = strpos($url, '?')) &&
$this->request->getConfig('digest_compat_ie')
) {
$url = substr($url, 0, $q);
}
$a1 = md5($user . ':' . $challenge['realm'] . ':' . $password);
$a2 = md5($this->request->getMethod() . ':' . $url);
if (empty($challenge['qop'])) {
$digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $a2);
} else {
$challenge['cnonce'] = 'Req2.' . rand();
if (empty($challenge['nc'])) {
$challenge['nc'] = 1;
}
$nc = sprintf('%08x', $challenge['nc']++);
$digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $nc . ':' .
$challenge['cnonce'] . ':auth:' . $a2);
}
return 'Digest username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $user) . '", ' .
'realm="' . $challenge['realm'] . '", ' .
'nonce="' . $challenge['nonce'] . '", ' .
'uri="' . $url . '", ' .
'response="' . $digest . '"' .
(!empty($challenge['opaque'])?
', opaque="' . $challenge['opaque'] . '"':
'') .
(!empty($challenge['qop'])?
', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"':
'');
}
/**
* Adds 'Authorization' header (if needed) to request headers array
*
* @param array request headers
* @param string request host (needed for digest authentication)
* @param string request URL (needed for digest authentication)
* @throws HTTP_Request2_Exception
*/
protected function addAuthorizationHeader(&$headers, $requestHost, $requestUrl)
{
if (!($auth = $this->request->getAuth())) {
return;
}
switch ($auth['scheme']) {
case HTTP_Request2::AUTH_BASIC:
$headers['authorization'] =
'Basic ' . base64_encode($auth['user'] . ':' . $auth['password']);
break;
case HTTP_Request2::AUTH_DIGEST:
unset($this->serverChallenge);
$fullUrl = ('/' == $requestUrl[0])?
$this->request->getUrl()->getScheme() . '://' .
$requestHost . $requestUrl:
$requestUrl;
foreach (array_keys(self::$challenges) as $key) {
if ($key == substr($fullUrl, 0, strlen($key))) {
$headers['authorization'] = $this->createDigestResponse(
$auth['user'], $auth['password'],
$requestUrl, self::$challenges[$key]
);
$this->serverChallenge =& self::$challenges[$key];
break;
}
}
break;
default:
throw new HTTP_Request2_Exception(
"Unknown HTTP authentication scheme '{$auth['scheme']}'"
);
}
}
/**
* Adds 'Proxy-Authorization' header (if needed) to request headers array
*
* @param array request headers
* @param string request URL (needed for digest authentication)
* @throws HTTP_Request2_Exception
*/
protected function addProxyAuthorizationHeader(&$headers, $requestUrl)
{
if (!$this->request->getConfig('proxy_host') ||
!($user = $this->request->getConfig('proxy_user')) ||
(0 == strcasecmp('https', $this->request->getUrl()->getScheme()) &&
HTTP_Request2::METHOD_CONNECT != $this->request->getMethod())
) {
return;
}
$password = $this->request->getConfig('proxy_password');
switch ($this->request->getConfig('proxy_auth_scheme')) {
case HTTP_Request2::AUTH_BASIC:
$headers['proxy-authorization'] =
'Basic ' . base64_encode($user . ':' . $password);
break;
case HTTP_Request2::AUTH_DIGEST:
unset($this->proxyChallenge);
$proxyUrl = 'proxy://' . $this->request->getConfig('proxy_host') .
':' . $this->request->getConfig('proxy_port');
if (!empty(self::$challenges[$proxyUrl])) {
$headers['proxy-authorization'] = $this->createDigestResponse(
$user, $password,
$requestUrl, self::$challenges[$proxyUrl]
);
$this->proxyChallenge =& self::$challenges[$proxyUrl];
}
break;
default:
throw new HTTP_Request2_Exception(
"Unknown HTTP authentication scheme '" .
$this->request->getConfig('proxy_auth_scheme') . "'"
);
}
}
/**
* Creates the string with the Request-Line and request headers
*
* @return string
* @throws HTTP_Request2_Exception
*/
protected function prepareHeaders()
{
$headers = $this->request->getHeaders();
$url = $this->request->getUrl();
$connect = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
$host = $url->getHost();
$defaultPort = 0 == strcasecmp($url->getScheme(), 'https')? 443: 80;
if (($port = $url->getPort()) && $port != $defaultPort || $connect) {
$host .= ':' . (empty($port)? $defaultPort: $port);
}
// Do not overwrite explicitly set 'Host' header, see bug #16146
if (!isset($headers['host'])) {
$headers['host'] = $host;
}
if ($connect) {
$requestUrl = $host;
} else {
if (!$this->request->getConfig('proxy_host') ||
0 == strcasecmp($url->getScheme(), 'https')
) {
$requestUrl = '';
} else {
$requestUrl = $url->getScheme() . '://' . $host;
}
$path = $url->getPath();
$query = $url->getQuery();
$requestUrl .= (empty($path)? '/': $path) . (empty($query)? '': '?' . $query);
}
if ('1.1' == $this->request->getConfig('protocol_version') &&
extension_loaded('zlib') && !isset($headers['accept-encoding'])
) {
$headers['accept-encoding'] = 'gzip, deflate';
}
$this->addAuthorizationHeader($headers, $host, $requestUrl);
$this->addProxyAuthorizationHeader($headers, $requestUrl);
$this->calculateRequestLength($headers);
$headersStr = $this->request->getMethod() . ' ' . $requestUrl . ' HTTP/' .
$this->request->getConfig('protocol_version') . "\r\n";
foreach ($headers as $name => $value) {
$canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
$headersStr .= $canonicalName . ': ' . $value . "\r\n";
}
return $headersStr . "\r\n";
}
/**
* Sends the request body
*
* @throws HTTP_Request2_Exception
*/
protected function writeBody()
{
if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||
0 == $this->contentLength
) {
return;
}
$position = 0;
$bufferSize = $this->request->getConfig('buffer_size');
while ($position < $this->contentLength) {
if (is_string($this->requestBody)) {
$str = substr($this->requestBody, $position, $bufferSize);
} elseif (is_resource($this->requestBody)) {
$str = fread($this->requestBody, $bufferSize);
} else {
$str = $this->requestBody->read($bufferSize);
}
if (false === @fwrite($this->socket, $str, strlen($str))) {
throw new HTTP_Request2_Exception('Error writing request');
}
// Provide the length of written string to the observer, request #7630
$this->request->setLastEvent('sentBodyPart', strlen($str));
$position += strlen($str);
}
}
/**
* Reads the remote server's response
*
* @return HTTP_Request2_Response
* @throws HTTP_Request2_Exception
*/
protected function readResponse()
{
$bufferSize = $this->request->getConfig('buffer_size');
do {
$response = new HTTP_Request2_Response($this->readLine($bufferSize), true);
do {
$headerLine = $this->readLine($bufferSize);
$response->parseHeaderLine($headerLine);
} while ('' != $headerLine);
} while (in_array($response->getStatus(), array(100, 101)));
$this->request->setLastEvent('receivedHeaders', $response);
// No body possible in such responses
if (HTTP_Request2::METHOD_HEAD == $this->request->getMethod() ||
(HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&
200 <= $response->getStatus() && 300 > $response->getStatus()) ||
in_array($response->getStatus(), array(204, 304))
) {
return $response;
}
$chunked = 'chunked' == $response->getHeader('transfer-encoding');
$length = $response->getHeader('content-length');
$hasBody = false;
if ($chunked || null === $length || 0 < intval($length)) {
// RFC 2616, section 4.4:
// 3. ... If a message is received with both a
// Transfer-Encoding header field and a Content-Length header field,
// the latter MUST be ignored.
$toRead = ($chunked || null === $length)? null: $length;
$this->chunkLength = 0;
while (!feof($this->socket) && (is_null($toRead) || 0 < $toRead)) {
if ($chunked) {
$data = $this->readChunked($bufferSize);
} elseif (is_null($toRead)) {
$data = $this->fread($bufferSize);
} else {
$data = $this->fread(min($toRead, $bufferSize));
$toRead -= strlen($data);
}
if ('' == $data && (!$this->chunkLength || feof($this->socket))) {
break;
}
$hasBody = true;
if ($this->request->getConfig('store_body')) {
$response->appendBody($data);
}
if (!in_array($response->getHeader('content-encoding'), array('identity', null))) {
$this->request->setLastEvent('receivedEncodedBodyPart', $data);
} else {
$this->request->setLastEvent('receivedBodyPart', $data);
}
}
}
if ($hasBody) {
$this->request->setLastEvent('receivedBody', $response);
}
return $response;
}
/**
* Reads until either the end of the socket or a newline, whichever comes first
*
* Strips the trailing newline from the returned data, handles global
* request timeout. Method idea borrowed from Net_Socket PEAR package.
*
* @param int buffer size to use for reading
* @return Available data up to the newline (not including newline)
* @throws HTTP_Request2_Exception In case of timeout
*/
protected function readLine($bufferSize)
{
$line = '';
while (!feof($this->socket)) {
if ($this->deadline) {
stream_set_timeout($this->socket, max($this->deadline - time(), 1));
}
$line .= @fgets($this->socket, $bufferSize);
$info = stream_get_meta_data($this->socket);
if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
$reason = $this->deadline
? 'after ' . $this->request->getConfig('timeout') . ' second(s)'
: 'due to default_socket_timeout php.ini setting';
throw new HTTP_Request2_Exception("Request timed out {$reason}");
}
if (substr($line, -1) == "\n") {
return rtrim($line, "\r\n");
}
}
return $line;
}
/**
* Wrapper around fread(), handles global request timeout
*
* @param int Reads up to this number of bytes
* @return Data read from socket
* @throws HTTP_Request2_Exception In case of timeout
*/
protected function fread($length)
{
if ($this->deadline) {
stream_set_timeout($this->socket, max($this->deadline - time(), 1));
}
$data = fread($this->socket, $length);
$info = stream_get_meta_data($this->socket);
if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
$reason = $this->deadline
? 'after ' . $this->request->getConfig('timeout') . ' second(s)'
: 'due to default_socket_timeout php.ini setting';
throw new HTTP_Request2_Exception("Request timed out {$reason}");
}
return $data;
}
/**
* Reads a part of response body encoded with chunked Transfer-Encoding
*
* @param int buffer size to use for reading
* @return string
* @throws HTTP_Request2_Exception
*/
protected function readChunked($bufferSize)
{
// at start of the next chunk?
if (0 == $this->chunkLength) {
$line = $this->readLine($bufferSize);
if (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {
throw new HTTP_Request2_Exception(
"Cannot decode chunked response, invalid chunk length '{$line}'"
);
} else {
$this->chunkLength = hexdec($matches[1]);
// Chunk with zero length indicates the end
if (0 == $this->chunkLength) {
$this->readLine($bufferSize);
return '';
}
}
}
$data = $this->fread(min($this->chunkLength, $bufferSize));
$this->chunkLength -= strlen($data);
if (0 == $this->chunkLength) {
$this->readLine($bufferSize); // Trailing CRLF
}
return $data;
}
}
?>
\ No newline at end of file
<?php
/**
* Exception class for HTTP_Request2 package
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: Exception.php 290192 2009-11-03 21:29:32Z avb $
* @link http://pear.php.net/package/HTTP_Request2
*/
/**
* Base class for exceptions in PEAR
*/
require_once 'PEAR/Exception.php';
/**
* Exception class for HTTP_Request2 package
*
* Such a class is required by the Exception RFC:
* http://pear.php.net/pepr/pepr-proposal-show.php?id=132
*
* @category HTTP
* @package HTTP_Request2
* @version Release: 0.5.1
*/
class HTTP_Request2_Exception extends PEAR_Exception
{
}
?>
\ No newline at end of file
<?php
/**
* Helper class for building multipart/form-data request body
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: MultipartBody.php 290192 2009-11-03 21:29:32Z avb $
* @link http://pear.php.net/package/HTTP_Request2
*/
/**
* Class for building multipart/form-data request body
*
* The class helps to reduce memory consumption by streaming large file uploads
* from disk, it also allows monitoring of upload progress (see request #7630)
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @version Release: 0.5.1
* @link http://tools.ietf.org/html/rfc1867
*/
class HTTP_Request2_MultipartBody
{
/**
* MIME boundary
* @var string
*/
private $_boundary;
/**
* Form parameters added via {@link HTTP_Request2::addPostParameter()}
* @var array
*/
private $_params = array();
/**
* File uploads added via {@link HTTP_Request2::addUpload()}
* @var array
*/
private $_uploads = array();
/**
* Header for parts with parameters
* @var string
*/
private $_headerParam = "--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n";
/**
* Header for parts with uploads
* @var string
*/
private $_headerUpload = "--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n";
/**
* Current position in parameter and upload arrays
*
* First number is index of "current" part, second number is position within
* "current" part
*
* @var array
*/
private $_pos = array(0, 0);
/**
* Constructor. Sets the arrays with POST data.
*
* @param array values of form fields set via {@link HTTP_Request2::addPostParameter()}
* @param array file uploads set via {@link HTTP_Request2::addUpload()}
* @param bool whether to append brackets to array variable names
*/
public function __construct(array $params, array $uploads, $useBrackets = true)
{
$this->_params = self::_flattenArray('', $params, $useBrackets);
foreach ($uploads as $fieldName => $f) {
if (!is_array($f['fp'])) {
$this->_uploads[] = $f + array('name' => $fieldName);
} else {
for ($i = 0; $i < count($f['fp']); $i++) {
$upload = array(
'name' => ($useBrackets? $fieldName . '[' . $i . ']': $fieldName)
);
foreach (array('fp', 'filename', 'size', 'type') as $key) {
$upload[$key] = $f[$key][$i];
}
$this->_uploads[] = $upload;
}
}
}
}
/**
* Returns the length of the body to use in Content-Length header
*
* @return integer
*/
public function getLength()
{
$boundaryLength = strlen($this->getBoundary());
$headerParamLength = strlen($this->_headerParam) - 4 + $boundaryLength;
$headerUploadLength = strlen($this->_headerUpload) - 8 + $boundaryLength;
$length = $boundaryLength + 6;
foreach ($this->_params as $p) {
$length += $headerParamLength + strlen($p[0]) + strlen($p[1]) + 2;
}
foreach ($this->_uploads as $u) {
$length += $headerUploadLength + strlen($u['name']) + strlen($u['type']) +
strlen($u['filename']) + $u['size'] + 2;
}
return $length;
}
/**
* Returns the boundary to use in Content-Type header
*
* @return string
*/
public function getBoundary()
{
if (empty($this->_boundary)) {
$this->_boundary = '--' . md5('PEAR-HTTP_Request2-' . microtime());
}
return $this->_boundary;
}
/**
* Returns next chunk of request body
*
* @param integer Amount of bytes to read
* @return string Up to $length bytes of data, empty string if at end
*/
public function read($length)
{
$ret = '';
$boundary = $this->getBoundary();
$paramCount = count($this->_params);
$uploadCount = count($this->_uploads);
while ($length > 0 && $this->_pos[0] <= $paramCount + $uploadCount) {
$oldLength = $length;
if ($this->_pos[0] < $paramCount) {
$param = sprintf($this->_headerParam, $boundary,
$this->_params[$this->_pos[0]][0]) .
$this->_params[$this->_pos[0]][1] . "\r\n";
$ret .= substr($param, $this->_pos[1], $length);
$length -= min(strlen($param) - $this->_pos[1], $length);
} elseif ($this->_pos[0] < $paramCount + $uploadCount) {
$pos = $this->_pos[0] - $paramCount;
$header = sprintf($this->_headerUpload, $boundary,
$this->_uploads[$pos]['name'],
$this->_uploads[$pos]['filename'],
$this->_uploads[$pos]['type']);
if ($this->_pos[1] < strlen($header)) {
$ret .= substr($header, $this->_pos[1], $length);
$length -= min(strlen($header) - $this->_pos[1], $length);
}
$filePos = max(0, $this->_pos[1] - strlen($header));
if ($length > 0 && $filePos < $this->_uploads[$pos]['size']) {
$ret .= fread($this->_uploads[$pos]['fp'], $length);
$length -= min($length, $this->_uploads[$pos]['size'] - $filePos);
}
if ($length > 0) {
$start = $this->_pos[1] + ($oldLength - $length) -
strlen($header) - $this->_uploads[$pos]['size'];
$ret .= substr("\r\n", $start, $length);
$length -= min(2 - $start, $length);
}
} else {
$closing = '--' . $boundary . "--\r\n";
$ret .= substr($closing, $this->_pos[1], $length);
$length -= min(strlen($closing) - $this->_pos[1], $length);
}
if ($length > 0) {
$this->_pos = array($this->_pos[0] + 1, 0);
} else {
$this->_pos[1] += $oldLength;
}
}
return $ret;
}
/**
* Sets the current position to the start of the body
*
* This allows reusing the same body in another request
*/
public function rewind()
{
$this->_pos = array(0, 0);
foreach ($this->_uploads as $u) {
rewind($u['fp']);
}
}
/**
* Returns the body as string
*
* Note that it reads all file uploads into memory so it is a good idea not
* to use this method with large file uploads and rely on read() instead.
*
* @return string
*/
public function __toString()
{
$this->rewind();
return $this->read($this->getLength());
}
/**
* Helper function to change the (probably multidimensional) associative array
* into the simple one.
*
* @param string name for item
* @param mixed item's values
* @param bool whether to append [] to array variables' names
* @return array array with the following items: array('item name', 'item value');
*/
private static function _flattenArray($name, $values, $useBrackets)
{
if (!is_array($values)) {
return array(array($name, $values));
} else {
$ret = array();
foreach ($values as $k => $v) {
if (empty($name)) {
$newName = $k;
} elseif ($useBrackets) {
$newName = $name . '[' . $k . ']';
} else {
$newName = $name;
}
$ret = array_merge($ret, self::_flattenArray($newName, $v, $useBrackets));
}
return $ret;
}
}
}
?>
<?php
/**
* An observer useful for debugging / testing.
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTTP
* @package HTTP_Request2
* @author David Jean Louis <izi@php.net>
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: Log.php 290743 2009-11-14 13:27:49Z avb $
* @link http://pear.php.net/package/HTTP_Request2
*/
/**
* Exception class for HTTP_Request2 package
*/
require_once 'HTTP/Request2/Exception.php';
/**
* A debug observer useful for debugging / testing.
*
* This observer logs to a log target data corresponding to the various request
* and response events, it logs by default to php://output but can be configured
* to log to a file or via the PEAR Log package.
*
* A simple example:
* <code>
* require_once 'HTTP/Request2.php';
* require_once 'HTTP/Request2/Observer/Log.php';
*
* $request = new HTTP_Request2('http://www.example.com');
* $observer = new HTTP_Request2_Observer_Log();
* $request->attach($observer);
* $request->send();
* </code>
*
* A more complex example with PEAR Log:
* <code>
* require_once 'HTTP/Request2.php';
* require_once 'HTTP/Request2/Observer/Log.php';
* require_once 'Log.php';
*
* $request = new HTTP_Request2('http://www.example.com');
* // we want to log with PEAR log
* $observer = new HTTP_Request2_Observer_Log(Log::factory('console'));
*
* // we only want to log received headers
* $observer->events = array('receivedHeaders');
*
* $request->attach($observer);
* $request->send();
* </code>
*
* @category HTTP
* @package HTTP_Request2
* @author David Jean Louis <izi@php.net>
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version Release: 0.5.1
* @link http://pear.php.net/package/HTTP_Request2
*/
class HTTP_Request2_Observer_Log implements SplObserver
{
// properties {{{
/**
* The log target, it can be a a resource or a PEAR Log instance.
*
* @var resource|Log $target
*/
protected $target = null;
/**
* The events to log.
*
* @var array $events
*/
public $events = array(
'connect',
'sentHeaders',
'sentBodyPart',
'receivedHeaders',
'receivedBody',
'disconnect',
);
// }}}
// __construct() {{{
/**
* Constructor.
*
* @param mixed $target Can be a file path (default: php://output), a resource,
* or an instance of the PEAR Log class.
* @param array $events Array of events to listen to (default: all events)
*
* @return void
*/
public function __construct($target = 'php://output', array $events = array())
{
if (!empty($events)) {
$this->events = $events;
}
if (is_resource($target) || $target instanceof Log) {
$this->target = $target;
} elseif (false === ($this->target = @fopen($target, 'w'))) {
throw new HTTP_Request2_Exception("Unable to open '{$target}'");
}
}
// }}}
// update() {{{
/**
* Called when the request notifies us of an event.
*
* @param HTTP_Request2 $subject The HTTP_Request2 instance
*
* @return void
*/
public function update(SplSubject $subject)
{
$event = $subject->getLastEvent();
if (!in_array($event['name'], $this->events)) {
return;
}
switch ($event['name']) {
case 'connect':
$this->log('* Connected to ' . $event['data']);
break;
case 'sentHeaders':
$headers = explode("\r\n", $event['data']);
array_pop($headers);
foreach ($headers as $header) {
$this->log('> ' . $header);
}
break;
case 'sentBodyPart':
$this->log('> ' . $event['data'] . ' byte(s) sent');
break;
case 'receivedHeaders':
$this->log(sprintf('< HTTP/%s %s %s',
$event['data']->getVersion(),
$event['data']->getStatus(),
$event['data']->getReasonPhrase()));
$headers = $event['data']->getHeader();
foreach ($headers as $key => $val) {
$this->log('< ' . $key . ': ' . $val);
}
$this->log('< ');
break;
case 'receivedBody':
$this->log($event['data']->getBody());
break;
case 'disconnect':
$this->log('* Disconnected');
break;
}
}
// }}}
// log() {{{
/**
* Logs the given message to the configured target.
*
* @param string $message Message to display
*
* @return void
*/
protected function log($message)
{
if ($this->target instanceof Log) {
$this->target->debug($message);
} elseif (is_resource($this->target)) {
fwrite($this->target, $message . "\r\n");
}
}
// }}}
}
?>
\ No newline at end of file
<?php
/**
* Class representing a HTTP response
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The names of the authors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version SVN: $Id: Response.php 290520 2009-11-11 20:09:42Z avb $
* @link http://pear.php.net/package/HTTP_Request2
*/
/**
* Exception class for HTTP_Request2 package
*/
require_once 'HTTP/Request2/Exception.php';
/**
* Class representing a HTTP response
*
* The class is designed to be used in "streaming" scenario, building the
* response as it is being received:
* <code>
* $statusLine = read_status_line();
* $response = new HTTP_Request2_Response($statusLine);
* do {
* $headerLine = read_header_line();
* $response->parseHeaderLine($headerLine);
* } while ($headerLine != '');
*
* while ($chunk = read_body()) {
* $response->appendBody($chunk);
* }
*
* var_dump($response->getHeader(), $response->getCookies(), $response->getBody());
* </code>
*
*
* @category HTTP
* @package HTTP_Request2
* @author Alexey Borzov <avb@php.net>
* @version Release: 0.5.1
* @link http://tools.ietf.org/html/rfc2616#section-6
*/
class HTTP_Request2_Response
{
/**
* HTTP protocol version (e.g. 1.0, 1.1)
* @var string
*/
protected $version;
/**
* Status code
* @var integer
* @link http://tools.ietf.org/html/rfc2616#section-6.1.1
*/
protected $code;
/**
* Reason phrase
* @var string
* @link http://tools.ietf.org/html/rfc2616#section-6.1.1
*/
protected $reasonPhrase;
/**
* Associative array of response headers
* @var array
*/
protected $headers = array();
/**
* Cookies set in the response
* @var array
*/
protected $cookies = array();
/**
* Name of last header processed by parseHederLine()
*
* Used to handle the headers that span multiple lines
*
* @var string
*/
protected $lastHeader = null;
/**
* Response body
* @var string
*/
protected $body = '';
/**
* Whether the body is still encoded by Content-Encoding
*
* cURL provides the decoded body to the callback; if we are reading from
* socket the body is still gzipped / deflated
*
* @var bool
*/
protected $bodyEncoded;
/**
* Associative array of HTTP status code / reason phrase.
*
* @var array
* @link http://tools.ietf.org/html/rfc2616#section-10
*/
protected static $phrases = array(
// 1xx: Informational - Request received, continuing process
100 => 'Continue',
101 => 'Switching Protocols',
// 2xx: Success - The action was successfully received, understood and
// accepted
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
// 3xx: Redirection - Further action must be taken in order to complete
// the request
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found', // 1.1
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
// 4xx: Client Error - The request contains bad syntax or cannot be
// fulfilled
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',
// 5xx: Server Error - The server failed to fulfill an apparently
// valid request
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
509 => 'Bandwidth Limit Exceeded',
);
/**
* Constructor, parses the response status line
*
* @param string Response status line (e.g. "HTTP/1.1 200 OK")
* @param bool Whether body is still encoded by Content-Encoding
* @throws HTTP_Request2_Exception if status line is invalid according to spec
*/
public function __construct($statusLine, $bodyEncoded = true)
{
if (!preg_match('!^HTTP/(\d\.\d) (\d{3})(?: (.+))?!', $statusLine, $m)) {
throw new HTTP_Request2_Exception("Malformed response: {$statusLine}");
}
$this->version = $m[1];
$this->code = intval($m[2]);
if (!empty($m[3])) {
$this->reasonPhrase = trim($m[3]);
} elseif (!empty(self::$phrases[$this->code])) {
$this->reasonPhrase = self::$phrases[$this->code];
}
$this->bodyEncoded = (bool)$bodyEncoded;
}
/**
* Parses the line from HTTP response filling $headers array
*
* The method should be called after reading the line from socket or receiving
* it into cURL callback. Passing an empty string here indicates the end of
* response headers and triggers additional processing, so be sure to pass an
* empty string in the end.
*
* @param string Line from HTTP response
*/
public function parseHeaderLine($headerLine)
{
$headerLine = trim($headerLine, "\r\n");
// empty string signals the end of headers, process the received ones
if ('' == $headerLine) {
if (!empty($this->headers['set-cookie'])) {
$cookies = is_array($this->headers['set-cookie'])?
$this->headers['set-cookie']:
array($this->headers['set-cookie']);
foreach ($cookies as $cookieString) {
$this->parseCookie($cookieString);
}
unset($this->headers['set-cookie']);
}
foreach (array_keys($this->headers) as $k) {
if (is_array($this->headers[$k])) {
$this->headers[$k] = implode(', ', $this->headers[$k]);
}
}
// string of the form header-name: header value
} elseif (preg_match('!^([^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+):(.+)$!', $headerLine, $m)) {
$name = strtolower($m[1]);
$value = trim($m[2]);
if (empty($this->headers[$name])) {
$this->headers[$name] = $value;
} else {
if (!is_array($this->headers[$name])) {
$this->headers[$name] = array($this->headers[$name]);
}
$this->headers[$name][] = $value;
}
$this->lastHeader = $name;
// continuation of a previous header
} elseif (preg_match('!^\s+(.+)$!', $headerLine, $m) && $this->lastHeader) {
if (!is_array($this->headers[$this->lastHeader])) {
$this->headers[$this->lastHeader] .= ' ' . trim($m[1]);
} else {
$key = count($this->headers[$this->lastHeader]) - 1;
$this->headers[$this->lastHeader][$key] .= ' ' . trim($m[1]);
}
}
}
/**
* Parses a Set-Cookie header to fill $cookies array
*
* @param string value of Set-Cookie header
* @link http://web.archive.org/web/20080331104521/http://cgi.netscape.com/newsref/std/cookie_spec.html
*/
protected function parseCookie($cookieString)
{
$cookie = array(
'expires' => null,
'domain' => null,
'path' => null,
'secure' => false
);
// Only a name=value pair
if (!strpos($cookieString, ';')) {
$pos = strpos($cookieString, '=');
$cookie['name'] = trim(substr($cookieString, 0, $pos));
$cookie['value'] = trim(substr($cookieString, $pos + 1));
// Some optional parameters are supplied
} else {
$elements = explode(';', $cookieString);
$pos = strpos($elements[0], '=');
$cookie['name'] = trim(substr($elements[0], 0, $pos));
$cookie['value'] = trim(substr($elements[0], $pos + 1));
for ($i = 1; $i < count($elements); $i++) {
if (false === strpos($elements[$i], '=')) {
$elName = trim($elements[$i]);
$elValue = null;
} else {
list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));
}
$elName = strtolower($elName);
if ('secure' == $elName) {
$cookie['secure'] = true;
} elseif ('expires' == $elName) {
$cookie['expires'] = str_replace('"', '', $elValue);
} elseif ('path' == $elName || 'domain' == $elName) {
$cookie[$elName] = urldecode($elValue);
} else {
$cookie[$elName] = $elValue;
}
}
}
$this->cookies[] = $cookie;
}
/**
* Appends a string to the response body
* @param string
*/
public function appendBody($bodyChunk)
{
$this->body .= $bodyChunk;
}
/**
* Returns the status code
* @return integer
*/
public function getStatus()
{
return $this->code;
}
/**
* Returns the reason phrase
* @return string
*/
public function getReasonPhrase()
{
return $this->reasonPhrase;
}
/**
* Whether response is a redirect that can be automatically handled by HTTP_Request2
* @return bool
*/
public function isRedirect()
{
return in_array($this->code, array(300, 301, 302, 303, 307))
&& isset($this->headers['location']);
}
/**
* Returns either the named header or all response headers
*
* @param string Name of header to return
* @return string|array Value of $headerName header (null if header is
* not present), array of all response headers if
* $headerName is null
*/
public function getHeader($headerName = null)
{
if (null === $headerName) {
return $this->headers;
} else {
$headerName = strtolower($headerName);
return isset($this->headers[$headerName])? $this->headers[$headerName]: null;
}
}
/**
* Returns cookies set in response
*
* @return array
*/
public function getCookies()
{
return $this->cookies;
}
/**
* Returns the body of the response
*
* @return string
* @throws HTTP_Request2_Exception if body cannot be decoded
*/
public function getBody()
{
if (!$this->bodyEncoded ||
!in_array(strtolower($this->getHeader('content-encoding')), array('gzip', 'deflate'))
) {
return $this->body;
} else {
if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {
$oldEncoding = mb_internal_encoding();
mb_internal_encoding('iso-8859-1');
}
try {
switch (strtolower($this->getHeader('content-encoding'))) {
case 'gzip':
$decoded = self::decodeGzip($this->body);
break;
case 'deflate':
$decoded = self::decodeDeflate($this->body);
}
} catch (Exception $e) {
}
if (!empty($oldEncoding)) {
mb_internal_encoding($oldEncoding);
}
if (!empty($e)) {
throw $e;
}
return $decoded;
}
}
/**
* Get the HTTP version of the response
*
* @return string
*/
public function getVersion()
{
return $this->version;
}
/**
* Decodes the message-body encoded by gzip
*
* The real decoding work is done by gzinflate() built-in function, this
* method only parses the header and checks data for compliance with
* RFC 1952
*
* @param string gzip-encoded data
* @return string decoded data
* @throws HTTP_Request2_Exception
* @link http://tools.ietf.org/html/rfc1952
*/
public static function decodeGzip($data)
{
$length = strlen($data);
// If it doesn't look like gzip-encoded data, don't bother
if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) {
return $data;
}
if (!function_exists('gzinflate')) {
throw new HTTP_Request2_Exception('Unable to decode body: gzip extension not available');
}
$method = ord(substr($data, 2, 1));
if (8 != $method) {
throw new HTTP_Request2_Exception('Error parsing gzip header: unknown compression method');
}
$flags = ord(substr($data, 3, 1));
if ($flags & 224) {
throw new HTTP_Request2_Exception('Error parsing gzip header: reserved bits are set');
}
// header is 10 bytes minimum. may be longer, though.
$headerLength = 10;
// extra fields, need to skip 'em
if ($flags & 4) {
if ($length - $headerLength - 2 < 8) {
throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');
}
$extraLength = unpack('v', substr($data, 10, 2));
if ($length - $headerLength - 2 - $extraLength[1] < 8) {
throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');
}
$headerLength += $extraLength[1] + 2;
}
// file name, need to skip that
if ($flags & 8) {
if ($length - $headerLength - 1 < 8) {
throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');
}
$filenameLength = strpos(substr($data, $headerLength), chr(0));
if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) {
throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');
}
$headerLength += $filenameLength + 1;
}
// comment, need to skip that also
if ($flags & 16) {
if ($length - $headerLength - 1 < 8) {
throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');
}
$commentLength = strpos(substr($data, $headerLength), chr(0));
if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) {
throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');
}
$headerLength += $commentLength + 1;
}
// have a CRC for header. let's check
if ($flags & 2) {
if ($length - $headerLength - 2 < 8) {
throw new HTTP_Request2_Exception('Error parsing gzip header: data too short');
}
$crcReal = 0xffff & crc32(substr($data, 0, $headerLength));
$crcStored = unpack('v', substr($data, $headerLength, 2));
if ($crcReal != $crcStored[1]) {
throw new HTTP_Request2_Exception('Header CRC check failed');
}
$headerLength += 2;
}
// unpacked data CRC and size at the end of encoded data
$tmp = unpack('V2', substr($data, -8));
$dataCrc = $tmp[1];
$dataSize = $tmp[2];
// finally, call the gzinflate() function
// don't pass $dataSize to gzinflate, see bugs #13135, #14370
$unpacked = gzinflate(substr($data, $headerLength, -8));
if (false === $unpacked) {
throw new HTTP_Request2_Exception('gzinflate() call failed');
} elseif ($dataSize != strlen($unpacked)) {
throw new HTTP_Request2_Exception('Data size check failed');
} elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {
throw new HTTP_Request2_Exception('Data CRC check failed');
}
return $unpacked;
}
/**
* Decodes the message-body encoded by deflate
*
* @param string deflate-encoded data
* @return string decoded data
* @throws HTTP_Request2_Exception
*/
public static function decodeDeflate($data)
{
if (!function_exists('gzuncompress')) {
throw new HTTP_Request2_Exception('Unable to decode body: gzip extension not available');
}
// RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950,
// while many applications send raw deflate stream from RFC 1951.
// We should check for presence of zlib header and use gzuncompress() or
// gzinflate() as needed. See bug #15305
$header = unpack('n', substr($data, 0, 2));
return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);
}
}
?>
\ No newline at end of file
<?php
/**
* Net_URL2, a class representing a URL as per RFC 3986.
*
* PHP version 5
*
* LICENSE:
*
* Copyright (c) 2007-2009, Peytz & Co. A/S
* 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 Net_URL2 nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category Networking
* @package Net_URL2
* @author Christian Schmidt <schmidt@php.net>
* @copyright 2007-2009 Peytz & Co. A/S
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id: URL2.php 290036 2009-10-28 19:52:49Z schmidt $
* @link http://www.rfc-editor.org/rfc/rfc3986.txt
*/
/**
* Represents a URL as per RFC 3986.
*
* @category Networking
* @package Net_URL2
* @author Christian Schmidt <schmidt@php.net>
* @copyright 2007-2009 Peytz & Co. A/S
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @version Release: @package_version@
* @link http://pear.php.net/package/Net_URL2
*/
class Net_URL2
{
/**
* Do strict parsing in resolve() (see RFC 3986, section 5.2.2). Default
* is true.
*/
const OPTION_STRICT = 'strict';
/**
* Represent arrays in query using PHP's [] notation. Default is true.
*/
const OPTION_USE_BRACKETS = 'use_brackets';
/**
* URL-encode query variable keys. Default is true.
*/
const OPTION_ENCODE_KEYS = 'encode_keys';
/**
* Query variable separators when parsing the query string. Every character
* is considered a separator. Default is "&".
*/
const OPTION_SEPARATOR_INPUT = 'input_separator';
/**
* Query variable separator used when generating the query string. Default
* is "&".
*/
const OPTION_SEPARATOR_OUTPUT = 'output_separator';
/**
* Default options corresponds to how PHP handles $_GET.
*/
private $_options = array(
self::OPTION_STRICT => true,
self::OPTION_USE_BRACKETS => true,
self::OPTION_ENCODE_KEYS => true,
self::OPTION_SEPARATOR_INPUT => '&',
self::OPTION_SEPARATOR_OUTPUT => '&',
);
/**
* @var string|bool
*/
private $_scheme = false;
/**
* @var string|bool
*/
private $_userinfo = false;
/**
* @var string|bool
*/
private $_host = false;
/**
* @var string|bool
*/
private $_port = false;
/**
* @var string
*/
private $_path = '';
/**
* @var string|bool
*/
private $_query = false;
/**
* @var string|bool
*/
private $_fragment = false;
/**
* Constructor.
*
* @param string $url an absolute or relative URL
* @param array $options an array of OPTION_xxx constants
*/
public function __construct($url, array $options = array())
{
foreach ($options as $optionName => $value) {
if (array_key_exists($optionName, $this->_options)) {
$this->_options[$optionName] = $value;
}
}
// The regular expression is copied verbatim from RFC 3986, appendix B.
// The expression does not validate the URL but matches any string.
preg_match('!^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?!',
$url,
$matches);
// "path" is always present (possibly as an empty string); the rest
// are optional.
$this->_scheme = !empty($matches[1]) ? $matches[2] : false;
$this->setAuthority(!empty($matches[3]) ? $matches[4] : false);
$this->_path = $matches[5];
$this->_query = !empty($matches[6]) ? $matches[7] : false;
$this->_fragment = !empty($matches[8]) ? $matches[9] : false;
}
/**
* Magic Setter.
*
* This method will magically set the value of a private variable ($var)
* with the value passed as the args
*
* @param string $var The private variable to set.
* @param mixed $arg An argument of any type.
* @return void
*/
public function __set($var, $arg)
{
$method = 'set' . $var;
if (method_exists($this, $method)) {
$this->$method($arg);
}
}
/**
* Magic Getter.
*
* This is the magic get method to retrieve the private variable
* that was set by either __set() or it's setter...
*
* @param string $var The property name to retrieve.
* @return mixed $this->$var Either a boolean false if the
* property is not set or the value
* of the private property.
*/
public function __get($var)
{
$method = 'get' . $var;
if (method_exists($this, $method)) {
return $this->$method();
}
return false;
}
/**
* Returns the scheme, e.g. "http" or "urn", or false if there is no
* scheme specified, i.e. if this is a relative URL.
*
* @return string|bool
*/
public function getScheme()
{
return $this->_scheme;
}
/**
* Sets the scheme, e.g. "http" or "urn". Specify false if there is no
* scheme specified, i.e. if this is a relative URL.
*
* @param string|bool $scheme e.g. "http" or "urn", or false if there is no
* scheme specified, i.e. if this is a relative
* URL
*
* @return void
* @see getScheme()
*/
public function setScheme($scheme)
{
$this->_scheme = $scheme;
}
/**
* Returns the user part of the userinfo part (the part preceding the first
* ":"), or false if there is no userinfo part.
*
* @return string|bool
*/
public function getUser()
{
return $this->_userinfo !== false
? preg_replace('@:.*$@', '', $this->_userinfo)
: false;
}
/**
* Returns the password part of the userinfo part (the part after the first
* ":"), or false if there is no userinfo part (i.e. the URL does not
* contain "@" in front of the hostname) or the userinfo part does not
* contain ":".
*
* @return string|bool
*/
public function getPassword()
{
return $this->_userinfo !== false
? substr(strstr($this->_userinfo, ':'), 1)
: false;
}
/**
* Returns the userinfo part, or false if there is none, i.e. if the
* authority part does not contain "@".
*
* @return string|bool
*/
public function getUserinfo()
{
return $this->_userinfo;
}
/**
* Sets the userinfo part. If two arguments are passed, they are combined
* in the userinfo part as username ":" password.
*
* @param string|bool $userinfo userinfo or username
* @param string|bool $password optional password, or false
*
* @return void
*/
public function setUserinfo($userinfo, $password = false)
{
$this->_userinfo = $userinfo;
if ($password !== false) {
$this->_userinfo .= ':' . $password;
}
}
/**
* Returns the host part, or false if there is no authority part, e.g.
* relative URLs.
*
* @return string|bool a hostname, an IP address, or false
*/
public function getHost()
{
return $this->_host;
}
/**
* Sets the host part. Specify false if there is no authority part, e.g.
* relative URLs.
*
* @param string|bool $host a hostname, an IP address, or false
*
* @return void
*/
public function setHost($host)
{
$this->_host = $host;
}
/**
* Returns the port number, or false if there is no port number specified,
* i.e. if the default port is to be used.
*
* @return string|bool
*/
public function getPort()
{
return $this->_port;
}
/**
* Sets the port number. Specify false if there is no port number specified,
* i.e. if the default port is to be used.
*
* @param string|bool $port a port number, or false
*
* @return void
*/
public function setPort($port)
{
$this->_port = $port;
}
/**
* Returns the authority part, i.e. [ userinfo "@" ] host [ ":" port ], or
* false if there is no authority.
*
* @return string|bool
*/
public function getAuthority()
{
if (!$this->_host) {
return false;
}
$authority = '';
if ($this->_userinfo !== false) {
$authority .= $this->_userinfo . '@';
}
$authority .= $this->_host;
if ($this->_port !== false) {
$authority .= ':' . $this->_port;
}
return $authority;
}
/**
* Sets the authority part, i.e. [ userinfo "@" ] host [ ":" port ]. Specify
* false if there is no authority.
*
* @param string|false $authority a hostname or an IP addresse, possibly
* with userinfo prefixed and port number
* appended, e.g. "foo:bar@example.org:81".
*
* @return void
*/
public function setAuthority($authority)
{
$this->_userinfo = false;
$this->_host = false;
$this->_port = false;
if (preg_match('@^(([^\@]*)\@)?([^:]+)(:(\d*))?$@', $authority, $reg)) {
if ($reg[1]) {
$this->_userinfo = $reg[2];
}
$this->_host = $reg[3];
if (isset($reg[5])) {
$this->_port = $reg[5];
}
}
}
/**
* Returns the path part (possibly an empty string).
*
* @return string
*/
public function getPath()
{
return $this->_path;
}
/**
* Sets the path part (possibly an empty string).
*
* @param string $path a path
*
* @return void
*/
public function setPath($path)
{
$this->_path = $path;
}
/**
* Returns the query string (excluding the leading "?"), or false if "?"
* is not present in the URL.
*
* @return string|bool
* @see self::getQueryVariables()
*/
public function getQuery()
{
return $this->_query;
}
/**
* Sets the query string (excluding the leading "?"). Specify false if "?"
* is not present in the URL.
*
* @param string|bool $query a query string, e.g. "foo=1&bar=2"
*
* @return void
* @see self::setQueryVariables()
*/
public function setQuery($query)
{
$this->_query = $query;
}
/**
* Returns the fragment name, or false if "#" is not present in the URL.
*
* @return string|bool
*/
public function getFragment()
{
return $this->_fragment;
}
/**
* Sets the fragment name. Specify false if "#" is not present in the URL.
*
* @param string|bool $fragment a fragment excluding the leading "#", or
* false
*
* @return void
*/
public function setFragment($fragment)
{
$this->_fragment = $fragment;
}
/**
* Returns the query string like an array as the variables would appear in
* $_GET in a PHP script. If the URL does not contain a "?", an empty array
* is returned.
*
* @return array
*/
public function getQueryVariables()
{
$pattern = '/[' .
preg_quote($this->getOption(self::OPTION_SEPARATOR_INPUT), '/') .
']/';
$parts = preg_split($pattern, $this->_query, -1, PREG_SPLIT_NO_EMPTY);
$return = array();
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
list($key, $value) = explode('=', $part, 2);
} else {
$key = $part;
$value = null;
}
if ($this->getOption(self::OPTION_ENCODE_KEYS)) {
$key = rawurldecode($key);
}
$value = rawurldecode($value);
if ($this->getOption(self::OPTION_USE_BRACKETS) &&
preg_match('#^(.*)\[([0-9a-z_-]*)\]#i', $key, $matches)) {
$key = $matches[1];
$idx = $matches[2];
// Ensure is an array
if (empty($return[$key]) || !is_array($return[$key])) {
$return[$key] = array();
}
// Add data
if ($idx === '') {
$return[$key][] = $value;
} else {
$return[$key][$idx] = $value;
}
} elseif (!$this->getOption(self::OPTION_USE_BRACKETS)
&& !empty($return[$key])
) {
$return[$key] = (array) $return[$key];
$return[$key][] = $value;
} else {
$return[$key] = $value;
}
}
return $return;
}
/**
* Sets the query string to the specified variable in the query string.
*
* @param array $array (name => value) array
*
* @return void
*/
public function setQueryVariables(array $array)
{
if (!$array) {
$this->_query = false;
} else {
foreach ($array as $name => $value) {
if ($this->getOption(self::OPTION_ENCODE_KEYS)) {
$name = self::urlencode($name);
}
if (is_array($value)) {
foreach ($value as $k => $v) {
$parts[] = $this->getOption(self::OPTION_USE_BRACKETS)
? sprintf('%s[%s]=%s', $name, $k, $v)
: ($name . '=' . $v);
}
} elseif (!is_null($value)) {
$parts[] = $name . '=' . self::urlencode($value);
} else {
$parts[] = $name;
}
}
$this->_query = implode($this->getOption(self::OPTION_SEPARATOR_OUTPUT),
$parts);
}
}
/**
* Sets the specified variable in the query string.
*
* @param string $name variable name
* @param mixed $value variable value
*
* @return array
*/
public function setQueryVariable($name, $value)
{
$array = $this->getQueryVariables();
$array[$name] = $value;
$this->setQueryVariables($array);
}
/**
* Removes the specifed variable from the query string.
*
* @param string $name a query string variable, e.g. "foo" in "?foo=1"
*
* @return void
*/
public function unsetQueryVariable($name)
{
$array = $this->getQueryVariables();
unset($array[$name]);
$this->setQueryVariables($array);
}
/**
* Returns a string representation of this URL.
*
* @return string
*/
public function getURL()
{
// See RFC 3986, section 5.3
$url = "";
if ($this->_scheme !== false) {
$url .= $this->_scheme . ':';
}
$authority = $this->getAuthority();
if ($authority !== false) {
$url .= '//' . $authority;
}
$url .= $this->_path;
if ($this->_query !== false) {
$url .= '?' . $this->_query;
}
if ($this->_fragment !== false) {
$url .= '#' . $this->_fragment;
}
return $url;
}
/**
* Returns a string representation of this URL.
*
* @return string
* @see toString()
*/
public function __toString()
{
return $this->getURL();
}
/**
* Returns a normalized string representation of this URL. This is useful
* for comparison of URLs.
*
* @return string
*/
public function getNormalizedURL()
{
$url = clone $this;
$url->normalize();
return $url->getUrl();
}
/**
* Returns a normalized Net_URL2 instance.
*
* @return Net_URL2
*/
public function normalize()
{
// See RFC 3886, section 6
// Schemes are case-insensitive
if ($this->_scheme) {
$this->_scheme = strtolower($this->_scheme);
}
// Hostnames are case-insensitive
if ($this->_host) {
$this->_host = strtolower($this->_host);
}
// Remove default port number for known schemes (RFC 3986, section 6.2.3)
if ($this->_port &&
$this->_scheme &&
$this->_port == getservbyname($this->_scheme, 'tcp')) {
$this->_port = false;
}
// Normalize case of %XX percentage-encodings (RFC 3986, section 6.2.2.1)
foreach (array('_userinfo', '_host', '_path') as $part) {
if ($this->$part) {
$this->$part = preg_replace('/%[0-9a-f]{2}/ie',
'strtoupper("\0")',
$this->$part);
}
}
// Path segment normalization (RFC 3986, section 6.2.2.3)
$this->_path = self::removeDotSegments($this->_path);
// Scheme based normalization (RFC 3986, section 6.2.3)
if ($this->_host && !$this->_path) {
$this->_path = '/';
}
}
/**
* Returns whether this instance represents an absolute URL.
*
* @return bool
*/
public function isAbsolute()
{
return (bool) $this->_scheme;
}
/**
* Returns an Net_URL2 instance representing an absolute URL relative to
* this URL.
*
* @param Net_URL2|string $reference relative URL
*
* @return Net_URL2
*/
public function resolve($reference)
{
if (!$reference instanceof Net_URL2) {
$reference = new self($reference);
}
if (!$this->isAbsolute()) {
throw new Exception('Base-URL must be absolute');
}
// A non-strict parser may ignore a scheme in the reference if it is
// identical to the base URI's scheme.
if (!$this->getOption(self::OPTION_STRICT) && $reference->_scheme == $this->_scheme) {
$reference->_scheme = false;
}
$target = new self('');
if ($reference->_scheme !== false) {
$target->_scheme = $reference->_scheme;
$target->setAuthority($reference->getAuthority());
$target->_path = self::removeDotSegments($reference->_path);
$target->_query = $reference->_query;
} else {
$authority = $reference->getAuthority();
if ($authority !== false) {
$target->setAuthority($authority);
$target->_path = self::removeDotSegments($reference->_path);
$target->_query = $reference->_query;
} else {
if ($reference->_path == '') {
$target->_path = $this->_path;
if ($reference->_query !== false) {
$target->_query = $reference->_query;
} else {
$target->_query = $this->_query;
}
} else {
if (substr($reference->_path, 0, 1) == '/') {
$target->_path = self::removeDotSegments($reference->_path);
} else {
// Merge paths (RFC 3986, section 5.2.3)
if ($this->_host !== false && $this->_path == '') {
$target->_path = '/' . $this->_path;
} else {
$i = strrpos($this->_path, '/');
if ($i !== false) {
$target->_path = substr($this->_path, 0, $i + 1);
}
$target->_path .= $reference->_path;
}
$target->_path = self::removeDotSegments($target->_path);
}
$target->_query = $reference->_query;
}
$target->setAuthority($this->getAuthority());
}
$target->_scheme = $this->_scheme;
}
$target->_fragment = $reference->_fragment;
return $target;
}
/**
* Removes dots as described in RFC 3986, section 5.2.4, e.g.
* "/foo/../bar/baz" => "/bar/baz"
*
* @param string $path a path
*
* @return string a path
*/
public static function removeDotSegments($path)
{
$output = '';
// Make sure not to be trapped in an infinite loop due to a bug in this
// method
$j = 0;
while ($path && $j++ < 100) {
if (substr($path, 0, 2) == './') {
// Step 2.A
$path = substr($path, 2);
} elseif (substr($path, 0, 3) == '../') {
// Step 2.A
$path = substr($path, 3);
} elseif (substr($path, 0, 3) == '/./' || $path == '/.') {
// Step 2.B
$path = '/' . substr($path, 3);
} elseif (substr($path, 0, 4) == '/../' || $path == '/..') {
// Step 2.C
$path = '/' . substr($path, 4);
$i = strrpos($output, '/');
$output = $i === false ? '' : substr($output, 0, $i);
} elseif ($path == '.' || $path == '..') {
// Step 2.D
$path = '';
} else {
// Step 2.E
$i = strpos($path, '/');
if ($i === 0) {
$i = strpos($path, '/', 1);
}
if ($i === false) {
$i = strlen($path);
}
$output .= substr($path, 0, $i);
$path = substr($path, $i);
}
}
return $output;
}
/**
* Percent-encodes all non-alphanumeric characters except these: _ . - ~
* Similar to PHP's rawurlencode(), except that it also encodes ~ in PHP
* 5.2.x and earlier.
*
* @param $raw the string to encode
* @return string
*/
public static function urlencode($string)
{
$encoded = rawurlencode($string);
// This is only necessary in PHP < 5.3.
$encoded = str_replace('%7E', '~', $encoded);
return $encoded;
}
/**
* Returns a Net_URL2 instance representing the canonical URL of the
* currently executing PHP script.
*
* @return string
*/
public static function getCanonical()
{
if (!isset($_SERVER['REQUEST_METHOD'])) {
// ALERT - no current URL
throw new Exception('Script was not called through a webserver');
}
// Begin with a relative URL
$url = new self($_SERVER['PHP_SELF']);
$url->_scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http';
$url->_host = $_SERVER['SERVER_NAME'];
$port = $_SERVER['SERVER_PORT'];
if ($url->_scheme == 'http' && $port != 80 ||
$url->_scheme == 'https' && $port != 443) {
$url->_port = $port;
}
return $url;
}
/**
* Returns the URL used to retrieve the current request.
*
* @return string
*/
public static function getRequestedURL()
{
return self::getRequested()->getUrl();
}
/**
* Returns a Net_URL2 instance representing the URL used to retrieve the
* current request.
*
* @return Net_URL2
*/
public static function getRequested()
{
if (!isset($_SERVER['REQUEST_METHOD'])) {
// ALERT - no current URL
throw new Exception('Script was not called through a webserver');
}
// Begin with a relative URL
$url = new self($_SERVER['REQUEST_URI']);
$url->_scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http';
// Set host and possibly port
$url->setAuthority($_SERVER['HTTP_HOST']);
return $url;
}
/**
* Returns the value of the specified option.
*
* @param string $optionName The name of the option to retrieve
*
* @return mixed
*/
function getOption($optionName)
{
return isset($this->_options[$optionName])
? $this->_options[$optionName] : false;
}
}
<?php
/**
* The OS_Guess class
*
* PHP versions 4 and 5
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Gregory Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id: Guess.php 278521 2009-04-09 22:24:12Z dufuz $
* @link http://pear.php.net/package/PEAR
* @since File available since PEAR 0.1
*/
// {{{ uname examples
// php_uname() without args returns the same as 'uname -a', or a PHP-custom
// string for Windows.
// PHP versions prior to 4.3 return the uname of the host where PHP was built,
// as of 4.3 it returns the uname of the host running the PHP code.
//
// PC RedHat Linux 7.1:
// Linux host.example.com 2.4.2-2 #1 Sun Apr 8 20:41:30 EDT 2001 i686 unknown
//
// PC Debian Potato:
// Linux host 2.4.17 #2 SMP Tue Feb 12 15:10:04 CET 2002 i686 unknown
//
// PC FreeBSD 3.3:
// FreeBSD host.example.com 3.3-STABLE FreeBSD 3.3-STABLE #0: Mon Feb 21 00:42:31 CET 2000 root@example.com:/usr/src/sys/compile/CONFIG i386
//
// PC FreeBSD 4.3:
// FreeBSD host.example.com 4.3-RELEASE FreeBSD 4.3-RELEASE #1: Mon Jun 25 11:19:43 EDT 2001 root@example.com:/usr/src/sys/compile/CONFIG i386
//
// PC FreeBSD 4.5:
// FreeBSD host.example.com 4.5-STABLE FreeBSD 4.5-STABLE #0: Wed Feb 6 23:59:23 CET 2002 root@example.com:/usr/src/sys/compile/CONFIG i386
//
// PC FreeBSD 4.5 w/uname from GNU shellutils:
// FreeBSD host.example.com 4.5-STABLE FreeBSD 4.5-STABLE #0: Wed Feb i386 unknown
//
// HP 9000/712 HP-UX 10:
// HP-UX iq B.10.10 A 9000/712 2008429113 two-user license
//
// HP 9000/712 HP-UX 10 w/uname from GNU shellutils:
// HP-UX host B.10.10 A 9000/712 unknown
//
// IBM RS6000/550 AIX 4.3:
// AIX host 3 4 000003531C00
//
// AIX 4.3 w/uname from GNU shellutils:
// AIX host 3 4 000003531C00 unknown
//
// SGI Onyx IRIX 6.5 w/uname from GNU shellutils:
// IRIX64 host 6.5 01091820 IP19 mips
//
// SGI Onyx IRIX 6.5:
// IRIX64 host 6.5 01091820 IP19
//
// SparcStation 20 Solaris 8 w/uname from GNU shellutils:
// SunOS host.example.com 5.8 Generic_108528-12 sun4m sparc
//
// SparcStation 20 Solaris 8:
// SunOS host.example.com 5.8 Generic_108528-12 sun4m sparc SUNW,SPARCstation-20
//
// Mac OS X (Darwin)
// Darwin home-eden.local 7.5.0 Darwin Kernel Version 7.5.0: Thu Aug 5 19:26:16 PDT 2004; root:xnu/xnu-517.7.21.obj~3/RELEASE_PPC Power Macintosh
//
// Mac OS X early versions
//
// }}}
/* TODO:
* - define endianness, to allow matchSignature("bigend") etc.
*/
/**
* Retrieves information about the current operating system
*
* This class uses php_uname() to grok information about the current OS
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Gregory Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version Release: 1.9.0
* @link http://pear.php.net/package/PEAR
* @since Class available since Release 0.1
*/
class OS_Guess
{
var $sysname;
var $nodename;
var $cpu;
var $release;
var $extra;
function OS_Guess($uname = null)
{
list($this->sysname,
$this->release,
$this->cpu,
$this->extra,
$this->nodename) = $this->parseSignature($uname);
}
function parseSignature($uname = null)
{
static $sysmap = array(
'HP-UX' => 'hpux',
'IRIX64' => 'irix',
);
static $cpumap = array(
'i586' => 'i386',
'i686' => 'i386',
'ppc' => 'powerpc',
);
if ($uname === null) {
$uname = php_uname();
}
$parts = preg_split('/\s+/', trim($uname));
$n = count($parts);
$release = $machine = $cpu = '';
$sysname = $parts[0];
$nodename = $parts[1];
$cpu = $parts[$n-1];
$extra = '';
if ($cpu == 'unknown') {
$cpu = $parts[$n - 2];
}
switch ($sysname) {
case 'AIX' :
$release = "$parts[3].$parts[2]";
break;
case 'Windows' :
switch ($parts[1]) {
case '95/98':
$release = '9x';
break;
default:
$release = $parts[1];
break;
}
$cpu = 'i386';
break;
case 'Linux' :
$extra = $this->_detectGlibcVersion();
// use only the first two digits from the kernel version
$release = preg_replace('/^([0-9]+\.[0-9]+).*/', '\1', $parts[2]);
break;
case 'Mac' :
$sysname = 'darwin';
$nodename = $parts[2];
$release = $parts[3];
if ($cpu == 'Macintosh') {
if ($parts[$n - 2] == 'Power') {
$cpu = 'powerpc';
}
}
break;
case 'Darwin' :
if ($cpu == 'Macintosh') {
if ($parts[$n - 2] == 'Power') {
$cpu = 'powerpc';
}
}
$release = preg_replace('/^([0-9]+\.[0-9]+).*/', '\1', $parts[2]);
break;
default:
$release = preg_replace('/-.*/', '', $parts[2]);
break;
}
if (isset($sysmap[$sysname])) {
$sysname = $sysmap[$sysname];
} else {
$sysname = strtolower($sysname);
}
if (isset($cpumap[$cpu])) {
$cpu = $cpumap[$cpu];
}
return array($sysname, $release, $cpu, $extra, $nodename);
}
function _detectGlibcVersion()
{
static $glibc = false;
if ($glibc !== false) {
return $glibc; // no need to run this multiple times
}
$major = $minor = 0;
include_once "System.php";
// Use glibc's <features.h> header file to
// get major and minor version number:
if (@file_exists('/usr/include/features.h') &&
@is_readable('/usr/include/features.h')) {
if (!@file_exists('/usr/bin/cpp') || !@is_executable('/usr/bin/cpp')) {
$features_file = fopen('/usr/include/features.h', 'rb');
while (!feof($features_file)) {
$line = fgets($features_file, 8192);
if (!$line || (strpos($line, '#define') === false)) {
continue;
}
if (strpos($line, '__GLIBC__')) {
// major version number #define __GLIBC__ version
$line = preg_split('/\s+/', $line);
$glibc_major = trim($line[2]);
if (isset($glibc_minor)) {
break;
}
continue;
}
if (strpos($line, '__GLIBC_MINOR__')) {
// got the minor version number
// #define __GLIBC_MINOR__ version
$line = preg_split('/\s+/', $line);
$glibc_minor = trim($line[2]);
if (isset($glibc_major)) {
break;
}
continue;
}
}
fclose($features_file);
if (!isset($glibc_major) || !isset($glibc_minor)) {
return $glibc = '';
}
return $glibc = 'glibc' . trim($glibc_major) . "." . trim($glibc_minor) ;
} // no cpp
$tmpfile = System::mktemp("glibctest");
$fp = fopen($tmpfile, "w");
fwrite($fp, "#include <features.h>\n__GLIBC__ __GLIBC_MINOR__\n");
fclose($fp);
$cpp = popen("/usr/bin/cpp $tmpfile", "r");
while ($line = fgets($cpp, 1024)) {
if ($line{0} == '#' || trim($line) == '') {
continue;
}
if (list($major, $minor) = explode(' ', trim($line))) {
break;
}
}
pclose($cpp);
unlink($tmpfile);
} // features.h
if (!($major && $minor) && @is_link('/lib/libc.so.6')) {
// Let's try reading the libc.so.6 symlink
if (preg_match('/^libc-(.*)\.so$/', basename(readlink('/lib/libc.so.6')), $matches)) {
list($major, $minor) = explode('.', $matches[1]);
}
}
if (!($major && $minor)) {
return $glibc = '';
}
return $glibc = "glibc{$major}.{$minor}";
}
function getSignature()
{
if (empty($this->extra)) {
return "{$this->sysname}-{$this->release}-{$this->cpu}";
}
return "{$this->sysname}-{$this->release}-{$this->cpu}-{$this->extra}";
}
function getSysname()
{
return $this->sysname;
}
function getNodename()
{
return $this->nodename;
}
function getCpu()
{
return $this->cpu;
}
function getRelease()
{
return $this->release;
}
function getExtra()
{
return $this->extra;
}
function matchSignature($match)
{
$fragments = is_array($match) ? $match : explode('-', $match);
$n = count($fragments);
$matches = 0;
if ($n > 0) {
$matches += $this->_matchFragment($fragments[0], $this->sysname);
}
if ($n > 1) {
$matches += $this->_matchFragment($fragments[1], $this->release);
}
if ($n > 2) {
$matches += $this->_matchFragment($fragments[2], $this->cpu);
}
if ($n > 3) {
$matches += $this->_matchFragment($fragments[3], $this->extra);
}
return ($matches == $n);
}
function _matchFragment($fragment, $value)
{
if (strcspn($fragment, '*?') < strlen($fragment)) {
$reg = '/^' . str_replace(array('*', '?', '/'), array('.*', '.', '\\/'), $fragment) . '\\z/';
return preg_match($reg, $value);
}
return ($fragment == '*' || !strcasecmp($fragment, $value));
}
}
/*
* Local Variables:
* indent-tabs-mode: nil
* c-basic-offset: 4
* End:
*/
\ No newline at end of file
<?php
/**
* PEAR, the PHP Extension and Application Repository
*
* PEAR class and PEAR_Error class
*
* PHP versions 4 and 5
*
* @category pear
* @package PEAR
* @author Sterling Hughes <sterling@php.net>
* @author Stig Bakken <ssb@php.net>
* @author Tomas V.V.Cox <cox@idecnet.com>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id: PEAR.php 286670 2009-08-02 14:16:06Z dufuz $
* @link http://pear.php.net/package/PEAR
* @since File available since Release 0.1
*/
/**#@+
* ERROR constants
*/
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
}
$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;
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Tomas V.V. Cox <cox@idecnet.com>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2006 The PHP Group
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version Release: 1.9.0
* @link http://pear.php.net/package/PEAR
* @see PEAR_Error
* @since Class available since PHP 4.0.2
* @link http://pear.php.net/manual/en/core.pear.php#core.pear.pear
*/
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;
if (!isset($properties[$class])) {
$properties[$class] = array();
}
if (!array_key_exists($var, $properties[$class])) {
$properties[$class][$var] = null;
}
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())
{
// if we are called statically, there is a potential
// that no shutdown func is registered. Bug #6445
if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
register_shutdown_function("_PEAR_call_destructors");
$GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
}
$GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args);
}
// }}}
// {{{ isError()
/**
* Tell whether a value is a PEAR error.
*
* @param mixed $data the value to test
* @param int $code if $data is an error object, return true
* only if $code is a string and
* $obj->getMessage() == $code or
* $code is an integer and $obj->getCode() == $code
* @access public
* @return bool true if parameter is an error
*/
function isError($data, $code = null)
{
if (!is_a($data, 'PEAR_Error')) {
return false;
}
if (is_null($code)) {
return true;
} elseif (is_string($code)) {
return $data->getMessage() == $code;
}
return $data->getCode() == $code;
}
// }}}
// {{{ setErrorHandling()
/**
* Sets how errors generated by this object should be handled.
* Can be invoked both in objects and statically. If called
* statically, setErrorHandling sets the default behaviour for all
* PEAR objects. If called in an object, setErrorHandling sets
* the default behaviour for that object.
*
* @param int $mode
* One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
* PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
* PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION.
*
* @param mixed $options
* When $mode is PEAR_ERROR_TRIGGER, this is the error level (one
* of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
*
* When $mode is PEAR_ERROR_CALLBACK, this parameter is expected
* to be the callback function or method. A callback
* function is a string with the name of the function, a
* callback method is an array of two elements: the element
* at index 0 is the object, and the element at index 1 is
* the name of the method to call in the object.
*
* When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is
* a printf format string used when printing the error
* message.
*
* @access public
* @return void
* @see PEAR_ERROR_RETURN
* @see PEAR_ERROR_PRINT
* @see PEAR_ERROR_TRIGGER
* @see PEAR_ERROR_DIE
* @see PEAR_ERROR_CALLBACK
* @see PEAR_ERROR_EXCEPTION
*
* @since PHP 4.0.5
*/
function setErrorHandling($mode = null, $options = null)
{
if (isset($this) && is_a($this, 'PEAR')) {
$setmode = &$this->_default_error_mode;
$setoptions = &$this->_default_error_options;
} else {
$setmode = &$GLOBALS['_PEAR_default_error_mode'];
$setoptions = &$GLOBALS['_PEAR_default_error_options'];
}
switch ($mode) {
case PEAR_ERROR_EXCEPTION:
case PEAR_ERROR_RETURN:
case PEAR_ERROR_PRINT:
case PEAR_ERROR_TRIGGER:
case PEAR_ERROR_DIE:
case null:
$setmode = $mode;
$setoptions = $options;
break;
case PEAR_ERROR_CALLBACK:
$setmode = $mode;
// class/object method callback
if (is_callable($options)) {
$setoptions = $options;
} else {
trigger_error("invalid error callback", E_USER_WARNING);
}
break;
default:
trigger_error("invalid error mode", E_USER_WARNING);
break;
}
}
// }}}
// {{{ expectError()
/**
* This method is used to tell which errors you expect to get.
* Expected errors are always returned with error mode
* PEAR_ERROR_RETURN. Expected error codes are stored in a stack,
* and this method pushes a new element onto it. The list of
* expected errors are in effect until they are popped off the
* stack with the popExpect() method.
*
* Note that this method can not be called statically
*
* @param mixed $code a single error code or an array of error codes to expect
*
* @return int the new depth of the "expected errors" stack
* @access public
*/
function expectError($code = '*')
{
if (is_array($code)) {
array_push($this->_expected_errors, $code);
} else {
array_push($this->_expected_errors, array($code));
}
return sizeof($this->_expected_errors);
}
// }}}
// {{{ popExpect()
/**
* This method pops one element off the expected error codes
* stack.
*
* @return array the list of error codes that were popped
*/
function popExpect()
{
return array_pop($this->_expected_errors);
}
// }}}
// {{{ _checkDelExpect()
/**
* This method checks unsets an error code if available
*
* @param mixed error code
* @return bool true if the error code was unset, false otherwise
* @access private
* @since PHP 4.3.0
*/
function _checkDelExpect($error_code)
{
$deleted = false;
foreach ($this->_expected_errors AS $key => $error_array) {
if (in_array($error_code, $error_array)) {
unset($this->_expected_errors[$key][array_search($error_code, $error_array)]);
$deleted = true;
}
// clean up empty arrays
if (0 == count($this->_expected_errors[$key])) {
unset($this->_expected_errors[$key]);
}
}
return $deleted;
}
// }}}
// {{{ delExpect()
/**
* This method deletes all occurences of the specified element from
* the expected error codes stack.
*
* @param mixed $error_code error code that should be deleted
* @return mixed list of error codes that were deleted or error
* @access public
* @since PHP 4.3.0
*/
function delExpect($error_code)
{
$deleted = false;
if ((is_array($error_code) && (0 != count($error_code)))) {
// $error_code is a non-empty array here;
// we walk through it trying to unset all
// values
foreach($error_code as $key => $error) {
if ($this->_checkDelExpect($error)) {
$deleted = true;
} else {
$deleted = false;
}
}
return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
} elseif (!empty($error_code)) {
// $error_code comes alone, trying to unset it
if ($this->_checkDelExpect($error_code)) {
return true;
} else {
return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
}
}
// $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 (intval(PHP_VERSION) < 5) {
// little non-eval hack to fix bug #12147
include 'PEAR/FixPHP5PEARWarnings.php';
return $a;
}
if ($skipmsg) {
$a = new $ec($code, $mode, $options, $userinfo);
} else {
$a = new $ec($message, $code, $mode, $options, $userinfo);
}
return $a;
}
// }}}
// {{{ throwError()
/**
* Simpler form of raiseError with fewer options. In most cases
* message, code and userinfo are enough.
*
* @param string $message
*
*/
function &throwError($message = null,
$code = null,
$userinfo = null)
{
if (isset($this) && is_a($this, 'PEAR')) {
$a = &$this->raiseError($message, $code, null, null, $userinfo);
return $a;
}
$a = &PEAR::raiseError($message, $code, null, null, $userinfo);
return $a;
}
// }}}
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) && is_a($this, 'PEAR')) {
$def_mode = &$this->_default_error_mode;
$def_options = &$this->_default_error_options;
} else {
$def_mode = &$GLOBALS['_PEAR_default_error_mode'];
$def_options = &$GLOBALS['_PEAR_default_error_options'];
}
$stack[] = array($def_mode, $def_options);
if (isset($this) && is_a($this, 'PEAR')) {
$this->setErrorHandling($mode, $options);
} else {
PEAR::setErrorHandling($mode, $options);
}
$stack[] = array($mode, $options);
return true;
}
// }}}
// {{{ popErrorHandling()
/**
* Pop the last error handler used
*
* @return bool Always true
*
* @see PEAR::pushErrorHandling
*/
function popErrorHandling()
{
$stack = &$GLOBALS['_PEAR_error_handler_stack'];
array_pop($stack);
list($mode, $options) = $stack[sizeof($stack) - 1];
array_pop($stack);
if (isset($this) && is_a($this, 'PEAR')) {
$this->setErrorHandling($mode, $options);
} else {
PEAR::setErrorHandling($mode, $options);
}
return true;
}
// }}}
// {{{ loadExtension()
/**
* OS independant PHP extension load. Remember to take care
* on the correct extension name for case sensitive OSes.
*
* @param string $ext The extension name
* @return bool Success or not on the dl() call
*/
function loadExtension($ext)
{
if (!extension_loaded($ext)) {
// if either returns true dl() will produce a FATAL error, stop that
if ((ini_get('enable_dl') != 1) || (ini_get('safe_mode') == 1)) {
return false;
}
if (OS_WINDOWS) {
$suffix = '.dll';
} elseif (PHP_OS == 'HP-UX') {
$suffix = '.sl';
} elseif (PHP_OS == 'AIX') {
$suffix = '.a';
} elseif (PHP_OS == 'OSX') {
$suffix = '.bundle';
} else {
$suffix = '.so';
}
return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
}
return true;
}
// }}}
}
if (PEAR_ZE2) {
include_once 'PEAR5.php';
}
// {{{ _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_ZE2) {
$destructLifoExists = PEAR5::getStaticProperty('PEAR', 'destructlifo');
} else {
$destructLifoExists = PEAR::getStaticProperty('PEAR', 'destructlifo');
}
if ($destructLifoExists) {
$_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 (isset($GLOBALS['_PEAR_shutdown_funcs']) AND 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]);
}
}
}
// }}}
/**
* Standard PEAR error class for PHP 4
*
* This class is supserseded by {@link PEAR_Exception} in PHP 5
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Tomas V.V. Cox <cox@idecnet.com>
* @author Gregory Beaver <cellog@php.net>
* @copyright 1997-2006 The PHP Group
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version Release: 1.9.0
* @link http://pear.php.net/manual/en/core.pear.pear-error.php
* @see PEAR::raiseError(), PEAR::throwError()
* @since Class available since PHP 4.0.2
*/
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 (PEAR_ZE2) {
$skiptrace = PEAR5::getStaticProperty('PEAR_Error', 'skiptrace');
} else {
$skiptrace = PEAR::getStaticProperty('PEAR_Error', 'skiptrace');
}
if (!$skiptrace) {
$this->backtrace = debug_backtrace();
if (isset($this->backtrace[0]) && isset($this->backtrace[0]['object'])) {
unset($this->backtrace[0]['object']);
}
}
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_Exception for exceptions", E_USER_WARNING);
eval('$e = new Exception($this->message, $this->code);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 (defined('PEAR_IGNORE_BACKTRACE')) {
return 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()
function __toString()
{
return $this->getMessage();
}
// }}}
// {{{ 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:
*/
<?php
/**
* Class auto-loader
*
* PHP versions 4
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id: Autoloader.php 276383 2009-02-24 23:39:37Z dufuz $
* @link http://pear.php.net/manual/en/core.ppm.php#core.ppm.pear-autoloader
* @since File available since Release 0.1
* @deprecated File deprecated in Release 1.4.0a1
*/
// /* vim: set expandtab tabstop=4 shiftwidth=4: */
if (!extension_loaded("overload")) {
// die hard without ext/overload
die("Rebuild PHP with the `overload' extension to use PEAR_Autoloader");
}
/**
* Include for PEAR_Error and PEAR classes
*/
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.
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version Release: 1.9.0
* @link http://pear.php.net/manual/en/core.ppm.php#core.ppm.pear-autoloader
* @since File available since Release 0.1
* @deprecated File deprecated in Release 1.4.0a1
*/
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");
?>
<?php
/**
* PEAR_Builder for building PHP extensions (PECL packages)
*
* PHP versions 4 and 5
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id: Builder.php 276383 2009-02-24 23:39:37Z dufuz $
* @link http://pear.php.net/package/PEAR
* @since File available since Release 0.1
*
* TODO: log output parameters in PECL command line
* TODO: msdev path in configuration
*/
/**
* Needed for extending PEAR_Builder
*/
require_once 'PEAR/Common.php';
require_once 'PEAR/PackageFile.php';
/**
* Class to handle building (compiling) extensions.
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version Release: 1.9.0
* @link http://pear.php.net/package/PEAR
* @since Class available since PHP 4.0.2
* @see http://pear.php.net/manual/en/core.ppm.pear-builder.php
*/
class PEAR_Builder extends PEAR_Common
{
var $php_api_version = 0;
var $zend_module_api_no = 0;
var $zend_extension_api_no = 0;
var $extensions_built = array();
/**
* @var string Used for reporting when it is not possible to pass function
* via extra parameter, e.g. log, msdevCallback
*/
var $current_callback = null;
// used for msdev builds
var $_lastline = null;
var $_firstline = null;
/**
* 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 an extension from source on windows.
* requires msdev
*/
function _build_win32($descfile, $callback = null)
{
if (is_object($descfile)) {
$pkg = $descfile;
$descfile = $pkg->getPackageFile();
} else {
$pf = &new PEAR_PackageFile($this->config, $this->debug);
$pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
if (PEAR::isError($pkg)) {
return $pkg;
}
}
$dir = dirname($descfile);
$old_cwd = getcwd();
if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) {
return $this->raiseError("could not chdir to $dir");
}
// packages that were in a .tar have the packagefile in this directory
$vdir = $pkg->getPackage() . '-' . $pkg->getVersion();
if (file_exists($dir) && is_dir($vdir)) {
if (!chdir($vdir)) {
return $this->raiseError("could not chdir to " . realpath($vdir));
}
$dir = getcwd();
}
$this->log(2, "building in $dir");
$dsp = $pkg->getPackage().'.dsp';
if (!file_exists("$dir/$dsp")) {
return $this->raiseError("The DSP $dsp does not exist.");
}
// XXX TODO: make release build type configurable
$command = 'msdev '.$dsp.' /MAKE "'.$pkg->getPackage(). ' - Release"';
$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('/.*?'.$pkg->getPackage().'\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+("'.
$pkg->getPackage().'\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.");
}
// realpath returns false if the file doesn't exist
if ($outfile && 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;
call_user_func($this->current_callback, $what, $data);
}
/**
* @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 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|PEAR_PackageFile_v* $descfile path to XML package description file, or
* a PEAR_PackageFile object
*
* @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
*/
function build($descfile, $callback = null)
{
if (preg_match('/(\\/|\\\\|^)([^\\/\\\\]+)?php(.+)?$/',
$this->config->get('php_bin'), $matches)) {
if (isset($matches[2]) && strlen($matches[2]) &&
trim($matches[2]) != trim($this->config->get('php_prefix'))) {
$this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') .
' appears to have a prefix ' . $matches[2] . ', but' .
' config variable php_prefix does not match');
}
if (isset($matches[3]) && strlen($matches[3]) &&
trim($matches[3]) != trim($this->config->get('php_suffix'))) {
$this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') .
' appears to have a suffix ' . $matches[3] . ', but' .
' config variable php_suffix does not match');
}
}
$this->current_callback = $callback;
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 (is_object($descfile)) {
$pkg = $descfile;
$descfile = $pkg->getPackageFile();
if (is_a($pkg, 'PEAR_PackageFile_v1')) {
$dir = dirname($descfile);
} else {
$dir = $pkg->_config->get('temp_dir') . '/' . $pkg->getName();
// automatically delete at session end
$this->addTempFile($dir);
}
} else {
$pf = &new PEAR_PackageFile($this->config);
$pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
if (PEAR::isError($pkg)) {
return $pkg;
}
$dir = dirname($descfile);
}
$old_cwd = getcwd();
if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) {
return $this->raiseError("could not chdir to $dir");
}
$vdir = $pkg->getPackage() . '-' . $pkg->getVersion();
if (is_dir($vdir)) {
chdir($vdir);
}
$dir = getcwd();
$this->log(2, "building in $dir");
putenv('PATH=' . $this->config->get('bin_dir') . ':' . getenv('PATH'));
$err = $this->_runCommand($this->config->get('php_prefix')
. "phpize" .
$this->config->get('php_suffix'),
array(&$this, 'phpizeCallback'));
if (PEAR::isError($err)) {
return $err;
}
if (!$err) {
return $this->raiseError("`phpize' failed");
}
// {{{ start of interactive part
$configure_command = "$dir/configure";
$configure_options = $pkg->getConfigureOptions();
if ($configure_options) {
foreach ($configure_options as $o) {
$default = array_key_exists('default', $o) ? $o['default'] : null;
list($r) = $this->ui->userDialog('build',
array($o['prompt']),
array('text'),
array($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/$vdir";
$inst_dir = "$build_basedir/install-$vdir";
$this->log(1, "building in $build_dir");
if (is_dir($build_dir)) {
System::rm(array('-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\" | xargs ls -dils"
);
if (!file_exists($build_dir) || !is_dir($build_dir) || !chdir($build_dir)) {
return $this->raiseError("could not chdir to $build_dir");
}
putenv('PHP_PEAR_VERSION=1.9.0');
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($this->config->get('php_prefix')
. "php-config" .
$this->config->get('php_suffix') . " --prefix");
$this->_harvestInstDir($prefix, $inst_dir . DIRECTORY_SEPARATOR . $prefix, $built_files);
chdir($old_cwd);
return $built_files;
}
/**
* 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);
}
}
}
/**
* 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 = is_resource($pp) ? pclose($pp) : -1;
return ($exitcode == 0);
}
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);
}
}
\ No newline at end of file