CC-2166: Packaging Improvements. Moved the Zend app into airtime_mvc. It is now installed to /var/www/airtime. Storage is now set to /srv/airtime/stor. Utils are now installed to /usr/lib/airtime/utils/. Added install/airtime-dircheck.php as a simple test to see if everything is install/uninstalled correctly.

This commit is contained in:
Paul Baranowski 2011-04-14 18:55:04 -04:00
parent 514777e8d2
commit b11cbd8159
4546 changed files with 138 additions and 51 deletions

View file

@ -0,0 +1,397 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* XML_Beautifier
*
* XML Beautifier package
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2003-2008 Stephan Schmidt <schst@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category XML
* @package XML_Beautifier
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version CVS: $Id: Beautifier.php,v 1.15 2008/08/24 19:44:14 ashnazg Exp $
* @link http://pear.php.net/package/XML_Beautifier
*/
/**
* define include path constant
*/
if (!defined('XML_BEAUTIFIER_INCLUDE_PATH')) {
define('XML_BEAUTIFIER_INCLUDE_PATH', 'XML/Beautifier');
}
/**
* element is empty
*/
define('XML_BEAUTIFIER_EMPTY', 0);
/**
* CData
*/
define('XML_BEAUTIFIER_CDATA', 1);
/**
* XML element
*/
define('XML_BEAUTIFIER_ELEMENT', 2);
/**
* processing instruction
*/
define('XML_BEAUTIFIER_PI', 4);
/**
* entity
*/
define('XML_BEAUTIFIER_ENTITY', 8);
/**
* comment
*/
define('XML_BEAUTIFIER_COMMENT', 16);
/**
* XML declaration
*/
define('XML_BEAUTIFIER_XML_DECLARATION', 32);
/**
* doctype declaration
*/
define('XML_BEAUTIFIER_DT_DECLARATION', 64);
/**
* cdata section
*/
define('XML_BEAUTIFIER_CDATA_SECTION', 128);
/**
* default
*/
define('XML_BEAUTIFIER_DEFAULT', 256);
/**
* overwrite the original file
*/
define('XML_BEAUTIFIER_OVERWRITE', -1);
/**
* could not write to output file
*/
define('XML_BEAUTIFIER_ERROR_NO_OUTPUT_FILE', 151);
/**
* could not load renderer
*/
define('XML_BEAUTIFIER_ERROR_UNKNOWN_RENDERER', 152);
/**
* XML_Beautifier is a class that adds linebreaks and
* indentation to your XML files. It can be used on XML
* that looks ugly (e.g. any generated XML) to transform it
* to a nicely looking XML that can be read by humans.
*
* It removes unnecessary whitespace and adds indentation
* depending on the nesting level.
*
* It is able to treat tags, data, processing instructions
* comments, external entities and the XML prologue.
*
* XML_Beautifier is using XML_Beautifier_Tokenizer to parse an XML
* document with a SAX based parser and builds tokens of tags, comments,
* entities, data, etc.
* These tokens will be serialized and indented by a renderer
* with your indent string.
*
* Example 1: Formatting a file
* <code>
* require_once 'XML/Beautifier.php';
* $fmt = new XML_Beautifier();
* $result = $fmt->formatFile('oldFile.xml', 'newFile.xml');
* </code>
*
* Example 2: Formatting a string
* <code>
* require_once 'XML/Beautifier.php';
* $xml = '<root><foo bar = "pear"/></root>';
* $fmt = new XML_Beautifier();
* $result = $fmt->formatString($xml);
* </code>
*
* @category XML
* @package XML_Beautifier
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version Release: 1.2.0
* @link http://pear.php.net/package/XML_Beautifier
*/
class XML_Beautifier
{
/**
* default options for the output format
* @var array
* @access private
*/
var $_defaultOptions = array(
"removeLineBreaks" => true,
"removeLeadingSpace" => true, // not implemented, yet
"indent" => " ",
"linebreak" => "\n",
"caseFolding" => false,
"caseFoldingTo" => "uppercase",
"normalizeComments" => false,
"maxCommentLine" => -1,
"multilineTags" => false
);
/**
* options for the output format
* @var array
* @access private
*/
var $_options = array();
/**
* Constructor
*
* This is only used to specify the options of the
* beautifying process.
*
* @param array $options options that override default options
*
* @access public
*/
function XML_Beautifier($options = array())
{
$this->_options = array_merge($this->_defaultOptions, $options);
$this->folding = false;
}
/**
* reset all options to default options
*
* @return void
* @access public
* @see setOption(), XML_Beautifier(), setOptions()
*/
function resetOptions()
{
$this->_options = $this->_defaultOptions;
}
/**
* set an option
*
* You can use this method if you do not want
* to set all options in the constructor
*
* @param string $name option name
* @param mixed $value option value
*
* @return void
* @access public
* @see resetOptions(), XML_Beautifier(), setOptions()
*/
function setOption($name, $value)
{
$this->_options[$name] = $value;
}
/**
* set several options at once
*
* You can use this method if you do not want
* to set all options in the constructor
*
* @param array $options an options array
*
* @return void
* @access public
* @see resetOptions(), XML_Beautifier()
*/
function setOptions($options)
{
$this->_options = array_merge($this->_options, $options);
}
/**
* format a file or URL
*
* @param string $file filename
* @param mixed $newFile filename for beautified XML file
* (if none is given, the XML string
* will be returned).
* if you want overwrite the original file,
* use XML_BEAUTIFIER_OVERWRITE
* @param string $renderer Renderer to use,
* default is the plain xml renderer
*
* @return mixed XML string of no file should be written,
* true if file could be written
* @access public
* @throws PEAR_Error
* @uses _loadRenderer() to load the desired renderer
* @todo PEAR CS - should require_once be include_once?
*/
function formatFile($file, $newFile = null, $renderer = "Plain")
{
if ($newFile == XML_BEAUTIFIER_OVERWRITE) {
$newFile = $file;
}
/**
* Split the document into tokens
* using the XML_Tokenizer
*/
require_once XML_BEAUTIFIER_INCLUDE_PATH . '/Tokenizer.php';
$tokenizer = new XML_Beautifier_Tokenizer();
$tokens = $tokenizer->tokenize($file, true);
if (PEAR::isError($tokens)) {
return $tokens;
}
$renderer = $this->_loadRenderer($renderer, $this->_options);
if (PEAR::isError($renderer)) {
return $renderer;
}
$xml = $renderer->serialize($tokens);
if ($newFile == null) {
return $xml;
}
$fp = @fopen($newFile, "w");
if (!$fp) {
return PEAR::raiseError("Could not write to output file",
XML_BEAUTIFIER_ERROR_NO_OUTPUT_FILE);
}
flock($fp, LOCK_EX);
fwrite($fp, $xml);
flock($fp, LOCK_UN);
fclose($fp);
return true;
}
/**
* format an XML string
*
* @param string $string XML
* @param string $renderer the renderer type
*
* @return string formatted XML string
* @access public
* @throws PEAR_Error
* @todo PEAR CS - should require_once be include_once?
*/
function formatString($string, $renderer = "Plain")
{
/**
* Split the document into tokens
* using the XML_Tokenizer
*/
require_once XML_BEAUTIFIER_INCLUDE_PATH . '/Tokenizer.php';
$tokenizer = new XML_Beautifier_Tokenizer();
$tokens = $tokenizer->tokenize($string, false);
if (PEAR::isError($tokens)) {
return $tokens;
}
$renderer = $this->_loadRenderer($renderer, $this->_options);
if (PEAR::isError($renderer)) {
return $renderer;
}
$xml = $renderer->serialize($tokens);
return $xml;
}
/**
* load a renderer
*
* Renderers are used to serialize the XML tokens back
* to an XML string.
*
* Renderers are located in the XML/Beautifier/Renderer directory.
*
* NOTE: the "@" error suppression is used in this method
*
* @param string $name name of the renderer
* @param array $options options for the renderer
*
* @return object renderer
* @access private
* @throws PEAR_Error
*/
function &_loadRenderer($name, $options = array())
{
$file = XML_BEAUTIFIER_INCLUDE_PATH . "/Renderer/$name.php";
$class = "XML_Beautifier_Renderer_$name";
@include_once $file;
if (!class_exists($class)) {
return PEAR::raiseError("Could not load renderer.",
XML_BEAUTIFIER_ERROR_UNKNOWN_RENDERER);
}
$renderer = &new $class($options);
return $renderer;
}
/**
* return API version
*
* @access public
* @static
* @return string $version API version
*/
function apiVersion()
{
return "1.0";
}
}
?>

View file

@ -0,0 +1,226 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* XML_Beautifier/Renderer
*
* XML Beautifier's Rendere
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2003-2008 Stephan Schmidt <schst@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category XML
* @package XML_Beautifier
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version CVS: $Id: Renderer.php,v 1.6 2008/08/24 19:44:14 ashnazg Exp $
* @link http://pear.php.net/package/XML_Beautifier
*/
/**
* Renderer base class for XML_Beautifier
*
* @category XML
* @package XML_Beautifier
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version Release: 1.2.0
* @link http://pear.php.net/package/XML_Beautifier
*/
class XML_Beautifier_Renderer
{
/**
* options
* @var array
*/
var $_options = array();
/**
* create a new renderer
*
* @param array $options for the serialization
*
* @access public
*/
function XML_Beautifier_Renderer($options = array())
{
$this->_options = $options;
}
/**
* Serialize the XML tokens
*
* @param array $tokens XML tokens
*
* @return string XML document
* @access public
* @abstract
*/
function serialize($tokens)
{
return '';
}
/**
* normalize the XML tree
*
* When normalizing an XML tree, adjacent data sections
* are combined to one data section.
*
* @param array $tokens XML tree as returned by the tokenizer
*
* @return array XML tree
* @access public
*/
function normalize($tokens)
{
$tmp = array();
foreach ($tokens as $token) {
array_push($tmp, $this->_normalizeToken($token));
}
return $tmp;
}
/**
* normalize one element in the XML tree
*
* This method will combine all data sections of an element.
*
* @param array $token token array
*
* @return array $struct
* @access private
*/
function _normalizeToken($token)
{
if ((isset($token["children"]))
&& !is_array($token["children"])
|| empty($token["children"])
) {
return $token;
}
$children = $token["children"];
$token["children"] = array();
$cnt = count($children);
$currentMode = 0;
for ($i = 0; $i < $cnt; $i++ ) {
// no data section
if ($children[$i]["type"] != XML_BEAUTIFIER_CDATA
&& $children[$i]["type"] != XML_BEAUTIFIER_CDATA_SECTION
) {
$children[$i] = $this->_normalizeToken($children[$i]);
$currentMode = 0;
array_push($token["children"], $children[$i]);
continue;
}
/*
* remove whitespace
*/
if ($this->_options['removeLineBreaks'] == true) {
$children[$i]['data'] = trim($children[$i]['data']);
if ($children[$i]['data'] == '') {
continue;
}
}
if ($currentMode == $children[$i]["type"]) {
$tmp = array_pop($token["children"]);
if ($children[$i]['data'] != '') {
if ($tmp['data'] != ''
&& $this->_options['removeLineBreaks'] == true
) {
$tmp['data'] .= ' ';
}
$tmp["data"] .= $children[$i]["data"];
}
array_push($token["children"], $tmp);
} else {
array_push($token["children"], $children[$i]);
}
$currentMode = $children[$i]["type"];
}
return $token;
}
/**
* indent a text block consisting of several lines
*
* @param string $text textblock
* @param integer $depth depth to indent
* @param boolean $trim trim the lines
*
* @return string indented text block
* @access private
*/
function _indentTextBlock($text, $depth, $trim = false)
{
$indent = $this->_getIndentString($depth);
$tmp = explode("\n", $text);
$cnt = count($tmp);
$xml = '';
for ($i = 0; $i < $cnt; $i++ ) {
if ($trim) {
$tmp[$i] = trim($tmp[$i]);
}
if ($tmp[$i] == '') {
continue;
}
$xml .= $indent.$tmp[$i].$this->_options["linebreak"];
}
return $xml;
}
/**
* get the string that is used for indentation in a specific depth
*
* This depends on the option 'indent'.
*
* @param integer $depth nesting level
*
* @return string indent string
* @access private
*/
function _getIndentString($depth)
{
if ($depth > 0) {
return str_repeat($this->_options["indent"], $depth);
}
return "";
}
}
?>

View file

@ -0,0 +1,313 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* XML_Beautifier
*
* XML Beautifier's Plain Renderer
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2003-2008 Stephan Schmidt <schst@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category XML
* @package XML_Beautifier
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version CVS: $Id: Plain.php,v 1.7 2008/08/24 19:44:14 ashnazg Exp $
* @link http://pear.php.net/package/XML_Beautifier
*/
/**
* XML_Util is needed to create the tags
*/
require_once 'XML/Util.php';
/**
* Renderer base class
*/
require_once XML_BEAUTIFIER_INCLUDE_PATH . '/Renderer.php';
/**
* Basic XML Renderer for XML Beautifier
*
* @category XML
* @package XML_Beautifier
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version Release: 1.2.0
* @link http://pear.php.net/package/XML_Beautifier
* @todo option to specify inline tags
* @todo option to specify treatment of whitespace in data sections
*/
class XML_Beautifier_Renderer_Plain extends XML_Beautifier_Renderer
{
/**
* Serialize the XML tokens
*
* @param array $tokens XML tokens
*
* @return string XML document
* @access public
*/
function serialize($tokens)
{
$tokens = $this->normalize($tokens);
$xml = '';
$cnt = count($tokens);
for ($i = 0; $i < $cnt; $i++) {
$xml .= $this->_serializeToken($tokens[$i]);
}
return $xml;
}
/**
* serialize a token
*
* This method does the actual beautifying.
*
* @param array $token structure that should be serialized
*
* @return mixed
* @access private
* @todo split this method into smaller methods
*/
function _serializeToken($token)
{
switch ($token["type"]) {
/*
* serialize XML Element
*/
case XML_BEAUTIFIER_ELEMENT:
$indent = $this->_getIndentString($token["depth"]);
// adjust tag case
if ($this->_options["caseFolding"] === true) {
switch ($this->_options["caseFoldingTo"]) {
case "uppercase":
$token["tagname"] = strtoupper($token["tagname"]);
$token["attribs"] =
array_change_key_case($token["attribs"], CASE_UPPER);
break;
case "lowercase":
$token["tagname"] = strtolower($token["tagname"]);
$token["attribs"] =
array_change_key_case($token["attribs"], CASE_LOWER);
break;
}
}
if ($this->_options["multilineTags"] == true) {
$attIndent = $indent . str_repeat(" ",
(2+strlen($token["tagname"])));
} else {
$attIndent = null;
}
// check for children
switch ($token["contains"]) {
// contains only CData or is empty
case XML_BEAUTIFIER_CDATA:
case XML_BEAUTIFIER_EMPTY:
if (sizeof($token["children"]) >= 1) {
$data = $token["children"][0]["data"];
} else {
$data = '';
}
if (strstr($data, "\n")) {
$data = "\n"
. $this->_indentTextBlock($data, $token['depth']+1, true);
}
$xml = $indent
. XML_Util::createTag($token["tagname"],
$token["attribs"], $data, null, XML_UTIL_REPLACE_ENTITIES,
$this->_options["multilineTags"], $attIndent)
. $this->_options["linebreak"];
break;
// contains mixed content
default:
$xml = $indent . XML_Util::createStartElement($token["tagname"],
$token["attribs"], null, $this->_options["multilineTags"],
$attIndent) . $this->_options["linebreak"];
$cnt = count($token["children"]);
for ($i = 0; $i < $cnt; $i++) {
$xml .= $this->_serializeToken($token["children"][$i]);
}
$xml .= $indent . XML_Util::createEndElement($token["tagname"])
. $this->_options["linebreak"];
break;
break;
}
break;
/*
* serialize CData
*/
case XML_BEAUTIFIER_CDATA:
if ($token["depth"] > 0) {
$xml = str_repeat($this->_options["indent"], $token["depth"]);
} else {
$xml = "";
}
$xml .= XML_Util::replaceEntities($token["data"])
. $this->_options["linebreak"];
break;
/*
* serialize CData section
*/
case XML_BEAUTIFIER_CDATA_SECTION:
if ($token["depth"] > 0) {
$xml = str_repeat($this->_options["indent"], $token["depth"]);
} else {
$xml = "";
}
$xml .= '<![CDATA['.$token["data"].']]>' . $this->_options["linebreak"];
break;
/*
* serialize entity
*/
case XML_BEAUTIFIER_ENTITY:
if ($token["depth"] > 0) {
$xml = str_repeat($this->_options["indent"], $token["depth"]);
} else {
$xml = "";
}
$xml .= "&".$token["name"].";".$this->_options["linebreak"];
break;
/*
* serialize Processing instruction
*/
case XML_BEAUTIFIER_PI:
$indent = $this->_getIndentString($token["depth"]);
$xml = $indent."<?".$token["target"].$this->_options["linebreak"]
. $this->_indentTextBlock(rtrim($token["data"]), $token["depth"])
. $indent."?>".$this->_options["linebreak"];
break;
/*
* comments
*/
case XML_BEAUTIFIER_COMMENT:
$lines = count(explode("\n", $token["data"]));
/*
* normalize comment, i.e. combine it to one
* line and remove whitespace
*/
if ($this->_options["normalizeComments"] && $lines > 1) {
$comment = preg_replace("/\s\s+/s", " ",
str_replace("\n", " ", $token["data"]));
$lines = 1;
} else {
$comment = $token["data"];
}
/*
* check for the maximum length of one line
*/
if ($this->_options["maxCommentLine"] > 0) {
if ($lines > 1) {
$commentLines = explode("\n", $comment);
} else {
$commentLines = array($comment);
}
$comment = "";
for ($i = 0; $i < $lines; $i++) {
if (strlen($commentLines[$i])
<= $this->_options["maxCommentLine"]
) {
$comment .= $commentLines[$i];
continue;
}
$comment .= wordwrap($commentLines[$i],
$this->_options["maxCommentLine"]);
if ($i != ($lines-1)) {
$comment .= "\n";
}
}
$lines = count(explode("\n", $comment));
}
$indent = $this->_getIndentString($token["depth"]);
if ($lines > 1) {
$xml = $indent . "<!--" . $this->_options["linebreak"]
. $this->_indentTextBlock($comment, $token["depth"]+1, true)
. $indent . "-->" . $this->_options["linebreak"];
} else {
$xml = $indent . sprintf("<!-- %s -->", trim($comment))
. $this->_options["linebreak"];
}
break;
/*
* xml declaration
*/
case XML_BEAUTIFIER_XML_DECLARATION:
$indent = $this->_getIndentString($token["depth"]);
$xml = $indent . XML_Util::getXMLDeclaration($token["version"],
$token["encoding"], $token["standalone"]);
break;
/*
* xml declaration
*/
case XML_BEAUTIFIER_DT_DECLARATION:
$xml = $token["data"];
break;
/*
* all other elements
*/
case XML_BEAUTIFIER_DEFAULT:
default:
$xml = XML_Util::replaceEntities($token["data"]);
break;
}
return $xml;
}
}
?>

View file

@ -0,0 +1,456 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* XML_Beautifier/Tokenizer
*
* XML Beautifier package's Tokenizer
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2003-2008 Stephan Schmidt <schst@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category XML
* @package XML_Beautifier
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version CVS: $Id: Tokenizer.php,v 1.10 2008/08/24 19:44:14 ashnazg Exp $
* @link http://pear.php.net/package/XML_Beautifier
*/
/**
* XML_Parser is needed to parse the document
*/
require_once 'XML/Parser.php';
/**
* Tokenizer for XML_Beautifier
*
* This class breaks an XML document in seperate tokens
* that will be rendered by an XML_Beautifier renderer.
*
* @category XML
* @package XML_Beautifier
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version Release: 1.2.0
* @link http://pear.php.net/package/XML_Beautifier
* @todo tokenize DTD
* @todo check for xml:space attribute
*/
class XML_Beautifier_Tokenizer extends XML_Parser
{
/**
* current depth
* @var integer
* @access private
*/
var $_depth = 0;
/**
* stack for all found elements
* @var array
* @access private
*/
var $_struct = array();
/**
* current parsing mode
* @var string
* @access private
*/
var $_mode = "xml";
/**
* indicates, whether parser is in cdata section
* @var boolean
* @access private
*/
var $_inCDataSection = false;
/**
* Tokenize a document
*
* @param string $document filename or XML document
* @param boolean $isFile flag to indicate whether
* the first parameter is a file
*
* @return mixed
*/
function tokenize($document, $isFile = true)
{
$this->folding = false;
$this->XML_Parser();
$this->_resetVars();
if ($isFile === true) {
$this->setInputFile($document);
$result = $this->parse();
} else {
$result = $this->parseString($document);
}
if ($this->isError($result)) {
return $result;
}
return $this->_struct;
}
/**
* Start element handler for XML parser
*
* @param object $parser XML parser object
* @param string $element XML element
* @param array $attribs attributes of XML tag
*
* @return void
* @access protected
*/
function startHandler($parser, $element, $attribs)
{
$struct = array(
"type" => XML_BEAUTIFIER_ELEMENT,
"tagname" => $element,
"attribs" => $attribs,
"contains" => XML_BEAUTIFIER_EMPTY,
"depth" => $this->_depth++,
"children" => array()
);
array_push($this->_struct, $struct);
}
/**
* End element handler for XML parser
*
* @param object $parser XML parser object
* @param string $element element
*
* @return void
* @access protected
*/
function endHandler($parser, $element)
{
$struct = array_pop($this->_struct);
if ($struct["depth"] > 0) {
$parent = array_pop($this->_struct);
array_push($parent["children"], $struct);
$parent["contains"] = $parent["contains"] | XML_BEAUTIFIER_ELEMENT;
array_push($this->_struct, $parent);
} else {
array_push($this->_struct, $struct);
}
$this->_depth--;
}
/**
* Handler for character data
*
* @param object $parser XML parser object
* @param string $cdata CDATA
*
* @return void
* @access protected
*/
function cdataHandler($parser, $cdata)
{
if ((string)$cdata === '') {
return true;
}
if ($this->_inCDataSection === true) {
$type = XML_BEAUTIFIER_CDATA_SECTION;
} else {
$type = XML_BEAUTIFIER_CDATA;
}
$struct = array(
"type" => $type,
"data" => $cdata,
"depth" => $this->_depth
);
$this->_appendToParent($struct);
}
/**
* Handler for processing instructions
*
* @param object $parser XML parser object
* @param string $target target
* @param string $data data
*
* @return void
* @access protected
*/
function piHandler($parser, $target, $data)
{
$struct = array(
"type" => XML_BEAUTIFIER_PI,
"target" => $target,
"data" => $data,
"depth" => $this->_depth
);
$this->_appendToParent($struct);
}
/**
* Handler for external entities
*
* @param object $parser XML parser object
* @param string $open_entity_names entity name
* @param string $base ?? (unused?)
* @param string $system_id ?? (unused?)
* @param string $public_id ?? (unused?)
*
* @return bool
* @access protected
* @todo revisit parameter signature... doesn't seem to be correct
* @todo PEAR CS - need to shorten arg list for 85-char rule
*/
function entityrefHandler($parser, $open_entity_names, $base, $system_id, $public_id)
{
$struct = array(
"type" => XML_BEAUTIFIER_ENTITY,
"name" => $open_entity_names,
"depth" => $this->_depth
);
$this->_appendToParent($struct);
return true;
}
/**
* Handler for all other stuff
*
* @param object $parser XML parser object
* @param string $data data
*
* @return void
* @access protected
*/
function defaultHandler($parser, $data)
{
switch ($this->_mode) {
case "xml":
$this->_handleXMLDefault($data);
break;
case "doctype":
$this->_handleDoctype($data);
break;
}
}
/**
* handler for all data inside the doctype declaration
*
* @param string $data data
*
* @return void
* @access private
* @todo improve doctype parsing to split the declaration into seperate tokens
*/
function _handleDoctype($data)
{
if (eregi(">", $data)) {
$last = $this->_getLastToken();
if ($last["data"] == "]" ) {
$this->_mode = "xml";
}
}
$struct = array(
"type" => XML_BEAUTIFIER_DT_DECLARATION,
"data" => $data,
"depth" => $this->_depth
);
$this->_appendToParent($struct);
}
/**
* handler for all default XML data
*
* @param string $data data
*
* @return bool
* @access private
*/
function _handleXMLDefault($data)
{
if (strncmp("<!--", $data, 4) == 0) {
/*
* handle comment
*/
$regs = array();
eregi("<!--(.+)-->", $data, $regs);
$comment = trim($regs[1]);
$struct = array(
"type" => XML_BEAUTIFIER_COMMENT,
"data" => $comment,
"depth" => $this->_depth
);
} elseif ($data == "<![CDATA[") {
/*
* handle start of cdata section
*/
$this->_inCDataSection = true;
$struct = null;
} elseif ($data == "]]>") {
/*
* handle end of cdata section
*/
$this->_inCDataSection = false;
$struct = null;
} elseif (strncmp("<?", $data, 2) == 0) {
/*
* handle XML declaration
*/
preg_match_all('/([a-zA-Z_]+)="((?:\\\.|[^"\\\])*)"/', $data, $match);
$cnt = count($match[1]);
$attribs = array();
for ($i = 0; $i < $cnt; $i++) {
$attribs[$match[1][$i]] = $match[2][$i];
}
if (!isset($attribs["version"])) {
$attribs["version"] = "1.0";
}
if (!isset($attribs["encoding"])) {
$attribs["encoding"] = "UTF-8";
}
if (!isset($attribs["standalone"])) {
$attribs["standalone"] = true;
} else {
if ($attribs["standalone"] === 'yes') {
$attribs["standalone"] = true;
} else {
$attribs["standalone"] = false;
}
}
$struct = array(
"type" => XML_BEAUTIFIER_XML_DECLARATION,
"version" => $attribs["version"],
"encoding" => $attribs["encoding"],
"standalone" => $attribs["standalone"],
"depth" => $this->_depth
);
} elseif (eregi("^<!DOCTYPE", $data)) {
$this->_mode = "doctype";
$struct = array(
"type" => XML_BEAUTIFIER_DT_DECLARATION,
"data" => $data,
"depth" => $this->_depth
);
} else {
/*
* handle all other data
*/
$struct = array(
"type" => XML_BEAUTIFIER_DEFAULT,
"data" => $data,
"depth" => $this->_depth
);
}
if (!is_null($struct)) {
$this->_appendToParent($struct);
}
return true;
}
/**
* append a struct to the last struct on the stack
*
* @param array $struct structure to append
*
* @return bool
* @access private
*/
function _appendToParent($struct)
{
if ($this->_depth > 0) {
$parent = array_pop($this->_struct);
array_push($parent["children"], $struct);
$parent["contains"] = $parent["contains"] | $struct["type"];
array_push($this->_struct, $parent);
return true;
}
array_push($this->_struct, $struct);
}
/**
* get the last token
*
* @access private
* @return array
*/
function _getLastToken()
{
$parent = array_pop($this->_struct);
if (isset($parent["children"]) && is_array($parent["children"])) {
$last = array_pop($parent["children"]);
array_push($parent["children"], $last);
} else {
$last = $parent;
}
array_push($this->_struct, $parent);
return $last;
}
/**
* reset all used object properties
*
* This method is called before parsing a new document
*
* @return void
* @access private
*/
function _resetVars()
{
$this->_depth = 0;
$this->_struct = array();
$this->_mode = "xml";
$this->_inCDataSection = false;
}
}
?>

View file

@ -0,0 +1,768 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* XML_Parser
*
* XML Parser package
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2002-2008 The PHP Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category XML
* @package XML_Parser
* @author Stig Bakken <ssb@fast.no>
* @author Tomas V.V.Cox <cox@idecnet.com>
* @author Stephan Schmidt <schst@php.net>
* @copyright 2002-2008 The PHP Group
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version CVS: $Id: Parser.php,v 1.30 2008/09/16 16:06:22 ashnazg Exp $
* @link http://pear.php.net/package/XML_Parser
*/
/**
* uses PEAR's error handling
*/
require_once 'PEAR.php';
/**
* resource could not be created
*/
define('XML_PARSER_ERROR_NO_RESOURCE', 200);
/**
* unsupported mode
*/
define('XML_PARSER_ERROR_UNSUPPORTED_MODE', 201);
/**
* invalid encoding was given
*/
define('XML_PARSER_ERROR_INVALID_ENCODING', 202);
/**
* specified file could not be read
*/
define('XML_PARSER_ERROR_FILE_NOT_READABLE', 203);
/**
* invalid input
*/
define('XML_PARSER_ERROR_INVALID_INPUT', 204);
/**
* remote file cannot be retrieved in safe mode
*/
define('XML_PARSER_ERROR_REMOTE', 205);
/**
* XML Parser class.
*
* This is an XML parser based on PHP's "xml" extension,
* based on the bundled expat library.
*
* Notes:
* - It requires PHP 4.0.4pl1 or greater
* - From revision 1.17, the function names used by the 'func' mode
* are in the format "xmltag_$elem", for example: use "xmltag_name"
* to handle the <name></name> tags of your xml file.
* - different parsing modes
*
* @category XML
* @package XML_Parser
* @author Stig Bakken <ssb@fast.no>
* @author Tomas V.V.Cox <cox@idecnet.com>
* @author Stephan Schmidt <schst@php.net>
* @copyright 2002-2008 The PHP Group
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version Release: @package_version@
* @link http://pear.php.net/package/XML_Parser
* @todo create XML_Parser_Namespace to parse documents with namespaces
* @todo create XML_Parser_Pull
* @todo Tests that need to be made:
* - mixing character encodings
* - a test using all expat handlers
* - options (folding, output charset)
*/
class XML_Parser extends PEAR
{
// {{{ properties
/**
* XML parser handle
*
* @var resource
* @see xml_parser_create()
*/
var $parser;
/**
* File handle if parsing from a file
*
* @var resource
*/
var $fp;
/**
* Whether to do case folding
*
* If set to true, all tag and attribute names will
* be converted to UPPER CASE.
*
* @var boolean
*/
var $folding = true;
/**
* Mode of operation, one of "event" or "func"
*
* @var string
*/
var $mode;
/**
* Mapping from expat handler function to class method.
*
* @var array
*/
var $handler = array(
'character_data_handler' => 'cdataHandler',
'default_handler' => 'defaultHandler',
'processing_instruction_handler' => 'piHandler',
'unparsed_entity_decl_handler' => 'unparsedHandler',
'notation_decl_handler' => 'notationHandler',
'external_entity_ref_handler' => 'entityrefHandler'
);
/**
* source encoding
*
* @var string
*/
var $srcenc;
/**
* target encoding
*
* @var string
*/
var $tgtenc;
/**
* handler object
*
* @var object
*/
var $_handlerObj;
/**
* valid encodings
*
* @var array
*/
var $_validEncodings = array('ISO-8859-1', 'UTF-8', 'US-ASCII');
// }}}
// {{{ php4 constructor
/**
* Creates an XML parser.
*
* This is needed for PHP4 compatibility, it will
* call the constructor, when a new instance is created.
*
* @param string $srcenc source charset encoding, use NULL (default) to use
* whatever the document specifies
* @param string $mode how this parser object should work, "event" for
* startelement/endelement-type events, "func"
* to have it call functions named after elements
* @param string $tgtenc a valid target encoding
*/
function XML_Parser($srcenc = null, $mode = 'event', $tgtenc = null)
{
XML_Parser::__construct($srcenc, $mode, $tgtenc);
}
// }}}
// {{{ php5 constructor
/**
* PHP5 constructor
*
* @param string $srcenc source charset encoding, use NULL (default) to use
* whatever the document specifies
* @param string $mode how this parser object should work, "event" for
* startelement/endelement-type events, "func"
* to have it call functions named after elements
* @param string $tgtenc a valid target encoding
*/
function __construct($srcenc = null, $mode = 'event', $tgtenc = null)
{
$this->PEAR('XML_Parser_Error');
$this->mode = $mode;
$this->srcenc = $srcenc;
$this->tgtenc = $tgtenc;
}
// }}}
/**
* Sets the mode of the parser.
*
* Possible modes are:
* - func
* - event
*
* You can set the mode using the second parameter
* in the constructor.
*
* This method is only needed, when switching to a new
* mode at a later point.
*
* @param string $mode mode, either 'func' or 'event'
*
* @return boolean|object true on success, PEAR_Error otherwise
* @access public
*/
function setMode($mode)
{
if ($mode != 'func' && $mode != 'event') {
$this->raiseError('Unsupported mode given',
XML_PARSER_ERROR_UNSUPPORTED_MODE);
}
$this->mode = $mode;
return true;
}
/**
* Sets the object, that will handle the XML events
*
* This allows you to create a handler object independent of the
* parser object that you are using and easily switch the underlying
* parser.
*
* If no object will be set, XML_Parser assumes that you
* extend this class and handle the events in $this.
*
* @param object &$obj object to handle the events
*
* @return boolean will always return true
* @access public
* @since v1.2.0beta3
*/
function setHandlerObj(&$obj)
{
$this->_handlerObj = &$obj;
return true;
}
/**
* Init the element handlers
*
* @return mixed
* @access private
*/
function _initHandlers()
{
if (!is_resource($this->parser)) {
return false;
}
if (!is_object($this->_handlerObj)) {
$this->_handlerObj = &$this;
}
switch ($this->mode) {
case 'func':
xml_set_object($this->parser, $this->_handlerObj);
xml_set_element_handler($this->parser,
array(&$this, 'funcStartHandler'), array(&$this, 'funcEndHandler'));
break;
case 'event':
xml_set_object($this->parser, $this->_handlerObj);
xml_set_element_handler($this->parser, 'startHandler', 'endHandler');
break;
default:
return $this->raiseError('Unsupported mode given',
XML_PARSER_ERROR_UNSUPPORTED_MODE);
break;
}
/**
* set additional handlers for character data, entities, etc.
*/
foreach ($this->handler as $xml_func => $method) {
if (method_exists($this->_handlerObj, $method)) {
$xml_func = 'xml_set_' . $xml_func;
$xml_func($this->parser, $method);
}
}
}
// {{{ _create()
/**
* create the XML parser resource
*
* Has been moved from the constructor to avoid
* problems with object references.
*
* Furthermore it allows us returning an error
* if something fails.
*
* NOTE: uses '@' error suppresion in this method
*
* @return bool|PEAR_Error true on success, PEAR_Error otherwise
* @access private
* @see xml_parser_create
*/
function _create()
{
if ($this->srcenc === null) {
$xp = @xml_parser_create();
} else {
$xp = @xml_parser_create($this->srcenc);
}
if (is_resource($xp)) {
if ($this->tgtenc !== null) {
if (!@xml_parser_set_option($xp, XML_OPTION_TARGET_ENCODING,
$this->tgtenc)
) {
return $this->raiseError('invalid target encoding',
XML_PARSER_ERROR_INVALID_ENCODING);
}
}
$this->parser = $xp;
$result = $this->_initHandlers($this->mode);
if ($this->isError($result)) {
return $result;
}
xml_parser_set_option($xp, XML_OPTION_CASE_FOLDING, $this->folding);
return true;
}
if (!in_array(strtoupper($this->srcenc), $this->_validEncodings)) {
return $this->raiseError('invalid source encoding',
XML_PARSER_ERROR_INVALID_ENCODING);
}
return $this->raiseError('Unable to create XML parser resource.',
XML_PARSER_ERROR_NO_RESOURCE);
}
// }}}
// {{{ reset()
/**
* Reset the parser.
*
* This allows you to use one parser instance
* to parse multiple XML documents.
*
* @access public
* @return boolean|object true on success, PEAR_Error otherwise
*/
function reset()
{
$result = $this->_create();
if ($this->isError($result)) {
return $result;
}
return true;
}
// }}}
// {{{ setInputFile()
/**
* Sets the input xml file to be parsed
*
* @param string $file Filename (full path)
*
* @return resource fopen handle of the given file
* @access public
* @throws XML_Parser_Error
* @see setInput(), setInputString(), parse()
*/
function setInputFile($file)
{
/**
* check, if file is a remote file
*/
if (eregi('^(http|ftp)://', substr($file, 0, 10))) {
if (!ini_get('allow_url_fopen')) {
return $this->
raiseError('Remote files cannot be parsed, as safe mode is enabled.',
XML_PARSER_ERROR_REMOTE);
}
}
$fp = @fopen($file, 'rb');
if (is_resource($fp)) {
$this->fp = $fp;
return $fp;
}
return $this->raiseError('File could not be opened.',
XML_PARSER_ERROR_FILE_NOT_READABLE);
}
// }}}
// {{{ setInputString()
/**
* XML_Parser::setInputString()
*
* Sets the xml input from a string
*
* @param string $data a string containing the XML document
*
* @return null
*/
function setInputString($data)
{
$this->fp = $data;
return null;
}
// }}}
// {{{ setInput()
/**
* Sets the file handle to use with parse().
*
* You should use setInputFile() or setInputString() if you
* pass a string
*
* @param mixed $fp Can be either a resource returned from fopen(),
* a URL, a local filename or a string.
*
* @return mixed
* @access public
* @see parse()
* @uses setInputString(), setInputFile()
*/
function setInput($fp)
{
if (is_resource($fp)) {
$this->fp = $fp;
return true;
} elseif (eregi('^[a-z]+://', substr($fp, 0, 10))) {
// see if it's an absolute URL (has a scheme at the beginning)
return $this->setInputFile($fp);
} elseif (file_exists($fp)) {
// see if it's a local file
return $this->setInputFile($fp);
} else {
// it must be a string
$this->fp = $fp;
return true;
}
return $this->raiseError('Illegal input format',
XML_PARSER_ERROR_INVALID_INPUT);
}
// }}}
// {{{ parse()
/**
* Central parsing function.
*
* @return bool|PEAR_Error returns true on success, or a PEAR_Error otherwise
* @access public
*/
function parse()
{
/**
* reset the parser
*/
$result = $this->reset();
if ($this->isError($result)) {
return $result;
}
// if $this->fp was fopened previously
if (is_resource($this->fp)) {
while ($data = fread($this->fp, 4096)) {
if (!$this->_parseString($data, feof($this->fp))) {
$error = &$this->raiseError();
$this->free();
return $error;
}
}
} else {
// otherwise, $this->fp must be a string
if (!$this->_parseString($this->fp, true)) {
$error = &$this->raiseError();
$this->free();
return $error;
}
}
$this->free();
return true;
}
/**
* XML_Parser::_parseString()
*
* @param string $data data
* @param bool $eof end-of-file flag
*
* @return bool
* @access private
* @see parseString()
**/
function _parseString($data, $eof = false)
{
return xml_parse($this->parser, $data, $eof);
}
// }}}
// {{{ parseString()
/**
* XML_Parser::parseString()
*
* Parses a string.
*
* @param string $data XML data
* @param boolean $eof If set and TRUE, data is the last piece
* of data sent in this parser
*
* @return bool|PEAR_Error true on success or a PEAR Error
* @throws XML_Parser_Error
* @see _parseString()
*/
function parseString($data, $eof = false)
{
if (!isset($this->parser) || !is_resource($this->parser)) {
$this->reset();
}
if (!$this->_parseString($data, $eof)) {
$error = &$this->raiseError();
$this->free();
return $error;
}
if ($eof === true) {
$this->free();
}
return true;
}
/**
* XML_Parser::free()
*
* Free the internal resources associated with the parser
*
* @return null
**/
function free()
{
if (isset($this->parser) && is_resource($this->parser)) {
xml_parser_free($this->parser);
unset( $this->parser );
}
if (isset($this->fp) && is_resource($this->fp)) {
fclose($this->fp);
}
unset($this->fp);
return null;
}
/**
* XML_Parser::raiseError()
*
* Throws a XML_Parser_Error
*
* @param string $msg the error message
* @param integer $ecode the error message code
*
* @return XML_Parser_Error reference to the error object
**/
function &raiseError($msg = null, $ecode = 0)
{
$msg = !is_null($msg) ? $msg : $this->parser;
$err = &new XML_Parser_Error($msg, $ecode);
return parent::raiseError($err);
}
// }}}
// {{{ funcStartHandler()
/**
* derives and calls the Start Handler function
*
* @param mixed $xp ??
* @param mixed $elem ??
* @param mixed $attribs ??
*
* @return void
*/
function funcStartHandler($xp, $elem, $attribs)
{
$func = 'xmltag_' . $elem;
$func = str_replace(array('.', '-', ':'), '_', $func);
if (method_exists($this->_handlerObj, $func)) {
call_user_func(array(&$this->_handlerObj, $func), $xp, $elem, $attribs);
} elseif (method_exists($this->_handlerObj, 'xmltag')) {
call_user_func(array(&$this->_handlerObj, 'xmltag'),
$xp, $elem, $attribs);
}
}
// }}}
// {{{ funcEndHandler()
/**
* derives and calls the End Handler function
*
* @param mixed $xp ??
* @param mixed $elem ??
*
* @return void
*/
function funcEndHandler($xp, $elem)
{
$func = 'xmltag_' . $elem . '_';
$func = str_replace(array('.', '-', ':'), '_', $func);
if (method_exists($this->_handlerObj, $func)) {
call_user_func(array(&$this->_handlerObj, $func), $xp, $elem);
} elseif (method_exists($this->_handlerObj, 'xmltag_')) {
call_user_func(array(&$this->_handlerObj, 'xmltag_'), $xp, $elem);
}
}
// }}}
// {{{ startHandler()
/**
* abstract method signature for Start Handler
*
* @param mixed $xp ??
* @param mixed $elem ??
* @param mixed &$attribs ??
*
* @return null
* @abstract
*/
function startHandler($xp, $elem, &$attribs)
{
return null;
}
// }}}
// {{{ endHandler()
/**
* abstract method signature for End Handler
*
* @param mixed $xp ??
* @param mixed $elem ??
*
* @return null
* @abstract
*/
function endHandler($xp, $elem)
{
return null;
}
// }}}me
}
/**
* error class, replaces PEAR_Error
*
* An instance of this class will be returned
* if an error occurs inside XML_Parser.
*
* There are three advantages over using the standard PEAR_Error:
* - All messages will be prefixed
* - check for XML_Parser error, using is_a( $error, 'XML_Parser_Error' )
* - messages can be generated from the xml_parser resource
*
* @category XML
* @package XML_Parser
* @author Stig Bakken <ssb@fast.no>
* @author Tomas V.V.Cox <cox@idecnet.com>
* @author Stephan Schmidt <schst@php.net>
* @copyright 2002-2008 The PHP Group
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version Release: @package_version@
* @link http://pear.php.net/package/XML_Parser
* @see PEAR_Error
*/
class XML_Parser_Error extends PEAR_Error
{
// {{{ properties
/**
* prefix for all messages
*
* @var string
*/
var $error_message_prefix = 'XML_Parser: ';
// }}}
// {{{ constructor()
/**
* construct a new error instance
*
* You may either pass a message or an xml_parser resource as first
* parameter. If a resource has been passed, the last error that
* happened will be retrieved and returned.
*
* @param string|resource $msgorparser message or parser resource
* @param integer $code error code
* @param integer $mode error handling
* @param integer $level error level
*
* @access public
* @todo PEAR CS - can't meet 85char line limit without arg refactoring
*/
function XML_Parser_Error($msgorparser = 'unknown error', $code = 0, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE)
{
if (is_resource($msgorparser)) {
$code = xml_get_error_code($msgorparser);
$msgorparser = sprintf('%s at XML input line %d:%d',
xml_error_string($code),
xml_get_current_line_number($msgorparser),
xml_get_current_column_number($msgorparser));
}
$this->PEAR_Error($msgorparser, $code, $mode, $level);
}
// }}}
}
?>

View file

@ -0,0 +1,326 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* XML_Parser
*
* XML Parser's Simple parser class
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2002-2008 The PHP Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category XML
* @package XML_Parser
* @author Stephan Schmidt <schst@php.net>
* @copyright 2004-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version CVS: $Id: Simple.php,v 1.7 2008/08/24 21:48:21 ashnazg Exp $
* @link http://pear.php.net/package/XML_Parser
*/
/**
* built on XML_Parser
*/
require_once 'XML/Parser.php';
/**
* Simple XML parser class.
*
* This class is a simplified version of XML_Parser.
* In most XML applications the real action is executed,
* when a closing tag is found.
*
* XML_Parser_Simple allows you to just implement one callback
* for each tag that will receive the tag with its attributes
* and CData.
*
* <code>
* require_once '../Parser/Simple.php';
*
* class myParser extends XML_Parser_Simple
* {
* function myParser()
* {
* $this->XML_Parser_Simple();
* }
*
* function handleElement($name, $attribs, $data)
* {
* printf('handle %s<br>', $name);
* }
* }
*
* $p = &new myParser();
*
* $result = $p->setInputFile('myDoc.xml');
* $result = $p->parse();
* </code>
*
* @category XML
* @package XML_Parser
* @author Stephan Schmidt <schst@php.net>
* @copyright 2004-2008 The PHP Group
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version Release: @package_version@
* @link http://pear.php.net/package/XML_Parser
*/
class XML_Parser_Simple extends XML_Parser
{
/**
* element stack
*
* @access private
* @var array
*/
var $_elStack = array();
/**
* all character data
*
* @access private
* @var array
*/
var $_data = array();
/**
* element depth
*
* @access private
* @var integer
*/
var $_depth = 0;
/**
* Mapping from expat handler function to class method.
*
* @var array
*/
var $handler = array(
'default_handler' => 'defaultHandler',
'processing_instruction_handler' => 'piHandler',
'unparsed_entity_decl_handler' => 'unparsedHandler',
'notation_decl_handler' => 'notationHandler',
'external_entity_ref_handler' => 'entityrefHandler'
);
/**
* Creates an XML parser.
*
* This is needed for PHP4 compatibility, it will
* call the constructor, when a new instance is created.
*
* @param string $srcenc source charset encoding, use NULL (default) to use
* whatever the document specifies
* @param string $mode how this parser object should work, "event" for
* handleElement(), "func" to have it call functions
* named after elements (handleElement_$name())
* @param string $tgtenc a valid target encoding
*/
function XML_Parser_Simple($srcenc = null, $mode = 'event', $tgtenc = null)
{
$this->XML_Parser($srcenc, $mode, $tgtenc);
}
/**
* inits the handlers
*
* @return mixed
* @access private
*/
function _initHandlers()
{
if (!is_object($this->_handlerObj)) {
$this->_handlerObj = &$this;
}
if ($this->mode != 'func' && $this->mode != 'event') {
return $this->raiseError('Unsupported mode given',
XML_PARSER_ERROR_UNSUPPORTED_MODE);
}
xml_set_object($this->parser, $this->_handlerObj);
xml_set_element_handler($this->parser, array(&$this, 'startHandler'),
array(&$this, 'endHandler'));
xml_set_character_data_handler($this->parser, array(&$this, 'cdataHandler'));
/**
* set additional handlers for character data, entities, etc.
*/
foreach ($this->handler as $xml_func => $method) {
if (method_exists($this->_handlerObj, $method)) {
$xml_func = 'xml_set_' . $xml_func;
$xml_func($this->parser, $method);
}
}
}
/**
* Reset the parser.
*
* This allows you to use one parser instance
* to parse multiple XML documents.
*
* @access public
* @return boolean|object true on success, PEAR_Error otherwise
*/
function reset()
{
$this->_elStack = array();
$this->_data = array();
$this->_depth = 0;
$result = $this->_create();
if ($this->isError($result)) {
return $result;
}
return true;
}
/**
* start handler
*
* Pushes attributes and tagname onto a stack
*
* @param resource $xp xml parser resource
* @param string $elem element name
* @param array &$attribs attributes
*
* @return mixed
* @access private
* @final
*/
function startHandler($xp, $elem, &$attribs)
{
array_push($this->_elStack, array(
'name' => $elem,
'attribs' => $attribs
));
$this->_depth++;
$this->_data[$this->_depth] = '';
}
/**
* end handler
*
* Pulls attributes and tagname from a stack
*
* @param resource $xp xml parser resource
* @param string $elem element name
*
* @return mixed
* @access private
* @final
*/
function endHandler($xp, $elem)
{
$el = array_pop($this->_elStack);
$data = $this->_data[$this->_depth];
$this->_depth--;
switch ($this->mode) {
case 'event':
$this->_handlerObj->handleElement($el['name'], $el['attribs'], $data);
break;
case 'func':
$func = 'handleElement_' . $elem;
if (strchr($func, '.')) {
$func = str_replace('.', '_', $func);
}
if (method_exists($this->_handlerObj, $func)) {
call_user_func(array(&$this->_handlerObj, $func),
$el['name'], $el['attribs'], $data);
}
break;
}
}
/**
* handle character data
*
* @param resource $xp xml parser resource
* @param string $data data
*
* @return void
* @access private
* @final
*/
function cdataHandler($xp, $data)
{
$this->_data[$this->_depth] .= $data;
}
/**
* handle a tag
*
* Implement this in your parser
*
* @param string $name element name
* @param array $attribs attributes
* @param string $data character data
*
* @return void
* @access public
* @abstract
*/
function handleElement($name, $attribs, $data)
{
}
/**
* get the current tag depth
*
* The root tag is in depth 0.
*
* @access public
* @return integer
*/
function getCurrentDepth()
{
return $this->_depth;
}
/**
* add some string to the current ddata.
*
* This is commonly needed, when a document is parsed recursively.
*
* @param string $data data to add
*
* @return void
* @access public
*/
function addToData($data)
{
$this->_data[$this->_depth] .= $data;
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,189 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Function and class to dump XML_RPC_Value objects in a nice way
*
* Should be helpful as a normal var_dump(..) displays all internals which
* doesn't really give you an overview due to too much information.
*
* @category Web Services
* @package XML_RPC
* @author Christian Weiske <cweiske@php.net>
* @license http://www.php.net/license/3_01.txt PHP License
* @version SVN: $Id: Dump.php 300962 2010-07-03 02:24:24Z danielc $
* @link http://pear.php.net/package/XML_RPC
*/
/**
* Pull in the XML_RPC class
*/
require_once 'XML/RPC.php';
/**
* Generates the dump of the XML_RPC_Value and echoes it
*
* @param object $value the XML_RPC_Value object to dump
*
* @return void
*/
function XML_RPC_Dump($value)
{
$dumper = new XML_RPC_Dump();
echo $dumper->generateDump($value);
}
/**
* Class which generates a dump of a XML_RPC_Value object
*
* @category Web Services
* @package XML_RPC
* @author Christian Weiske <cweiske@php.net>
* @license http://www.php.net/license/3_01.txt PHP License
* @version Release: @package_version@
* @link http://pear.php.net/package/XML_RPC
*/
class XML_RPC_Dump
{
/**
* The indentation array cache
* @var array
*/
var $arIndent = array();
/**
* The spaces used for indenting the XML
* @var string
*/
var $strBaseIndent = ' ';
/**
* Returns the dump in XML format without printing it out
*
* @param object $value the XML_RPC_Value object to dump
* @param int $nLevel the level of indentation
*
* @return string the dump
*/
function generateDump($value, $nLevel = 0)
{
if (!is_object($value) || strtolower(get_class($value)) != 'xml_rpc_value') {
require_once 'PEAR.php';
PEAR::raiseError('Tried to dump non-XML_RPC_Value variable' . "\r\n",
0, PEAR_ERROR_PRINT);
if (is_object($value)) {
$strType = get_class($value);
} else {
$strType = gettype($value);
}
return $this->getIndent($nLevel) . 'NOT A XML_RPC_Value: '
. $strType . "\r\n";
}
switch ($value->kindOf()) {
case 'struct':
$ret = $this->genStruct($value, $nLevel);
break;
case 'array':
$ret = $this->genArray($value, $nLevel);
break;
case 'scalar':
$ret = $this->genScalar($value->scalarval(), $nLevel);
break;
default:
require_once 'PEAR.php';
PEAR::raiseError('Illegal type "' . $value->kindOf()
. '" in XML_RPC_Value' . "\r\n", 0,
PEAR_ERROR_PRINT);
}
return $ret;
}
/**
* Returns the scalar value dump
*
* @param object $value the scalar XML_RPC_Value object to dump
* @param int $nLevel the level of indentation
*
* @return string Dumped version of the scalar value
*/
function genScalar($value, $nLevel)
{
if (gettype($value) == 'object') {
$strClass = ' ' . get_class($value);
} else {
$strClass = '';
}
return $this->getIndent($nLevel) . gettype($value) . $strClass
. ' ' . $value . "\r\n";
}
/**
* Returns the dump of a struct
*
* @param object $value the struct XML_RPC_Value object to dump
* @param int $nLevel the level of indentation
*
* @return string Dumped version of the scalar value
*/
function genStruct($value, $nLevel)
{
$value->structreset();
$strOutput = $this->getIndent($nLevel) . 'struct' . "\r\n";
while (list($key, $keyval) = $value->structeach()) {
$strOutput .= $this->getIndent($nLevel + 1) . $key . "\r\n";
$strOutput .= $this->generateDump($keyval, $nLevel + 2);
}
return $strOutput;
}
/**
* Returns the dump of an array
*
* @param object $value the array XML_RPC_Value object to dump
* @param int $nLevel the level of indentation
*
* @return string Dumped version of the scalar value
*/
function genArray($value, $nLevel)
{
$nSize = $value->arraysize();
$strOutput = $this->getIndent($nLevel) . 'array' . "\r\n";
for($nA = 0; $nA < $nSize; $nA++) {
$strOutput .= $this->getIndent($nLevel + 1) . $nA . "\r\n";
$strOutput .= $this->generateDump($value->arraymem($nA),
$nLevel + 2);
}
return $strOutput;
}
/**
* Returns the indent for a specific level and caches it for faster use
*
* @param int $nLevel the level
*
* @return string the indented string
*/
function getIndent($nLevel)
{
if (!isset($this->arIndent[$nLevel])) {
$this->arIndent[$nLevel] = str_repeat($this->strBaseIndent, $nLevel);
}
return $this->arIndent[$nLevel];
}
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/
?>

View file

@ -0,0 +1,672 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Server commands for our PHP implementation of the XML-RPC protocol
*
* This is a PEAR-ified version of Useful inc's XML-RPC for PHP.
* It has support for HTTP transport, proxies and authentication.
*
* PHP versions 4 and 5
*
* @category Web Services
* @package XML_RPC
* @author Edd Dumbill <edd@usefulinc.com>
* @author Stig Bakken <stig@php.net>
* @author Martin Jansen <mj@php.net>
* @author Daniel Convissor <danielc@php.net>
* @copyright 1999-2001 Edd Dumbill, 2001-2010 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License
* @version SVN: $Id: Server.php 300961 2010-07-03 02:17:34Z danielc $
* @link http://pear.php.net/package/XML_RPC
*/
/**
* Pull in the XML_RPC class
*/
require_once 'XML/RPC.php';
/**
* signature for system.listMethods: return = array,
* parameters = a string or nothing
* @global array $GLOBALS['XML_RPC_Server_listMethods_sig']
*/
$GLOBALS['XML_RPC_Server_listMethods_sig'] = array(
array($GLOBALS['XML_RPC_Array'],
$GLOBALS['XML_RPC_String']
),
array($GLOBALS['XML_RPC_Array'])
);
/**
* docstring for system.listMethods
* @global string $GLOBALS['XML_RPC_Server_listMethods_doc']
*/
$GLOBALS['XML_RPC_Server_listMethods_doc'] = 'This method lists all the'
. ' methods that the XML-RPC server knows how to dispatch';
/**
* signature for system.methodSignature: return = array,
* parameters = string
* @global array $GLOBALS['XML_RPC_Server_methodSignature_sig']
*/
$GLOBALS['XML_RPC_Server_methodSignature_sig'] = array(
array($GLOBALS['XML_RPC_Array'],
$GLOBALS['XML_RPC_String']
)
);
/**
* docstring for system.methodSignature
* @global string $GLOBALS['XML_RPC_Server_methodSignature_doc']
*/
$GLOBALS['XML_RPC_Server_methodSignature_doc'] = 'Returns an array of known'
. ' signatures (an array of arrays) for the method name passed. If'
. ' no signatures are known, returns a none-array (test for type !='
. ' array to detect missing signature)';
/**
* signature for system.methodHelp: return = string,
* parameters = string
* @global array $GLOBALS['XML_RPC_Server_methodHelp_sig']
*/
$GLOBALS['XML_RPC_Server_methodHelp_sig'] = array(
array($GLOBALS['XML_RPC_String'],
$GLOBALS['XML_RPC_String']
)
);
/**
* docstring for methodHelp
* @global string $GLOBALS['XML_RPC_Server_methodHelp_doc']
*/
$GLOBALS['XML_RPC_Server_methodHelp_doc'] = 'Returns help text if defined'
. ' for the method passed, otherwise returns an empty string';
/**
* dispatch map for the automatically declared XML-RPC methods.
* @global array $GLOBALS['XML_RPC_Server_dmap']
*/
$GLOBALS['XML_RPC_Server_dmap'] = array(
'system.listMethods' => array(
'function' => 'XML_RPC_Server_listMethods',
'signature' => $GLOBALS['XML_RPC_Server_listMethods_sig'],
'docstring' => $GLOBALS['XML_RPC_Server_listMethods_doc']
),
'system.methodHelp' => array(
'function' => 'XML_RPC_Server_methodHelp',
'signature' => $GLOBALS['XML_RPC_Server_methodHelp_sig'],
'docstring' => $GLOBALS['XML_RPC_Server_methodHelp_doc']
),
'system.methodSignature' => array(
'function' => 'XML_RPC_Server_methodSignature',
'signature' => $GLOBALS['XML_RPC_Server_methodSignature_sig'],
'docstring' => $GLOBALS['XML_RPC_Server_methodSignature_doc']
)
);
/**
* @global string $GLOBALS['XML_RPC_Server_debuginfo']
*/
$GLOBALS['XML_RPC_Server_debuginfo'] = '';
/**
* Lists all the methods that the XML-RPC server knows how to dispatch
*
* @return object a new XML_RPC_Response object
*/
function XML_RPC_Server_listMethods($server, $m)
{
global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap;
$v = new XML_RPC_Value();
$outAr = array();
foreach ($server->dmap as $key => $val) {
$outAr[] = new XML_RPC_Value($key, 'string');
}
foreach ($XML_RPC_Server_dmap as $key => $val) {
$outAr[] = new XML_RPC_Value($key, 'string');
}
$v->addArray($outAr);
return new XML_RPC_Response($v);
}
/**
* Returns an array of known signatures (an array of arrays)
* for the given method
*
* If no signatures are known, returns a none-array
* (test for type != array to detect missing signature)
*
* @return object a new XML_RPC_Response object
*/
function XML_RPC_Server_methodSignature($server, $m)
{
global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap;
$methName = $m->getParam(0);
$methName = $methName->scalarval();
if (strpos($methName, 'system.') === 0) {
$dmap = $XML_RPC_Server_dmap;
$sysCall = 1;
} else {
$dmap = $server->dmap;
$sysCall = 0;
}
// print "<!-- ${methName} -->\n";
if (isset($dmap[$methName])) {
if ($dmap[$methName]['signature']) {
$sigs = array();
$thesigs = $dmap[$methName]['signature'];
for ($i = 0; $i < sizeof($thesigs); $i++) {
$cursig = array();
$inSig = $thesigs[$i];
for ($j = 0; $j < sizeof($inSig); $j++) {
$cursig[] = new XML_RPC_Value($inSig[$j], 'string');
}
$sigs[] = new XML_RPC_Value($cursig, 'array');
}
$r = new XML_RPC_Response(new XML_RPC_Value($sigs, 'array'));
} else {
$r = new XML_RPC_Response(new XML_RPC_Value('undef', 'string'));
}
} else {
$r = new XML_RPC_Response(0, $XML_RPC_err['introspect_unknown'],
$XML_RPC_str['introspect_unknown']);
}
return $r;
}
/**
* Returns help text if defined for the method passed, otherwise returns
* an empty string
*
* @return object a new XML_RPC_Response object
*/
function XML_RPC_Server_methodHelp($server, $m)
{
global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap;
$methName = $m->getParam(0);
$methName = $methName->scalarval();
if (strpos($methName, 'system.') === 0) {
$dmap = $XML_RPC_Server_dmap;
$sysCall = 1;
} else {
$dmap = $server->dmap;
$sysCall = 0;
}
if (isset($dmap[$methName])) {
if ($dmap[$methName]['docstring']) {
$r = new XML_RPC_Response(new XML_RPC_Value($dmap[$methName]['docstring']),
'string');
} else {
$r = new XML_RPC_Response(new XML_RPC_Value('', 'string'));
}
} else {
$r = new XML_RPC_Response(0, $XML_RPC_err['introspect_unknown'],
$XML_RPC_str['introspect_unknown']);
}
return $r;
}
/**
* @return void
*/
function XML_RPC_Server_debugmsg($m)
{
global $XML_RPC_Server_debuginfo;
$XML_RPC_Server_debuginfo = $XML_RPC_Server_debuginfo . $m . "\n";
}
/**
* A server for receiving and replying to XML RPC requests
*
* <code>
* $server = new XML_RPC_Server(
* array(
* 'isan8' =>
* array(
* 'function' => 'is_8',
* 'signature' =>
* array(
* array('boolean', 'int'),
* array('boolean', 'int', 'boolean'),
* array('boolean', 'string'),
* array('boolean', 'string', 'boolean'),
* ),
* 'docstring' => 'Is the value an 8?'
* ),
* ),
* 1,
* 0
* );
* </code>
*
* @category Web Services
* @package XML_RPC
* @author Edd Dumbill <edd@usefulinc.com>
* @author Stig Bakken <stig@php.net>
* @author Martin Jansen <mj@php.net>
* @author Daniel Convissor <danielc@php.net>
* @copyright 1999-2001 Edd Dumbill, 2001-2010 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License
* @version Release: @package_version@
* @link http://pear.php.net/package/XML_RPC
*/
class XML_RPC_Server
{
/**
* Should the payload's content be passed through mb_convert_encoding()?
*
* @see XML_RPC_Server::setConvertPayloadEncoding()
* @since Property available since Release 1.5.1
* @var boolean
*/
var $convert_payload_encoding = false;
/**
* The dispatch map, listing the methods this server provides.
* @var array
*/
var $dmap = array();
/**
* The present response's encoding
* @var string
* @see XML_RPC_Message::getEncoding()
*/
var $encoding = '';
/**
* Debug mode (0 = off, 1 = on)
* @var integer
*/
var $debug = 0;
/**
* The response's HTTP headers
* @var string
*/
var $server_headers = '';
/**
* The response's XML payload
* @var string
*/
var $server_payload = '';
/**
* Constructor for the XML_RPC_Server class
*
* @param array $dispMap the dispatch map. An associative array
* explaining each function. The keys of the main
* array are the procedure names used by the
* clients. The value is another associative array
* that contains up to three elements:
* + The 'function' element's value is the name
* of the function or method that gets called.
* To define a class' method: 'class::method'.
* + The 'signature' element (optional) is an
* array describing the return values and
* parameters
* + The 'docstring' element (optional) is a
* string describing what the method does
* @param int $serviceNow should the HTTP response be sent now?
* (1 = yes, 0 = no)
* @param int $debug should debug output be displayed?
* (1 = yes, 0 = no)
*
* @return void
*/
function XML_RPC_Server($dispMap, $serviceNow = 1, $debug = 0)
{
global $HTTP_RAW_POST_DATA;
if ($debug) {
$this->debug = 1;
} else {
$this->debug = 0;
}
$this->dmap = $dispMap;
if ($serviceNow) {
$this->service();
} else {
$this->createServerPayload();
$this->createServerHeaders();
}
}
/**
* @return string the debug information if debug debug mode is on
*/
function serializeDebug()
{
global $XML_RPC_Server_debuginfo, $HTTP_RAW_POST_DATA;
if ($this->debug) {
XML_RPC_Server_debugmsg('vvv POST DATA RECEIVED BY SERVER vvv' . "\n"
. $HTTP_RAW_POST_DATA
. "\n" . '^^^ END POST DATA ^^^');
}
if ($XML_RPC_Server_debuginfo != '') {
return "<!-- PEAR XML_RPC SERVER DEBUG INFO:\n\n"
. str_replace('--', '- - ', $XML_RPC_Server_debuginfo)
. "-->\n";
} else {
return '';
}
}
/**
* Sets whether the payload's content gets passed through
* mb_convert_encoding()
*
* Returns PEAR_ERROR object if mb_convert_encoding() isn't available.
*
* @param int $in where 1 = on, 0 = off
*
* @return void
*
* @see XML_RPC_Message::getEncoding()
* @since Method available since Release 1.5.1
*/
function setConvertPayloadEncoding($in)
{
if ($in && !function_exists('mb_convert_encoding')) {
return $this->raiseError('mb_convert_encoding() is not available',
XML_RPC_ERROR_PROGRAMMING);
}
$this->convert_payload_encoding = $in;
}
/**
* Sends the response
*
* The encoding and content-type are determined by
* XML_RPC_Message::getEncoding()
*
* @return void
*
* @uses XML_RPC_Server::createServerPayload(),
* XML_RPC_Server::createServerHeaders()
*/
function service()
{
if (!$this->server_payload) {
$this->createServerPayload();
}
if (!$this->server_headers) {
$this->createServerHeaders();
}
/*
* $server_headers needs to remain a string for compatibility with
* old scripts using this package, but PHP 4.4.2 no longer allows
* line breaks in header() calls. So, we split each header into
* an individual call. The initial replace handles the off chance
* that someone composed a single header with multiple lines, which
* the RFCs allow.
*/
$this->server_headers = preg_replace("@[\r\n]+[ \t]+@",
' ', trim($this->server_headers));
$headers = preg_split("@[\r\n]+@", $this->server_headers);
foreach ($headers as $header)
{
header($header);
}
print $this->server_payload;
}
/**
* Generates the payload and puts it in the $server_payload property
*
* If XML_RPC_Server::setConvertPayloadEncoding() was set to true,
* the payload gets passed through mb_convert_encoding()
* to ensure the payload matches the encoding set in the
* XML declaration. The encoding type can be manually set via
* XML_RPC_Message::setSendEncoding().
*
* @return void
*
* @uses XML_RPC_Server::parseRequest(), XML_RPC_Server::$encoding,
* XML_RPC_Response::serialize(), XML_RPC_Server::serializeDebug()
* @see XML_RPC_Server::setConvertPayloadEncoding()
*/
function createServerPayload()
{
$r = $this->parseRequest();
$this->server_payload = '<?xml version="1.0" encoding="'
. $this->encoding . '"?>' . "\n"
. $this->serializeDebug()
. $r->serialize();
if ($this->convert_payload_encoding) {
$this->server_payload = mb_convert_encoding($this->server_payload,
$this->encoding);
}
}
/**
* Determines the HTTP headers and puts them in the $server_headers
* property
*
* @return boolean TRUE if okay, FALSE if $server_payload isn't set.
*
* @uses XML_RPC_Server::createServerPayload(),
* XML_RPC_Server::$server_headers
*/
function createServerHeaders()
{
if (!$this->server_payload) {
return false;
}
$this->server_headers = 'Content-Length: '
. strlen($this->server_payload) . "\r\n"
. 'Content-Type: text/xml;'
. ' charset=' . $this->encoding;
return true;
}
/**
* @return array
*/
function verifySignature($in, $sig)
{
for ($i = 0; $i < sizeof($sig); $i++) {
// check each possible signature in turn
$cursig = $sig[$i];
if (sizeof($cursig) == $in->getNumParams() + 1) {
$itsOK = 1;
for ($n = 0; $n < $in->getNumParams(); $n++) {
$p = $in->getParam($n);
// print "<!-- $p -->\n";
if ($p->kindOf() == 'scalar') {
$pt = $p->scalartyp();
} else {
$pt = $p->kindOf();
}
// $n+1 as first type of sig is return type
if ($pt != $cursig[$n+1]) {
$itsOK = 0;
$pno = $n+1;
$wanted = $cursig[$n+1];
$got = $pt;
break;
}
}
if ($itsOK) {
return array(1);
}
}
}
if (isset($wanted)) {
return array(0, "Wanted ${wanted}, got ${got} at param ${pno}");
} else {
$allowed = array();
foreach ($sig as $val) {
end($val);
$allowed[] = key($val);
}
$allowed = array_unique($allowed);
$last = count($allowed) - 1;
if ($last > 0) {
$allowed[$last] = 'or ' . $allowed[$last];
}
return array(0,
'Signature permits ' . implode(', ', $allowed)
. ' parameters but the request had '
. $in->getNumParams());
}
}
/**
* @return object a new XML_RPC_Response object
*
* @uses XML_RPC_Message::getEncoding(), XML_RPC_Server::$encoding
*/
function parseRequest($data = '')
{
global $XML_RPC_xh, $HTTP_RAW_POST_DATA,
$XML_RPC_err, $XML_RPC_str, $XML_RPC_errxml,
$XML_RPC_defencoding, $XML_RPC_Server_dmap;
if ($data == '') {
$data = $HTTP_RAW_POST_DATA;
}
$this->encoding = XML_RPC_Message::getEncoding($data);
$parser_resource = xml_parser_create($this->encoding);
$parser = (int) $parser_resource;
$XML_RPC_xh[$parser] = array();
$XML_RPC_xh[$parser]['cm'] = 0;
$XML_RPC_xh[$parser]['isf'] = 0;
$XML_RPC_xh[$parser]['params'] = array();
$XML_RPC_xh[$parser]['method'] = '';
$XML_RPC_xh[$parser]['stack'] = array();
$XML_RPC_xh[$parser]['valuestack'] = array();
$plist = '';
// decompose incoming XML into request structure
xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee');
xml_set_character_data_handler($parser_resource, 'XML_RPC_cd');
if (!xml_parse($parser_resource, $data, 1)) {
// return XML error as a faultCode
$r = new XML_RPC_Response(0,
$XML_RPC_errxml+xml_get_error_code($parser_resource),
sprintf('XML error: %s at line %d',
xml_error_string(xml_get_error_code($parser_resource)),
xml_get_current_line_number($parser_resource)));
xml_parser_free($parser_resource);
} elseif ($XML_RPC_xh[$parser]['isf']>1) {
$r = new XML_RPC_Response(0,
$XML_RPC_err['invalid_request'],
$XML_RPC_str['invalid_request']
. ': '
. $XML_RPC_xh[$parser]['isf_reason']);
xml_parser_free($parser_resource);
} else {
xml_parser_free($parser_resource);
$m = new XML_RPC_Message($XML_RPC_xh[$parser]['method']);
// now add parameters in
for ($i = 0; $i < sizeof($XML_RPC_xh[$parser]['params']); $i++) {
// print '<!-- ' . $XML_RPC_xh[$parser]['params'][$i]. "-->\n";
$plist .= "$i - " . var_export($XML_RPC_xh[$parser]['params'][$i], true) . " \n";
$m->addParam($XML_RPC_xh[$parser]['params'][$i]);
}
if ($this->debug) {
XML_RPC_Server_debugmsg($plist);
}
// now to deal with the method
$methName = $XML_RPC_xh[$parser]['method'];
if (strpos($methName, 'system.') === 0) {
$dmap = $XML_RPC_Server_dmap;
$sysCall = 1;
} else {
$dmap = $this->dmap;
$sysCall = 0;
}
if (isset($dmap[$methName]['function'])
&& is_string($dmap[$methName]['function'])
&& strpos($dmap[$methName]['function'], '::') !== false)
{
$dmap[$methName]['function'] =
explode('::', $dmap[$methName]['function']);
}
if (isset($dmap[$methName]['function'])
&& is_callable($dmap[$methName]['function']))
{
// dispatch if exists
if (isset($dmap[$methName]['signature'])) {
$sr = $this->verifySignature($m,
$dmap[$methName]['signature'] );
}
if (!isset($dmap[$methName]['signature']) || $sr[0]) {
// if no signature or correct signature
if ($sysCall) {
$r = call_user_func($dmap[$methName]['function'], $this, $m);
} else {
$r = call_user_func($dmap[$methName]['function'], $m);
}
if (!is_a($r, 'XML_RPC_Response')) {
$r = new XML_RPC_Response(0, $XML_RPC_err['not_response_object'],
$XML_RPC_str['not_response_object']);
}
} else {
$r = new XML_RPC_Response(0, $XML_RPC_err['incorrect_params'],
$XML_RPC_str['incorrect_params']
. ': ' . $sr[1]);
}
} else {
// else prepare error response
$r = new XML_RPC_Response(0, $XML_RPC_err['unknown_method'],
$XML_RPC_str['unknown_method']);
}
}
return $r;
}
/**
* Echos back the input packet as a string value
*
* @return void
*
* Useful for debugging.
*/
function echoInput()
{
global $HTTP_RAW_POST_DATA;
$r = new XML_RPC_Response(0);
$r->xv = new XML_RPC_Value("'Aha said I: '" . $HTTP_RAW_POST_DATA, 'string');
print $r->serialize();
}
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,983 @@
<?PHP
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* XML_Unserializer
*
* Parses any XML document into PHP data structures.
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2003-2008 Stephan Schmidt <schst@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category XML
* @package XML_Serializer
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version CVS: $Id: Unserializer.php,v 1.42 2009/02/09 14:49:52 ashnazg Exp $
* @link http://pear.php.net/package/XML_Serializer
* @see XML_Unserializer
*/
/**
* uses PEAR error managemt
*/
require_once 'PEAR.php';
/**
* uses XML_Parser to unserialize document
*/
require_once 'XML/Parser.php';
/**
* option: Convert nested tags to array or object
*
* Possible values:
* - array
* - object
* - associative array to define this option per tag name
*/
define('XML_UNSERIALIZER_OPTION_COMPLEXTYPE', 'complexType');
/**
* option: Name of the attribute that stores the original key
*
* Possible values:
* - any string
*/
define('XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY', 'keyAttribute');
/**
* option: Name of the attribute that stores the type
*
* Possible values:
* - any string
*/
define('XML_UNSERIALIZER_OPTION_ATTRIBUTE_TYPE', 'typeAttribute');
/**
* option: Name of the attribute that stores the class name
*
* Possible values:
* - any string
*/
define('XML_UNSERIALIZER_OPTION_ATTRIBUTE_CLASS', 'classAttribute');
/**
* option: Whether to use the tag name as a class name
*
* Possible values:
* - true or false
*/
define('XML_UNSERIALIZER_OPTION_TAG_AS_CLASSNAME', 'tagAsClass');
/**
* option: Name of the default class
*
* Possible values:
* - any string
*/
define('XML_UNSERIALIZER_OPTION_DEFAULT_CLASS', 'defaultClass');
/**
* option: Whether to parse attributes
*
* Possible values:
* - true or false
*/
define('XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE', 'parseAttributes');
/**
* option: Key of the array to store attributes (if any)
*
* Possible values:
* - any string
* - false (disabled)
*/
define('XML_UNSERIALIZER_OPTION_ATTRIBUTES_ARRAYKEY', 'attributesArray');
/**
* option: string to prepend attribute name (if any)
*
* Possible values:
* - any string
* - false (disabled)
*/
define('XML_UNSERIALIZER_OPTION_ATTRIBUTES_PREPEND', 'prependAttributes');
/**
* option: key to store the content,
* if XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE is used
*
* Possible values:
* - any string
*/
define('XML_UNSERIALIZER_OPTION_CONTENT_KEY', 'contentName');
/**
* option: map tag names
*
* Possible values:
* - associative array
*/
define('XML_UNSERIALIZER_OPTION_TAG_MAP', 'tagMap');
/**
* option: list of tags that will always be enumerated
*
* Possible values:
* - indexed array
*/
define('XML_UNSERIALIZER_OPTION_FORCE_ENUM', 'forceEnum');
/**
* option: Encoding of the XML document
*
* Possible values:
* - UTF-8
* - ISO-8859-1
*/
define('XML_UNSERIALIZER_OPTION_ENCODING_SOURCE', 'encoding');
/**
* option: Desired target encoding of the data
*
* Possible values:
* - UTF-8
* - ISO-8859-1
*/
define('XML_UNSERIALIZER_OPTION_ENCODING_TARGET', 'targetEncoding');
/**
* option: Callback that will be applied to textual data
*
* Possible values:
* - any valid PHP callback
*/
define('XML_UNSERIALIZER_OPTION_DECODE_FUNC', 'decodeFunction');
/**
* option: whether to return the result of the unserialization from unserialize()
*
* Possible values:
* - true
* - false (default)
*/
define('XML_UNSERIALIZER_OPTION_RETURN_RESULT', 'returnResult');
/**
* option: set the whitespace behaviour
*
* Possible values:
* - XML_UNSERIALIZER_WHITESPACE_KEEP
* - XML_UNSERIALIZER_WHITESPACE_TRIM
* - XML_UNSERIALIZER_WHITESPACE_NORMALIZE
*/
define('XML_UNSERIALIZER_OPTION_WHITESPACE', 'whitespace');
/**
* Keep all whitespace
*/
define('XML_UNSERIALIZER_WHITESPACE_KEEP', 'keep');
/**
* remove whitespace from start and end of the data
*/
define('XML_UNSERIALIZER_WHITESPACE_TRIM', 'trim');
/**
* normalize whitespace
*/
define('XML_UNSERIALIZER_WHITESPACE_NORMALIZE', 'normalize');
/**
* option: whether to ovverride all options that have been set before
*
* Possible values:
* - true
* - false (default)
*/
define('XML_UNSERIALIZER_OPTION_OVERRIDE_OPTIONS', 'overrideOptions');
/**
* option: list of tags, that will not be used as keys
*/
define('XML_UNSERIALIZER_OPTION_IGNORE_KEYS', 'ignoreKeys');
/**
* option: whether to use type guessing for scalar values
*/
define('XML_UNSERIALIZER_OPTION_GUESS_TYPES', 'guessTypes');
/**
* error code for no serialization done
*/
define('XML_UNSERIALIZER_ERROR_NO_UNSERIALIZATION', 151);
/**
* XML_Unserializer
*
* class to unserialize XML documents that have been created with
* XML_Serializer. To unserialize an XML document you have to add
* type hints to the XML_Serializer options.
*
* If no type hints are available, XML_Unserializer will guess how
* the tags should be treated, that means complex structures will be
* arrays and tags with only CData in them will be strings.
*
* <code>
* require_once 'XML/Unserializer.php';
*
* // be careful to always use the ampersand in front of the new operator
* $unserializer = &new XML_Unserializer();
*
* $unserializer->unserialize($xml);
*
* $data = $unserializer->getUnserializedData();
* <code>
*
* @category XML
* @package XML_Serializer
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version Release: 0.20.0
* @link http://pear.php.net/package/XML_Serializer
* @see XML_Serializer
*/
class XML_Unserializer extends PEAR
{
/**
* list of all available options
*
* @access private
* @var array
*/
var $_knownOptions = array(
XML_UNSERIALIZER_OPTION_COMPLEXTYPE,
XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY,
XML_UNSERIALIZER_OPTION_ATTRIBUTE_TYPE,
XML_UNSERIALIZER_OPTION_ATTRIBUTE_CLASS,
XML_UNSERIALIZER_OPTION_TAG_AS_CLASSNAME,
XML_UNSERIALIZER_OPTION_DEFAULT_CLASS,
XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE,
XML_UNSERIALIZER_OPTION_ATTRIBUTES_ARRAYKEY,
XML_UNSERIALIZER_OPTION_ATTRIBUTES_PREPEND,
XML_UNSERIALIZER_OPTION_CONTENT_KEY,
XML_UNSERIALIZER_OPTION_TAG_MAP,
XML_UNSERIALIZER_OPTION_FORCE_ENUM,
XML_UNSERIALIZER_OPTION_ENCODING_SOURCE,
XML_UNSERIALIZER_OPTION_ENCODING_TARGET,
XML_UNSERIALIZER_OPTION_DECODE_FUNC,
XML_UNSERIALIZER_OPTION_RETURN_RESULT,
XML_UNSERIALIZER_OPTION_WHITESPACE,
XML_UNSERIALIZER_OPTION_IGNORE_KEYS,
XML_UNSERIALIZER_OPTION_GUESS_TYPES
);
/**
* default options for the serialization
*
* @access private
* @var array
*/
var $_defaultOptions = array(
// complex types will be converted to arrays, if no type hint is given
XML_UNSERIALIZER_OPTION_COMPLEXTYPE => 'array',
// get array key/property name from this attribute
XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY => '_originalKey',
// get type from this attribute
XML_UNSERIALIZER_OPTION_ATTRIBUTE_TYPE => '_type',
// get class from this attribute (if not given, use tag name)
XML_UNSERIALIZER_OPTION_ATTRIBUTE_CLASS => '_class',
// use the tagname as the classname
XML_UNSERIALIZER_OPTION_TAG_AS_CLASSNAME => true,
// name of the class that is used to create objects
XML_UNSERIALIZER_OPTION_DEFAULT_CLASS => 'stdClass',
// parse the attributes of the tag into an array
XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE => false,
// parse them into sperate array (specify name of array here)
XML_UNSERIALIZER_OPTION_ATTRIBUTES_ARRAYKEY => false,
// prepend attribute names with this string
XML_UNSERIALIZER_OPTION_ATTRIBUTES_PREPEND => '',
// put cdata found in a tag that has been converted
// to a complex type in this key
XML_UNSERIALIZER_OPTION_CONTENT_KEY => '_content',
// use this to map tagnames
XML_UNSERIALIZER_OPTION_TAG_MAP => array(),
// these tags will always be an indexed array
XML_UNSERIALIZER_OPTION_FORCE_ENUM => array(),
// specify the encoding character of the document to parse
XML_UNSERIALIZER_OPTION_ENCODING_SOURCE => null,
// specify the target encoding
XML_UNSERIALIZER_OPTION_ENCODING_TARGET => null,
// function used to decode data
XML_UNSERIALIZER_OPTION_DECODE_FUNC => null,
// unserialize() returns the result of the unserialization instead of true
XML_UNSERIALIZER_OPTION_RETURN_RESULT => false,
// remove whitespace around data
XML_UNSERIALIZER_OPTION_WHITESPACE => XML_UNSERIALIZER_WHITESPACE_TRIM,
// List of tags that will automatically be added to the parent,
// instead of adding a new key
XML_UNSERIALIZER_OPTION_IGNORE_KEYS => array(),
// Whether to use type guessing
XML_UNSERIALIZER_OPTION_GUESS_TYPES => false
);
/**
* current options for the serialization
*
* @access public
* @var array
*/
var $options = array();
/**
* unserialized data
*
* @access private
* @var string
*/
var $_unserializedData = null;
/**
* name of the root tag
*
* @access private
* @var string
*/
var $_root = null;
/**
* stack for all data that is found
*
* @access private
* @var array
*/
var $_dataStack = array();
/**
* stack for all values that are generated
*
* @access private
* @var array
*/
var $_valStack = array();
/**
* current tag depth
*
* @access private
* @var int
*/
var $_depth = 0;
/**
* XML_Parser instance
*
* @access private
* @var object XML_Parser
*/
var $_parser = null;
/**
* constructor
*
* @param mixed $options array containing options for the unserialization
*
* @access public
*/
function XML_Unserializer($options = null)
{
if (is_array($options)) {
$this->options = array_merge($this->_defaultOptions, $options);
} else {
$this->options = $this->_defaultOptions;
}
}
/**
* return API version
*
* @access public
* @return string $version API version
* @static
*/
function apiVersion()
{
return '0.20.0';
}
/**
* reset all options to default options
*
* @return void
* @access public
* @see setOption(), XML_Unserializer(), setOptions()
*/
function resetOptions()
{
$this->options = $this->_defaultOptions;
}
/**
* set an option
*
* You can use this method if you do not want
* to set all options in the constructor
*
* @param string $name name of option
* @param mixed $value value of option
*
* @return void
* @access public
* @see resetOption(), XML_Unserializer(), setOptions()
*/
function setOption($name, $value)
{
$this->options[$name] = $value;
}
/**
* sets several options at once
*
* You can use this method if you do not want
* to set all options in the constructor
*
* @param array $options options array
*
* @return void
* @access public
* @see resetOption(), XML_Unserializer(), setOption()
*/
function setOptions($options)
{
$this->options = array_merge($this->options, $options);
}
/**
* unserialize data
*
* @param mixed $data data to unserialize (string, filename or resource)
* @param boolean $isFile data should be treated as a file
* @param array $options options that will override
* the global options for this call
*
* @return boolean $success
* @access public
*/
function unserialize($data, $isFile = false, $options = null)
{
$this->_unserializedData = null;
$this->_root = null;
// if options have been specified, use them instead
// of the previously defined ones
if (is_array($options)) {
$optionsBak = $this->options;
if (isset($options[XML_UNSERIALIZER_OPTION_OVERRIDE_OPTIONS])
&& $options[XML_UNSERIALIZER_OPTION_OVERRIDE_OPTIONS] == true
) {
$this->options = array_merge($this->_defaultOptions, $options);
} else {
$this->options = array_merge($this->options, $options);
}
} else {
$optionsBak = null;
}
$this->_valStack = array();
$this->_dataStack = array();
$this->_depth = 0;
$this->_createParser();
if (is_string($data)) {
if ($isFile) {
$result = $this->_parser->setInputFile($data);
if (PEAR::isError($result)) {
return $result;
}
$result = $this->_parser->parse();
} else {
$result = $this->_parser->parseString($data, true);
}
} else {
$this->_parser->setInput($data);
$result = $this->_parser->parse();
}
if ($this->options[XML_UNSERIALIZER_OPTION_RETURN_RESULT] === true) {
$return = $this->_unserializedData;
} else {
$return = true;
}
if ($optionsBak !== null) {
$this->options = $optionsBak;
}
if (PEAR::isError($result)) {
return $result;
}
return $return;
}
/**
* get the result of the serialization
*
* @access public
* @return string $serializedData
*/
function getUnserializedData()
{
if ($this->_root === null) {
return $this->raiseError('No unserialized data available. '
. 'Use XML_Unserializer::unserialize() first.',
XML_UNSERIALIZER_ERROR_NO_UNSERIALIZATION);
}
return $this->_unserializedData;
}
/**
* get the name of the root tag
*
* @access public
* @return string $rootName
*/
function getRootName()
{
if ($this->_root === null) {
return $this->raiseError('No unserialized data available. '
. 'Use XML_Unserializer::unserialize() first.',
XML_UNSERIALIZER_ERROR_NO_UNSERIALIZATION);
}
return $this->_root;
}
/**
* Start element handler for XML parser
*
* @param object $parser XML parser object
* @param string $element XML element
* @param array $attribs attributes of XML tag
*
* @return void
* @access private
*/
function startHandler($parser, $element, $attribs)
{
if (isset($attribs[$this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_TYPE]])
) {
$type = $attribs[$this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_TYPE]];
$guessType = false;
} else {
$type = 'string';
if ($this->options[XML_UNSERIALIZER_OPTION_GUESS_TYPES] === true) {
$guessType = true;
} else {
$guessType = false;
}
}
if ($this->options[XML_UNSERIALIZER_OPTION_DECODE_FUNC] !== null) {
$attribs = array_map($this->options[XML_UNSERIALIZER_OPTION_DECODE_FUNC],
$attribs);
}
$this->_depth++;
$this->_dataStack[$this->_depth] = null;
if (is_array($this->options[XML_UNSERIALIZER_OPTION_TAG_MAP])
&& isset($this->options[XML_UNSERIALIZER_OPTION_TAG_MAP][$element])
) {
$element = $this->options[XML_UNSERIALIZER_OPTION_TAG_MAP][$element];
}
$val = array(
'name' => $element,
'value' => null,
'type' => $type,
'guessType' => $guessType,
'childrenKeys' => array(),
'aggregKeys' => array()
);
if ($this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE] == true
&& (count($attribs) > 0)
) {
$val['children'] = array();
$val['type'] = $this->_getComplexType($element);
$val['class'] = $element;
if ($this->options[XML_UNSERIALIZER_OPTION_GUESS_TYPES] === true) {
$attribs = $this->_guessAndSetTypes($attribs);
}
if ($this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTES_ARRAYKEY] != false
) {
$val['children'][$this->
options[XML_UNSERIALIZER_OPTION_ATTRIBUTES_ARRAYKEY]] = $attribs;
} else {
foreach ($attribs as $attrib => $value) {
$val['children'][$this->
options[XML_UNSERIALIZER_OPTION_ATTRIBUTES_PREPEND]
. $attrib] = $value;
}
}
}
$keyAttr = false;
if (is_string($this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY])) {
$keyAttr = $this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY];
} elseif (is_array($this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY])) {
if (isset($this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY]
[$element])
) {
$keyAttr =
$this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY][$element];
} elseif (isset($this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY]
['#default'])
) {
$keyAttr = $this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY]
['#default'];
} elseif (isset($this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY]
['__default'])
) {
// keep this for BC
$keyAttr =
$this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY]
['__default'];
}
}
if ($keyAttr !== false && isset($attribs[$keyAttr])) {
$val['name'] = $attribs[$keyAttr];
}
if (isset($attribs[$this->
options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_CLASS]])
) {
$val['class'] =
$attribs[$this->options[XML_UNSERIALIZER_OPTION_ATTRIBUTE_CLASS]];
}
array_push($this->_valStack, $val);
}
/**
* Try to guess the type of several values and
* set them accordingly
*
* @param array $array array containing the values
*
* @return array array, containing the values with their correct types
* @access private
*/
function _guessAndSetTypes($array)
{
foreach ($array as $key => $value) {
$array[$key] = $this->_guessAndSetType($value);
}
return $array;
}
/**
* Try to guess the type of a value and
* set it accordingly
*
* @param string $value character data
*
* @return mixed value with the best matching type
* @access private
*/
function _guessAndSetType($value)
{
if ($value === 'true') {
return true;
}
if ($value === 'false') {
return false;
}
if ($value === 'NULL') {
return null;
}
if (preg_match('/^[-+]?[0-9]{1,}\\z/', $value)) {
return intval($value);
}
if (preg_match('/^[-+]?[0-9]{1,}\.[0-9]{1,}\\z/', $value)) {
return doubleval($value);
}
return (string)$value;
}
/**
* End element handler for XML parser
*
* @param object $parser XML parser object
* @param string $element element
*
* @return void
* @access private
*/
function endHandler($parser, $element)
{
$value = array_pop($this->_valStack);
switch ($this->options[XML_UNSERIALIZER_OPTION_WHITESPACE]) {
case XML_UNSERIALIZER_WHITESPACE_KEEP:
$data = $this->_dataStack[$this->_depth];
break;
case XML_UNSERIALIZER_WHITESPACE_NORMALIZE:
$data = trim(preg_replace('/\s\s+/m', ' ',
$this->_dataStack[$this->_depth]));
break;
case XML_UNSERIALIZER_WHITESPACE_TRIM:
default:
$data = trim($this->_dataStack[$this->_depth]);
break;
}
// adjust type of the value
switch(strtolower($value['type'])) {
// unserialize an object
case 'object':
if (isset($value['class'])) {
$classname = $value['class'];
} else {
$classname = '';
}
// instantiate the class
if ($this->options[XML_UNSERIALIZER_OPTION_TAG_AS_CLASSNAME] === true
&& class_exists($classname)
) {
$value['value'] = &new $classname;
} else {
$value['value'] =
&new $this->options[XML_UNSERIALIZER_OPTION_DEFAULT_CLASS];
}
if (trim($data) !== '') {
if ($value['guessType'] === true) {
$data = $this->_guessAndSetType($data);
}
$value['children'][$this->
options[XML_UNSERIALIZER_OPTION_CONTENT_KEY]] = $data;
}
// set properties
foreach ($value['children'] as $prop => $propVal) {
// check whether there is a special method to set this property
$setMethod = 'set'.$prop;
if (method_exists($value['value'], $setMethod)) {
call_user_func(array(&$value['value'], $setMethod), $propVal);
} else {
$value['value']->$prop = $propVal;
}
}
// check for magic function
if (method_exists($value['value'], '__wakeup')) {
$value['value']->__wakeup();
}
break;
// unserialize an array
case 'array':
if (trim($data) !== '') {
if ($value['guessType'] === true) {
$data = $this->_guessAndSetType($data);
}
$value['children'][$this->
options[XML_UNSERIALIZER_OPTION_CONTENT_KEY]] = $data;
}
if (isset($value['children'])) {
$value['value'] = $value['children'];
} else {
$value['value'] = array();
}
break;
// unserialize a null value
case 'null':
$data = null;
break;
// unserialize a resource => this is not possible :-(
case 'resource':
$value['value'] = $data;
break;
// unserialize any scalar value
default:
if ($value['guessType'] === true) {
$data = $this->_guessAndSetType($data);
} else {
settype($data, $value['type']);
}
$value['value'] = $data;
break;
}
$parent = array_pop($this->_valStack);
if ($parent === null) {
$this->_unserializedData = &$value['value'];
$this->_root = &$value['name'];
return true;
} else {
// parent has to be an array
if (!isset($parent['children']) || !is_array($parent['children'])) {
$parent['children'] = array();
if (!in_array($parent['type'], array('array', 'object'))) {
$parent['type'] = $this->_getComplexType($parent['name']);
if ($parent['type'] == 'object') {
$parent['class'] = $parent['name'];
}
}
}
if (in_array($element,
$this->options[XML_UNSERIALIZER_OPTION_IGNORE_KEYS])
) {
$ignoreKey = true;
} else {
$ignoreKey = false;
}
if (!empty($value['name']) && $ignoreKey === false) {
// there already has been a tag with this name
if (in_array($value['name'], $parent['childrenKeys'])
|| in_array($value['name'],
$this->options[XML_UNSERIALIZER_OPTION_FORCE_ENUM])
) {
// no aggregate has been created for this tag
if (!in_array($value['name'], $parent['aggregKeys'])) {
if (isset($parent['children'][$value['name']])) {
$parent['children'][$value['name']] =
array($parent['children'][$value['name']]);
} else {
$parent['children'][$value['name']] = array();
}
array_push($parent['aggregKeys'], $value['name']);
}
array_push($parent['children'][$value['name']], $value['value']);
} else {
$parent['children'][$value['name']] = &$value['value'];
array_push($parent['childrenKeys'], $value['name']);
}
} else {
array_push($parent['children'], $value['value']);
}
array_push($this->_valStack, $parent);
}
$this->_depth--;
}
/**
* Handler for character data
*
* @param object $parser XML parser object
* @param string $cdata CDATA
*
* @return void
* @access private
*/
function cdataHandler($parser, $cdata)
{
if ($this->options[XML_UNSERIALIZER_OPTION_DECODE_FUNC] !== null) {
$cdata = call_user_func($this->
options[XML_UNSERIALIZER_OPTION_DECODE_FUNC], $cdata);
}
$this->_dataStack[$this->_depth] .= $cdata;
}
/**
* get the complex type, that should be used for a specified tag
*
* @param string $tagname name of the tag
*
* @return string complex type ('array' or 'object')
* @access private
*/
function _getComplexType($tagname)
{
if (is_string($this->options[XML_UNSERIALIZER_OPTION_COMPLEXTYPE])) {
return $this->options[XML_UNSERIALIZER_OPTION_COMPLEXTYPE];
}
if (isset($this->options[XML_UNSERIALIZER_OPTION_COMPLEXTYPE][$tagname])) {
return $this->options[XML_UNSERIALIZER_OPTION_COMPLEXTYPE][$tagname];
}
if (isset($this->options[XML_UNSERIALIZER_OPTION_COMPLEXTYPE]['#default'])) {
return $this->options[XML_UNSERIALIZER_OPTION_COMPLEXTYPE]['#default'];
}
return 'array';
}
/**
* create the XML_Parser instance
*
* @return boolean
* @access private
*/
function _createParser()
{
if (is_object($this->_parser)) {
$this->_parser->free();
unset($this->_parser);
}
$this->_parser = &new XML_Parser($this->
options[XML_UNSERIALIZER_OPTION_ENCODING_SOURCE],
'event', $this->options[XML_UNSERIALIZER_OPTION_ENCODING_TARGET]);
$this->_parser->folding = false;
$this->_parser->setHandlerObj($this);
return true;
}
}
?>

View file

@ -0,0 +1,911 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* XML_Util
*
* XML Utilities package
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2003-2008 Stephan Schmidt <schst@php.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category XML
* @package XML_Util
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version CVS: $Id: Util.php,v 1.38 2008/11/13 00:03:38 ashnazg Exp $
* @link http://pear.php.net/package/XML_Util
*/
/**
* error code for invalid chars in XML name
*/
define('XML_UTIL_ERROR_INVALID_CHARS', 51);
/**
* error code for invalid chars in XML name
*/
define('XML_UTIL_ERROR_INVALID_START', 52);
/**
* error code for non-scalar tag content
*/
define('XML_UTIL_ERROR_NON_SCALAR_CONTENT', 60);
/**
* error code for missing tag name
*/
define('XML_UTIL_ERROR_NO_TAG_NAME', 61);
/**
* replace XML entities
*/
define('XML_UTIL_REPLACE_ENTITIES', 1);
/**
* embedd content in a CData Section
*/
define('XML_UTIL_CDATA_SECTION', 5);
/**
* do not replace entitites
*/
define('XML_UTIL_ENTITIES_NONE', 0);
/**
* replace all XML entitites
* This setting will replace <, >, ", ' and &
*/
define('XML_UTIL_ENTITIES_XML', 1);
/**
* replace only required XML entitites
* This setting will replace <, " and &
*/
define('XML_UTIL_ENTITIES_XML_REQUIRED', 2);
/**
* replace HTML entitites
* @link http://www.php.net/htmlentities
*/
define('XML_UTIL_ENTITIES_HTML', 3);
/**
* Collapse all empty tags.
*/
define('XML_UTIL_COLLAPSE_ALL', 1);
/**
* Collapse only empty XHTML tags that have no end tag.
*/
define('XML_UTIL_COLLAPSE_XHTML_ONLY', 2);
/**
* utility class for working with XML documents
*
* @category XML
* @package XML_Util
* @author Stephan Schmidt <schst@php.net>
* @copyright 2003-2008 Stephan Schmidt <schst@php.net>
* @license http://opensource.org/licenses/bsd-license New BSD License
* @version Release: 1.2.1
* @link http://pear.php.net/package/XML_Util
*/
class XML_Util
{
/**
* return API version
*
* @return string $version API version
* @access public
* @static
*/
function apiVersion()
{
return '1.1';
}
/**
* replace XML entities
*
* With the optional second parameter, you may select, which
* entities should be replaced.
*
* <code>
* require_once 'XML/Util.php';
*
* // replace XML entites:
* $string = XML_Util::replaceEntities('This string contains < & >.');
* </code>
*
* With the optional third parameter, you may pass the character encoding
* <code>
* require_once 'XML/Util.php';
*
* // replace XML entites in UTF-8:
* $string = XML_Util::replaceEntities(
* 'This string contains < & > as well as ä, ö, ß, à and ê',
* XML_UTIL_ENTITIES_HTML,
* 'UTF-8'
* );
* </code>
*
* @param string $string string where XML special chars
* should be replaced
* @param int $replaceEntities setting for entities in attribute values
* (one of XML_UTIL_ENTITIES_XML,
* XML_UTIL_ENTITIES_XML_REQUIRED,
* XML_UTIL_ENTITIES_HTML)
* @param string $encoding encoding value (if any)...
* must be a valid encoding as determined
* by the htmlentities() function
*
* @return string string with replaced chars
* @access public
* @static
* @see reverseEntities()
*/
function replaceEntities($string, $replaceEntities = XML_UTIL_ENTITIES_XML,
$encoding = 'ISO-8859-1')
{
switch ($replaceEntities) {
case XML_UTIL_ENTITIES_XML:
return strtr($string, array(
'&' => '&amp;',
'>' => '&gt;',
'<' => '&lt;',
'"' => '&quot;',
'\'' => '&apos;' ));
break;
case XML_UTIL_ENTITIES_XML_REQUIRED:
return strtr($string, array(
'&' => '&amp;',
'<' => '&lt;',
'"' => '&quot;' ));
break;
case XML_UTIL_ENTITIES_HTML:
return htmlentities($string, ENT_COMPAT, $encoding);
break;
}
return $string;
}
/**
* reverse XML entities
*
* With the optional second parameter, you may select, which
* entities should be reversed.
*
* <code>
* require_once 'XML/Util.php';
*
* // reverse XML entites:
* $string = XML_Util::reverseEntities('This string contains &lt; &amp; &gt;.');
* </code>
*
* With the optional third parameter, you may pass the character encoding
* <code>
* require_once 'XML/Util.php';
*
* // reverse XML entites in UTF-8:
* $string = XML_Util::reverseEntities(
* 'This string contains &lt; &amp; &gt; as well as'
* . ' &auml;, &ouml;, &szlig;, &agrave; and &ecirc;',
* XML_UTIL_ENTITIES_HTML,
* 'UTF-8'
* );
* </code>
*
* @param string $string string where XML special chars
* should be replaced
* @param int $replaceEntities setting for entities in attribute values
* (one of XML_UTIL_ENTITIES_XML,
* XML_UTIL_ENTITIES_XML_REQUIRED,
* XML_UTIL_ENTITIES_HTML)
* @param string $encoding encoding value (if any)...
* must be a valid encoding as determined
* by the html_entity_decode() function
*
* @return string string with replaced chars
* @access public
* @static
* @see replaceEntities()
*/
function reverseEntities($string, $replaceEntities = XML_UTIL_ENTITIES_XML,
$encoding = 'ISO-8859-1')
{
switch ($replaceEntities) {
case XML_UTIL_ENTITIES_XML:
return strtr($string, array(
'&amp;' => '&',
'&gt;' => '>',
'&lt;' => '<',
'&quot;' => '"',
'&apos;' => '\'' ));
break;
case XML_UTIL_ENTITIES_XML_REQUIRED:
return strtr($string, array(
'&amp;' => '&',
'&lt;' => '<',
'&quot;' => '"' ));
break;
case XML_UTIL_ENTITIES_HTML:
return html_entity_decode($string, ENT_COMPAT, $encoding);
break;
}
return $string;
}
/**
* build an xml declaration
*
* <code>
* require_once 'XML/Util.php';
*
* // get an XML declaration:
* $xmlDecl = XML_Util::getXMLDeclaration('1.0', 'UTF-8', true);
* </code>
*
* @param string $version xml version
* @param string $encoding character encoding
* @param bool $standalone document is standalone (or not)
*
* @return string xml declaration
* @access public
* @static
* @uses attributesToString() to serialize the attributes of the XML declaration
*/
function getXMLDeclaration($version = '1.0', $encoding = null,
$standalone = null)
{
$attributes = array(
'version' => $version,
);
// add encoding
if ($encoding !== null) {
$attributes['encoding'] = $encoding;
}
// add standalone, if specified
if ($standalone !== null) {
$attributes['standalone'] = $standalone ? 'yes' : 'no';
}
return sprintf('<?xml%s?>',
XML_Util::attributesToString($attributes, false));
}
/**
* build a document type declaration
*
* <code>
* require_once 'XML/Util.php';
*
* // get a doctype declaration:
* $xmlDecl = XML_Util::getDocTypeDeclaration('rootTag','myDocType.dtd');
* </code>
*
* @param string $root name of the root tag
* @param string $uri uri of the doctype definition
* (or array with uri and public id)
* @param string $internalDtd internal dtd entries
*
* @return string doctype declaration
* @access public
* @static
* @since 0.2
*/
function getDocTypeDeclaration($root, $uri = null, $internalDtd = null)
{
if (is_array($uri)) {
$ref = sprintf(' PUBLIC "%s" "%s"', $uri['id'], $uri['uri']);
} elseif (!empty($uri)) {
$ref = sprintf(' SYSTEM "%s"', $uri);
} else {
$ref = '';
}
if (empty($internalDtd)) {
return sprintf('<!DOCTYPE %s%s>', $root, $ref);
} else {
return sprintf("<!DOCTYPE %s%s [\n%s\n]>", $root, $ref, $internalDtd);
}
}
/**
* create string representation of an attribute list
*
* <code>
* require_once 'XML/Util.php';
*
* // build an attribute string
* $att = array(
* 'foo' => 'bar',
* 'argh' => 'tomato'
* );
*
* $attList = XML_Util::attributesToString($att);
* </code>
*
* @param array $attributes attribute array
* @param bool|array $sort sort attribute list alphabetically,
* may also be an assoc array containing
* the keys 'sort', 'multiline', 'indent',
* 'linebreak' and 'entities'
* @param bool $multiline use linebreaks, if more than
* one attribute is given
* @param string $indent string used for indentation of
* multiline attributes
* @param string $linebreak string used for linebreaks of
* multiline attributes
* @param int $entities setting for entities in attribute values
* (one of XML_UTIL_ENTITIES_NONE,
* XML_UTIL_ENTITIES_XML,
* XML_UTIL_ENTITIES_XML_REQUIRED,
* XML_UTIL_ENTITIES_HTML)
*
* @return string string representation of the attributes
* @access public
* @static
* @uses replaceEntities() to replace XML entities in attribute values
* @todo allow sort also to be an options array
*/
function attributesToString($attributes, $sort = true, $multiline = false,
$indent = ' ', $linebreak = "\n", $entities = XML_UTIL_ENTITIES_XML)
{
/*
* second parameter may be an array
*/
if (is_array($sort)) {
if (isset($sort['multiline'])) {
$multiline = $sort['multiline'];
}
if (isset($sort['indent'])) {
$indent = $sort['indent'];
}
if (isset($sort['linebreak'])) {
$multiline = $sort['linebreak'];
}
if (isset($sort['entities'])) {
$entities = $sort['entities'];
}
if (isset($sort['sort'])) {
$sort = $sort['sort'];
} else {
$sort = true;
}
}
$string = '';
if (is_array($attributes) && !empty($attributes)) {
if ($sort) {
ksort($attributes);
}
if ( !$multiline || count($attributes) == 1) {
foreach ($attributes as $key => $value) {
if ($entities != XML_UTIL_ENTITIES_NONE) {
if ($entities === XML_UTIL_CDATA_SECTION) {
$entities = XML_UTIL_ENTITIES_XML;
}
$value = XML_Util::replaceEntities($value, $entities);
}
$string .= ' ' . $key . '="' . $value . '"';
}
} else {
$first = true;
foreach ($attributes as $key => $value) {
if ($entities != XML_UTIL_ENTITIES_NONE) {
$value = XML_Util::replaceEntities($value, $entities);
}
if ($first) {
$string .= ' ' . $key . '="' . $value . '"';
$first = false;
} else {
$string .= $linebreak . $indent . $key . '="' . $value . '"';
}
}
}
}
return $string;
}
/**
* Collapses empty tags.
*
* @param string $xml XML
* @param int $mode Whether to collapse all empty tags (XML_UTIL_COLLAPSE_ALL)
* or only XHTML (XML_UTIL_COLLAPSE_XHTML_ONLY) ones.
*
* @return string XML
* @access public
* @static
* @todo PEAR CS - unable to avoid "space after open parens" error
* in the IF branch
*/
function collapseEmptyTags($xml, $mode = XML_UTIL_COLLAPSE_ALL)
{
if ($mode == XML_UTIL_COLLAPSE_XHTML_ONLY) {
return preg_replace(
'/<(area|base(?:font)?|br|col|frame|hr|img|input|isindex|link|meta|'
. 'param)([^>]*)><\/\\1>/s',
'<\\1\\2 />',
$xml);
} else {
return preg_replace('/<(\w+)([^>]*)><\/\\1>/s', '<\\1\\2 />', $xml);
}
}
/**
* create a tag
*
* This method will call XML_Util::createTagFromArray(), which
* is more flexible.
*
* <code>
* require_once 'XML/Util.php';
*
* // create an XML tag:
* $tag = XML_Util::createTag('myNs:myTag',
* array('foo' => 'bar'),
* 'This is inside the tag',
* 'http://www.w3c.org/myNs#');
* </code>
*
* @param string $qname qualified tagname (including namespace)
* @param array $attributes array containg attributes
* @param mixed $content the content
* @param string $namespaceUri URI of the namespace
* @param int $replaceEntities whether to replace XML special chars in
* content, embedd it in a CData section
* or none of both
* @param bool $multiline whether to create a multiline tag where
* each attribute gets written to a single line
* @param string $indent string used to indent attributes
* (_auto indents attributes so they start
* at the same column)
* @param string $linebreak string used for linebreaks
* @param bool $sortAttributes Whether to sort the attributes or not
*
* @return string XML tag
* @access public
* @static
* @see createTagFromArray()
* @uses createTagFromArray() to create the tag
*/
function createTag($qname, $attributes = array(), $content = null,
$namespaceUri = null, $replaceEntities = XML_UTIL_REPLACE_ENTITIES,
$multiline = false, $indent = '_auto', $linebreak = "\n",
$sortAttributes = true)
{
$tag = array(
'qname' => $qname,
'attributes' => $attributes
);
// add tag content
if ($content !== null) {
$tag['content'] = $content;
}
// add namespace Uri
if ($namespaceUri !== null) {
$tag['namespaceUri'] = $namespaceUri;
}
return XML_Util::createTagFromArray($tag, $replaceEntities, $multiline,
$indent, $linebreak, $sortAttributes);
}
/**
* create a tag from an array
* this method awaits an array in the following format
* <pre>
* array(
* // qualified name of the tag
* 'qname' => $qname
*
* // namespace prefix (optional, if qname is specified or no namespace)
* 'namespace' => $namespace
*
* // local part of the tagname (optional, if qname is specified)
* 'localpart' => $localpart,
*
* // array containing all attributes (optional)
* 'attributes' => array(),
*
* // tag content (optional)
* 'content' => $content,
*
* // namespaceUri for the given namespace (optional)
* 'namespaceUri' => $namespaceUri
* )
* </pre>
*
* <code>
* require_once 'XML/Util.php';
*
* $tag = array(
* 'qname' => 'foo:bar',
* 'namespaceUri' => 'http://foo.com',
* 'attributes' => array('key' => 'value', 'argh' => 'fruit&vegetable'),
* 'content' => 'I\'m inside the tag',
* );
* // creating a tag with qualified name and namespaceUri
* $string = XML_Util::createTagFromArray($tag);
* </code>
*
* @param array $tag tag definition
* @param int $replaceEntities whether to replace XML special chars in
* content, embedd it in a CData section
* or none of both
* @param bool $multiline whether to create a multiline tag where each
* attribute gets written to a single line
* @param string $indent string used to indent attributes
* (_auto indents attributes so they start
* at the same column)
* @param string $linebreak string used for linebreaks
* @param bool $sortAttributes Whether to sort the attributes or not
*
* @return string XML tag
* @access public
* @static
* @see createTag()
* @uses attributesToString() to serialize the attributes of the tag
* @uses splitQualifiedName() to get local part and namespace of a qualified name
* @uses createCDataSection()
* @uses raiseError()
*/
function createTagFromArray($tag, $replaceEntities = XML_UTIL_REPLACE_ENTITIES,
$multiline = false, $indent = '_auto', $linebreak = "\n",
$sortAttributes = true)
{
if (isset($tag['content']) && !is_scalar($tag['content'])) {
return XML_Util::raiseError('Supplied non-scalar value as tag content',
XML_UTIL_ERROR_NON_SCALAR_CONTENT);
}
if (!isset($tag['qname']) && !isset($tag['localPart'])) {
return XML_Util::raiseError('You must either supply a qualified name '
. '(qname) or local tag name (localPart).',
XML_UTIL_ERROR_NO_TAG_NAME);
}
// if no attributes hav been set, use empty attributes
if (!isset($tag['attributes']) || !is_array($tag['attributes'])) {
$tag['attributes'] = array();
}
if (isset($tag['namespaces'])) {
foreach ($tag['namespaces'] as $ns => $uri) {
$tag['attributes']['xmlns:' . $ns] = $uri;
}
}
if (!isset($tag['qname'])) {
// qualified name is not given
// check for namespace
if (isset($tag['namespace']) && !empty($tag['namespace'])) {
$tag['qname'] = $tag['namespace'] . ':' . $tag['localPart'];
} else {
$tag['qname'] = $tag['localPart'];
}
} elseif (isset($tag['namespaceUri']) && !isset($tag['namespace'])) {
// namespace URI is set, but no namespace
$parts = XML_Util::splitQualifiedName($tag['qname']);
$tag['localPart'] = $parts['localPart'];
if (isset($parts['namespace'])) {
$tag['namespace'] = $parts['namespace'];
}
}
if (isset($tag['namespaceUri']) && !empty($tag['namespaceUri'])) {
// is a namespace given
if (isset($tag['namespace']) && !empty($tag['namespace'])) {
$tag['attributes']['xmlns:' . $tag['namespace']] =
$tag['namespaceUri'];
} else {
// define this Uri as the default namespace
$tag['attributes']['xmlns'] = $tag['namespaceUri'];
}
}
// check for multiline attributes
if ($multiline === true) {
if ($indent === '_auto') {
$indent = str_repeat(' ', (strlen($tag['qname'])+2));
}
}
// create attribute list
$attList = XML_Util::attributesToString($tag['attributes'],
$sortAttributes, $multiline, $indent, $linebreak, $replaceEntities);
if (!isset($tag['content']) || (string)$tag['content'] == '') {
$tag = sprintf('<%s%s />', $tag['qname'], $attList);
} else {
switch ($replaceEntities) {
case XML_UTIL_ENTITIES_NONE:
break;
case XML_UTIL_CDATA_SECTION:
$tag['content'] = XML_Util::createCDataSection($tag['content']);
break;
default:
$tag['content'] = XML_Util::replaceEntities($tag['content'],
$replaceEntities);
break;
}
$tag = sprintf('<%s%s>%s</%s>', $tag['qname'], $attList, $tag['content'],
$tag['qname']);
}
return $tag;
}
/**
* create a start element
*
* <code>
* require_once 'XML/Util.php';
*
* // create an XML start element:
* $tag = XML_Util::createStartElement('myNs:myTag',
* array('foo' => 'bar') ,'http://www.w3c.org/myNs#');
* </code>
*
* @param string $qname qualified tagname (including namespace)
* @param array $attributes array containg attributes
* @param string $namespaceUri URI of the namespace
* @param bool $multiline whether to create a multiline tag where each
* attribute gets written to a single line
* @param string $indent string used to indent attributes (_auto indents
* attributes so they start at the same column)
* @param string $linebreak string used for linebreaks
* @param bool $sortAttributes Whether to sort the attributes or not
*
* @return string XML start element
* @access public
* @static
* @see createEndElement(), createTag()
*/
function createStartElement($qname, $attributes = array(), $namespaceUri = null,
$multiline = false, $indent = '_auto', $linebreak = "\n",
$sortAttributes = true)
{
// if no attributes hav been set, use empty attributes
if (!isset($attributes) || !is_array($attributes)) {
$attributes = array();
}
if ($namespaceUri != null) {
$parts = XML_Util::splitQualifiedName($qname);
}
// check for multiline attributes
if ($multiline === true) {
if ($indent === '_auto') {
$indent = str_repeat(' ', (strlen($qname)+2));
}
}
if ($namespaceUri != null) {
// is a namespace given
if (isset($parts['namespace']) && !empty($parts['namespace'])) {
$attributes['xmlns:' . $parts['namespace']] = $namespaceUri;
} else {
// define this Uri as the default namespace
$attributes['xmlns'] = $namespaceUri;
}
}
// create attribute list
$attList = XML_Util::attributesToString($attributes, $sortAttributes,
$multiline, $indent, $linebreak);
$element = sprintf('<%s%s>', $qname, $attList);
return $element;
}
/**
* create an end element
*
* <code>
* require_once 'XML/Util.php';
*
* // create an XML start element:
* $tag = XML_Util::createEndElement('myNs:myTag');
* </code>
*
* @param string $qname qualified tagname (including namespace)
*
* @return string XML end element
* @access public
* @static
* @see createStartElement(), createTag()
*/
function createEndElement($qname)
{
$element = sprintf('</%s>', $qname);
return $element;
}
/**
* create an XML comment
*
* <code>
* require_once 'XML/Util.php';
*
* // create an XML start element:
* $tag = XML_Util::createComment('I am a comment');
* </code>
*
* @param string $content content of the comment
*
* @return string XML comment
* @access public
* @static
*/
function createComment($content)
{
$comment = sprintf('<!-- %s -->', $content);
return $comment;
}
/**
* create a CData section
*
* <code>
* require_once 'XML/Util.php';
*
* // create a CData section
* $tag = XML_Util::createCDataSection('I am content.');
* </code>
*
* @param string $data data of the CData section
*
* @return string CData section with content
* @access public
* @static
*/
function createCDataSection($data)
{
return sprintf('<![CDATA[%s]]>',
preg_replace('/\]\]>/', ']]]]><![CDATA[>', strval($data)));
}
/**
* split qualified name and return namespace and local part
*
* <code>
* require_once 'XML/Util.php';
*
* // split qualified tag
* $parts = XML_Util::splitQualifiedName('xslt:stylesheet');
* </code>
* the returned array will contain two elements:
* <pre>
* array(
* 'namespace' => 'xslt',
* 'localPart' => 'stylesheet'
* );
* </pre>
*
* @param string $qname qualified tag name
* @param string $defaultNs default namespace (optional)
*
* @return array array containing namespace and local part
* @access public
* @static
*/
function splitQualifiedName($qname, $defaultNs = null)
{
if (strstr($qname, ':')) {
$tmp = explode(':', $qname);
return array(
'namespace' => $tmp[0],
'localPart' => $tmp[1]
);
}
return array(
'namespace' => $defaultNs,
'localPart' => $qname
);
}
/**
* check, whether string is valid XML name
*
* <p>XML names are used for tagname, attribute names and various
* other, lesser known entities.</p>
* <p>An XML name may only consist of alphanumeric characters,
* dashes, undescores and periods, and has to start with a letter
* or an underscore.</p>
*
* <code>
* require_once 'XML/Util.php';
*
* // verify tag name
* $result = XML_Util::isValidName('invalidTag?');
* if (is_a($result, 'PEAR_Error')) {
* print 'Invalid XML name: ' . $result->getMessage();
* }
* </code>
*
* @param string $string string that should be checked
*
* @return mixed true, if string is a valid XML name, PEAR error otherwise
* @access public
* @static
* @todo support for other charsets
* @todo PEAR CS - unable to avoid 85-char limit on second preg_match
*/
function isValidName($string)
{
// check for invalid chars
if (!preg_match('/^[[:alpha:]_]$/', $string{0})) {
return XML_Util::raiseError('XML names may only start with letter '
. 'or underscore', XML_UTIL_ERROR_INVALID_START);
}
// check for invalid chars
if (!preg_match('/^([[:alpha:]_]([[:alnum:]\-\.]*)?:)?[[:alpha:]_]([[:alnum:]\_\-\.]+)?$/',
$string)
) {
return XML_Util::raiseError('XML names may only contain alphanumeric '
. 'chars, period, hyphen, colon and underscores',
XML_UTIL_ERROR_INVALID_CHARS);
}
// XML name is valid
return true;
}
/**
* replacement for XML_Util::raiseError
*
* Avoids the necessity to always require
* PEAR.php
*
* @param string $msg error message
* @param int $code error code
*
* @return PEAR_Error
* @access public
* @static
* @todo PEAR CS - should this use include_once instead?
*/
function raiseError($msg, $code)
{
require_once 'PEAR.php';
return PEAR::raiseError($msg, $code);
}
}
?>