From 0a9efdd6d41d4398c3a1676b4a779e6eea84dba9 Mon Sep 17 00:00:00 2001
From: YuCheng Hu ' . htmlentities($html) . '
');
+ } //printHTML
+
+ /**
+ * Establishes a client connection
+ */
+ function connect() {
+ if (!$this->headers->headerExists('Host')) {
+ $this->setHeader('Host', $this->connection->host);
+ }
+
+ return $this->connection->connect();
+ } //connect
+
+ /**
+ * Disconnects the current client connection if one exists
+ */
+ function disconnect() {
+ return $this->connection->disconnect();
+ } //disconnect
+
+ /**
+ * Evaluated whether the current client is connected
+ * @return boolean True if a connection exists
+ */
+ function isConnected() {
+ return $this->connection->isOpen();
+ } //isConnected
+
+ /**
+ * Performs an HTTP GET
+ * @param string The target url
+ * @return object An HTTP response object
+ */
+ function &get($url) {
+ $this->setRequestMethod('GET');
+ $this->setRequestPath($url);
+
+ $this->get_custom($url);
+
+ $this->connect();
+
+ $result = $this->send('');
+
+ return $result;
+ } //get
+
+ /**
+ * Handler for customizing the HTTP GET call
+ * @param string The target url
+ */
+ function get_custom($url) {
+ //do nothing; meant to be overridden
+ } //get_custom
+
+ /**
+ * Performs an HTTP POST
+ * @param string The posted data
+ * @return object An HTTP response object
+ */
+ function &post($data) {
+ $this->setRequestMethod('POST');
+ $this->setHeader('Content-Type', 'text/html');
+ $this->post_custom($data);
+
+ $this->connect();
+
+ return $this->send($data);
+ } //post
+
+ /**
+ * Handler for customizing the HTTP POST call
+ * @param string The post data
+ */
+ function post_custom($data) {
+ //do nothing; meant to be overridden
+ } //post_custom
+
+ /**
+ * Performs an HTTP HEAD
+ * @param string The target url
+ * @return object An HTTP response object
+ */
+ function &head($url) {
+ $this->setRequestMethod('HEAD');
+ $this->head_custom($url);
+
+ $this->connect();
+
+ return $this->send('');
+ } //head
+
+ /**
+ * Handler for customizing the HTTP HEAD call
+ * @param string The target url
+ */
+ function head_custom($url) {
+ //do nothing; meant to be overridden
+ } //head_custom
+
+ /**
+ * Sends data through the client connection
+ * @param string The message to be sent
+ * @return string The http response
+ */
+ function send($message) {
+ $conn =& $this->connection;
+
+ if ($conn->isOpen()) {
+ //build header info
+ $request = $this->requestMethod . ' ' . $this->requestPath . ' ' . $this->protocol .
+ '/' . $this->protocolVersion . CRLF;
+ $request .= $this->headers->toString() . CRLF;
+ $request .= $message;
+
+ //init variables
+ $response = $headers = $body = '';
+ $readState = HTTP_READ_STATE_BEGIN;
+
+ $this->fireEvent('onRequest', $request);
+
+ //send request
+ $connResource =& $conn->connection;
+ fputs ($connResource, $request);
+
+ //read response
+ while (!feof($connResource)) {
+ $data = fgets($connResource, 4096);
+ $this->fireEvent('onRead', $data);
+
+ switch ($readState) {
+ case HTTP_READ_STATE_BEGIN:
+ $this->response->statusLine = $data;
+ $readState = HTTP_READ_STATE_HEADERS;
+ break;
+
+ case HTTP_READ_STATE_HEADERS:
+ if (trim($data) == '') { //end of headers is signalled by a blank line
+ $readState = HTTP_READ_STATE_BODY;
+ }
+ else {
+ if ($this->responseHeadersAsObject) {
+ $this->response->setUnformattedHeader($data);
+ }
+ else {
+ $this->response->headers .= $data;
+ }
+ }
+ break;
+
+ case HTTP_READ_STATE_BODY:
+ $this->response->message .= $data;
+ break;
+ }
+ }
+
+ $this->normalizeResponseIfChunked();
+
+ $headerString = is_object($this->response->headers) ?
+ $this->response->headers->toString() : $this->response->headers;
+
+ $this->fireEvent('onResponseHeaders', $headerString);
+ $this->fireEvent('onResponseBody', $this->response->message);
+
+ $this->fireEvent('onResponse', $this->response->headers . $this->response->message);
+
+ return $this->response;
+ }
+ else {
+ HTTPExceptions::raiseException(HTTP_SOCKET_CONNECTION_ERR, ('HTTP Transport Error - Unable to establish connection to host ' .
+ $conn->host));
+ }
+ } //send
+
+ /**
+ * Determines if response data is transfer encoding chunked, then decodes
+ */
+ function normalizeResponseIfChunked() {
+ if (($this->protocolVersion = '1.1') && (!$this->response->isResponseChunkDecoded)) {
+ if ($this->responseHeadersAsObject) {
+ if ($this->response->headers->headerExists('Transfer-Encoding') &&
+ ($this->response->headers->getHeader('Transfer-Encoding') == 'chunked')) {
+ $this->response->message = $this->decodeChunkedData($this->response->getResponse());
+ $this->response->isResponseChunkDecoded = true;
+ }
+ }
+ else {
+ if ((strpos($this->response->headers, 'Transfer-Encoding') !== false) &&
+ (strpos($this->response->headers, 'chunked') !== false)){
+ $this->response->message = $this->decodeChunkedData($this->response->getResponse());
+ $this->response->isResponseChunkDecoded = true;
+ }
+ }
+ }
+ } //normalizeResponseIfChunked
+
+ /**
+ * Decodes data if transfer encoding chunked
+ * @param string The encoded data
+ * @return string The decoded data
+ */
+ function decodeChunkedData($data) {
+ $chunkStart = $chunkEnd = strpos($data, CRLF) + 2;
+ $chunkLengthInHex = substr($data, 0, $chunkEnd);
+ $chunkLength = hexdec(trim($chunkLengthInHex));
+
+ $decodedData = '';
+
+ while ($chunkLength > 0) {
+ $chunkEnd = strpos($data, CRLF, ($chunkStart + $chunkLength));
+
+ if (!$chunkEnd) {
+ //if the trailing CRLF is missing, return all the remaining data
+ $decodedData .= substr($data, $chunkStart);
+ break;
+ }
+
+ $decodedData .= substr($data, $chunkStart, ($chunkEnd - $chunkStart));
+ $chunkStart = $chunkEnd + 2;
+ $chunkEnd = strpos($data, CRLF, $chunkStart) + 2;
+
+ if (!$chunkEnd) break;
+
+ $chunkLengthInHex = substr($data, $chunkStart, ($chunkEnd - $chunkStart));
+ $chunkLength = hexdec(trim($chunkLengthInHex));
+ $chunkStart = $chunkEnd;
+ }
+
+ return $decodedData;
+ } //decodeChunkedData
+} //php_http_client_generic
+
+
+/**
+* An HTTP Connection class
+*
+* @package php-http-tools
+* @author John Heinstein " . $errorMessage . "
" . $errorMessage . ""; + } + + //log error to file + if ((isset($GLOBALS['DOMIT_RSS_Exception_log'])) && + ($GLOBALS['DOMIT_RSS_Exception_log'] != null)) { + require_once(DOMIT_RSS_INCLUDE_PATH . 'php_file_utilities.php'); + + $logItem = "\n" . date('Y-m-d H:i:s') . 'DOMIT! RSS Error ' . $errorMessageText; + php_file_utilities::putDataToFile($GLOBALS['DOMIT_RSS_Exception_log'], $logItem, 'a'); + } + + switch ($GLOBALS['DOMIT_RSS_Exception_mode']) { + case DOMIT_RSS_ONERROR_CONTINUE: + return; + break; + + case DOMIT_RSS_ONERROR_DIE: + die($errorMessage); + break; + } + } + } //raiseException + + /** + * custom handler for DOM RSS errors + * @param object A reference to the custom error handler + */ + function setErrorHandler($method) { + $GLOBALS['DOMIT_RSS_Exception_errorHandler'] =& $method; + + require_once(DOMIT_RSS_INCLUDE_PATH . 'php_http_exceptions.php'); + $GLOBALS['HTTP_Exception_errorHandler'] =& $method; + + require_once(DOMIT_RSS_INCLUDE_PATH . 'xml_domit_shared.php'); + $GLOBALS['HTTP_Exception_errorHandler'] =& $method; + } //setErrorHandler + + /** + * Set error mode + * @param int The DOMIT RSS error mode + */ + function setErrorMode($mode) { + $GLOBALS['DOMIT_RSS_Exception_mode'] = $mode; + + require_once(DOMIT_RSS_INCLUDE_PATH . 'php_http_exceptions.php'); + require_once(DOMIT_RSS_INCLUDE_PATH . 'xml_domit_shared.php'); + + if ($mode == DOMIT_RSS_ONERROR_CONTINUE) { + $GLOBALS['HTTP_Exception_mode'] = HTTP_ONERROR_CONTINUE; + $GLOBALS['DOMIT_DOMException_mode'] = DOMIT_ONERROR_CONTINUE; + } + else { + $GLOBALS['HTTP_Exception_mode'] = HTTP_ONERROR_DIE; + $GLOBALS['DOMIT_DOMException_mode'] = DOMIT_ONERROR_DIE; + } + } //setErrorMode + + /** + * Set error mode + * @param boolean True if errors should be logged + * @param string Absolute or relative path to log file + */ + function setErrorLog($doLogErrors, $logfile) { + require_once(DOMIT_RSS_INCLUDE_PATH . 'php_http_exceptions.php'); + + if ($doLogErrors) { + $GLOBALS['DOMIT_RSS_Exception_log'] = $logfile; + $GLOBALS['HTTP_Exception_log'] = $logfile; + $GLOBALS['DOMIT_Exception_log'] = $logfile; + } + else { + $GLOBALS['DOMIT_RSS_Exception_log'] = null; + $GLOBALS['HTTP_Exception_log'] = null; + $GLOBALS['DOMIT_Exception_log'] = null; + } + } //setErrorLog +} //xml_domit_rss_exception + +?> \ No newline at end of file diff --git a/oss/joomla/trunk/libraries/domit/xml_domit_shared.php b/oss/joomla/trunk/libraries/domit/xml_domit_shared.php new file mode 100644 index 00000000..7d50510c --- /dev/null +++ b/oss/joomla/trunk/libraries/domit/xml_domit_shared.php @@ -0,0 +1,267 @@ + +* @link http://www.engageinteractive.com/domit/ DOMIT! Home Page +* DOMIT! is Free Software +**/ + +if (!defined('DOMIT_INCLUDE_PATH')) { + /* Path to DOMIT! files */ + define('DOMIT_INCLUDE_PATH', (dirname(__FILE__) . "/")); +} + +//Nodes +/** DOM Element nodeType */ +define('DOMIT_ELEMENT_NODE', 1); +/** DOM Attr nodeType */ +define('DOMIT_ATTRIBUTE_NODE', 2); +/** DOM Text nodeType */ +define('DOMIT_TEXT_NODE', 3); +/** DOM CDATA Section nodeType */ +define('DOMIT_CDATA_SECTION_NODE', 4); +/** DOM Entity Reference nodeType */ +define('DOMIT_ENTITY_REFERENCE_NODE', 5); +/** DOM Entity nodeType */ +define('DOMIT_ENTITY_NODE', 6); +/** DOM Processing Instruction nodeType */ +define('DOMIT_PROCESSING_INSTRUCTION_NODE', 7); +/** DOM Comment nodeType */ +define('DOMIT_COMMENT_NODE', 8); +/** DOM Document nodeType */ +define('DOMIT_DOCUMENT_NODE', 9); +/** DOM DocType nodeType */ +define('DOMIT_DOCUMENT_TYPE_NODE', 10); +/** DOM Document Fragment nodeType */ +define('DOMIT_DOCUMENT_FRAGMENT_NODE', 11); +/** DOM Notation nodeType */ +define('DOMIT_NOTATION_NODE', 12); + +//DOM Level 1 Exceptions +/** DOM error: array index out of bounds */ +define('DOMIT_INDEX_SIZE_ERR', 1); +/** DOM error: text doesn't fit into a DOMString */ +define('DOMIT_DOMSTRING_SIZE_ERR', 2); +/** DOM error: node can't be inserted at this location */ +define('DOMIT_HIERARCHY_REQUEST_ERR', 3); +/** DOM error: node not a child of target document */ +define('DOMIT_WRONG_DOCUMENT_ERR', 4); +/** DOM error: invalid character specified */ +define('DOMIT_INVALID_CHARACTER_ERR', 5); +/** DOM error: data can't be added to current node */ +define('DOMIT_NO_DATA_ALLOWED_ERR', 6); +/** DOM error: node is read-only */ +define('DOMIT_NO_MODIFICATION_ALLOWED_ERR', 7); +/** DOM error: node can't be found in specified context */ +define('DOMIT_NOT_FOUND_ERR', 8); +/** DOM error: operation not supported by current implementation */ +define('DOMIT_NOT_SUPPORTED_ERR', 9); +/** DOM error: attribute currently in use elsewhere */ +define('DOMIT_INUSE_ATTRIBUTE_ERR', 10); + +//DOM Level 2 Exceptions +/** DOM error: attempt made to use an object that is no longer usable */ +define('DOMIT_INVALID_STATE_ERR', 11); +/** DOM error: invalid or illegal string specified */ +define('DOMIT_SYNTAX_ERR', 12); +/** DOM error: can't modify underlying type of node */ +define('DOMIT_INVALID_MODIFICATION_ERR', 13); +/** DOM error: attempt to change node in a way incompatible with namespaces */ +define('DOMIT_NAMESPACE_ERR', 14); +/** DOM error: operation unsupported by underlying object */ +define('DOMIT_INVALID_ACCESS_ERR', 15); + +//DOMIT! Exceptions +/** DOM error: attempt to instantiate abstract class */ +define('DOMIT_ABSTRACT_CLASS_INSTANTIATION_ERR', 100); +/** DOM error: attempt to call abstract method */ +define('DOMIT_ABSTRACT_METHOD_INVOCATION_ERR', 101); +/** DOM error: can't perform this action on or with Document Fragment */ +define('DOMIT_DOCUMENT_FRAGMENT_ERR', 102); + +//DOMIT! Error Modes +/** continue on error */ +define('DOMIT_ONERROR_CONTINUE', 1); +/** die on error */ +define('DOMIT_ONERROR_DIE', 2); + + +/** +*@global Object Instance of the UIDGenerator class +*/ +$GLOBALS['uidFactory'] = new UIDGenerator(); + +require_once(DOMIT_INCLUDE_PATH . 'xml_domit_nodemaps.php'); + +/** +* Generates unique ids for each node +* +* @package domit-xmlparser +* @author John Heinstein
" . $errorMessage . ""; + } + + //log error to file + if ((isset($GLOBALS['DOMIT_DOMException_log'])) && + ($GLOBALS['DOMIT_DOMException_log'] != null)) { + require_once(DOMIT_INCLUDE_PATH . 'php_file_utilities.php'); + $logItem = "\n" . date('Y-m-d H:i:s') . 'DOMIT! Error ' . $errorMessageText; + php_file_utilities::putDataToFile($GLOBALS['DOMIT_DOMException_log'], + $logItem, 'a'); + } + + switch ($GLOBALS['DOMIT_DOMException_mode']) { + case DOMIT_ONERROR_CONTINUE: + return; + break; + + case DOMIT_ONERROR_DIE: + die($errorMessage); + break; + } + } + } //raiseException + + /** + * custom handler for DOM errors + * @param object A reference to the custom error handler + */ + function setErrorHandler($method) { + $GLOBALS['DOMIT_DOMException_errorHandler'] =& $method; + } //setErrorHandler + + /** + * Set error mode + * @param int The DOM error mode + */ + function setErrorMode($mode) { + $GLOBALS['DOMIT_DOMException_mode'] = $mode; + } //setErrorMode + + /** + * Set error mode + * @param boolean True if errors should be logged + * @param string Absolute or relative path to log file + */ + function setErrorLog($doLogErrors, $logfile) { + if ($doLogErrors) { + $GLOBALS['DOMIT_DOMException_log'] = $logfile; + } + else { + $GLOBALS['DOMIT_DOMException_log'] = null; + } + } //setErrorLog +} //DOMIT_DOMException + +/** +* A class representing the DOM Implementation node +* +* @package domit-xmlparser +* @author John Heinstein
' . htmlspecialchars($text) . ''); + } + else { + return ('
' . htmlspecialchars($text) . ''); + } + } //forHTML + + /** + * Generates a node tree from an array and appends it to the specified document or node + * @param object The document or node to which the child nodes should be appended + * @param array An associative multidimensional array of elements and values + */ + function fromArray (&$node, &$myArray) { + if ($node->nodeType == DOMIT_DOCUMENT_NODE) { + $docNode =& $node; + } + else { + $docNode =& $node->ownerDocument; + } + + foreach ($myArray as $key => $value) { + if (is_array($value)) { + //check for numeric indices + $total = count($value); + + if (($total > 0) && isset($value[0])){ + for ($i = 0; $i < $total; $i++) { + $node->appendChild($docNode->createElement($key)); + DOMIT_Utilities::fromArray($node->lastChild, $value[$i]); + } + } + else { + //generate child elements + $node->appendChild($docNode->createElement($key)); + DOMIT_Utilities::fromArray($node->lastChild, $value); + } + } + else { + $node->appendChild($docNode->createElement($key)); + $node->lastChild->appendChild($docNode->createTextNode($value)); + } + } + } //fromArray + + function parseAttributes() { + + } //parseAttributes +} //DOMIT_Utilities +?> \ No newline at end of file diff --git a/oss/joomla/trunk/libraries/domit/xml_domit_xpath.php b/oss/joomla/trunk/libraries/domit/xml_domit_xpath.php new file mode 100644 index 00000000..de1e6fae --- /dev/null +++ b/oss/joomla/trunk/libraries/domit/xml_domit_xpath.php @@ -0,0 +1,1048 @@ + +* @link http://www.engageinteractive.com/domit/ DOMIT! Home Page +* DOMIT! is Free Software +**/ + +if (!defined('DOMIT_INCLUDE_PATH')) { + define('DOMIT_INCLUDE_PATH', (dirname(__FILE__) . "/")); +} + +/** Separator for absolute path */ +define('DOMIT_XPATH_SEPARATOR_ABSOLUTE', '/'); +/** Separator for relative path */ +define('DOMIT_XPATH_SEPARATOR_RELATIVE', '//'); +/** OR separator for multiple patterns */ +define('DOMIT_XPATH_SEPARATOR_OR', '|'); + +/** Constant for an absolute path search (starting at the document root) */ +define('DOMIT_XPATH_SEARCH_ABSOLUTE', 0); +/** Constant for a relative path search (starting at the level of the calling node) */ +define('DOMIT_XPATH_SEARCH_RELATIVE', 1); +/** Constant for a variable path search (finds all matches, regardless of place in the hierarchy) */ +define('DOMIT_XPATH_SEARCH_VARIABLE', 2); + + +/** +* DOMIT! XPath is an XPath parser. +*/ +class DOMIT_XPath { + /** @var Object The node from which the search is called */ + var $callingNode; + /** @var Object The node that is the current parent of the search */ + var $searchType; + /** @var array An array containing a series of path segments for which to search */ + var $arPathSegments = array(); + /** @var Object A DOMIT_NodeList of matching nodes */ + var $nodeList; + /** @var string A temporary string container */ + var $charContainer; + /** @var string The current character of the current pattern segment being parsed */ + var $currChar; + /** @var string The current pattern segment being parsed */ + var $currentSegment; + /** @var array A temporary node container for caching node references at the pattern level*/ + var $globalNodeContainer; + /** @var array A temporary node container for caching node references at the pattern segment level */ + var $localNodeContainer; + /** @var array Normalization table for XPath syntax */ + var $normalizationTable = array('child::' => '', 'self::' => '.', + 'attribute::' => '@', 'descendant::' => '*//', + "\t" => ' ', "\x0B" => ' '); + /** @var array A second-pass normalization table for XPath syntax */ + var $normalizationTable2 = array(' =' => '=', '= ' => '=', ' <' => '<', + ' >' => '>', '< ' => '<', '> ' => '>', + ' !' => '!', '( ' => '(', + ' )' => ')', ' ]' => ']', '] ' => ']', + ' [' => '[', '[ ' => '[', ' /' => '/', + '/ ' => '/', '"' => "'"); + /** @var array A third-pass normalization table for XPath syntax */ + var $normalizationTable3 = array('position()=' => '', + '/descendant-or-self::node()/' => "//", 'self::node()' => '.', + 'parent::node()' => '..'); + + /** + * Constructor - creates an empty DOMIT_NodeList to store matching nodes + */ + function DOMIT_XPath() { + require_once(DOMIT_INCLUDE_PATH . 'xml_domit_nodemaps.php'); + $this->nodeList = new DOMIT_NodeList(); + } //DOMIT_XPath + + /** + * Parses the supplied "path"-based pattern + * @param Object The node from which the search is called + * @param string The pattern + * @return Object The NodeList containing matching nodes + */ + function &parsePattern(&$node, $pattern, $nodeIndex = 0) { + $this->callingNode =& $node; + $pattern = $this->normalize(trim($pattern)); + + $this->splitPattern($pattern); + + $total = count($this->arPathSegments); + + //whole pattern level + for ($i = 0; $i < $total; $i++) { + $outerArray =& $this->arPathSegments[$i]; + $this->initSearch($outerArray); + + $outerTotal = count($outerArray); + $isInitialMatchAttempt = true; + + //variable path segment level + for ($j = 0; $j < $outerTotal; $j++) { + $innerArray =& $outerArray[$j]; + $innerTotal = count($innerArray); + + if (!$isInitialMatchAttempt) { + $this->searchType = DOMIT_XPATH_SEARCH_VARIABLE; + } + + //pattern segment level + for ($k = 0; $k < $innerTotal; $k++) { + $currentPattern = $innerArray[$k]; + + if (($k == 0) && ($currentPattern == null)) { + if ($innerTotal == 1) { + $isInitialMatchAttempt = false; + } + //else just skip current step and don't alter searchType + } + else { + if (!$isInitialMatchAttempt && ($k > 0)) { + $this->searchType = DOMIT_XPATH_SEARCH_RELATIVE; + } + + $this->currentSegment = $currentPattern; + $this->processPatternSegment(); + $isInitialMatchAttempt = false; + } + } + } + } + + if ($nodeIndex > 0) { + if ($nodeIndex <= count($this->globalNodeContainer)) { + return $this->globalNodeContainer[($nodeIndex - 1)]; + } + else { + $null = null; + return $null; + } + } + + if (count($this->globalNodeContainer) != 0) { + foreach ($this->globalNodeContainer as $key =>$value) { + $currNode =& $this->globalNodeContainer[$key]; + $this->nodeList->appendNode($currNode); + } + } + + return $this->nodeList; + } //parsePattern + + /** + * Generates a new globalNodeContainer of matches + */ + function processPatternSegment() { + $total = strlen($this->currentSegment); + $this->charContainer = ''; + $this->localNodeContainer = array(); + + for ($i = 0; $i < $total; $i++) { +// $this->currChar = $this->currentSegment{$i}; + $this->currChar = substr($this->currentSegment, $i, 1); + + switch ($this->currChar) { + case '@': + $this->selectAttribute(substr($this->currentSegment, ($this->currChar + 1))); + $this->updateNodeContainers(); + return; + //break; + + case '*': + if ($i == ($total - 1)) { + $this->selectNamedChild('*'); + } + else { + $this->charContainer .= $this->currChar; + } + break; + + case '.': + $this->charContainer .= $this->currChar; + + if ($i == ($total - 1)) { + if ($this->charContainer == '..') { + $this->selectParent(); + } + else { + return; + } + } + break; + + case ')': + $this->charContainer .= $this->currChar; + $this->selectNodesByFunction(); + break; + + case '[': + $this->parsePredicate($this->charContainer, + substr($this->currentSegment, ($i + 1))); + return; + //break; + + default: + $this->charContainer .= $this->currChar; + + } + } + + if ($this->charContainer != '') { + $this->selectNamedChild($this->charContainer); + } + + $this->updateNodeContainers(); + } //processPatternSegment + + /** + * Replaces the global node container with the local node container + */ + function updateNodeContainers() { + $this->globalNodeContainer =& $this->localNodeContainer; + unset($this->localNodeContainer); + } //updateNodeContainers + + + /** + * Parses a predicate expression [...] + * @param string The pattern segment containing the node expression + * @param string The pattern segment containing the predicate expression + */ + function parsePredicate($nodeName, $patternSegment) { + $arPredicates =& explode('][', $patternSegment); + + $total = count($arPredicates); + + $lastIndex = $total - 1; + $arPredicates[$lastIndex] = substr($arPredicates[$lastIndex], + 0, (strlen($arPredicates[$lastIndex]) - 1)); + + for ($i = 0; $i < $total; $i++) { + $isRecursive = ($this->searchType == DOMIT_XPATH_SEARCH_VARIABLE) ? true : false; + $currPredicate = $arPredicates[$i]; + + if (is_numeric($currPredicate)) { + if ($i == 0) { + $this->filterByIndex($nodeName, intval($currPredicate), $isRecursive); + } + else { + $this->refilterByIndex(intval($currPredicate)); + } + } + else { + if ($i == 0) { + $this->selectNamedChild($nodeName); + $this->updateNodeContainers(); + } + + $phpExpression = $this->predicateToPHP($currPredicate); + $this->filterByPHPExpression($phpExpression); + } + + $this->updateNodeContainers(); + } + + $this->charContainer = ''; + } //parsePredicate + + /** + * Converts the predicate into PHP evaluable code + * @param string The predicate + * @return string The converted PHP expression + */ + function predicateToPHP($predicate) { + $phpExpression = $predicate; + $currChar = ''; + $charContainer = ''; + $totalChars = strlen($predicate); + + for ($i = 0; $i < $totalChars; $i++) { + $currChar = substr($predicate, $i, 1); + + switch ($currChar) { + case '(': + case ')': + case ' ': + if ($charContainer != '') { + $convertedPredicate = $this->expressionToPHP($charContainer); + $phpExpression = str_replace($charContainer, $convertedPredicate, $phpExpression); + $charContainer = ''; + } + break; + + default: + $charContainer .= $currChar; + + } + } + + if ($charContainer != '') { + $convertedPredicate = $this->expressionToPHP($charContainer); + $phpExpression = str_replace($charContainer, $convertedPredicate, $phpExpression); + } + + return $phpExpression; + } //predicateToPHP + + + /** + * Converts the predicate expression into a PHP expression + * @param string The predicate expression + * @return string The converted PHP expression + */ + function expressionToPHP($expression) { + if ($expression == 'and') { + $expression = '&&'; + } + else if ($expression == 'or') { + $expression = '||'; + } + else if ($expression == 'not') { + $expression = '!'; + } + else { + $expression = trim($expression); + + if (strpos($expression, '@') !== false) { + if (strpos($expression, '>=') !== false) { + $expression = str_replace('@', ('floatval($' . "contextNode->getAttribute('"), $expression); + $expression = str_replace('>=', "')) >= floatval(", $expression); + if (!is_numeric($expression)) $expression = str_replace('floatval', '', $expression); + $expression .= ')'; + } + else if (strpos($expression, '<=') !== false) { + $expression = str_replace('@', ('floatval($' . "contextNode->getAttribute('"), $expression); + $expression = str_replace('<=', "')) <= floatval(", $expression); + if (!is_numeric($expression)) $expression = str_replace('floatval', '', $expression); + $expression .= ')'; + } + else if (strpos($expression, '!=') !== false) { + $expression = str_replace('@', ('$' . "contextNode->getAttribute('"), $expression); + $expression = str_replace('!=', "') != ", $expression); + } + else if (strpos($expression, '=') !== false) { + $expression = str_replace('@', ('$' . "contextNode->getAttribute('"), $expression); + $expression = str_replace('=', "') == ", $expression); + } + else if (strpos($expression, '>') !== false) { + $expression = str_replace('>', "')) > floatval(", $expression); //reverse so > doesn't get replaced + $expression = str_replace('@', ('floatval($' . "contextNode->getAttribute('"), $expression); + if (!is_numeric($expression)) $expression = str_replace('floatval', '', $expression); + $expression .= ')'; + } + else if (strpos($expression, '<') !== false) { + $expression = str_replace('@', ('floatval($' . "contextNode->getAttribute('"), $expression); + $expression = str_replace('<', "')) < floatval(", $expression); + if (!is_numeric($expression)) $expression = str_replace('floatval', '', $expression); + $expression .= ')'; + } + else { + $expression = str_replace('@', ('$' . "contextNode->hasAttribute('"), $expression); + $expression.= "')"; + } + } + else { + if (strpos($expression, '>=') !== false) { + $signPos = strpos($expression, '>='); + $elementName = trim(substr($expression, 0, $signPos)); + $elementValue = trim(substr($expression, ($signPos + 2))); + + $expression = '$' . "this->hasNamedChildElementGreaterThanOrEqualToValue(" . + '$' . "contextNode, '" . $elementName . "', " . + $elementValue . ')'; + } + else if (strpos($expression, '<=') !== false) { + $signPos = strpos($expression, '>='); + $elementName = trim(substr($expression, 0, $signPos)); + $elementValue = trim(substr($expression, ($signPos + 2))); + + $expression = '$' . "this->hasNamedChildElementLessThanOrEqualToValue(" . + '$' . "contextNode, '" . $elementName . "', " . + $elementValue . ')'; + } + else if (strpos($expression, '!=') !== false) { + $signPos = strpos($expression, '>='); + $elementName = trim(substr($expression, 0, $signPos)); + $elementValue = trim(substr($expression, ($signPos + 2))); + + $expression = '$' . "this->hasNamedChildElementNotEqualToValue(" . + '$' . "contextNode, '" . $elementName . "', " . + $elementValue . ')'; + } + else if (strpos($expression, '=') !== false) { + $signPos = strpos($expression, '='); + $elementName = trim(substr($expression, 0, $signPos)); + $elementValue = trim(substr($expression, ($signPos + 1))); + + $expression = '$' . "this->hasNamedChildElementEqualToValue(" . + '$' . "contextNode, '" . $elementName . "', " . + $elementValue . ')'; + + } + else if (strpos($expression, '>') !== false) { + $signPos = strpos($expression, '='); + $elementName = trim(substr($expression, 0, $signPos)); + $elementValue = trim(substr($expression, ($signPos + 1))); + + $expression = '$' . "this->hasNamedChildElementGreaterThanValue(" . + '$' . "contextNode, '" . $elementName . "', " . + $elementValue . ')'; + } + else if (strpos($expression, '<') !== false) { + $signPos = strpos($expression, '='); + $elementName = trim(substr($expression, 0, $signPos)); + $elementValue = trim(substr($expression, ($signPos + 1))); + + $expression = '$' . "this->hasNamedChildElementLessThanValue(" . + '$' . "contextNode, '" . $elementName . "', " . + $elementValue . ')'; + } + else { + $expression = '$' . "this->hasNamedChildElement(" . + '$' . "contextNode, '" . $expression . "')"; + } + } + } + + return $expression; + } //expressionToPHP + + /** + * Selects nodes that match the predicate expression + * @param string The predicate expression, formatted as a PHP expression + */ + function filterByPHPExpression($expression) { + if (count($this->globalNodeContainer) != 0) { + foreach ($this->globalNodeContainer as $key =>$value) { + $contextNode =& $this->globalNodeContainer[$key]; + + if ($contextNode->nodeType == DOMIT_ELEMENT_NODE) { + $evaluatedExpression = 'if (' . $expression . ") $" . + 'this->localNodeContainer[] =& $' . 'contextNode;'; + eval($evaluatedExpression); + } + } + } + } //filterByPHPExpression + + /** + * Selects nodes with child elements that match the specified name + * @param object The parent node of the child elements to match + * @param string The tag name to match on + * @return boolean True if a matching child element exists + */ + function hasNamedChildElement(&$parentNode, $nodeName) { + $total = $parentNode->childCount; + + for ($i = 0; $i < $total; $i++) { + $currNode =& $parentNode->childNodes[$i]; + + if (($currNode->nodeType == DOMIT_ELEMENT_NODE) && ($currNode->nodeName == $nodeName)) { + return true; + } + } + + return false; + } //hasNamedChildElement + + /** + * Selects nodes with child elements that match the specified name and text value + * @param object The parent node of the child elements to match + * @param string The tag name to match on + * @param string The text string to match on + * @return boolean True if a matching child element exists + */ + function hasNamedChildElementEqualToValue(&$parentNode, $nodeName, $nodeValue) { + $total = $parentNode->childCount; + + for ($i = 0; $i < $total; $i++) { + $currNode =& $parentNode->childNodes[$i]; + + if (($currNode->nodeType == DOMIT_ELEMENT_NODE) && + ($currNode->nodeName == $nodeName) && ($currNode->getText() == $nodeValue)) { + return true; + } + } + + return false; + } //hasNamedChildElementEqualToValue + + /** + * Selects nodes with child elements that are greater than or equal to the specified name and value + * @param object The parent node of the child elements to match + * @param string The tag name to match on + * @param string The text string to match on + * @return boolean True if a matching child element exists + */ + function hasNamedChildElementGreaterThanOrEqualToValue(&$parentNode, $nodeName, $nodeValue) { + $isNumeric = false; + + if (is_numeric($nodeValue)) { + $isNumeric = true; + $nodeValue = floatval($nodeValue); + } + + $total = $parentNode->childCount; + + for ($i = 0; $i < $total; $i++) { + $currNode =& $parentNode->childNodes[$i]; + + if (($currNode->nodeType == DOMIT_ELEMENT_NODE) && ($currNode->nodeName == $nodeName)) { + if ($isNumeric) {$compareVal = floatval($currNode->getText());} + else {$compareVal = $currNode->getText();} + if ($compareVal >= $nodeValue) return true; + } + } + + return false; + } //hasNamedChildElementGreaterThanOrEqualToValue + + + /** + * Selects nodes with child elements that are less than or equal to the specified name and value + * @param object The parent node of the child elements to match + * @param string The tag name to match on + * @param string The text string to match on + * @return boolean True if a matching child element exists + */ + function hasNamedChildElementLessThanOrEqualToValue(&$parentNode, $nodeName, $nodeValue) { + $isNumeric = false; + + if (is_numeric($nodeValue)) { + $isNumeric = true; + $nodeValue = floatval($nodeValue); + } + + $total = $parentNode->childCount; + + for ($i = 0; $i < $total; $i++) { + $currNode =& $parentNode->childNodes[$i]; + + if (($currNode->nodeType == DOMIT_ELEMENT_NODE) && ($currNode->nodeName == $nodeName)) { + if ($isNumeric) {$compareVal = floatval($currNode->getText());} + else {$compareVal = $currNode->getText();} + if ($compareVal <= $nodeValue) return true; + } + } + + return false; + } //hasNamedChildElementLessThanOrEqualToValue + + /** + * Selects nodes with child elements that are not equal to the specified name and value + * @param object The parent node of the child elements to match + * @param string The tag name to match on + * @param string The text string to match on + * @return boolean True if a matching child element exists + */ + function hasNamedChildElementNotEqualToValue(&$parentNode, $nodeName, $nodeValue) { + $isNumeric = false; + + if (is_numeric($nodeValue)) { + $isNumeric = true; + $nodeValue = floatval($nodeValue); + } + + $total = $parentNode->childCount; + + for ($i = 0; $i < $total; $i++) { + $currNode =& $parentNode->childNodes[$i]; + + if (($currNode->nodeType == DOMIT_ELEMENT_NODE) && ($currNode->nodeName == $nodeName)) { + if ($isNumeric) {$compareVal = floatval($currNode->getText());} + else {$compareVal = $currNode->getText();} + if ($compareVal != $nodeValue) return true; + } + } + + return false; + } //hasNamedChildElementNotEqualToValue + + /** + * Selects nodes with child elements that are greater than the specified name and value + * @param object The parent node of the child elements to match + * @param string The tag name to match on + * @param string The text string to match on + * @return boolean True if a matching child element exists + */ + function hasNamedChildElementGreaterThanValue(&$parentNode, $nodeName, $nodeValue) { + $isNumeric = false; + + if (is_numeric($nodeValue)) { + $isNumeric = true; + $nodeValue = floatval($nodeValue); + } + + $total = $parentNode->childCount; + + for ($i = 0; $i < $total; $i++) { + $currNode =& $parentNode->childNodes[$i]; + + if (($currNode->nodeType == DOMIT_ELEMENT_NODE) && ($currNode->nodeName == $nodeName)) { + if ($isNumeric) {$compareVal = floatval($currNode->getText());} + else {$compareVal = $currNode->getText();} + if ($compareVal > $nodeValue) return true; + } + } + + return false; + } //hasNamedChildElementGreaterThanValue + + + /** + * Selects nodes with child elements that are less than the specified name and value + * @param object The parent node of the child elements to match + * @param string The tag name to match on + * @param string The text string to match on + * @return boolean True if a matching child element exists + */ + function hasNamedChildElementLessThanValue(&$parentNode, $nodeName, $nodeValue) { + $isNumeric = false; + + if (is_numeric($nodeValue)) { + $isNumeric = true; + $nodeValue = floatval($nodeValue); + } + + $total = $parentNode->childCount; + + for ($i = 0; $i < $total; $i++) { + $currNode =& $parentNode->childNodes[$i]; + + if (($currNode->nodeType == DOMIT_ELEMENT_NODE) && ($currNode->nodeName == $nodeName)) { + if ($isNumeric) {$compareVal = floatval($currNode->getText());} + else {$compareVal = $currNode->getText();} + if ($compareVal < $nodeValue) return true; + } + } + + return false; + } //hasNamedChildElementLessThanValue + + /** + * Selects named elements of the specified index + * @param string The pattern segment containing the node expression + * @param int The index (base 1) of the matching node + * @param boolean True if the selection is to be performed recursively + */ + function refilterByIndex($index) { + if ($index > 1) { + if (count($this->globalNodeContainer) != 0) { + $counter = 0; + $lastParentID = null; + + foreach ($this->globalNodeContainer as $key =>$value) { + $currNode =& $this->globalNodeContainer[$key]; + + if (($lastParentID != null) && ($currNode->parentNode->uid != $lastParentID)) { + $counter = 0; + } + + $counter++; + + if (($counter == $index) && ($currNode->parentNode->uid == $lastParentID)) { + $this->localNodeContainer[] =& $currNode; + } + + $lastParentID = $currNode->parentNode->uid; + } + } + } + else { + $this->localNodeContainer =& $this->globalNodeContainer; + } + } //refilterByIndex + + + /** + * Selects named elements of the specified index + * @param string The pattern segment containing the node expression + * @param int The index (base 1) of the matching node + * @param boolean True if the selection is to be performed recursively + */ + function filterByIndex($nodeName, $index, $deep) { + if (count($this->globalNodeContainer) != 0) { + foreach ($this->globalNodeContainer as $key =>$value) { + $currNode =& $this->globalNodeContainer[$key]; + $this->_filterByIndex($currNode, $nodeName, $index, $deep); + } + } + } //filterByIndex + + /** + * Selects named elements of the specified index + * @param object The context node + * @param string The pattern segment containing the node expression + * @param int The index (base 1) of the matching node + * @param boolean True if the selection is to be performed recursively + */ + function _filterByIndex(&$contextNode, $nodeName, $index, $deep) { + if (($contextNode->nodeType == DOMIT_ELEMENT_NODE) || + ($contextNode->nodeType == DOMIT_DOCUMENT_NODE)) { + $total = $contextNode->childCount; + $nodeCounter = 0; + + for ($i = 0; $i < $total; $i++) { + $currChildNode =& $contextNode->childNodes[$i]; + + if ($currChildNode->nodeName == $nodeName) { + $nodeCounter++; + + if ($nodeCounter == $index) { + $this->localNodeContainer[] =& $currChildNode; + } + } + + if ($deep) { + $this->_filterByIndex($currChildNode, $nodeName, $index, $deep); + } + } + } + } //_filterByIndex + + /** + * Selects named elements with the specified named child + * @param string The pattern segment containing the node expression + * @param string The tag name of the matching child + * @param boolean True if the selection is to be performed recursively + */ + function filterByChildName($nodeName, $childName, $deep) { + if (count($this->globalNodeContainer) != 0) { + foreach ($this->globalNodeContainer as $key =>$value) { + $currNode =& $this->globalNodeContainer[$key]; + $this->_filterByChildName($currNode, $nodeName, $childName, $deep); + } + } + } //filterByChildName + + /** + * Selects named elements with the specified named child + * @param object The context node + * @param string The pattern segment containing the node expression + * @param string The tag name of the matching child + * @param boolean True if the selection is to be performed recursively + */ + function _filterByChildName(&$contextNode, $nodeName, $childName, $deep) { + if (($contextNode->nodeType == DOMIT_ELEMENT_NODE) || + ($contextNode->nodeType == DOMIT_DOCUMENT_NODE)) { + $total = $contextNode->childCount; + + for ($i = 0; $i < $total; $i++) { + $currChildNode =& $contextNode->childNodes[$i]; + + if (($currChildNode->nodeName == $nodeName) && + ($currChildNode->nodeType == DOMIT_ELEMENT_NODE)) { + $total2 = $currChildNode->childCount; + + for ($j = 0; $j < $total2; $j++) { + $currChildChildNode =& $currChildNode->childNodes[$j]; + + if ($currChildChildNode->nodeName == $childName) { + $this->localNodeContainer[] =& $currChildNode; + } + } + } + + if ($deep) { + $this->_filterByChildName($currChildNode, $nodeName, $childName, $deep); + } + } + } + } //_filterByChildName + + /** + * Selects named attributes of the current context nodes + * @param string The attribute name, or * to match all attributes + */ + function selectAttribute($attrName) { + if (count($this->globalNodeContainer) != 0) { + foreach ($this->globalNodeContainer as $key =>$value) { + $currNode =& $this->globalNodeContainer[$key]; + + $isRecursive = ($this->searchType == DOMIT_XPATH_SEARCH_VARIABLE) ? true : false; + $this->_selectAttribute($currNode, $attrName, $isRecursive); + } + } + + $this->charContainer = ''; + } //selectAttribute + + /** + * Selects all attributes of the context nodes + * @param object The context node + * @param string The attribute name, or * to match all attributes + * @param boolean True if the selection is to be performed recursively + */ + function _selectAttribute(&$contextNode, $attrName, $deep) { + if (($contextNode->nodeType == DOMIT_ELEMENT_NODE) || + ($contextNode->nodeType == DOMIT_DOCUMENT_NODE)) { + $total = $contextNode->childCount; + + for ($i = 0; $i < $total; $i++) { + $currNode =& $contextNode->childNodes[$i]; + + if ($currNode->nodeType == DOMIT_ELEMENT_NODE) { + if ($attrName == '*') { + $total2 = $currNode->attributes->getLength(); + + for ($j = 0; $j < $total2; $j++) { + $this->localNodeContainer[] =& $currNode->attributes->item($j); + } + } + else { + if ($currNode->hasAttribute($attrName)) { + $this->localNodeContainer[] =& $currNode->getAttributeNode($attrName); + } + } + } + + if ($deep) { + $this->_selectAttribute($currNode, $attrName, $deep); + } + } + } + } //_selectAttribute + + + /** + * Selects all child nodes of the current context nodes + * @param string The element name + */ + function selectNamedChild($tagName) { + if (count($this->globalNodeContainer) != 0) { + foreach ($this->globalNodeContainer as $key =>$value) { + $currNode =& $this->globalNodeContainer[$key]; + + $isRecursive = ($this->searchType == DOMIT_XPATH_SEARCH_VARIABLE) ? true : false; + $this->_selectNamedChild($currNode, $tagName, $isRecursive); + } + } + + $this->charContainer = ''; + } //selectNamedChild + + /** + * Selects all child nodes of the context node + * @param object The context node + * @param string The element name + * @param boolean True if the selection is to be performed recursively + */ + function _selectNamedChild(&$contextNode, $tagName, $deep = false) { + if (($contextNode->nodeType == DOMIT_ELEMENT_NODE) || + ($contextNode->nodeType == DOMIT_DOCUMENT_NODE)) { + $total = $contextNode->childCount; + + for ($i = 0; $i < $total; $i++) { + $currChildNode =& $contextNode->childNodes[$i]; + + if (($currChildNode->nodeType == DOMIT_ELEMENT_NODE) || + ($currChildNode->nodeType == DOMIT_DOCUMENT_NODE)) { + if (($tagName == '*') || ($tagName == $currChildNode->nodeName)) { + $this->localNodeContainer[] =& $currChildNode; + } + + if ($deep) { + $this->_selectNamedChild($currChildNode, $tagName, $deep); + } + } + } + } + } //_selectNamedChild + + /** + * Selects parent node of the current context nodes + */ + function selectParent() { + if (count($this->globalNodeContainer) != 0) { + foreach ($this->globalNodeContainer as $key =>$value) { + $currNode =& $this->globalNodeContainer[$key]; + + $isRecursive = ($this->searchType == DOMIT_XPATH_SEARCH_VARIABLE) ? true : false; + $this->_selectParent($currNode, $isRecursive); + } + } + + $this->charContainer = ''; + } //selectParent + + /** + * Selects parent node of the current context nodes + * @param object The context node + * @param boolean True if the selection is to be performed recursively + */ + function _selectParent(&$contextNode, $deep = false) { + if ($contextNode->nodeType == DOMIT_ELEMENT_NODE) { + if ($contextNode->parentNode != null) { + $this->localNodeContainer[] =& $contextNode->parentNode; + } + } + + if ($deep) { + if (($contextNode->nodeType == DOMIT_ELEMENT_NODE) || + ($contextNode->nodeType == DOMIT_DOCUMENT_NODE)) { + $total = $contextNode->childCount; + + for ($i = 0; $i < $total; $i++) { + $currNode =& $contextNode->childNodes[$i]; + + if ($currNode->nodeType == DOMIT_ELEMENT_NODE) { + $this->_selectParent($contextNode, $deep); + } + } + } + } + } //_selectParent + + /** + * Selects any nodes of the current context nodes which match the given function + */ + function selectNodesByFunction() { + $doProcess = false; + $targetNodeType = -1; + + switch (strtolower(trim($this->charContainer))) { + case 'last()': + if (count($this->globalNodeContainer) != 0) { + foreach ($this->globalNodeContainer as $key =>$value) { + $currNode =& $this->globalNodeContainer[$key]; + + if ($currNode->nodeType == DOMIT_ELEMENT_NODE) { + if ($currNode->lastChild != null) { + $this->localNodeContainer[] =& $currNode->lastChild; + } + } + } + } + break; + + case 'text()': + $doProcess = true; + $targetNodeType = DOMIT_TEXT_NODE; + break; + + case 'comment()': + $doProcess = true; + $targetNodeType = DOMIT_COMMENT_NODE; + break; + + case 'processing-instruction()': + $doProcess = true; + $targetNodeType = DOMIT_PROCESSING_INSTRUCTION_NODE; + break; + } + + if ($doProcess) { + if (count($this->globalNodeContainer) != 0) { + foreach ($this->globalNodeContainer as $key =>$value) { + $currNode =& $this->globalNodeContainer[$key]; + + if ($currNode->nodeType == DOMIT_ELEMENT_NODE) { + $total = $currNode->childCount; + + for ($j = 0; $j < $total; $j++) { + if ($currNode->childNodes[$j]->nodeType == $targetNodeType) { + $this->localNodeContainer[] =& $currNode->childNodes[$j]; + } + } + } + } + } + } + + $this->charContainer = ''; + } //selectNodesByFunction + + /** + * Splits the supplied pattern into searchable segments + * @param string The pattern + */ + function splitPattern($pattern) { + //split multiple patterns if they exist (e.g. pattern1 | pattern2 | pattern3) + $this->arPathSegments =& explode(DOMIT_XPATH_SEPARATOR_OR, $pattern); + + //split each pattern by relative path dividers (i.e., '//') + $total = count($this->arPathSegments); + + for ($i = 0; $i < $total; $i++) { + $this->arPathSegments[$i] =& explode(DOMIT_XPATH_SEPARATOR_RELATIVE, trim($this->arPathSegments[$i])); + + $currArray =& $this->arPathSegments[$i]; + $total2 = count($currArray); + + for ($j = 0; $j < $total2; $j++) { + $currArray[$j] =& explode(DOMIT_XPATH_SEPARATOR_ABSOLUTE, $currArray[$j]); + } + } + } //splitPattern + + /** + * Converts long XPath syntax into abbreviated XPath syntax + * @param string The pattern + * @return string The normalized pattern + */ + function normalize($pattern) { + $pattern = strtr($pattern, $this->normalizationTable); + + while (strpos($pattern, ' ') !== false) { + $pattern = str_replace(' ', ' ', $pattern); + } + + $pattern = strtr($pattern, $this->normalizationTable2); + $pattern = strtr($pattern, $this->normalizationTable3); + + return $pattern; + } //normalize + + /** + * Initializes the contextNode and searchType + * @param array The current array of path segments + * @return int The index of the first array item to begin the search at + */ + function initSearch(&$currArPathSegments) { + $this->globalNodeContainer = array(); + + if (is_null($currArPathSegments[0])) { + if (count($currArPathSegments) == 1) { + //variable path + $this->searchType = DOMIT_XPATH_SEARCH_VARIABLE; + $this->globalNodeContainer[] =& $this->callingNode->ownerDocument; + } + else { + //absolute path + $this->searchType = DOMIT_XPATH_SEARCH_ABSOLUTE; + $this->globalNodeContainer[] =& $this->callingNode->ownerDocument; + } + } + else { + //relative path + $this->searchType = DOMIT_XPATH_SEARCH_RELATIVE; + + if ($this->callingNode->uid != $this->callingNode->ownerDocument->uid) { + $this->globalNodeContainer[] =& $this->callingNode; + } + else { + $this->globalNodeContainer[] =& $this->callingNode->ownerDocument; + } + } + } //initSearch +} //DOMIT_XPath +?> \ No newline at end of file diff --git a/oss/joomla/trunk/libraries/domit/xml_saxy_lite_parser.php b/oss/joomla/trunk/libraries/domit/xml_saxy_lite_parser.php new file mode 100644 index 00000000..e0f522cf --- /dev/null +++ b/oss/joomla/trunk/libraries/domit/xml_saxy_lite_parser.php @@ -0,0 +1,243 @@ + +* @link http://www.engageinteractive.com/saxy/ SAXY Home Page +* SAXY is Free Software +**/ + +if (!defined('SAXY_INCLUDE_PATH')) { + define('SAXY_INCLUDE_PATH', (dirname(__FILE__) . "/")); +} + +/** current version of SAXY Lite */ +define ('SAXY_LITE_VERSION', '1.0'); + +/** initial saxy lite parse state, before anything is encountered */ +define('SAXY_STATE_NONE', 0); +/** saxy lite parse state, processing main document */ +define('SAXY_STATE_PARSING', 1); + +require_once(SAXY_INCLUDE_PATH . 'xml_saxy_shared.php'); + +/** +* The SAX Parser class +* +* @package saxy-xmlparser +* @subpackage saxy-xmlparser-lite +* @author John Heinstein
array(
+ * 'lang_name' => array('extension', 'extension', ...),
+ * 'lang_name' ...
+ * );
+ *
+ * @todo Complete rethink of this and above method
+ * @since 1.0.5
+ */
+ function load_from_file($file_name, $lookup = array()) {
+ if (is_readable($file_name)) {
+ $this->set_source(implode('', file($file_name)));
+ $this->set_language($this->get_language_name_from_extension(substr(strrchr($file_name, '.'), 1), $lookup));
+ }
+ else {
+ $this->error = GESHI_ERROR_FILE_NOT_READABLE;
+ }
+ }
+
+ /**
+ * Adds a keyword to a keyword group for highlighting
+ *
+ * @param int The key of the keyword group to add the keyword to
+ * @param string The word to add to the keyword group
+ * @since 1.0.0
+ */
+ function add_keyword($key, $word) {
+ $this->language_data['KEYWORDS'][$key][] = $word;
+ }
+
+ /**
+ * Removes a keyword from a keyword group
+ *
+ * @param int The key of the keyword group to remove the keyword from
+ * @param string The word to remove from the keyword group
+ * @since 1.0.0
+ */
+ function remove_keyword($key, $word) {
+ $this->language_data['KEYWORDS'][$key] =
+ array_diff($this->language_data['KEYWORDS'][$key], array($word));
+ }
+
+ /**
+ * Creates a new keyword group
+ *
+ * @param int The key of the keyword group to create
+ * @param string The styles for the keyword group
+ * @param boolean Whether the keyword group is case sensitive ornot
+ * @param array The words to use for the keyword group
+ * @since 1.0.0
+ */
+ function add_keyword_group($key, $styles, $case_sensitive = true, $words = array()) {
+ $words = (array) $words;
+ $this->language_data['KEYWORDS'][$key] = $words;
+ $this->lexic_permissions['KEYWORDS'][$key] = true;
+ $this->language_data['CASE_SENSITIVE'][$key] = $case_sensitive;
+ $this->language_data['STYLES']['KEYWORDS'][$key] = $styles;
+ }
+
+ /**
+ * Removes a keyword group
+ *
+ * @param int The key of the keyword group to remove
+ * @since 1.0.0
+ */
+ function remove_keyword_group ($key) {
+ unset($this->language_data['KEYWORDS'][$key]);
+ unset($this->lexic_permissions['KEYWORDS'][$key]);
+ unset($this->language_data['CASE_SENSITIVE'][$key]);
+ unset($this->language_data['STYLES']['KEYWORDS'][$key]);
+ }
+
+ /**
+ * Sets the content of the header block
+ *
+ * @param string The content of the header block
+ * @since 1.0.2
+ */
+ function set_header_content($content) {
+ $this->header_content = $content;
+ }
+
+ /**
+ * Sets the content of the footer block
+ *
+ * @param string The content of the footer block
+ * @since 1.0.2
+ */
+ function set_footer_content($content) {
+ $this->footer_content = $content;
+ }
+
+ /**
+ * Sets the style for the header content
+ *
+ * @param string The style for the header content
+ * @since 1.0.2
+ */
+ function set_header_content_style($style) {
+ $this->header_content_style = $style;
+ }
+
+ /**
+ * Sets the style for the footer content
+ *
+ * @param string The style for the footer content
+ * @since 1.0.2
+ */
+ function set_footer_content_style($style) {
+ $this->footer_content_style = $style;
+ }
+
+ /**
+ * Sets the base URL to be used for keywords
+ *
+ * @param int The key of the keyword group to set the URL for
+ * @param string The URL to set for the group. If {FNAME} is in
+ * the url somewhere, it is replaced by the keyword
+ * that the URL is being made for
+ * @since 1.0.2
+ */
+ function set_url_for_keyword_group($group, $url) {
+ $this->language_data['URLS'][$group] = $url;
+ }
+
+ /**
+ * Sets styles for links in code
+ *
+ * @param int A constant that specifies what state the style is being
+ * set for - e.g. :hover or :visited
+ * @param string The styles to use for that state
+ * @since 1.0.2
+ */
+ function set_link_styles($type, $styles) {
+ $this->link_styles[$type] = $styles;
+ }
+
+ /**
+ * Sets the target for links in code
+ *
+ * @param string The target for links in the code, e.g. _blank
+ * @since 1.0.3
+ */
+ function set_link_target($target) {
+ if (!$target) {
+ $this->link_target = '';
+ }
+ else {
+ $this->link_target = ' target="' . $target . '" ';
+ }
+ }
+
+ /**
+ * Sets styles for important parts of the code
+ *
+ * @param string The styles to use on important parts of the code
+ * @since 1.0.2
+ */
+ function set_important_styles($styles) {
+ $this->important_styles = $styles;
+ }
+
+ /**
+ * Sets whether context-important blocks are highlighted
+ *
+ * @todo REMOVE THIS SHIZ FROM GESHI!
+ * @deprecated
+ */
+ function enable_important_blocks($flag) {
+ $this->enable_important_blocks = ( $flag ) ? true : false;
+ }
+
+ /**
+ * Whether CSS IDs should be added to each line
+ *
+ * @param boolean If true, IDs will be added to each line.
+ * @since 1.0.2
+ */
+ function enable_ids($flag = true) {
+ $this->add_ids = ($flag) ? true : false;
+ }
+
+ /**
+ * Specifies which lines to highlight extra
+ *
+ * @param mixed An array of line numbers to highlight, or just a line
+ * number on its own.
+ * @since 1.0.2
+ * @todo Some data replication here that could be cut down on
+ */
+ function highlight_lines_extra($lines) {
+ if (is_array($lines)) {
+ foreach ($lines as $line) {
+ $this->highlight_extra_lines[intval($line)] = intval($line);
+ }
+ }
+ else {
+ $this->highlight_extra_lines[intval($lines)] = intval($lines);
+ }
+ }
+
+ /**
+ * Sets the style for extra-highlighted lines
+ *
+ * @param string The style for extra-highlighted lines
+ * @since 1.0.2
+ */
+ function set_highlight_lines_extra_style($styles) {
+ $this->highlight_extra_lines_style = $styles;
+ }
+
+ /**
+ * Sets what number line numbers should start at. Should
+ * be a positive integer, and will be converted to one.
+ *
+ * Warning: Using this method will add the "start"
+ * attribute to the <ol> that is used for line numbering.
+ * This is not valid XHTML strict, so if that's what you
+ * care about then don't use this method. Firefox is getting
+ * support for the CSS method of doing this in 1.1 and Opera
+ * has support for the CSS method, but (of course) IE doesn't
+ * so it's not worth doing it the CSS way yet.
+ *
+ * @param int The number to start line numbers at
+ * @since 1.0.2
+ */
+ function start_line_numbers_at($number) {
+ $this->line_numbers_start = abs(intval($number));
+ }
+
+ /**
+ * Sets the encoding used for htmlspecialchars(), for international
+ * support.
+ *
+ * NOTE: This is not needed for now because htmlspecialchars() is not
+ * being used (it has a security hole in PHP4 that has not been patched).
+ * Maybe in a future version it may make a return for speed reasons, but
+ * I doubt it.
+ *
+ * @param string The encoding to use for the source
+ * @since 1.0.3
+ */
+ function set_encoding($encoding) {
+ if ($encoding) {
+ $this->encoding = $encoding;
+ }
+ }
+
+ /**
+ * Turns linking of keywords on or off.
+ *
+ * @param boolean If true, links will be added to keywords
+ */
+ function enable_keyword_links($enable = true) {
+ $this->keyword_links = ($enable) ? true : false;
+ }
+
+ /**
+ * Returns the code in $this->source, highlighted and surrounded by the
+ * nessecary HTML.
+ *
+ * This should only be called ONCE, cos it's SLOW! If you want to highlight
+ * the same source multiple times, you're better off doing a whole lot of
+ * str_replaces to replace the <span>s
+ *
+ * @since 1.0.0
+ */
+ function parse_code () {
+ // Start the timer
+ $start_time = microtime();
+
+ // Firstly, if there is an error, we won't highlight
+ if ($this->error) {
+ $result = GeSHi::hsc($this->source);
+ // Timing is irrelevant
+ $this->set_time($start_time, $start_time);
+ return $this->finalise($result);
+ }
+
+ // Replace all newlines to a common form.
+ $code = str_replace("\r\n", "\n", $this->source);
+ $code = str_replace("\r", "\n", $code);
+ // Add spaces for regular expression matching and line numbers
+ $code = "\n" . $code . "\n";
+
+ // Initialise various stuff
+ $length = strlen($code);
+ $STRING_OPEN = '';
+ $CLOSE_STRING = false;
+ $ESCAPE_CHAR_OPEN = false;
+ $COMMENT_MATCHED = false;
+ // Turn highlighting on if strict mode doesn't apply to this language
+ $HIGHLIGHTING_ON = ( !$this->strict_mode ) ? true : '';
+ // Whether to highlight inside a block of code
+ $HIGHLIGHT_INSIDE_STRICT = false;
+ $HARDQUOTE_OPEN = false;
+ $STRICTATTRS = '';
+ $stuff_to_parse = '';
+ $result = '';
+
+ // "Important" selections are handled like multiline comments
+ // @todo GET RID OF THIS SHIZ
+ if ($this->enable_important_blocks) {
+ $this->language_data['COMMENT_MULTI'][GESHI_START_IMPORTANT] = GESHI_END_IMPORTANT;
+ }
+
+ if ($this->strict_mode) {
+ // Break the source into bits. Each bit will be a portion of the code
+ // within script delimiters - for example, HTML between < and >
+ $parts = array(0 => array(0 => ''));
+ $k = 0;
+ for ($i = 0; $i < $length; $i++) {
+ $char = substr($code, $i, 1);
+ if (!$HIGHLIGHTING_ON) {
+ foreach ($this->language_data['SCRIPT_DELIMITERS'] as $key => $delimiters) {
+ foreach ($delimiters as $open => $close) {
+ // Get the next little bit for this opening string
+ $check = substr($code, $i, strlen($open));
+ // If it matches...
+ if ($check == $open) {
+ // We start a new block with the highlightable
+ // code in it
+ $HIGHLIGHTING_ON = $open;
+ $i += strlen($open) - 1;
+ $char = $open;
+ $parts[++$k][0] = $char;
+
+ // No point going around again...
+ break(2);
+ }
+ }
+ }
+ }
+ else {
+ foreach ($this->language_data['SCRIPT_DELIMITERS'] as $key => $delimiters) {
+ foreach ($delimiters as $open => $close) {
+ if ($open == $HIGHLIGHTING_ON) {
+ // Found the closing tag
+ break(2);
+ }
+ }
+ }
+ // We check code from our current position BACKWARDS. This is so
+ // the ending string for highlighting can be included in the block
+ $check = substr($code, $i - strlen($close) + 1, strlen($close));
+ if ($check == $close) {
+ $HIGHLIGHTING_ON = '';
+ // Add the string to the rest of the string for this part
+ $parts[$k][1] = ( isset($parts[$k][1]) ) ? $parts[$k][1] . $char : $char;
+ $parts[++$k][0] = '';
+ $char = '';
+ }
+ }
+ $parts[$k][1] = ( isset($parts[$k][1]) ) ? $parts[$k][1] . $char : $char;
+ }
+ $HIGHLIGHTING_ON = '';
+ }
+ else {
+ // Not strict mode - simply dump the source into
+ // the array at index 1 (the first highlightable block)
+ $parts = array(
+ 1 => array(
+ 0 => '',
+ 1 => $code
+ )
+ );
+ }
+
+ // Now we go through each part. We know that even-indexed parts are
+ // code that shouldn't be highlighted, and odd-indexed parts should
+ // be highlighted
+ foreach ($parts as $key => $data) {
+ $part = $data[1];
+ // If this block should be highlighted...
+ if ($key % 2) {
+ if ($this->strict_mode) {
+ // Find the class key for this block of code
+ foreach ($this->language_data['SCRIPT_DELIMITERS'] as $script_key => $script_data) {
+ foreach ($script_data as $open => $close) {
+ if ($data[0] == $open) {
+ break(2);
+ }
+ }
+ }
+
+ if ($this->language_data['STYLES']['SCRIPT'][$script_key] != '' &&
+ $this->lexic_permissions['SCRIPT']) {
+ // Add a span element around the source to
+ // highlight the overall source block
+ if (!$this->use_classes &&
+ $this->language_data['STYLES']['SCRIPT'][$script_key] != '') {
+ $attributes = ' style="' . $this->language_data['STYLES']['SCRIPT'][$script_key] . '"';
+ }
+ else {
+ $attributes = ' class="sc' . $script_key . '"';
+ }
+ $result .= "";
+ $STRICTATTRS = $attributes;
+ }
+ }
+
+ if (!$this->strict_mode || $this->language_data['HIGHLIGHT_STRICT_BLOCK'][$script_key]) {
+ // Now, highlight the code in this block. This code
+ // is really the engine of GeSHi (along with the method
+ // parse_non_string_part).
+ $length = strlen($part);
+ for ($i = 0; $i < $length; $i++) {
+ // Get the next char
+ $char = substr($part, $i, 1);
+ $hq = isset($this->language_data['HARDQUOTE']) ? $this->language_data['HARDQUOTE'][0] : false;
+ // Is this char the newline and line numbers being used?
+ if (($this->line_numbers != GESHI_NO_LINE_NUMBERS
+ || count($this->highlight_extra_lines) > 0)
+ && $char == "\n") {
+ // If so, is there a string open? If there is, we should end it before
+ // the newline and begin it again (so when header, we shouldn't add newlines because + // thewill line-break them (and the
header + $parsed_code .= $line . "
$header"; + } + return "$footer_content"; + } + } + + /** + * Returns the footer content, formatted for output + * + * @return string The footer content, formatted for output + * @since 1.0.2 + * @access private + */ + function format_footer_content() { + $footer = $this->footer_content; + if ($footer) { + if ($this->header_type == GESHI_HEADER_PRE) { + $footer = str_replace("\n", '', $footer);; + } + $footer = $this->replace_keywords($footer); + + if ($this->use_classes) { + $attr = ' class="foot"'; + } + else { + $attr = " style=\"{$this->footer_content_style}\""; + } + return ""; + } + else if ($this->header_type == GESHI_HEADER_DIV) { + return "
$footer_content$header"; + } + else { + if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) { + return ""; + } + } + else { + if ($this->header_type == GESHI_HEADER_PRE) { + return "
$header"; + } + else if ($this->header_type == GESHI_HEADER_DIV) { + return "$header"; + } + } + } + + /** + * Returns the header content, formatted for output + * + * @return string The header content, formatted for output + * @since 1.0.2 + * @access private + */ + function format_header_content() { + $header = $this->header_content; + if ($header) { + if ($this->header_type == GESHI_HEADER_PRE) { + $header = str_replace("\n", '', $header); + } + $header = $this->replace_keywords($header); + + if ($this->use_classes) { + $attr = ' class="head"'; + } + else { + $attr = " style=\"{$this->header_content_style}\""; + } + return ""; + } + return "$footer_content$header"; + } + } + + /** + * Returns the footer for the code block. + * + * @return string The footer for the code block + * @since 1.0.0 + * @access private + */ + function footer() { + $footer_content = $this->format_footer_content(); + + if (GESHI_HEADER_NONE == $this->header_type) { + return ($this->line_numbers != GESHI_NO_LINE_NUMBERS) ? '' . $footer_content + : $footer_content; + } + + if ($this->header_type == GESHI_HEADER_DIV) { + if ($this->line_numbers != GESHI_NO_LINE_NUMBERS) { + return "$footer_content