diff --git a/oss/joomla/trunk/libraries/domit/domitBanner.gif b/oss/joomla/trunk/libraries/domit/domitBanner.gif new file mode 100644 index 00000000..e8757901 Binary files /dev/null and b/oss/joomla/trunk/libraries/domit/domitBanner.gif differ diff --git a/oss/joomla/trunk/libraries/domit/index.html b/oss/joomla/trunk/libraries/domit/index.html new file mode 100644 index 00000000..fa6d84e8 --- /dev/null +++ b/oss/joomla/trunk/libraries/domit/index.html @@ -0,0 +1 @@ +
\ No newline at end of file diff --git a/oss/joomla/trunk/libraries/domit/license.txt b/oss/joomla/trunk/libraries/domit/license.txt new file mode 100644 index 00000000..532c8911 --- /dev/null +++ b/oss/joomla/trunk/libraries/domit/license.txt @@ -0,0 +1,482 @@ +DOMIT! is a non-validating, but lightweight and fast DOM parser for PHP +DOMIT! RSS is a DOM based RSS parser for PHP + +By John Heinstein +jheinstein@engageinteractive.com +johnkarl@nbnet.nb.ca + +Copyright (C) 2004 John Heinstein +http://www.engageinteractive.com/domit/ +http://www.engageinteractive.com/domitrss/ +All rights reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + + + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/oss/joomla/trunk/libraries/domit/php_file_utilities.php b/oss/joomla/trunk/libraries/domit/php_file_utilities.php new file mode 100644 index 00000000..b881564d --- /dev/null +++ b/oss/joomla/trunk/libraries/domit/php_file_utilities.php @@ -0,0 +1,50 @@ + \ No newline at end of file diff --git a/oss/joomla/trunk/libraries/domit/php_http_client_generic.php b/oss/joomla/trunk/libraries/domit/php_http_client_generic.php new file mode 100644 index 00000000..bfbf76bb --- /dev/null +++ b/oss/joomla/trunk/libraries/domit/php_http_client_generic.php @@ -0,0 +1,761 @@ + +* @link http://www.engageinteractive.com/php_http_tools/ PHP HTTP Tools Home Page +* PHP HTTP Tools are Free Software +**/ + +if (!defined('PHP_HTTP_TOOLS_INCLUDE_PATH')) { + define('PHP_HTTP_TOOLS_INCLUDE_PATH', (dirname(__FILE__) . "/")); +} + +/** end-of-line character sequence as defined in HTTP spec */ +define ('CRLF', "\r\n"); +/** carriage return character */ +define ('CR', "\r"); +/** line feed character */ +define ('LF', "\n"); + +//http read states for client +/** beginning read state */ +define('HTTP_READ_STATE_BEGIN', 1); +/** state when reading headers */ +define('HTTP_READ_STATE_HEADERS', 2); +/** state when reading body of message */ +define('HTTP_READ_STATE_BODY', 3); + +require_once(PHP_HTTP_TOOLS_INCLUDE_PATH . 'php_http_exceptions.php'); + +/** + +* An HTTP Request class +* +* @package php-http-tools +* @author John Heinstein' . 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 . ""; + } + + //log error to file + if ((isset($GLOBALS['HTTP_Exception_log'])) && + ($GLOBALS['HTTP_Exception_log'] != null)) { + require_once(PHP_HTTP_TOOLS_INCLUDE_PATH . 'php_file_utilities.php'); + $logItem = "\n" . date('Y-m-d H:i:s') . ' HTTP Error ' . $errorMessageText; + php_file_utilities::putDataToFile($GLOBALS['HTTP_Exception_log'], + $logItem, 'a'); + } + + switch ($GLOBALS['HTTP_Exception_mode']) { + case HTTP_ONERROR_CONTINUE: + return; + break; + + case HTTP_ONERROR_DIE: + die($errorMessage); + break; + } + } + } //raiseException + + /** + * custom handler for HTTP errors + * @param object A reference to the custom error handler + */ + function setErrorHandler($method) { + $GLOBALS['HTTP_Exception_errorHandler'] =& $method; + } //setErrorHandler + + /** + * Set error mode + * @param int The HTTP error mode + */ + function setErrorMode($mode) { + $GLOBALS['HTTP_Exception_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['HTTP_Exception_log'] = $logfile; + } + else { + $GLOBALS['HTTP_Exception_log'] = null; + } + } //setErrorLog +} //HTTPExceptions + +?> \ No newline at end of file diff --git a/oss/joomla/trunk/libraries/domit/php_http_proxy.php b/oss/joomla/trunk/libraries/domit/php_http_proxy.php new file mode 100644 index 00000000..5f01f783 --- /dev/null +++ b/oss/joomla/trunk/libraries/domit/php_http_proxy.php @@ -0,0 +1,78 @@ + +* @link http://www.engageinteractive.com/php_http_tools/ PHP HTTP Tools Home Page +* PHP HTTP Tools are Free Software +**/ +if (!defined('PHP_HTTP_TOOLS_INCLUDE_PATH')) { + define('PHP_HTTP_TOOLS_INCLUDE_PATH', (dirname(__FILE__) . "/")); +} + +require_once(PHP_HTTP_TOOLS_INCLUDE_PATH . 'php_http_client_generic.php'); + +/** +* An HTTP Proxy class +* +* @package php-http-tools +* @author John Heinstein
" . $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