From d216b3147bc3f37cf2337acab5767c6a4f74aa2e Mon Sep 17 00:00:00 2001 From: emkael Date: Mon, 31 Oct 2016 21:58:33 +0100 Subject: * PHPTAL library --- lib/phptal/COPYING | 504 ++++++++ lib/phptal/PHPTAL.php | 1226 ++++++++++++++++++++ lib/phptal/PHPTAL/ConfigurationException.php | 24 + lib/phptal/PHPTAL/Context.php | 563 +++++++++ lib/phptal/PHPTAL/DefaultKeyword.php | 39 + lib/phptal/PHPTAL/Dom/Attr.php | 196 ++++ lib/phptal/PHPTAL/Dom/CDATASection.php | 49 + lib/phptal/PHPTAL/Dom/Comment.php | 28 + lib/phptal/PHPTAL/Dom/Defs.php | 246 ++++ lib/phptal/PHPTAL/Dom/DocumentBuilder.php | 63 + lib/phptal/PHPTAL/Dom/DocumentType.php | 33 + lib/phptal/PHPTAL/Dom/Element.php | 521 +++++++++ lib/phptal/PHPTAL/Dom/Node.php | 105 ++ lib/phptal/PHPTAL/Dom/PHPTALDocumentBuilder.php | 167 +++ lib/phptal/PHPTAL/Dom/ProcessingInstruction.php | 34 + lib/phptal/PHPTAL/Dom/SaxXmlParser.php | 480 ++++++++ lib/phptal/PHPTAL/Dom/Text.php | 31 + lib/phptal/PHPTAL/Dom/XmlDeclaration.php | 29 + lib/phptal/PHPTAL/Dom/XmlnsState.php | 95 ++ lib/phptal/PHPTAL/Exception.php | 23 + lib/phptal/PHPTAL/ExceptionHandler.php | 81 ++ lib/phptal/PHPTAL/FileSource.php | 51 + lib/phptal/PHPTAL/FileSourceResolver.php | 46 + lib/phptal/PHPTAL/Filter.php | 32 + lib/phptal/PHPTAL/GetTextTranslator.php | 183 +++ lib/phptal/PHPTAL/IOException.php | 25 + lib/phptal/PHPTAL/InvalidVariableNameException.php | 25 + lib/phptal/PHPTAL/Keywords.php | 26 + lib/phptal/PHPTAL/MacroMissingException.php | 24 + lib/phptal/PHPTAL/Namespace.php | 70 ++ lib/phptal/PHPTAL/Namespace/Builtin.php | 38 + lib/phptal/PHPTAL/Namespace/I18N.php | 32 + lib/phptal/PHPTAL/Namespace/METAL.php | 31 + lib/phptal/PHPTAL/Namespace/PHPTAL.php | 31 + lib/phptal/PHPTAL/Namespace/TAL.php | 36 + lib/phptal/PHPTAL/NamespaceAttribute.php | 99 ++ lib/phptal/PHPTAL/NamespaceAttributeContent.php | 23 + lib/phptal/PHPTAL/NamespaceAttributeReplace.php | 23 + lib/phptal/PHPTAL/NamespaceAttributeSurround.php | 23 + lib/phptal/PHPTAL/NothingKeyword.php | 39 + lib/phptal/PHPTAL/ParserException.php | 24 + lib/phptal/PHPTAL/Php/Attribute.php | 98 ++ .../PHPTAL/Php/Attribute/I18N/Attributes.php | 118 ++ lib/phptal/PHPTAL/Php/Attribute/I18N/Data.php | 36 + lib/phptal/PHPTAL/Php/Attribute/I18N/Domain.php | 50 + lib/phptal/PHPTAL/Php/Attribute/I18N/Name.php | 47 + lib/phptal/PHPTAL/Php/Attribute/I18N/Source.php | 48 + lib/phptal/PHPTAL/Php/Attribute/I18N/Target.php | 43 + lib/phptal/PHPTAL/Php/Attribute/I18N/Translate.php | 130 +++ .../PHPTAL/Php/Attribute/METAL/DefineMacro.php | 67 ++ .../PHPTAL/Php/Attribute/METAL/DefineSlot.php | 70 ++ lib/phptal/PHPTAL/Php/Attribute/METAL/FillSlot.php | 148 +++ lib/phptal/PHPTAL/Php/Attribute/METAL/UseMacro.php | 135 +++ lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Cache.php | 97 ++ lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Debug.php | 34 + lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Id.php | 53 + lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Tales.php | 45 + lib/phptal/PHPTAL/Php/Attribute/TAL/Attributes.php | 213 ++++ lib/phptal/PHPTAL/Php/Attribute/TAL/Comment.php | 30 + lib/phptal/PHPTAL/Php/Attribute/TAL/Condition.php | 93 ++ lib/phptal/PHPTAL/Php/Attribute/TAL/Content.php | 95 ++ lib/phptal/PHPTAL/Php/Attribute/TAL/Define.php | 193 +++ lib/phptal/PHPTAL/Php/Attribute/TAL/OmitTag.php | 70 ++ lib/phptal/PHPTAL/Php/Attribute/TAL/OnError.php | 73 ++ lib/phptal/PHPTAL/Php/Attribute/TAL/Repeat.php | 99 ++ lib/phptal/PHPTAL/Php/Attribute/TAL/Replace.php | 117 ++ lib/phptal/PHPTAL/Php/CodeWriter.php | 511 ++++++++ lib/phptal/PHPTAL/Php/State.php | 254 ++++ lib/phptal/PHPTAL/Php/TalesChainExecutor.php | 96 ++ lib/phptal/PHPTAL/Php/TalesChainReader.php | 25 + lib/phptal/PHPTAL/Php/TalesInternal.php | 503 ++++++++ lib/phptal/PHPTAL/Php/Transformer.php | 418 +++++++ lib/phptal/PHPTAL/PreFilter.php | 132 +++ lib/phptal/PHPTAL/PreFilter/Compress.php | 282 +++++ lib/phptal/PHPTAL/PreFilter/Normalize.php | 108 ++ lib/phptal/PHPTAL/PreFilter/StripComments.php | 34 + lib/phptal/PHPTAL/RepeatController.php | 323 ++++++ lib/phptal/PHPTAL/RepeatControllerGroups.php | 199 ++++ lib/phptal/PHPTAL/Source.php | 52 + lib/phptal/PHPTAL/SourceResolver.php | 25 + lib/phptal/PHPTAL/StringSource.php | 51 + lib/phptal/PHPTAL/Tales.php | 58 + lib/phptal/PHPTAL/TalesRegistry.php | 185 +++ lib/phptal/PHPTAL/TemplateException.php | 160 +++ lib/phptal/PHPTAL/Tokenizer.php | 69 ++ lib/phptal/PHPTAL/TranslationService.php | 62 + lib/phptal/PHPTAL/Trigger.php | 29 + lib/phptal/PHPTAL/UnknownModifierException.php | 35 + lib/phptal/PHPTAL/VariableNotFoundException.php | 24 + 89 files changed, 11255 insertions(+) create mode 100644 lib/phptal/COPYING create mode 100644 lib/phptal/PHPTAL.php create mode 100644 lib/phptal/PHPTAL/ConfigurationException.php create mode 100644 lib/phptal/PHPTAL/Context.php create mode 100644 lib/phptal/PHPTAL/DefaultKeyword.php create mode 100644 lib/phptal/PHPTAL/Dom/Attr.php create mode 100644 lib/phptal/PHPTAL/Dom/CDATASection.php create mode 100644 lib/phptal/PHPTAL/Dom/Comment.php create mode 100644 lib/phptal/PHPTAL/Dom/Defs.php create mode 100644 lib/phptal/PHPTAL/Dom/DocumentBuilder.php create mode 100644 lib/phptal/PHPTAL/Dom/DocumentType.php create mode 100644 lib/phptal/PHPTAL/Dom/Element.php create mode 100644 lib/phptal/PHPTAL/Dom/Node.php create mode 100644 lib/phptal/PHPTAL/Dom/PHPTALDocumentBuilder.php create mode 100644 lib/phptal/PHPTAL/Dom/ProcessingInstruction.php create mode 100644 lib/phptal/PHPTAL/Dom/SaxXmlParser.php create mode 100644 lib/phptal/PHPTAL/Dom/Text.php create mode 100644 lib/phptal/PHPTAL/Dom/XmlDeclaration.php create mode 100644 lib/phptal/PHPTAL/Dom/XmlnsState.php create mode 100644 lib/phptal/PHPTAL/Exception.php create mode 100644 lib/phptal/PHPTAL/ExceptionHandler.php create mode 100644 lib/phptal/PHPTAL/FileSource.php create mode 100644 lib/phptal/PHPTAL/FileSourceResolver.php create mode 100644 lib/phptal/PHPTAL/Filter.php create mode 100644 lib/phptal/PHPTAL/GetTextTranslator.php create mode 100644 lib/phptal/PHPTAL/IOException.php create mode 100644 lib/phptal/PHPTAL/InvalidVariableNameException.php create mode 100644 lib/phptal/PHPTAL/Keywords.php create mode 100644 lib/phptal/PHPTAL/MacroMissingException.php create mode 100644 lib/phptal/PHPTAL/Namespace.php create mode 100644 lib/phptal/PHPTAL/Namespace/Builtin.php create mode 100644 lib/phptal/PHPTAL/Namespace/I18N.php create mode 100644 lib/phptal/PHPTAL/Namespace/METAL.php create mode 100644 lib/phptal/PHPTAL/Namespace/PHPTAL.php create mode 100644 lib/phptal/PHPTAL/Namespace/TAL.php create mode 100644 lib/phptal/PHPTAL/NamespaceAttribute.php create mode 100644 lib/phptal/PHPTAL/NamespaceAttributeContent.php create mode 100644 lib/phptal/PHPTAL/NamespaceAttributeReplace.php create mode 100644 lib/phptal/PHPTAL/NamespaceAttributeSurround.php create mode 100644 lib/phptal/PHPTAL/NothingKeyword.php create mode 100644 lib/phptal/PHPTAL/ParserException.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/I18N/Attributes.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/I18N/Data.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/I18N/Domain.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/I18N/Name.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/I18N/Source.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/I18N/Target.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/I18N/Translate.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/METAL/DefineMacro.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/METAL/DefineSlot.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/METAL/FillSlot.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/METAL/UseMacro.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Cache.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Debug.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Id.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Tales.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/TAL/Attributes.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/TAL/Comment.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/TAL/Condition.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/TAL/Content.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/TAL/Define.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/TAL/OmitTag.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/TAL/OnError.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/TAL/Repeat.php create mode 100644 lib/phptal/PHPTAL/Php/Attribute/TAL/Replace.php create mode 100644 lib/phptal/PHPTAL/Php/CodeWriter.php create mode 100644 lib/phptal/PHPTAL/Php/State.php create mode 100644 lib/phptal/PHPTAL/Php/TalesChainExecutor.php create mode 100644 lib/phptal/PHPTAL/Php/TalesChainReader.php create mode 100644 lib/phptal/PHPTAL/Php/TalesInternal.php create mode 100644 lib/phptal/PHPTAL/Php/Transformer.php create mode 100644 lib/phptal/PHPTAL/PreFilter.php create mode 100644 lib/phptal/PHPTAL/PreFilter/Compress.php create mode 100644 lib/phptal/PHPTAL/PreFilter/Normalize.php create mode 100644 lib/phptal/PHPTAL/PreFilter/StripComments.php create mode 100644 lib/phptal/PHPTAL/RepeatController.php create mode 100644 lib/phptal/PHPTAL/RepeatControllerGroups.php create mode 100644 lib/phptal/PHPTAL/Source.php create mode 100644 lib/phptal/PHPTAL/SourceResolver.php create mode 100644 lib/phptal/PHPTAL/StringSource.php create mode 100644 lib/phptal/PHPTAL/Tales.php create mode 100644 lib/phptal/PHPTAL/TalesRegistry.php create mode 100644 lib/phptal/PHPTAL/TemplateException.php create mode 100644 lib/phptal/PHPTAL/Tokenizer.php create mode 100644 lib/phptal/PHPTAL/TranslationService.php create mode 100644 lib/phptal/PHPTAL/Trigger.php create mode 100644 lib/phptal/PHPTAL/UnknownModifierException.php create mode 100644 lib/phptal/PHPTAL/VariableNotFoundException.php (limited to 'lib') diff --git a/lib/phptal/COPYING b/lib/phptal/COPYING new file mode 100644 index 0000000..d3a38e5 --- /dev/null +++ b/lib/phptal/COPYING @@ -0,0 +1,504 @@ + 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 + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/lib/phptal/PHPTAL.php b/lib/phptal/PHPTAL.php new file mode 100644 index 0000000..1e3a846 --- /dev/null +++ b/lib/phptal/PHPTAL.php @@ -0,0 +1,1226 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +define('PHPTAL_VERSION', '1_3_0'); + +PHPTAL::autoloadRegister(); + +/** + * PHPTAL template entry point. + * + * + * title = 'Welcome here'; + * $tpl->result = range(1, 100); + * ... + * echo $tpl->execute(); + * } + * catch (Exception $e) { + * echo $e; + * } + * ?> + * + * + * @category HTML + * @package PHPTAL + * @author Laurent Bedubourg + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @link http://phptal.org/ + */ +class PHPTAL +{ + //{{{ + /** + * constants for output mode + * @see setOutputMode() + */ + const XHTML = 11; + const XML = 22; + const HTML5 = 55; + + /** + * @see getPreFilters() + */ + protected $prefilters = array(); + + /** + * Prefilters have been redesigned. Old property is no longer used. + * + * @deprecated + */ + private $_prefilter = 'REMOVED: DO NOT USE'; + protected $_postfilter = null; + + /** + * list of template source repositories given to file source resolver + */ + protected $_repositories = array(); + + /** + * template path (path that has been set, not necessarily loaded) + */ + protected $_path = null; + + /** + * template source resolvers (classes that search for templates by name) + */ + protected $resolvers = array(); + + /** + * template source (only set when not working with file) + */ + protected $_source = null; + + /** + * destination of PHP intermediate file + */ + protected $_codeFile = null; + + /** + * php function generated for the template + */ + protected $_functionName = null; + + /** + * set to true when template is ready for execution + */ + protected $_prepared = false; + + /** + * associative array of phptal:id => PHPTAL_Trigger + */ + protected $_triggers = array(); + + /** + * i18n translator + */ + protected $_translator = null; + + /** + * global execution context + */ + protected $_globalContext = null; + + /** + * current execution context + */ + protected $_context = null; + + /** + * list of on-error caught exceptions + */ + protected $_errors = array(); + + /** + * encoding used throughout + */ + protected $_encoding = 'UTF-8'; + + /** + * type of syntax used in generated templates + */ + protected $_outputMode = PHPTAL::XHTML; + /** + * should all comments be stripped + */ + + // configuration properties + + /** + * don't use code cache + */ + protected $_forceReparse = null; + + /** + * directory where code cache is + */ + private $_phpCodeDestination; + private $_phpCodeExtension = 'php'; + + /** + * number of days + */ + private $_cacheLifetime = 30; + + /** + * 1/x + */ + private $_cachePurgeFrequency = 30; + + /** + * speeds up calls to external templates + */ + private $externalMacroTemplatesCache = array(); + + //}}} + + /** + * PHPTAL Constructor. + * + * @param string $path Template file path. + */ + public function __construct($path=false) + { + $this->_path = $path; + $this->_globalContext = new stdClass(); + $this->_context = new PHPTAL_Context(); + $this->_context->setGlobal($this->_globalContext); + + if (function_exists('sys_get_temp_dir')) { + $this->setPhpCodeDestination(sys_get_temp_dir()); + } elseif (substr(PHP_OS, 0, 3) == 'WIN') { + if (file_exists('c:\\WINNT\\Temp\\')) { + $this->setPhpCodeDestination('c:\\WINNT\\Temp\\'); + } else { + $this->setPhpCodeDestination('c:\\WINDOWS\\Temp\\'); + } + } else { + $this->setPhpCodeDestination('/tmp/'); + } + } + + /** + * create + * returns a new PHPTAL object + * + * @param string $path Template file path. + * + * @return PHPTAL + */ + public static function create($path=false) + { + return new PHPTAL($path); + } + + /** + * Clone template state and context. + * + * @return void + */ + public function __clone() + { + $this->_context = $this->_context->pushContext(); + } + + /** + * Set template from file path. + * + * @param string $path filesystem path, + * or any path that will be accepted by source resolver + * + * @return $this + */ + public function setTemplate($path) + { + $this->_prepared = false; + $this->_functionName = null; + $this->_codeFile = null; + $this->_path = $path; + $this->_source = null; + $this->_context->_docType = null; + $this->_context->_xmlDeclaration = null; + return $this; + } + + /** + * Set template from source. + * + * Should be used only with temporary template sources. + * Use setTemplate() or addSourceResolver() whenever possible. + * + * @param string $src The phptal template source. + * @param string $path Fake and 'unique' template path. + * + * @return $this + */ + public function setSource($src, $path = null) + { + $this->_prepared = false; + $this->_functionName = null; + $this->_codeFile = null; + $this->_source = new PHPTAL_StringSource($src, $path); + $this->_path = $this->_source->getRealPath(); + $this->_context->_docType = null; + $this->_context->_xmlDeclaration = null; + return $this; + } + + /** + * Specify where to look for templates. + * + * @param mixed $rep string or Array of repositories + * + * @return $this + */ + public function setTemplateRepository($rep) + { + if (is_array($rep)) { + $this->_repositories = $rep; + } else { + $this->_repositories[] = $rep; + } + return $this; + } + + /** + * Get template repositories. + * + * @return array + */ + public function getTemplateRepositories() + { + return $this->_repositories; + } + + /** + * Clears the template repositories. + * + * @return $this + */ + public function clearTemplateRepositories() + { + $this->_repositories = array(); + return $this; + } + + /** + * Specify how to look for templates. + * + * @param PHPTAL_SourceResolver $resolver instance of resolver + * + * @return $this + */ + public function addSourceResolver(PHPTAL_SourceResolver $resolver) + { + $this->resolvers[] = $resolver; + return $this; + } + + /** + * Ignore XML/XHTML comments on parsing. + * Comments starting with '); + } + } +} diff --git a/lib/phptal/PHPTAL/Dom/Defs.php b/lib/phptal/PHPTAL/Dom/Defs.php new file mode 100644 index 0000000..4d12ed6 --- /dev/null +++ b/lib/phptal/PHPTAL/Dom/Defs.php @@ -0,0 +1,246 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * PHPTAL constants. + * + * This is a pseudo singleton class, a user may decide to provide + * his own singleton instance which will then be used by PHPTAL. + * + * This behaviour is mainly useful to remove builtin namespaces + * and provide custom ones. + * + * @package PHPTAL + * @subpackage Dom + * @author Laurent Bedubourg + */ +class PHPTAL_Dom_Defs +{ + /** + * this is a singleton + */ + public static function getInstance() + { + if (!self::$_instance) { + self::$_instance = new PHPTAL_Dom_Defs(); + } + return self::$_instance; + } + + protected function __construct() + { + $this->registerNamespace(new PHPTAL_Namespace_TAL()); + $this->registerNamespace(new PHPTAL_Namespace_METAL()); + $this->registerNamespace(new PHPTAL_Namespace_I18N()); + $this->registerNamespace(new PHPTAL_Namespace_PHPTAL()); + } + + /** + * true if it's empty in XHTML (e.g. ) + * it will assume elements with no namespace may be XHTML too. + * + * @param string $tagName local name of the tag + * + * @return bool + */ + public function isEmptyTagNS($namespace_uri, $local_name) + { + return ($namespace_uri === 'http://www.w3.org/1999/xhtml' || $namespace_uri === '') + && in_array(strtolower($local_name), self::$XHTML_EMPTY_TAGS); + } + + /** + * gives namespace URI for given registered (built-in) prefix + */ + public function prefixToNamespaceURI($prefix) + { + return isset($this->prefix_to_uri[$prefix]) ? $this->prefix_to_uri[$prefix] : false; + } + + /** + * gives typical prefix for given (built-in) namespace + */ + public function namespaceURIToPrefix($uri) + { + return array_search($uri, $this->prefix_to_uri, true); + } + + /** + * array prefix => uri for prefixes that don't have to be declared in PHPTAL + * @return array + */ + public function getPredefinedPrefixes() + { + return $this->prefix_to_uri; + } + + /** + * Returns true if the attribute is an xhtml boolean attribute. + * + * @param string $att local name + * + * @return bool + */ + public function isBooleanAttribute($att) + { + return in_array($att, self::$XHTML_BOOLEAN_ATTRIBUTES); + } + + /** + * true if elements content is parsed as CDATA in text/html + * and also accepts /* * / as comments. + */ + public function isCDATAElementInHTML($namespace_uri, $local_name) + { + return ($local_name === 'script' || $local_name === 'style') + && ($namespace_uri === 'http://www.w3.org/1999/xhtml' || $namespace_uri === ''); + } + + /** + * Returns true if the attribute is a valid phptal attribute + * + * Examples of valid attributes: tal:content, metal:use-slot + * Examples of invalid attributes: tal:unknown, metal:content + * + * @return bool + */ + public function isValidAttributeNS($namespace_uri, $local_name) + { + if (!$this->isHandledNamespace($namespace_uri)) return false; + + $attrs = $this->namespaces_by_uri[$namespace_uri]->getAttributes(); + return isset($attrs[$local_name]); + } + + /** + * is URI registered (built-in) namespace + */ + public function isHandledNamespace($namespace_uri) + { + return isset($this->namespaces_by_uri[$namespace_uri]); + } + + /** + * Returns true if the attribute is a phptal handled xml namespace + * declaration. + * + * Examples of handled xmlns: xmlns:tal, xmlns:metal + * + * @return bool + */ + public function isHandledXmlNs($qname, $value) + { + return substr(strtolower($qname), 0, 6) == 'xmlns:' && $this->isHandledNamespace($value); + } + + /** + * return objects that holds information about given TAL attribute + */ + public function getNamespaceAttribute($namespace_uri, $local_name) + { + $attrs = $this->namespaces_by_uri[$namespace_uri]->getAttributes(); + return $attrs[$local_name]; + } + + /** + * Register a PHPTAL_Namespace and its attribute into PHPTAL. + */ + public function registerNamespace(PHPTAL_Namespace $ns) + { + $this->namespaces_by_uri[$ns->getNamespaceURI()] = $ns; + $this->prefix_to_uri[$ns->getPrefix()] = $ns->getNamespaceURI(); + $prefix = strtolower($ns->getPrefix()); + foreach ($ns->getAttributes() as $name => $attribute) { + $key = $prefix.':'.strtolower($name); + $this->_dictionary[$key] = $attribute; + } + } + + private static $_instance = null; + private $_dictionary = array(); + /** + * list of PHPTAL_Namespace objects + */ + private $namespaces_by_uri = array(); + private $prefix_to_uri = array( + 'xml'=>'http://www.w3.org/XML/1998/namespace', + 'xmlns'=>'http://www.w3.org/2000/xmlns/', + ); + + /** + * This array contains XHTML tags that must be echoed in a <tag/> form + * instead of the <tag></tag> form. + * + * In fact, some browsers does not support the later form so PHPTAL + * ensure these tags are correctly echoed. + */ + private static $XHTML_EMPTY_TAGS = array( + 'area', + 'base', + 'basefont', + 'br', + 'col', + 'command', + 'embed', + 'frame', + 'hr', + 'img', + 'input', + 'isindex', + 'keygen', + 'link', + 'meta', + 'param', + 'wbr', + 'source', + 'track', + ); + + /** + * This array contains XHTML boolean attributes, their value is self + * contained (ie: they are present or not). + */ + private static $XHTML_BOOLEAN_ATTRIBUTES = array( + 'autoplay', + 'async', + 'autofocus', + 'checked', + 'compact', + 'controls', + 'declare', + 'default', + 'defer', + 'disabled', + 'formnovalidate', + 'hidden', + 'ismap', + 'itemscope', + 'loop', + 'multiple', + 'noresize', + 'noshade', + 'novalidate', + 'nowrap', + 'open', + 'pubdate', + 'readonly', + 'required', + 'reversed', + 'scoped', + 'seamless', + 'selected', + ); +} diff --git a/lib/phptal/PHPTAL/Dom/DocumentBuilder.php b/lib/phptal/PHPTAL/Dom/DocumentBuilder.php new file mode 100644 index 0000000..c08587f --- /dev/null +++ b/lib/phptal/PHPTAL/Dom/DocumentBuilder.php @@ -0,0 +1,63 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * DOM Builder + * + * @package PHPTAL + * @subpackage Dom + */ +abstract class PHPTAL_Dom_DocumentBuilder +{ + protected $_stack; /* array */ + protected $_current; /* PHPTAL_Dom_Node */ + + protected $file, $line; + + public function __construct() + { + $this->_stack = array(); + } + + abstract public function getResult(); + + abstract public function onDocumentStart(); + + abstract public function onDocumentEnd(); + + abstract public function onDocType($doctype); + + abstract public function onXmlDecl($decl); + + abstract public function onComment($data); + + abstract public function onCDATASection($data); + + abstract public function onProcessingInstruction($data); + + abstract public function onElementStart($element_qname, array $attributes); + + abstract public function onElementData($data); + + abstract public function onElementClose($qname); + + public function setSource($file, $line) + { + $this->file = $file; $this->line = $line; + } + + abstract public function setEncoding($encoding); +} + diff --git a/lib/phptal/PHPTAL/Dom/DocumentType.php b/lib/phptal/PHPTAL/Dom/DocumentType.php new file mode 100644 index 0000000..38b49e4 --- /dev/null +++ b/lib/phptal/PHPTAL/Dom/DocumentType.php @@ -0,0 +1,33 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * Document doctype representation. + * + * @package PHPTAL + * @subpackage Dom + */ +class PHPTAL_Dom_DocumentType extends PHPTAL_Dom_Node +{ + public function generateCode(PHPTAL_Php_CodeWriter $codewriter) + { + if ($codewriter->getOutputMode() === PHPTAL::HTML5) { + $codewriter->setDocType(''); + } else { + $codewriter->setDocType($this->getValueEscaped()); + } + $codewriter->doDoctype(); + } +} diff --git a/lib/phptal/PHPTAL/Dom/Element.php b/lib/phptal/PHPTAL/Dom/Element.php new file mode 100644 index 0000000..574c830 --- /dev/null +++ b/lib/phptal/PHPTAL/Dom/Element.php @@ -0,0 +1,521 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * Document Tag representation. + * + * @package PHPTAL + * @subpackage Dom + */ +class PHPTAL_Dom_Element extends PHPTAL_Dom_Node +{ + protected $qualifiedName, $namespace_uri; + private $attribute_nodes = array(); + protected $replaceAttributes = array(); + protected $contentAttributes = array(); + protected $surroundAttributes = array(); + public $headFootDisabled = false; + public $headPrintCondition = false; + public $footPrintCondition = false; + public $hidden = false; + + // W3C DOM interface + public $childNodes = array(); + public $parentNode; + + /** + * @param string $qname qualified name of the element, e.g. "tal:block" + * @param string $namespace_uri namespace of this element + * @param array $attribute_nodes array of PHPTAL_Dom_Attr elements + * @param object $xmlns object that represents namespaces/prefixes known in element's context + */ + public function __construct($qname, $namespace_uri, array $attribute_nodes, PHPTAL_Dom_XmlnsState $xmlns) + { + $this->qualifiedName = $qname; + $this->attribute_nodes = $attribute_nodes; + $this->namespace_uri = $namespace_uri; + $this->xmlns = $xmlns; + + // implements inheritance of element's namespace to tal attributes () + foreach ($attribute_nodes as $index => $attr) { + // it'll work only when qname == localname, which is good + if ($this->xmlns->isValidAttributeNS($namespace_uri, $attr->getQualifiedName())) { + $this->attribute_nodes[$index] = new PHPTAL_Dom_Attr($attr->getQualifiedName(), $namespace_uri, $attr->getValueEscaped(), $attr->getEncoding()); + } + } + + if ($this->xmlns->isHandledNamespace($this->namespace_uri)) { + $this->headFootDisabled = true; + } + + $talAttributes = $this->separateAttributes(); + $this->orderTalAttributes($talAttributes); + } + + /** + * returns object that represents namespaces known in element's context + */ + public function getXmlnsState() + { + return $this->xmlns; + } + + /** + * Replace + * with + * This avoids gotcha in text/html. + * + * Note that PHPTAL_Dom_CDATASection::generate() does reverse operation, if needed! + * + * @return void + */ + private function replaceTextWithCDATA() + { + $isCDATAelement = PHPTAL_Dom_Defs::getInstance()->isCDATAElementInHTML($this->getNamespaceURI(), $this->getLocalName()); + + if (!$isCDATAelement) { + return; + } + + $valueEscaped = ''; // sometimes parser generates split text nodes. "normalisation" is needed. + $value = ''; + foreach ($this->childNodes as $node) { + // leave it alone if there is CDATA, comment, or anything else. + if (!$node instanceof PHPTAL_Dom_Text) return; + + $value .= $node->getValue(); + $valueEscaped .= $node->getValueEscaped(); + + $encoding = $node->getEncoding(); // encoding of all nodes is the same + } + + // only add cdata if there are entities + // and there's no ${structure} (because it may rely on cdata syntax) + if (false === strpos($valueEscaped, '&') || preg_match('/<\?|\${structure/', $value)) { + return; + } + + $this->childNodes = array(); + + // appendChild sets parent + $this->appendChild(new PHPTAL_Dom_Text('/*', $encoding)); + $this->appendChild(new PHPTAL_Dom_CDATASection('*/'.$value.'/*', $encoding)); + $this->appendChild(new PHPTAL_Dom_Text('*/', $encoding)); + } + + public function appendChild(PHPTAL_Dom_Node $child) + { + if ($child->parentNode) $child->parentNode->removeChild($child); + $child->parentNode = $this; + $this->childNodes[] = $child; + } + + public function removeChild(PHPTAL_Dom_Node $child) + { + foreach ($this->childNodes as $k => $node) { + if ($child === $node) { + $child->parentNode = null; + array_splice($this->childNodes, $k, 1); + return; + } + } + throw new PHPTAL_Exception("Given node is not child of ".$this->getQualifiedName()); + } + + public function replaceChild(PHPTAL_Dom_Node $newElement, PHPTAL_Dom_Node $oldElement) + { + foreach ($this->childNodes as $k => $node) { + if ($node === $oldElement) { + $oldElement->parentNode = NULL; + + if ($newElement->parentNode) $newElement->parentNode->removeChild($child); + $newElement->parentNode = $this; + + $this->childNodes[$k] = $newElement; + return; + } + } + throw new PHPTAL_Exception("Given node is not child of ".$this->getQualifiedName()); + } + + public function generateCode(PHPTAL_Php_CodeWriter $codewriter) + { + try + { + /// self-modifications + + if ($codewriter->getOutputMode() === PHPTAL::XHTML) { + $this->replaceTextWithCDATA(); + } + + /// code generation + + if ($this->getSourceLine()) { + $codewriter->doComment('tag "'.$this->qualifiedName.'" from line '.$this->getSourceLine()); + } + + $this->generateSurroundHead($codewriter); + + if (count($this->replaceAttributes)) { + foreach ($this->replaceAttributes as $att) { + $att->before($codewriter); + $att->after($codewriter); + } + } elseif (!$this->hidden) { + // a surround tag may decide to hide us (tal:define for example) + $this->generateHead($codewriter); + $this->generateContent($codewriter); + $this->generateFoot($codewriter); + } + + $this->generateSurroundFoot($codewriter); + } + catch(PHPTAL_TemplateException $e) { + $e->hintSrcPosition($this->getSourceFile(), $this->getSourceLine()); + throw $e; + } + } + + /** + * Array with PHPTAL_Dom_Attr objects + * + * @return array + */ + public function getAttributeNodes() + { + return $this->attribute_nodes; + } + + /** + * Replace all attributes + * + * @param array $nodes array of PHPTAL_Dom_Attr objects + */ + public function setAttributeNodes(array $nodes) + { + $this->attribute_nodes = $nodes; + } + + /** Returns true if the element contains specified PHPTAL attribute. */ + public function hasAttribute($qname) + { + foreach($this->attribute_nodes as $attr) if ($attr->getQualifiedName() == $qname) return true; + return false; + } + + public function hasAttributeNS($ns_uri, $localname) + { + return null !== $this->getAttributeNodeNS($ns_uri, $localname); + } + + public function getAttributeNodeNS($ns_uri, $localname) + { + foreach ($this->attribute_nodes as $attr) { + if ($attr->getNamespaceURI() === $ns_uri && $attr->getLocalName() === $localname) return $attr; + } + return null; + } + + public function removeAttributeNS($ns_uri, $localname) + { + foreach ($this->attribute_nodes as $k => $attr) { + if ($attr->getNamespaceURI() === $ns_uri && $attr->getLocalName() === $localname) { + unset($this->attribute_nodes[$k]); + return; + } + } + } + + public function getAttributeNode($qname) + { + foreach($this->attribute_nodes as $attr) if ($attr->getQualifiedName() === $qname) return $attr; + return null; + } + + /** + * If possible, use getAttributeNodeNS and setAttributeNS. + * + * NB: This method doesn't handle namespaces properly. + */ + public function getOrCreateAttributeNode($qname) + { + if ($attr = $this->getAttributeNode($qname)) return $attr; + + $attr = new PHPTAL_Dom_Attr($qname, "", null, 'UTF-8'); // FIXME: should find namespace and encoding + $this->attribute_nodes[] = $attr; + return $attr; + } + + /** Returns textual (unescaped) value of specified element attribute. */ + public function getAttributeNS($namespace_uri, $localname) + { + if ($n = $this->getAttributeNodeNS($namespace_uri, $localname)) { + return $n->getValue(); + } + return ''; + } + + /** + * Set attribute value. Creates new attribute if it doesn't exist yet. + * + * @param string $namespace_uri full namespace URI. "" for default namespace + * @param string $qname prefixed qualified name (e.g. "atom:feed") or local name (e.g. "p") + * @param string $value unescaped value + * + * @return void + */ + public function setAttributeNS($namespace_uri, $qname, $value) + { + $localname = preg_replace('/^[^:]*:/', '', $qname); + if (!($n = $this->getAttributeNodeNS($namespace_uri, $localname))) { + $this->attribute_nodes[] = $n = new PHPTAL_Dom_Attr($qname, $namespace_uri, null, 'UTF-8'); // FIXME: find encoding + } + $n->setValue($value); + } + + /** + * Returns true if this element or one of its PHPTAL attributes has some + * content to print (an empty text node child does not count). + * + * @return bool + */ + public function hasRealContent() + { + if (count($this->contentAttributes) > 0) return true; + + foreach ($this->childNodes as $node) { + if (!$node instanceof PHPTAL_Dom_Text || $node->getValueEscaped() !== '') return true; + } + return false; + } + + public function hasRealAttributes() + { + if ($this->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'attributes')) return true; + foreach ($this->attribute_nodes as $attr) { + if ($attr->getReplacedState() !== PHPTAL_Dom_Attr::HIDDEN) return true; + } + return false; + } + + // ~~~~~ Generation methods may be called by some PHPTAL attributes ~~~~~ + + public function generateSurroundHead(PHPTAL_Php_CodeWriter $codewriter) + { + foreach ($this->surroundAttributes as $att) { + $att->before($codewriter); + } + } + + public function generateHead(PHPTAL_Php_CodeWriter $codewriter) + { + if ($this->headFootDisabled) return; + if ($this->headPrintCondition) { + $codewriter->doIf($this->headPrintCondition); + } + + $html5mode = ($codewriter->getOutputMode() === PHPTAL::HTML5); + + if ($html5mode) { + $codewriter->pushHTML('<'.$this->getLocalName()); + } else { + $codewriter->pushHTML('<'.$this->qualifiedName); + } + + $this->generateAttributes($codewriter); + + if (!$html5mode && $this->isEmptyNode($codewriter->getOutputMode())) { + $codewriter->pushHTML('/>'); + } else { + $codewriter->pushHTML('>'); + } + + if ($this->headPrintCondition) { + $codewriter->doEnd('if'); + } + } + + public function generateContent(PHPTAL_Php_CodeWriter $codewriter = null, $realContent=false) + { + if (!$this->isEmptyNode($codewriter->getOutputMode())) { + if ($realContent || !count($this->contentAttributes)) { + foreach($this->childNodes as $child) { + $child->generateCode($codewriter); + } + } + else foreach($this->contentAttributes as $att) { + $att->before($codewriter); + $att->after($codewriter); + } + } + } + + public function generateFoot(PHPTAL_Php_CodeWriter $codewriter) + { + if ($this->headFootDisabled) + return; + if ($this->isEmptyNode($codewriter->getOutputMode())) + return; + + if ($this->footPrintCondition) { + $codewriter->doIf($this->footPrintCondition); + } + + if ($codewriter->getOutputMode() === PHPTAL::HTML5) { + $codewriter->pushHTML('getLocalName().'>'); + } else { + $codewriter->pushHTML('getQualifiedName().'>'); + } + + if ($this->footPrintCondition) { + $codewriter->doEnd('if'); + } + } + + public function generateSurroundFoot(PHPTAL_Php_CodeWriter $codewriter) + { + for ($i = (count($this->surroundAttributes)-1); $i >= 0; $i--) { + $this->surroundAttributes[$i]->after($codewriter); + } + } + + // ~~~~~ Private members ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + private function generateAttributes(PHPTAL_Php_CodeWriter $codewriter) + { + $html5mode = ($codewriter->getOutputMode() === PHPTAL::HTML5); + + foreach ($this->getAttributeNodes() as $attr) { + + // xmlns:foo is not allowed in text/html + if ($html5mode && $attr->isNamespaceDeclaration()) { + continue; + } + + switch ($attr->getReplacedState()) { + case PHPTAL_Dom_Attr::NOT_REPLACED: + $codewriter->pushHTML(' '.$attr->getQualifiedName()); + if ($codewriter->getOutputMode() !== PHPTAL::HTML5 + || !PHPTAL_Dom_Defs::getInstance()->isBooleanAttribute($attr->getQualifiedName())) { + $html = $codewriter->interpolateHTML($attr->getValueEscaped()); + $codewriter->pushHTML('='.$codewriter->quoteAttributeValue($html)); + } + break; + + case PHPTAL_Dom_Attr::HIDDEN: + break; + + case PHPTAL_Dom_Attr::FULLY_REPLACED: + $codewriter->pushHTML($attr->getValueEscaped()); + break; + + case PHPTAL_Dom_Attr::VALUE_REPLACED: + $codewriter->pushHTML(' '.$attr->getQualifiedName().'="'); + $codewriter->pushHTML($attr->getValueEscaped()); + $codewriter->pushHTML('"'); + break; + } + } + } + + private function isEmptyNode($mode) + { + return (($mode === PHPTAL::XHTML || $mode === PHPTAL::HTML5) && PHPTAL_Dom_Defs::getInstance()->isEmptyTagNS($this->getNamespaceURI(), $this->getLocalName())) || + ( $mode === PHPTAL::XML && !$this->hasContent()); + } + + private function hasContent() + { + return count($this->childNodes) > 0 || count($this->contentAttributes) > 0; + } + + private function separateAttributes() + { + $talAttributes = array(); + foreach ($this->attribute_nodes as $index => $attr) { + // remove handled xml namespaces + if (PHPTAL_Dom_Defs::getInstance()->isHandledXmlNs($attr->getQualifiedName(), $attr->getValueEscaped())) { + unset($this->attribute_nodes[$index]); + } else if ($this->xmlns->isHandledNamespace($attr->getNamespaceURI())) { + $talAttributes[$attr->getQualifiedName()] = $attr; + $attr->hide(); + } else if (PHPTAL_Dom_Defs::getInstance()->isBooleanAttribute($attr->getQualifiedName())) { + $attr->setValue($attr->getLocalName()); + } + } + return $talAttributes; + } + + private function orderTalAttributes(array $talAttributes) + { + $temp = array(); + foreach ($talAttributes as $key => $domattr) { + $nsattr = PHPTAL_Dom_Defs::getInstance()->getNamespaceAttribute($domattr->getNamespaceURI(), $domattr->getLocalName()); + if (array_key_exists($nsattr->getPriority(), $temp)) { + throw new PHPTAL_TemplateException(sprintf("Attribute conflict in < %s > '%s' cannot appear with '%s'", + $this->qualifiedName, + $key, + $temp[$nsattr->getPriority()][0]->getNamespace()->getPrefix() . ':' . $temp[$nsattr->getPriority()][0]->getLocalName() + ), $this->getSourceFile(), $this->getSourceLine()); + } + $temp[$nsattr->getPriority()] = array($nsattr, $domattr); + } + ksort($temp); + + $this->talHandlers = array(); + foreach ($temp as $prio => $dat) { + list($nsattr, $domattr) = $dat; + $handler = $nsattr->createAttributeHandler($this, $domattr->getValue()); + $this->talHandlers[$prio] = $handler; + + if ($nsattr instanceof PHPTAL_NamespaceAttributeSurround) + $this->surroundAttributes[] = $handler; + else if ($nsattr instanceof PHPTAL_NamespaceAttributeReplace) + $this->replaceAttributes[] = $handler; + else if ($nsattr instanceof PHPTAL_NamespaceAttributeContent) + $this->contentAttributes[] = $handler; + else + throw new PHPTAL_ParserException("Unknown namespace attribute class ".get_class($nsattr), + $this->getSourceFile(), $this->getSourceLine()); + + } + } + + function getQualifiedName() + { + return $this->qualifiedName; + } + + function getNamespaceURI() + { + return $this->namespace_uri; + } + + function getLocalName() + { + $n = explode(':', $this->qualifiedName, 2); + return end($n); + } + + function __toString() + { + return '<{'.$this->getNamespaceURI().'}:'.$this->getLocalName().'>'; + } + + function setValueEscaped($e) { + throw new PHPTAL_Exception("Not supported"); + } +} diff --git a/lib/phptal/PHPTAL/Dom/Node.php b/lib/phptal/PHPTAL/Dom/Node.php new file mode 100644 index 0000000..5858df6 --- /dev/null +++ b/lib/phptal/PHPTAL/Dom/Node.php @@ -0,0 +1,105 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * Document node abstract class. + * + * @package PHPTAL + * @subpackage Dom + */ +abstract class PHPTAL_Dom_Node +{ + public $parentNode; + + private $value_escaped, $source_file, $source_line, $encoding; + + public function __construct($value_escaped, $encoding) + { + $this->value_escaped = $value_escaped; + $this->encoding = $encoding; + } + + /** + * hint where this node is in source code + */ + public function setSource($file, $line) + { + $this->source_file = $file; + $this->source_line = $line; + } + + /** + * file from which this node comes from + */ + public function getSourceFile() + { + return $this->source_file; + } + + /** + * line on which this node was defined + */ + public function getSourceLine() + { + return $this->source_line; + } + + /** + * depends on node type. Value will be escaped according to context that node comes from. + */ + function getValueEscaped() + { + return $this->value_escaped; + } + + /** + * Set value of the node (type-dependent) to this exact string. + * String must be HTML-escaped and use node's encoding. + * + * @param string $value_escaped new content + */ + function setValueEscaped($value_escaped) + { + $this->value_escaped = $value_escaped; + } + + + /** + * get value as plain text. Depends on node type. + */ + function getValue() + { + return html_entity_decode($this->getValueEscaped(), ENT_QUOTES, $this->encoding); + } + + /** + * encoding used by vaule of this node. + */ + public function getEncoding() + { + return $this->encoding; + } + + /** + * use CodeWriter to compile this element to PHP code + */ + public abstract function generateCode(PHPTAL_Php_CodeWriter $gen); + + function __toString() + { + return " “".$this->getValue()."” "; + } +} + diff --git a/lib/phptal/PHPTAL/Dom/PHPTALDocumentBuilder.php b/lib/phptal/PHPTAL/Dom/PHPTALDocumentBuilder.php new file mode 100644 index 0000000..a3157be --- /dev/null +++ b/lib/phptal/PHPTAL/Dom/PHPTALDocumentBuilder.php @@ -0,0 +1,167 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * DOM Builder + * + * @package PHPTAL + * @subpackage Dom + */ +class PHPTAL_Dom_PHPTALDocumentBuilder extends PHPTAL_Dom_DocumentBuilder +{ + private $_xmlns; /* PHPTAL_Dom_XmlnsState */ + private $encoding; + + public function __construct() + { + $this->_xmlns = new PHPTAL_Dom_XmlnsState(array(), ''); + } + + public function getResult() + { + return $this->documentElement; + } + + protected function getXmlnsState() + { + return $this->_xmlns; + } + + // ~~~~~ XmlParser implementation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + public function onDocumentStart() + { + $this->documentElement = new PHPTAL_Dom_Element('documentElement', 'http://xml.zope.org/namespaces/tal', array(), $this->getXmlnsState()); + $this->documentElement->setSource($this->file, $this->line); + $this->_current = $this->documentElement; + } + + public function onDocumentEnd() + { + if (count($this->_stack) > 0) { + $left='_current->getQualifiedName().'>'; + for ($i = count($this->_stack)-1; $i>0; $i--) $left .= '_stack[$i]->getQualifiedName().'>'; + throw new PHPTAL_ParserException("Not all elements were closed before end of the document. Missing: ".$left, + $this->file, $this->line); + } + } + + public function onDocType($doctype) + { + $this->pushNode(new PHPTAL_Dom_DocumentType($doctype, $this->encoding)); + } + + public function onXmlDecl($decl) + { + if (!$this->encoding) { + throw new PHPTAL_Exception("Encoding not set"); + } + $this->pushNode(new PHPTAL_Dom_XmlDeclaration($decl, $this->encoding)); + } + + public function onComment($data) + { + $this->pushNode(new PHPTAL_Dom_Comment($data, $this->encoding)); + } + + public function onCDATASection($data) + { + $this->pushNode(new PHPTAL_Dom_CDATASection($data, $this->encoding)); + } + + public function onProcessingInstruction($data) + { + $this->pushNode(new PHPTAL_Dom_ProcessingInstruction($data, $this->encoding)); + } + + public function onElementStart($element_qname, array $attributes) + { + $this->_xmlns = $this->_xmlns->newElement($attributes); + + if (preg_match('/^([^:]+):/', $element_qname, $m)) { + $prefix = $m[1]; + $namespace_uri = $this->_xmlns->prefixToNamespaceURI($prefix); + if (false === $namespace_uri) { + throw new PHPTAL_ParserException("There is no namespace declared for prefix of element < $element_qname >. You must have xmlns:$prefix declaration in the same document.", + $this->file, $this->line); + } + } else { + $namespace_uri = $this->_xmlns->getCurrentDefaultNamespaceURI(); + } + + $attrnodes = array(); + foreach ($attributes as $qname=>$value) { + + if (preg_match('/^([^:]+):(.+)$/', $qname, $m)) { + list(,$prefix, $local_name) = $m; + $attr_namespace_uri = $this->_xmlns->prefixToNamespaceURI($prefix); + + if (false === $attr_namespace_uri) { + throw new PHPTAL_ParserException("There is no namespace declared for prefix of attribute $qname of element < $element_qname >. You must have xmlns:$prefix declaration in the same document.", + $this->file, $this->line); + } + } else { + $local_name = $qname; + $attr_namespace_uri = ''; // default NS. Attributes don't inherit namespace per XMLNS spec + } + + if ($this->_xmlns->isHandledNamespace($attr_namespace_uri) + && !$this->_xmlns->isValidAttributeNS($attr_namespace_uri, $local_name)) { + throw new PHPTAL_ParserException("Attribute '$qname' is in '$attr_namespace_uri' namespace, but is not a supported PHPTAL attribute", + $this->file, $this->line); + } + + $attrnodes[] = new PHPTAL_Dom_Attr($qname, $attr_namespace_uri, $value, $this->encoding); + } + + $node = new PHPTAL_Dom_Element($element_qname, $namespace_uri, $attrnodes, $this->getXmlnsState()); + $this->pushNode($node); + $this->_stack[] = $this->_current; + $this->_current = $node; + } + + public function onElementData($data) + { + $this->pushNode(new PHPTAL_Dom_Text($data, $this->encoding)); + } + + public function onElementClose($qname) + { + if ($this->_current === $this->documentElement) { + throw new PHPTAL_ParserException("Found closing tag for < $qname > where there are no open tags", + $this->file, $this->line); + } + if ($this->_current->getQualifiedName() != $qname) { + throw new PHPTAL_ParserException("Tag closure mismatch, expected < /".$this->_current->getQualifiedName()." > (opened in line ".$this->_current->getSourceLine().") but found < /".$qname." >", + $this->file, $this->line); + } + $this->_current = array_pop($this->_stack); + if ($this->_current instanceof PHPTAL_Dom_Element) { + $this->_xmlns = $this->_current->getXmlnsState(); // restore namespace prefixes info to previous state + } + } + + private function pushNode(PHPTAL_Dom_Node $node) + { + $node->setSource($this->file, $this->line); + $this->_current->appendChild($node); + } + + public function setEncoding($encoding) + { + $this->encoding = $encoding; + } +} diff --git a/lib/phptal/PHPTAL/Dom/ProcessingInstruction.php b/lib/phptal/PHPTAL/Dom/ProcessingInstruction.php new file mode 100644 index 0000000..552462c --- /dev/null +++ b/lib/phptal/PHPTAL/Dom/ProcessingInstruction.php @@ -0,0 +1,34 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * processing instructions, including getValueEscaped())) { + // block will be executed as PHP + $codewriter->pushHTML($this->getValueEscaped()); + } else { + $codewriter->doEchoRaw("'<'"); + $codewriter->pushHTML(substr($codewriter->interpolateHTML($this->getValueEscaped()), 1)); + } + } +} diff --git a/lib/phptal/PHPTAL/Dom/SaxXmlParser.php b/lib/phptal/PHPTAL/Dom/SaxXmlParser.php new file mode 100644 index 0000000..b59a26d --- /dev/null +++ b/lib/phptal/PHPTAL/Dom/SaxXmlParser.php @@ -0,0 +1,480 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * Simple sax like xml parser for PHPTAL + * ("Dom" in the class name comes from name of the directory, not mode of operation) + * + * At the time this parser was created, standard PHP libraries were not suitable + * (could not retrieve doctypes, xml declaration, problems with comments and CDATA). + * + * There are still some problems: XML parsers don't care about exact format of enties + * or CDATA sections (PHPTAL tries to preserve them), + * blocks are not allowed in attributes. + * + * This parser failed to enforce some XML well-formedness constraints, + * and there are ill-formed templates "in the wild" because of this. + * + * @package PHPTAL + * @subpackage Dom + * @see PHPTAL_DOM_DocumentBuilder + */ +class PHPTAL_Dom_SaxXmlParser +{ + private $_file; + private $_line; + private $_source; + + // available parser states + const ST_ROOT = 0; + const ST_TEXT = 1; + const ST_LT = 2; + const ST_TAG_NAME = 3; + const ST_TAG_CLOSE = 4; + const ST_TAG_SINGLE = 5; + const ST_TAG_ATTRIBUTES = 6; + const ST_TAG_BETWEEN_ATTRIBUTE = 7; + const ST_CDATA = 8; + const ST_COMMENT = 9; + const ST_DOCTYPE = 10; + const ST_XMLDEC = 11; + const ST_PREPROC = 12; + const ST_ATTR_KEY = 13; + const ST_ATTR_EQ = 14; + const ST_ATTR_QUOTE = 15; + const ST_ATTR_VALUE = 16; + + const BOM_STR = "\xef\xbb\xbf"; + + + static $state_names = array( + self::ST_ROOT => 'root node', + self::ST_TEXT => 'text', + self::ST_LT => 'start of tag', + self::ST_TAG_NAME => 'tag name', + self::ST_TAG_CLOSE => 'closing tag', + self::ST_TAG_SINGLE => 'self-closing tag', + self::ST_TAG_ATTRIBUTES => 'tag', + self::ST_TAG_BETWEEN_ATTRIBUTE => 'tag attributes', + self::ST_CDATA => 'CDATA', + self::ST_COMMENT => 'comment', + self::ST_DOCTYPE => 'doctype', + self::ST_XMLDEC => 'XML declaration', + self::ST_PREPROC => 'preprocessor directive', + self::ST_ATTR_KEY => 'attribute name', + self::ST_ATTR_EQ => 'attribute value', + self::ST_ATTR_QUOTE => 'quoted attribute value', + self::ST_ATTR_VALUE => 'unquoted attribute value', + ); + + private $input_encoding; + public function __construct($input_encoding) + { + $this->input_encoding = $input_encoding; + $this->_file = ""; + } + + public function parseFile(PHPTAL_Dom_DocumentBuilder $builder, $src) + { + if (!file_exists($src)) { + throw new PHPTAL_IOException("file $src not found"); + } + return $this->parseString($builder, file_get_contents($src), $src); + } + + public function parseString(PHPTAL_Dom_DocumentBuilder $builder, $src, $filename = '') + { + try + { + $builder->setEncoding($this->input_encoding); + $this->_file = $filename; + + $this->_line = 1; + $state = self::ST_ROOT; + $mark = 0; + $len = strlen($src); + + $quoteStyle = '"'; + $tagname = ""; + $attribute = ""; + $attributes = array(); + + $customDoctype = false; + + $builder->setSource($this->_file, $this->_line); + $builder->onDocumentStart(); + + $i=0; + // remove BOM (UTF-8 byte order mark)... + if (substr($src, 0, 3) === self::BOM_STR) { + $i=3; + } + for (; $i<$len; $i++) { + $c = $src[$i]; // Change to substr($src, $i, 1); if you want to use mb_string.func_overload + + if ($c === "\n") $builder->setSource($this->_file, ++$this->_line); + + switch ($state) { + case self::ST_ROOT: + if ($c === '<') { + $mark = $i; // mark tag start + $state = self::ST_LT; + } elseif (!self::isWhiteChar($c)) { + $this->raiseError("Characters found before beginning of the document! (wrap document in < tal:block > to avoid this error)"); + } + break; + + case self::ST_TEXT: + if ($c === '<') { + if ($mark != $i) { + $builder->onElementData($this->sanitizeEscapedText($this->checkEncoding(substr($src, $mark, $i-$mark)))); + } + $mark = $i; + $state = self::ST_LT; + } + break; + + case self::ST_LT: + if ($c === '/') { + $mark = $i+1; + $state = self::ST_TAG_CLOSE; + } elseif ($c === '?' and strtolower(substr($src, $i, 5)) === '?xml ') { + $state = self::ST_XMLDEC; + } elseif ($c === '?') { + $state = self::ST_PREPROC; + } elseif ($c === '!' and substr($src, $i, 3) === '!--') { + $state = self::ST_COMMENT; + } elseif ($c === '!' and substr($src, $i, 8) === '![CDATA[') { + $state = self::ST_CDATA; + $mark = $i+8; // past opening tag + } elseif ($c === '!' and strtoupper(substr($src, $i, 8)) === '!DOCTYPE') { + $state = self::ST_DOCTYPE; + } elseif (self::isWhiteChar($c)) { + $state = self::ST_TEXT; + } else { + $mark = $i; // mark node name start + $attributes = array(); + $attribute = ""; + $state = self::ST_TAG_NAME; + } + break; + + case self::ST_TAG_NAME: + if (self::isWhiteChar($c) || $c === '/' || $c === '>') { + $tagname = substr($src, $mark, $i-$mark); + if (!$this->isValidQName($tagname)) $this->raiseError("Invalid tag name '$tagname'"); + + if ($c === '/') { + $state = self::ST_TAG_SINGLE; + } elseif ($c === '>') { + $mark = $i+1; // mark text start + $state = self::ST_TEXT; + $builder->onElementStart($tagname, $attributes); + } else /* isWhiteChar */ { + $state = self::ST_TAG_ATTRIBUTES; + } + } + break; + + case self::ST_TAG_CLOSE: + if ($c === '>') { + $tagname = rtrim(substr($src, $mark, $i-$mark)); + $builder->onElementClose($tagname); + $mark = $i+1; // mark text start + $state = self::ST_TEXT; + } + break; + + case self::ST_TAG_SINGLE: + if ($c !== '>') { + $this->raiseError("Expected '/>', but found '/$c' inside tag < $tagname >"); + } + $mark = $i+1; // mark text start + $state = self::ST_TEXT; + $builder->onElementStart($tagname, $attributes); + $builder->onElementClose($tagname); + break; + + case self::ST_TAG_BETWEEN_ATTRIBUTE: + case self::ST_TAG_ATTRIBUTES: + if ($c === '>') { + $mark = $i+1; // mark text start + $state = self::ST_TEXT; + $builder->onElementStart($tagname, $attributes); + } elseif ($c === '/') { + $state = self::ST_TAG_SINGLE; + } elseif (self::isWhiteChar($c)) { + $state = self::ST_TAG_ATTRIBUTES; + } elseif ($state === self::ST_TAG_ATTRIBUTES && $this->isValidQName($c)) { + $mark = $i; // mark attribute key start + $state = self::ST_ATTR_KEY; + } else $this->raiseError("Unexpected character '$c' between attributes of < $tagname >"); + break; + + case self::ST_COMMENT: + if ($c === '>' && $i > $mark+4 && substr($src, $i-2, 2) === '--') { + + if (preg_match('/^-|--|-$/', substr($src, $mark +4, $i-$mark+1 -7))) { + $this->raiseError("Ill-formed comment. XML comments are not allowed to contain '--' or start/end with '-': ".substr($src, $mark+4, $i-$mark+1-7)); + } + + $builder->onComment($this->checkEncoding(substr($src, $mark+4, $i-$mark+1-7))); + $mark = $i+1; // mark text start + $state = self::ST_TEXT; + } + break; + + case self::ST_CDATA: + if ($c === '>' and substr($src, $i-2, 2) === ']]') { + $builder->onCDATASection($this->checkEncoding(substr($src, $mark, $i-$mark-2))); + $mark = $i+1; // mark text start + $state = self::ST_TEXT; + } + break; + + case self::ST_XMLDEC: + if ($c === '?' && substr($src, $i, 2) === '?>') { + $builder->onXmlDecl($this->checkEncoding(substr($src, $mark, $i-$mark+2))); + $i++; // skip '>' + $mark = $i+1; // mark text start + $state = self::ST_TEXT; + } + break; + + case self::ST_DOCTYPE: + if ($c === '[') { + $customDoctype = true; + } elseif ($customDoctype && $c === '>' && substr($src, $i-1, 2) === ']>') { + $customDoctype = false; + $builder->onDocType($this->checkEncoding(substr($src, $mark, $i-$mark+1))); + $mark = $i+1; // mark text start + $state = self::ST_TEXT; + } elseif (!$customDoctype && $c === '>') { + $customDoctype = false; + $builder->onDocType($this->checkEncoding(substr($src, $mark, $i-$mark+1))); + $mark = $i+1; // mark text start + $state = self::ST_TEXT; + } + break; + + case self::ST_PREPROC: + if ($c === '>' and substr($src, $i-1, 1) === '?') { + $builder->onProcessingInstruction($this->checkEncoding(substr($src, $mark, $i-$mark+1))); + $mark = $i+1; // mark text start + $state = self::ST_TEXT; + } + break; + + case self::ST_ATTR_KEY: + if ($c === '=' || self::isWhiteChar($c)) { + $attribute = substr($src, $mark, $i-$mark); + if (!$this->isValidQName($attribute)) { + $this->raiseError("Invalid attribute name '$attribute' in < $tagname >"); + } + if (isset($attributes[$attribute])) { + $this->raiseError("Attribute $attribute in < $tagname > is defined more than once"); + } + + if ($c === '=') $state = self::ST_ATTR_VALUE; + else /* white char */ $state = self::ST_ATTR_EQ; + } elseif ($c === '/' || $c==='>') { + $attribute = substr($src, $mark, $i-$mark); + if (!$this->isValidQName($attribute)) { + $this->raiseError("Invalid attribute name '$attribute'"); + } + $this->raiseError("Attribute $attribute does not have value (found end of tag instead of '=')"); + } + break; + + case self::ST_ATTR_EQ: + if ($c === '=') { + $state = self::ST_ATTR_VALUE; + } elseif (!self::isWhiteChar($c)) { + $this->raiseError("Attribute $attribute in < $tagname > does not have value (found character '$c' instead of '=')"); + } + break; + + case self::ST_ATTR_VALUE: + if (self::isWhiteChar($c)) { + } elseif ($c === '"' or $c === '\'') { + $quoteStyle = $c; + $state = self::ST_ATTR_QUOTE; + $mark = $i+1; // mark attribute real value start + } else { + $this->raiseError("Value of attribute $attribute in < $tagname > is not in quotes (found character '$c' instead of quote)"); + } + break; + + case self::ST_ATTR_QUOTE: + if ($c === $quoteStyle) { + $attributes[$attribute] = $this->sanitizeEscapedText($this->checkEncoding(substr($src, $mark, $i-$mark))); + + // PHPTAL's code generator assumes input is escaped for double-quoted strings. Single-quoted attributes need to be converted. + // FIXME: it should be escaped at later stage. + $attributes[$attribute] = str_replace('"',""", $attributes[$attribute]); + $state = self::ST_TAG_BETWEEN_ATTRIBUTE; + } + break; + } + } + + if ($state === self::ST_TEXT) // allows text past root node, which is in violation of XML spec + { + if ($i > $mark) { + $text = substr($src, $mark, $i-$mark); + if (!ctype_space($text)) $this->raiseError("Characters found after end of the root element (wrap document in < tal:block > to avoid this error)"); + } + } else { + if ($state === self::ST_ROOT) { + $msg = "Document does not have any tags"; + } else { + $msg = "Finished document in unexpected state: ".self::$state_names[$state]." is not finished"; + } + $this->raiseError($msg); + } + + $builder->onDocumentEnd(); + } + catch(PHPTAL_TemplateException $e) + { + $e->hintSrcPosition($this->_file, $this->_line); + throw $e; + } + return $builder; + } + + private function isValidQName($name) + { + $name = $this->checkEncoding($name); + return preg_match('/^([a-z_\x80-\xff]+[a-z0-9._\x80-\xff-]*:)?[a-z_\x80-\xff]+[a-z0-9._\x80-\xff-]*$/i', $name); + } + + private function checkEncoding($str) + { + if ($str === '') return ''; + + if ($this->input_encoding === 'UTF-8') { + + // $match expression below somehow triggers quite deep recurrency and stack overflow in preg + // to avoid this, check string bit by bit, omitting ASCII fragments. + if (strlen($str) > 200) { + $chunks = preg_split('/(?>[\x09\x0A\x0D\x20-\x7F]+)/',$str,null,PREG_SPLIT_NO_EMPTY); + foreach ($chunks as $chunk) { + if (strlen($chunk) < 200) { + $this->checkEncoding($chunk); + } + } + return $str; + } + + // http://www.w3.org/International/questions/qa-forms-utf-8 + $match = '[\x09\x0A\x0D\x20-\x7F]' // ASCII + . '|[\xC2-\xDF][\x80-\xBF]' // non-overlong 2-byte + . '|\xE0[\xA0-\xBF][\x80-\xBF]' // excluding overlongs + . '|[\xE1-\xEC\xEE\xEE][\x80-\xBF]{2}' // straight 3-byte (exclude FFFE and FFFF) + . '|\xEF[\x80-\xBE][\x80-\xBF]' // straight 3-byte + . '|\xEF\xBF[\x80-\xBD]' // straight 3-byte + . '|\xED[\x80-\x9F][\x80-\xBF]' // excluding surrogates + . '|\xF0[\x90-\xBF][\x80-\xBF]{2}' // planes 1-3 + . '|[\xF1-\xF3][\x80-\xBF]{3}' // planes 4-15 + . '|\xF4[\x80-\x8F][\x80-\xBF]{2}'; // plane 16 + + if (!preg_match('/^(?:(?>'.$match.'))+$/s',$str)) { + $res = preg_split('/((?>'.$match.')+)/s',$str,null,PREG_SPLIT_DELIM_CAPTURE); + for($i=0; $i < count($res); $i+=2) + { + $res[$i] = self::convertBytesToEntities(array(1=>$res[$i])); + } + $this->raiseError("Invalid UTF-8 bytes: ".implode('', $res)); + } + } + if ($this->input_encoding === 'ISO-8859-1') { + + // http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-RestrictedChar + $forbid = '/((?>[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F]+))/s'; + + if (preg_match($forbid, $str)) { + $str = preg_replace_callback($forbid, array('self', 'convertBytesToEntities'), $str); + $this->raiseError("Invalid ISO-8859-1 characters: ".$str); + } + } + + return $str; + } + + /** + * preg callback + * Changes all bytes to hexadecimal XML entities + * + * @param array $m first array element is used for input + * + * @return string + */ + private static function convertBytesToEntities(array $m) + { + $m = $m[1]; $out = ''; + for($i=0; $i < strlen($m); $i++) + { + $out .= '&#X'.strtoupper(dechex(ord($m[$i]))).';'; + } + return $out; + } + + /** + * This is where this parser violates XML and refuses to be an annoying bastard. + */ + private function sanitizeEscapedText($str) + { + $str = str_replace(''', ''', $str); // PHP's html_entity_decode doesn't seem to support that! + + /* blocks can't reliably work in attributes (due to escaping impossible in XML) + so they have to be converted into special TALES expression + */ + $types = ini_get('short_open_tag')?'php|=|':'php'; + $str = preg_replace_callback("/<\?($types)(.*?)\?>/", array('self', 'convertPHPBlockToTALES'), $str); + + // corrects all non-entities and neutralizes potentially problematic CDATA end marker + $str = strtr(preg_replace('/&(?!(?:#x?[a-f0-9]+|[a-z][a-z0-9]*);)/i', '&', $str), array('<'=>'<', ']]>'=>']]>')); + + return $str; + } + + private static function convertPHPBlockToTALES($m) + { + list(, $type, $code) = $m; + if ($type === '=') $code = 'echo '.$code; + return '${structure phptal-internal-php-block:'.rawurlencode($code).'}'; + } + + public function getSourceFile() + { + return $this->_file; + } + + public function getLineNumber() + { + return $this->_line; + } + + public static function isWhiteChar($c) + { + return strpos(" \t\n\r\0", $c) !== false; + } + + protected function raiseError($errStr) + { + throw new PHPTAL_ParserException($errStr, $this->_file, $this->_line); + } +} diff --git a/lib/phptal/PHPTAL/Dom/Text.php b/lib/phptal/PHPTAL/Dom/Text.php new file mode 100644 index 0000000..f8ef2ab --- /dev/null +++ b/lib/phptal/PHPTAL/Dom/Text.php @@ -0,0 +1,31 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * Document text data representation. + * + * @package PHPTAL + * @subpackage Dom + */ +class PHPTAL_Dom_Text extends PHPTAL_Dom_Node +{ + public function generateCode(PHPTAL_Php_CodeWriter $codewriter) + { + if ($this->getValueEscaped() !== '') { + $codewriter->pushHTML($codewriter->interpolateHTML($this->getValueEscaped())); + } + } +} diff --git a/lib/phptal/PHPTAL/Dom/XmlDeclaration.php b/lib/phptal/PHPTAL/Dom/XmlDeclaration.php new file mode 100644 index 0000000..e28dfb9 --- /dev/null +++ b/lib/phptal/PHPTAL/Dom/XmlDeclaration.php @@ -0,0 +1,29 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * XML declaration node. + * + * @package PHPTAL + * @subpackage Dom + */ +class PHPTAL_Dom_XmlDeclaration extends PHPTAL_Dom_Node +{ + public function generateCode(PHPTAL_Php_CodeWriter $codewriter) + { + $codewriter->setXmlDeclaration($this->getValueEscaped()); + $codewriter->doXmlDeclaration(); + } +} diff --git a/lib/phptal/PHPTAL/Dom/XmlnsState.php b/lib/phptal/PHPTAL/Dom/XmlnsState.php new file mode 100644 index 0000000..4e9288f --- /dev/null +++ b/lib/phptal/PHPTAL/Dom/XmlnsState.php @@ -0,0 +1,95 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ +/** + * Stores XMLNS aliases fluctuation in the xml flow. + * + * This class is used to bind a PHPTAL namespace to an alias, for example using + * xmlns:t="http://xml.zope.org/namespaces/tal" and later use t:repeat instead + * of tal:repeat. + * + * @package PHPTAL + * @subpackage Dom + * @author Laurent Bedubourg + */ +class PHPTAL_Dom_XmlnsState +{ + /** Create a new XMLNS state inheriting provided aliases. */ + public function __construct(array $prefix_to_uri, $current_default) + { + $this->prefix_to_uri = $prefix_to_uri; + $this->current_default = $current_default; + } + + public function prefixToNamespaceURI($prefix) + { + if ($prefix === 'xmlns') return 'http://www.w3.org/2000/xmlns/'; + if ($prefix === 'xml') return 'http://www.w3.org/XML/1998/namespace'; + + // domdefs provides fallback for all known phptal ns + if (isset($this->prefix_to_uri[$prefix])) { + return $this->prefix_to_uri[$prefix]; + } else { + return PHPTAL_Dom_Defs::getInstance()->prefixToNamespaceURI($prefix); + } + } + + /** Returns true if $attName is a valid attribute name, false otherwise. */ + public function isValidAttributeNS($namespace_uri, $local_name) + { + return PHPTAL_Dom_Defs::getInstance()->isValidAttributeNS($namespace_uri, $local_name); + } + + public function isHandledNamespace($namespace_uri) + { + return PHPTAL_Dom_Defs::getInstance()->isHandledNamespace($namespace_uri); + } + + /** + * Returns a new XmlnsState inheriting of $this if $nodeAttributes contains + * xmlns attributes, returns $this otherwise. + * + * This method is used by the PHPTAL parser to keep track of xmlns fluctuation for + * each encountered node. + */ + public function newElement(array $nodeAttributes) + { + $prefix_to_uri = $this->prefix_to_uri; + $current_default = $this->current_default; + + $changed = false; + foreach ($nodeAttributes as $qname => $value) { + if (preg_match('/^xmlns:(.+)$/', $qname, $m)) { + $changed = true; + list(, $prefix) = $m; + $prefix_to_uri[$prefix] = $value; + } + + if ($qname == 'xmlns') {$changed=true;$current_default = $value;} + } + + if ($changed) { + return new PHPTAL_Dom_XmlnsState($prefix_to_uri, $current_default); + } else { + return $this; + } + } + + function getCurrentDefaultNamespaceURI() + { + return $this->current_default; + } + + private $prefix_to_uri, $current_default; +} diff --git a/lib/phptal/PHPTAL/Exception.php b/lib/phptal/PHPTAL/Exception.php new file mode 100644 index 0000000..6d4f312 --- /dev/null +++ b/lib/phptal/PHPTAL/Exception.php @@ -0,0 +1,23 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ +/** + * @package PHPTAL + * @subpackage Exception + */ +class PHPTAL_Exception extends Exception +{ +} + + diff --git a/lib/phptal/PHPTAL/ExceptionHandler.php b/lib/phptal/PHPTAL/ExceptionHandler.php new file mode 100644 index 0000000..dca7bb7 --- /dev/null +++ b/lib/phptal/PHPTAL/ExceptionHandler.php @@ -0,0 +1,81 @@ + + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id: $ + * @link http://phptal.org/ + */ + +class PHPTAL_ExceptionHandler +{ + private $encoding; + function __construct($encoding) + { + $this->encoding = $encoding; + } + + /** + * PHP's default exception handler allows error pages to be indexed and can reveal too much information, + * so if possible PHPTAL sets up its own handler to fix this. + * + * Doesn't change exception handler if non-default one is set. + * + * @param Exception e exception to re-throw and display + * + * @return void + * @throws Exception + */ + public static function handleException(Exception $e, $encoding) + { + // PHPTAL's handler is only useful on fresh HTTP response + if (PHP_SAPI !== 'cli' && !headers_sent()) { + $old_exception_handler = set_exception_handler(array(new PHPTAL_ExceptionHandler($encoding), '_defaultExceptionHandler')); + + if ($old_exception_handler !== NULL) { + restore_exception_handler(); // if there's user's exception handler, let it work + } + } + throw $e; // throws instead of outputting immediately to support user's try/catch + } + + + /** + * Generates simple error page. Sets appropriate HTTP status to prevent page being indexed. + * + * @param Exception e exception to display + */ + public function _defaultExceptionHandler($e) + { + if (!headers_sent()) { + header('HTTP/1.1 500 PHPTAL Exception'); + header('Content-Type:text/html;charset='.$this->encoding); + } + + $line = $e->getFile(); + if ($e->getLine()) { + $line .= ' line '.$e->getLine(); + } + + if (ini_get('display_errors')) { + $title = get_class($e).': '.htmlspecialchars($e->getMessage()); + $body = "

\n".htmlspecialchars($e->getMessage()).'

' . + '

In '.htmlspecialchars($line)."

\n".htmlspecialchars($e->getTraceAsString()).'
'; + } else { + $title = "PHPTAL Exception"; + $body = "

This page cannot be displayed.


" . + "

Enable display_errors to see detailed message.

"; + } + + echo "\n"; + echo $title.'

PHPTAL Exception

'.$body; + error_log($e->getMessage().' in '.$line); + echo ''.str_repeat(' ', 100)."\n"; // IE won't display error pages < 512b + exit(1); + } +} diff --git a/lib/phptal/PHPTAL/FileSource.php b/lib/phptal/PHPTAL/FileSource.php new file mode 100644 index 0000000..84d8719 --- /dev/null +++ b/lib/phptal/PHPTAL/FileSource.php @@ -0,0 +1,51 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * Reads template from the filesystem + * + * @package PHPTAL + */ +class PHPTAL_FileSource implements PHPTAL_Source +{ + private $_path; + + public function __construct($path) + { + $this->_path = realpath($path); + if ($this->_path === false) throw new PHPTAL_IOException("Unable to find real path of file '$path' (in ".getcwd().')'); + } + + public function getRealPath() + { + return $this->_path; + } + + public function getLastModifiedTime() + { + return filemtime($this->_path); + } + + public function getData() + { + $content = file_get_contents($this->_path); + + // file_get_contents returns "" when loading directory!? + if (false === $content || ("" === $content && is_dir($this->_path))) { + throw new PHPTAL_IOException("Unable to load file ".$this->_path); + } + return $content; + } +} diff --git a/lib/phptal/PHPTAL/FileSourceResolver.php b/lib/phptal/PHPTAL/FileSourceResolver.php new file mode 100644 index 0000000..3cb001a --- /dev/null +++ b/lib/phptal/PHPTAL/FileSourceResolver.php @@ -0,0 +1,46 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * Finds template on disk by looking through repositories first + * + * @package PHPTAL + */ +class PHPTAL_FileSourceResolver implements PHPTAL_SourceResolver +{ + public function __construct($repositories) + { + $this->_repositories = $repositories; + } + + public function resolve($path) + { + foreach ($this->_repositories as $repository) { + $file = $repository . DIRECTORY_SEPARATOR . $path; + if (file_exists($file)) { + return new PHPTAL_FileSource($file); + } + } + + if (file_exists($path)) { + return new PHPTAL_FileSource($path); + } + + return null; + } + + private $_repositories; +} diff --git a/lib/phptal/PHPTAL/Filter.php b/lib/phptal/PHPTAL/Filter.php new file mode 100644 index 0000000..813c746 --- /dev/null +++ b/lib/phptal/PHPTAL/Filter.php @@ -0,0 +1,32 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * Objects passed to PHPTAL::setPre/PostFilter() must implement this interface + * + * @package PHPTAL + */ +interface PHPTAL_Filter +{ + /** + * In prefilter it gets template source file and is expected to return new source. + * Prefilters are called only once before template is compiled, so they can be slow. + * + * In postfilter template output is passed to this method, and final output goes to the browser. + * TAL or PHP tags won't be executed. Postfilters should be fast. + */ + public function filter($str); +} + diff --git a/lib/phptal/PHPTAL/GetTextTranslator.php b/lib/phptal/PHPTAL/GetTextTranslator.php new file mode 100644 index 0000000..108e8f5 --- /dev/null +++ b/lib/phptal/PHPTAL/GetTextTranslator.php @@ -0,0 +1,183 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * PHPTAL_TranslationService gettext implementation. + * + * Because gettext is the most common translation library in use, this + * implementation is shipped with the PHPTAL library. + * + * Please refer to the PHPTAL documentation for usage examples. + * + * @package PHPTAL + * @author Laurent Bedubourg + */ +class PHPTAL_GetTextTranslator implements PHPTAL_TranslationService +{ + private $_vars = array(); + private $_currentDomain; + private $_encoding = 'UTF-8'; + private $_canonicalize = false; + + public function __construct() + { + if (!function_exists('gettext')) throw new PHPTAL_ConfigurationException("Gettext not installed"); + $this->useDomain("messages"); // PHP bug #21965 + } + + /** + * set encoding that is used by template and is expected from gettext + * the default is UTF-8 + * + * @param string $enc encoding name + */ + public function setEncoding($enc) + { + $this->_encoding = $enc; + } + + /** + * if true, all non-ASCII characters in keys will be converted to C form. This impacts performance. + * by default keys will be passed to gettext unmodified. + * + * This function is only for backwards compatibility + * + * @param bool $bool enable old behavior + */ + public function setCanonicalize($bool) + { + $this->_canonicalize = $bool; + } + + /** + * It expects locale names as arguments. + * Choses first one that works. + * + * setLanguage("en_US.utf8","en_US","en_GB","en") + * + * @return string - chosen language + */ + public function setLanguage(/*...*/) + { + $langs = func_get_args(); + + $langCode = $this->trySettingLanguages(LC_ALL, $langs); + if ($langCode) return $langCode; + + if (defined("LC_MESSAGES")) { + $langCode = $this->trySettingLanguages(LC_MESSAGES, $langs); + if ($langCode) return $langCode; + } + + throw new PHPTAL_ConfigurationException('Language(s) code(s) "'.implode(', ', $langs).'" not supported by your system'); + } + + private function trySettingLanguages($category, array $langs) + { + foreach ($langs as $langCode) { + putenv("LANG=$langCode"); + putenv("LC_ALL=$langCode"); + putenv("LANGUAGE=$langCode"); + if (setlocale($category, $langCode)) { + return $langCode; + } + } + return null; + } + + /** + * Adds translation domain (usually it's the same as name of .po file [without extension]) + * + * Encoding must be set before calling addDomain! + */ + public function addDomain($domain, $path='./locale/') + { + bindtextdomain($domain, $path); + if ($this->_encoding) { + bind_textdomain_codeset($domain, $this->_encoding); + } + $this->useDomain($domain); + } + + /** + * Switches to one of the domains previously set via addDomain() + * + * @param string $domain name of translation domain to be used. + * + * @return string - old domain + */ + public function useDomain($domain) + { + $old = $this->_currentDomain; + $this->_currentDomain = $domain; + textdomain($domain); + return $old; + } + + /** + * used by generated PHP code. Don't use directly. + */ + public function setVar($key, $value) + { + $this->_vars[$key] = $value; + } + + /** + * translate given key. + * + * @param bool $htmlencode if true, output will be HTML-escaped. + */ + public function translate($key, $htmlencode=true) + { + if ($this->_canonicalize) $key = self::_canonicalizeKey($key); + + $value = gettext($key); + + if ($htmlencode) { + $value = htmlspecialchars($value, ENT_QUOTES, $this->_encoding); + } + while (preg_match('/\${(.*?)\}/sm', $value, $m)) { + list($src, $var) = $m; + if (!array_key_exists($var, $this->_vars)) { + throw new PHPTAL_VariableNotFoundException('Interpolation error. Translation uses ${'.$var.'}, which is not defined in the template (via i18n:name)'); + } + $value = str_replace($src, $this->_vars[$var], $value); + } + return $value; + } + + /** + * For backwards compatibility only. + */ + private static function _canonicalizeKey($key_) + { + $result = ""; + $key_ = trim($key_); + $key_ = str_replace("\n", "", $key_); + $key_ = str_replace("\r", "", $key_); + for ($i = 0; $i 127) { + $result .= 'C<'.$o.'>'; + } else { + $result .= $c; + } + } + return $result; + } +} + diff --git a/lib/phptal/PHPTAL/IOException.php b/lib/phptal/PHPTAL/IOException.php new file mode 100644 index 0000000..166290d --- /dev/null +++ b/lib/phptal/PHPTAL/IOException.php @@ -0,0 +1,25 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * PHPTAL failed to load template + * + * @package PHPTAL + * @subpackage Exception + */ +class PHPTAL_IOException extends PHPTAL_Exception +{ +} diff --git a/lib/phptal/PHPTAL/InvalidVariableNameException.php b/lib/phptal/PHPTAL/InvalidVariableNameException.php new file mode 100644 index 0000000..427e138 --- /dev/null +++ b/lib/phptal/PHPTAL/InvalidVariableNameException.php @@ -0,0 +1,25 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * Parse error in TALES expression. + * + * @package PHPTAL + * @subpackage Exception + */ +class PHPTAL_InvalidVariableNameException extends PHPTAL_Exception +{ +} diff --git a/lib/phptal/PHPTAL/Keywords.php b/lib/phptal/PHPTAL/Keywords.php new file mode 100644 index 0000000..bee7b7a --- /dev/null +++ b/lib/phptal/PHPTAL/Keywords.php @@ -0,0 +1,26 @@ + + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * Interface for template keywords + * + * @package PHPTAL + * @subpackage Keywords + */ +interface PHPTAL_Keywords extends Countable +{ + public function __toString(); +} +?> diff --git a/lib/phptal/PHPTAL/MacroMissingException.php b/lib/phptal/PHPTAL/MacroMissingException.php new file mode 100644 index 0000000..0e3a057 --- /dev/null +++ b/lib/phptal/PHPTAL/MacroMissingException.php @@ -0,0 +1,24 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * Wrong macro name in metal:use-macro + * + * @package PHPTAL + * @subpackage Exception + */ +class PHPTAL_MacroMissingException extends PHPTAL_TemplateException +{ +} diff --git a/lib/phptal/PHPTAL/Namespace.php b/lib/phptal/PHPTAL/Namespace.php new file mode 100644 index 0000000..17d5911 --- /dev/null +++ b/lib/phptal/PHPTAL/Namespace.php @@ -0,0 +1,70 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * @see PHPTAL_NamespaceAttribute + * @package PHPTAL + * @subpackage Namespace + */ +abstract class PHPTAL_Namespace +{ + private $prefix, $namespace_uri; + protected $_attributes; + + public function __construct($prefix, $namespace_uri) + { + if (!$namespace_uri || !$prefix) { + throw new PHPTAL_ConfigurationException("Can't create namespace with empty prefix or namespace URI"); + } + + $this->_attributes = array(); + $this->prefix = $prefix; + $this->namespace_uri = $namespace_uri; + } + + public function getPrefix() + { + return $this->prefix; + } + + public function getNamespaceURI() + { + return $this->namespace_uri; + } + + public function hasAttribute($attributeName) + { + return array_key_exists(strtolower($attributeName), $this->_attributes); + } + + public function getAttribute($attributeName) + { + return $this->_attributes[strtolower($attributeName)]; + } + + public function addAttribute(PHPTAL_NamespaceAttribute $attribute) + { + $attribute->setNamespace($this); + $this->_attributes[strtolower($attribute->getLocalName())] = $attribute; + } + + public function getAttributes() + { + return $this->_attributes; + } + + abstract public function createAttributeHandler(PHPTAL_NamespaceAttribute $att, PHPTAL_Dom_Element $tag, $expression); +} diff --git a/lib/phptal/PHPTAL/Namespace/Builtin.php b/lib/phptal/PHPTAL/Namespace/Builtin.php new file mode 100644 index 0000000..5cec74d --- /dev/null +++ b/lib/phptal/PHPTAL/Namespace/Builtin.php @@ -0,0 +1,38 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * @package PHPTAL + * @subpackage Namespace + */ +class PHPTAL_Namespace_Builtin extends PHPTAL_Namespace +{ + public function createAttributeHandler(PHPTAL_NamespaceAttribute $att, PHPTAL_Dom_Element $tag, $expression) + { + $name = $att->getLocalName(); + + // change define-macro to "define macro" and capitalize words + $name = str_replace(' ', '', ucwords(strtr($name, '-', ' '))); + + // case is important when using autoload on case-sensitive filesystems + if (version_compare(PHP_VERSION, '5.3', '>=') && __NAMESPACE__) { + $class = 'PHPTALNAMESPACE\\Php\\Attribute\\'.strtoupper($this->getPrefix()).'\\'.$name; + } else { + $class = 'PHPTAL_Php_Attribute_'.strtoupper($this->getPrefix()).'_'.$name; + } + $result = new $class($tag, $expression); + return $result; + } +} diff --git a/lib/phptal/PHPTAL/Namespace/I18N.php b/lib/phptal/PHPTAL/Namespace/I18N.php new file mode 100644 index 0000000..81dd8e6 --- /dev/null +++ b/lib/phptal/PHPTAL/Namespace/I18N.php @@ -0,0 +1,32 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * @package PHPTAL + * @subpackage Namespace + */ +class PHPTAL_Namespace_I18N extends PHPTAL_Namespace_Builtin +{ + public function __construct() + { + parent::__construct('i18n', 'http://xml.zope.org/namespaces/i18n'); + $this->addAttribute(new PHPTAL_NamespaceAttributeContent('translate', 5)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('name', 5)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('attributes', 10)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('domain', 3)); + } +} + diff --git a/lib/phptal/PHPTAL/Namespace/METAL.php b/lib/phptal/PHPTAL/Namespace/METAL.php new file mode 100644 index 0000000..2773667 --- /dev/null +++ b/lib/phptal/PHPTAL/Namespace/METAL.php @@ -0,0 +1,31 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * @package PHPTAL + * @subpackage Namespace + */ +class PHPTAL_Namespace_METAL extends PHPTAL_Namespace_Builtin +{ + public function __construct() + { + parent::__construct('metal', 'http://xml.zope.org/namespaces/metal'); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('define-macro', 1)); + $this->addAttribute(new PHPTAL_NamespaceAttributeReplace('use-macro', 9)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('define-slot', 9)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('fill-slot', 9)); + } +} diff --git a/lib/phptal/PHPTAL/Namespace/PHPTAL.php b/lib/phptal/PHPTAL/Namespace/PHPTAL.php new file mode 100644 index 0000000..4d4270a --- /dev/null +++ b/lib/phptal/PHPTAL/Namespace/PHPTAL.php @@ -0,0 +1,31 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * @package PHPTAL + * @subpackage Namespace + */ +class PHPTAL_Namespace_PHPTAL extends PHPTAL_Namespace_Builtin +{ + public function __construct() + { + parent::__construct('phptal', 'http://phptal.org/ns/phptal'); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('tales', -1)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('debug', -2)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('id', 7)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('cache', -3)); + } +} diff --git a/lib/phptal/PHPTAL/Namespace/TAL.php b/lib/phptal/PHPTAL/Namespace/TAL.php new file mode 100644 index 0000000..74cd90a --- /dev/null +++ b/lib/phptal/PHPTAL/Namespace/TAL.php @@ -0,0 +1,36 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * @package PHPTAL + * @subpackage Namespace + */ +class PHPTAL_Namespace_TAL extends PHPTAL_Namespace_Builtin +{ + public function __construct() + { + parent::__construct('tal', 'http://xml.zope.org/namespaces/tal'); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('define', 4)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('condition', 6)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('repeat', 8)); + $this->addAttribute(new PHPTAL_NamespaceAttributeContent('content', 11)); + $this->addAttribute(new PHPTAL_NamespaceAttributeReplace('replace', 9)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('attributes', 9)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('omit-tag', 0)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('comment', 12)); + $this->addAttribute(new PHPTAL_NamespaceAttributeSurround('on-error', 2)); + } +} diff --git a/lib/phptal/PHPTAL/NamespaceAttribute.php b/lib/phptal/PHPTAL/NamespaceAttribute.php new file mode 100644 index 0000000..db1fd95 --- /dev/null +++ b/lib/phptal/PHPTAL/NamespaceAttribute.php @@ -0,0 +1,99 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * Information about TAL attributes (in which order they are executed and how they generate the code) + * + * From http://dev.zope.org/Wikis/DevSite/Projects/ZPT/TAL%20Specification%201.4 + * + * Order of Operations + * + * When there is only one TAL statement per element, the order in which + * they are executed is simple. Starting with the root element, each + * element's statements are executed, then each of its child elements is + * visited, in order, to do the same. + * + * Any combination of statements may appear on the same elements, except + * that the content and replace statements may not appear together. + * + * When an element has multiple statements, they are executed in this + * order: + * + * * define + * * condition + * * repeat + * * content or replace + * * attributes + * * omit-tag + * + * Since the on-error statement is only invoked when an error occurs, it + * does not appear in the list. + * + * The reasoning behind this ordering goes like this: You often want to set + * up variables for use in other statements, so define comes first. The + * very next thing to do is decide whether this element will be included at + * all, so condition is next; since the condition may depend on variables + * you just set, it comes after define. It is valuable be able to replace + * various parts of an element with different values on each iteration of a + * repeat, so repeat is next. It makes no sense to replace attributes and + * then throw them away, so attributes is last. The remaining statements + * clash, because they each replace or edit the statement element. + * + * If you want to override this ordering, you must do so by enclosing the + * element in another element, possibly div or span, and placing some of + * the statements on this new element. + * + * + * @package PHPTAL + * @subpackage Namespace + */ +abstract class PHPTAL_NamespaceAttribute +{ + /** Attribute name without the namespace: prefix */ + private $local_name; + + /** [0 - 1000] */ + private $_priority; + + /** PHPTAL_Namespace */ + private $_namespace; + + /** + * @param string $name The attribute name + * @param int $priority Attribute execution priority + */ + public function __construct($local_name, $priority) + { + $this->local_name = $local_name; + $this->_priority = $priority; + } + + /** + * @return string + */ + public function getLocalName() + { + return $this->local_name; + } + + public function getPriority() { return $this->_priority; } + public function getNamespace() { return $this->_namespace; } + public function setNamespace(PHPTAL_Namespace $ns) { $this->_namespace = $ns; } + + public function createAttributeHandler(PHPTAL_Dom_Element $tag, $expression) + { + return $this->_namespace->createAttributeHandler($this, $tag, $expression); + } +} diff --git a/lib/phptal/PHPTAL/NamespaceAttributeContent.php b/lib/phptal/PHPTAL/NamespaceAttributeContent.php new file mode 100644 index 0000000..de33521 --- /dev/null +++ b/lib/phptal/PHPTAL/NamespaceAttributeContent.php @@ -0,0 +1,23 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * This type of attribute replaces element's content entirely + * @package PHPTAL + * @subpackage Namespace + */ +class PHPTAL_NamespaceAttributeContent extends PHPTAL_NamespaceAttribute +{ +} diff --git a/lib/phptal/PHPTAL/NamespaceAttributeReplace.php b/lib/phptal/PHPTAL/NamespaceAttributeReplace.php new file mode 100644 index 0000000..defc360 --- /dev/null +++ b/lib/phptal/PHPTAL/NamespaceAttributeReplace.php @@ -0,0 +1,23 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * This type of attribute replaces element entirely + * @package PHPTAL + * @subpackage Namespace + */ +class PHPTAL_NamespaceAttributeReplace extends PHPTAL_NamespaceAttribute +{ +} diff --git a/lib/phptal/PHPTAL/NamespaceAttributeSurround.php b/lib/phptal/PHPTAL/NamespaceAttributeSurround.php new file mode 100644 index 0000000..fca87d6 --- /dev/null +++ b/lib/phptal/PHPTAL/NamespaceAttributeSurround.php @@ -0,0 +1,23 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * This type of attribute wraps element + * @package PHPTAL + * @subpackage Namespace + */ +class PHPTAL_NamespaceAttributeSurround extends PHPTAL_NamespaceAttribute +{ +} diff --git a/lib/phptal/PHPTAL/NothingKeyword.php b/lib/phptal/PHPTAL/NothingKeyword.php new file mode 100644 index 0000000..22a79b0 --- /dev/null +++ b/lib/phptal/PHPTAL/NothingKeyword.php @@ -0,0 +1,39 @@ + + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * Representation of the template 'nothing' keyword + * + * @package PHPTAL + * @subpackage Keywords + */ +class PHPTAL_NothingKeyword implements PHPTAL_Keywords +{ + public function __toString() + { + return 'null'; + } + + public function count() + { + return 0; + } + + public function jsonSerialize() + { + return null; + } +} +?> diff --git a/lib/phptal/PHPTAL/ParserException.php b/lib/phptal/PHPTAL/ParserException.php new file mode 100644 index 0000000..225ad54 --- /dev/null +++ b/lib/phptal/PHPTAL/ParserException.php @@ -0,0 +1,24 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * XML well-formedness errors and alike. + * + * @package PHPTAL + * @subpackage Exception + */ +class PHPTAL_ParserException extends PHPTAL_TemplateException +{ +} diff --git a/lib/phptal/PHPTAL/Php/Attribute.php b/lib/phptal/PHPTAL/Php/Attribute.php new file mode 100644 index 0000000..ceb8a12 --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute.php @@ -0,0 +1,98 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * Base class for all PHPTAL attributes. + * + * Attributes are first ordered by PHPTAL then called depending on their + * priority before and after the element printing. + * + * An attribute must implements start() and end(). + * + * @package PHPTAL + * @subpackage Php + * @author Laurent Bedubourg + */ +abstract class PHPTAL_Php_Attribute +{ + const ECHO_TEXT = 'text'; + const ECHO_STRUCTURE = 'structure'; + + /** Attribute value specified by the element. */ + protected $expression; + + /** Element using this attribute (PHPTAL's counterpart of XML node) */ + protected $phpelement; + + /** + * Called before element printing. + */ + abstract function before(PHPTAL_Php_CodeWriter $codewriter); + + /** + * Called after element printing. + */ + abstract function after(PHPTAL_Php_CodeWriter $codewriter); + + function __construct(PHPTAL_Dom_Element $phpelement, $expression) + { + $this->expression = $expression; + $this->phpelement = $phpelement; + } + + /** + * Remove structure|text keyword from expression and stores it for later + * doEcho() usage. + * + * $expression = 'stucture my/path'; + * $expression = $this->extractEchoType($expression); + * + * ... + * + * $this->doEcho($code); + */ + protected function extractEchoType($expression) + { + $echoType = self::ECHO_TEXT; + $expression = trim($expression); + if (preg_match('/^(text|structure)\s+(.*?)$/ism', $expression, $m)) { + list(, $echoType, $expression) = $m; + } + $this->_echoType = strtolower($echoType); + return trim($expression); + } + + protected function doEchoAttribute(PHPTAL_Php_CodeWriter $codewriter, $code) + { + if ($this->_echoType === self::ECHO_TEXT) + $codewriter->doEcho($code); + else + $codewriter->doEchoRaw($code); + } + + protected function parseSetExpression($exp) + { + $exp = trim($exp); + // (dest) (value) + if (preg_match('/^([a-z0-9:\-_]+)\s+(.*?)$/si', $exp, $m)) { + return array($m[1], trim($m[2])); + } + // (dest) + return array($exp, null); + } + + protected $_echoType = PHPTAL_Php_Attribute::ECHO_TEXT; +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/I18N/Attributes.php b/lib/phptal/PHPTAL/Php/Attribute/I18N/Attributes.php new file mode 100644 index 0000000..5eb3fac --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/I18N/Attributes.php @@ -0,0 +1,118 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * i18n:attributes + * + * This attribute will allow us to translate attributes of HTML tags, such + * as the alt attribute in the img tag. The i18n:attributes attribute + * specifies a list of attributes to be translated with optional message + * IDs? for each; if multiple attribute names are given, they must be + * separated by semi-colons. Message IDs? used in this context must not + * include whitespace. + * + * Note that the value of the particular attributes come either from the + * HTML attribute value itself or from the data inserted by tal:attributes. + * + * If an attibute is to be both computed using tal:attributes and translated, + * the translation service is passed the result of the TALES expression for + * that attribute. + * + * An example: + * + * Visit us + * + * + * In this example, let tal:attributes set the value of the alt attribute to + * the text "Stop by for a visit!". This text will be passed to the + * translation service, which uses the result of language negotiation to + * translate "Stop by for a visit!" into the requested language. The example + * text in the template, "Visit us", will simply be discarded. + * + * Another example, with explicit message IDs: + * + * Up + * + * Here, the message ID up-arrow-icon will be used to generate the link to + * an icon image file, and the message ID up-arrow-alttext will be used for + * the "alt" text. + * + * + * + * @package PHPTAL + * @subpackage Php.attribute.i18n + */ +class PHPTAL_Php_Attribute_I18N_Attributes extends PHPTAL_Php_Attribute +{ + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + // split attributes to translate + foreach ($codewriter->splitExpression($this->expression) as $exp) { + list($qname, $key) = $this->parseSetExpression($exp); + + // if the translation key is specified and not empty (but may be '0') + if (strlen($key)) { + // we use it and replace the tag attribute with the result of the translation + $code = $this->_getTranslationCode($codewriter, $key); + } else { + $attr = $this->phpelement->getAttributeNode($qname); + if (!$attr) throw new PHPTAL_TemplateException("Unable to translate attribute $qname, because there is no translation key specified", + $this->phpelement->getSourceFile(), $this->phpelement->getSourceLine()); + + if ($attr->getReplacedState() === PHPTAL_Dom_Attr::NOT_REPLACED) { + $code = $this->_getTranslationCode($codewriter, $attr->getValue()); + } elseif ($attr->getReplacedState() === PHPTAL_Dom_Attr::VALUE_REPLACED && $attr->getOverwrittenVariableName()) { + // sadly variables won't be interpolated in this translation + $code = 'echo '.$codewriter->escapeCode($codewriter->getTranslatorReference(). '->translate('.$attr->getOverwrittenVariableName().', false)'); + } else { + throw new PHPTAL_TemplateException("Unable to translate attribute $qname, because other TAL attributes are using it", + $this->phpelement->getSourceFile(), $this->phpelement->getSourceLine()); + } + } + $this->phpelement->getOrCreateAttributeNode($qname)->overwriteValueWithCode($code); + } + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + } + + /** + * @param key - unescaped string (not PHP code) for the key + */ + private function _getTranslationCode(PHPTAL_Php_CodeWriter $codewriter, $key) + { + $code = ''; + if (preg_match_all('/\$\{(.*?)\}/', $key, $m)) { + array_shift($m); + $m = array_shift($m); + foreach ($m as $name) { + $code .= "\n".$codewriter->getTranslatorReference(). '->setVar('.$codewriter->str($name).','.PHPTAL_Php_TalesInternal::compileToPHPExpression($name).');'; // allow more complex TAL expressions + } + $code .= "\n"; + } + + // notice the false boolean which indicate that the html is escaped + // elsewhere looks like an hack doesn't it ? :) + $code .= 'echo '.$codewriter->escapeCode($codewriter->getTranslatorReference().'->translate('.$codewriter->str($key).', false)'); + return $code; + } +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/I18N/Data.php b/lib/phptal/PHPTAL/Php/Attribute/I18N/Data.php new file mode 100644 index 0000000..bad310f --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/I18N/Data.php @@ -0,0 +1,36 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * i18n:data + * + * Since TAL always returns strings, we need a way in ZPT to translate + * objects, the most obvious case being DateTime objects. The data attribute + * will allow us to specify such an object, and i18n:translate will provide + * us with a legal format string for that object. If data is used, + * i18n:translate must be used to give an explicit message ID, rather than + * relying on a message ID computed from the content. + * + * + * + * @package PHPTAL + * @subpackage Php.attribute.i18n + */ +class PHPTAL_Php_Attribute_I18N_Data extends PHPTAL_Php_Attribute +{ + public function before(PHPTAL_Php_CodeWriter $codewriter){} + public function after(PHPTAL_Php_CodeWriter $codewriter){} +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/I18N/Domain.php b/lib/phptal/PHPTAL/Php/Attribute/I18N/Domain.php new file mode 100644 index 0000000..92ece11 --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/I18N/Domain.php @@ -0,0 +1,50 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * i18n:domain + * + * The i18n:domain attribute is used to specify the domain to be used to get + * the translation. If not specified, the translation services will use a + * default domain. The value of the attribute is used directly; it is not + * a TALES expression. + * + * @package PHPTAL + * @subpackage Php.attribute.i18n + */ +class PHPTAL_Php_Attribute_I18N_Domain extends PHPTAL_Php_Attribute +{ + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + // ensure a domain stack exists or create it + $codewriter->doIf('!isset($_i18n_domains)'); + $codewriter->pushCode('$_i18n_domains = array()'); + $codewriter->doEnd('if'); + + $expression = $codewriter->interpolateTalesVarsInString($this->expression); + + // push current domain and use new domain + $code = '$_i18n_domains[] = '.$codewriter->getTranslatorReference().'->useDomain('.$expression.')'; + $codewriter->pushCode($code); + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + // restore domain + $code = $codewriter->getTranslatorReference().'->useDomain(array_pop($_i18n_domains))'; + $codewriter->pushCode($code); + } +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/I18N/Name.php b/lib/phptal/PHPTAL/Php/Attribute/I18N/Name.php new file mode 100644 index 0000000..8a8f4e7 --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/I18N/Name.php @@ -0,0 +1,47 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** i18n:name + * + * Name the content of the current element for use in interpolation within + * translated content. This allows a replaceable component in content to be + * re-ordered by translation. For example: + * + * + * was born in + * . + * + * + * would cause this text to be passed to the translation service: + * + * "${name} was born in ${country}." + * + * + * @package PHPTAL + * @subpackage Php.attribute.i18n + */ +class PHPTAL_Php_Attribute_I18N_Name extends PHPTAL_Php_Attribute +{ + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + $codewriter->pushCode('ob_start()'); + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + $codewriter->pushCode($codewriter->getTranslatorReference().'->setVar('.$codewriter->str($this->expression).', ob_get_clean())'); + } +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/I18N/Source.php b/lib/phptal/PHPTAL/Php/Attribute/I18N/Source.php new file mode 100644 index 0000000..9575fae --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/I18N/Source.php @@ -0,0 +1,48 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * i18n:source + * + * The i18n:source attribute specifies the language of the text to be + * translated. The default is "nothing", which means we don't provide + * this information to the translation services. + * + * + * @package PHPTAL + * @subpackage Php.attribute.i18n + */ +class PHPTAL_Php_Attribute_I18N_Source extends PHPTAL_Php_Attribute +{ + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + // ensure that a sources stack exists or create it + $codewriter->doIf('!isset($_i18n_sources)'); + $codewriter->pushCode('$_i18n_sources = array()'); + $codewriter->end(); + + // push current source and use new one + $codewriter->pushCode('$_i18n_sources[] = ' . $codewriter->getTranslatorReference(). '->setSource('.$codewriter->str($this->expression).')'); + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + // restore source + $code = $codewriter->getTranslatorReference().'->setSource(array_pop($_i18n_sources))'; + $codewriter->pushCode($code); + } +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/I18N/Target.php b/lib/phptal/PHPTAL/Php/Attribute/I18N/Target.php new file mode 100644 index 0000000..9cf2a67 --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/I18N/Target.php @@ -0,0 +1,43 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * i18n:target + * + * The i18n:target attribute specifies the language of the translation we + * want to get. If the value is "default", the language negotiation services + * will be used to choose the destination language. If the value is + * "nothing", no translation will be performed; this can be used to suppress + * translation within a larger translated unit. Any other value must be a + * language code. + * + * The attribute value is a TALES expression; the result of evaluating the + * expression is the language code or one of the reserved values. + * + * Note that i18n:target is primarily used for hints to text extraction + * tools and translation teams. If you had some text that should only be + * translated to e.g. German, then it probably shouldn't be wrapped in an + * i18n:translate span. + * + * + * @package PHPTAL + * @subpackage Php.attribute.i18n + */ +class PHPTAL_Php_Attribute_I18N_Target extends PHPTAL_Php_Attribute +{ + public function before(PHPTAL_Php_CodeWriter $codewriter){} + public function after(PHPTAL_Php_CodeWriter $codewriter){} +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/I18N/Translate.php b/lib/phptal/PHPTAL/Php/Attribute/I18N/Translate.php new file mode 100644 index 0000000..a0e26c2 --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/I18N/Translate.php @@ -0,0 +1,130 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * ZPTInternationalizationSupport + * + * i18n:translate + * + * This attribute is used to mark units of text for translation. If this + * attribute is specified with an empty string as the value, the message ID + * is computed from the content of the element bearing this attribute. + * Otherwise, the value of the element gives the message ID. + * + * + * @package PHPTAL + * @subpackage Php.attribute.i18n + */ +class PHPTAL_Php_Attribute_I18N_Translate extends PHPTAL_Php_Attribute_TAL_Content +{ + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + $escape = true; + $this->_echoType = PHPTAL_Php_Attribute::ECHO_TEXT; + if (preg_match('/^(text|structure)(?:\s+(.*)|\s*$)/', $this->expression, $m)) { + if ($m[1]=='structure') { $escape=false; $this->_echoType = PHPTAL_Php_Attribute::ECHO_STRUCTURE; } + $this->expression = isset($m[2])?$m[2]:''; + } + + $this->_prepareNames($codewriter, $this->phpelement); + + // if no expression is given, the content of the node is used as + // a translation key + if (strlen(trim($this->expression)) == 0) { + $key = $this->_getTranslationKey($this->phpelement, !$escape, $codewriter->getEncoding()); + $key = trim(preg_replace('/\s+/sm'.($codewriter->getEncoding()=='UTF-8'?'u':''), ' ', $key)); + if ('' === trim($key)) { + throw new PHPTAL_TemplateException("Empty translation key", + $this->phpelement->getSourceFile(), $this->phpelement->getSourceLine()); + } + $code = $codewriter->str($key); + } else { + $code = $codewriter->evaluateExpression($this->expression); + if (is_array($code)) + return $this->generateChainedContent($codewriter, $code); + + $code = $codewriter->evaluateExpression($this->expression); + } + + $codewriter->pushCode('echo '.$codewriter->getTranslatorReference().'->translate('.$code.','.($escape ? 'true':'false').');'); + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + } + + public function talesChainPart(PHPTAL_Php_TalesChainExecutor $executor, $exp, $islast) + { + $codewriter = $executor->getCodeWriter(); + + $escape = !($this->_echoType == PHPTAL_Php_Attribute::ECHO_STRUCTURE); + $exp = $codewriter->getTranslatorReference()."->translate($exp, " . ($escape ? 'true':'false') . ')'; + if (!$islast) { + $var = $codewriter->createTempVariable(); + $executor->doIf('!phptal_isempty('.$var.' = '.$exp.')'); + $codewriter->pushCode("echo $var"); + $codewriter->recycleTempVariable($var); + } else { + $executor->doElse(); + $codewriter->pushCode("echo $exp"); + } + } + + private function _getTranslationKey(PHPTAL_Dom_Node $tag, $preserve_tags, $encoding) + { + $result = ''; + foreach ($tag->childNodes as $child) { + if ($child instanceof PHPTAL_Dom_Text) { + if ($preserve_tags) { + $result .= $child->getValueEscaped(); + } else { + $result .= $child->getValue($encoding); + } + } elseif ($child instanceof PHPTAL_Dom_Element) { + if ($attr = $child->getAttributeNodeNS('http://xml.zope.org/namespaces/i18n', 'name')) { + $result .= '${' . $attr->getValue() . '}'; + } else { + + if ($preserve_tags) { + $result .= '<'.$child->getQualifiedName(); + foreach ($child->getAttributeNodes() as $attr) { + if ($attr->getReplacedState() === PHPTAL_Dom_Attr::HIDDEN) continue; + + $result .= ' '.$attr->getQualifiedName().'="'.$attr->getValueEscaped().'"'; + } + $result .= '>'.$this->_getTranslationKey($child, $preserve_tags, $encoding) . 'getQualifiedName().'>'; + } else { + $result .= $this->_getTranslationKey($child, $preserve_tags, $encoding); + } + } + } + } + return $result; + } + + private function _prepareNames(PHPTAL_Php_CodeWriter $codewriter, PHPTAL_Dom_Node $tag) + { + foreach ($tag->childNodes as $child) { + if ($child instanceof PHPTAL_Dom_Element) { + if ($child->hasAttributeNS('http://xml.zope.org/namespaces/i18n', 'name')) { + $child->generateCode($codewriter); + } else { + $this->_prepareNames($codewriter, $child); + } + } + } + } +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/METAL/DefineMacro.php b/lib/phptal/PHPTAL/Php/Attribute/METAL/DefineMacro.php new file mode 100644 index 0000000..ef04840 --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/METAL/DefineMacro.php @@ -0,0 +1,67 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * METAL Specification 1.0 + * + * argument ::= Name + * + * Example: + * + *

+ * Copyright 2001, Foobar Inc. + *

+ * + * PHPTAL: + * + * + *

+ * Copyright 2001, Foobar Inc. + *

+ * + * + * @package PHPTAL + * @subpackage Php.attribute.metal + * @author Laurent Bedubourg + */ +class PHPTAL_Php_Attribute_METAL_DefineMacro extends PHPTAL_Php_Attribute +{ + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + $macroname = strtr(trim($this->expression), '-', '_'); + if (!preg_match('/^[a-z0-9_]+$/i', $macroname)) { + throw new PHPTAL_ParserException('Bad macro name "'.$macroname.'"', + $this->phpelement->getSourceFile(), $this->phpelement->getSourceLine()); + } + + if ($codewriter->functionExists($macroname)) { + throw new PHPTAL_TemplateException("Macro $macroname is defined twice", + $this->phpelement->getSourceFile(), $this->phpelement->getSourceLine()); + } + + $codewriter->doFunction($macroname, 'PHPTAL $_thistpl, PHPTAL $tpl'); + $codewriter->doSetVar('$tpl', 'clone $tpl'); + $codewriter->doSetVar('$ctx', '$tpl->getContext()'); + $codewriter->doInitTranslator(); + $codewriter->doXmlDeclaration(true); + $codewriter->doDoctype(true); + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + $codewriter->doEnd('function'); + } +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/METAL/DefineSlot.php b/lib/phptal/PHPTAL/Php/Attribute/METAL/DefineSlot.php new file mode 100644 index 0000000..010849a --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/METAL/DefineSlot.php @@ -0,0 +1,70 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * METAL Specification 1.0 + * + * argument ::= Name + * + * Example: + * + * + * + * + *
Links
+ * A Link + *
+ * + * PHPTAL: (access to slots may be renamed) + * + * + * + * + * + * slots->links)): ? > + * slots->links ? > + * + * + *
Links
+ * A Link + *
+ * + * + * @package PHPTAL + * @subpackage Php.attribute.metal + * @author Laurent Bedubourg + */ +class PHPTAL_Php_Attribute_METAL_DefineSlot extends PHPTAL_Php_Attribute +{ + private $tmp_var; + + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + $this->tmp_var = $codewriter->createTempVariable(); + + $codewriter->doSetVar($this->tmp_var, $codewriter->interpolateTalesVarsInString($this->expression)); + $codewriter->doIf('$ctx->hasSlot('.$this->tmp_var.')'); + $codewriter->pushCode('$ctx->echoSlot('.$this->tmp_var.')'); + $codewriter->doElse(); + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + $codewriter->doEnd('if'); + + $codewriter->recycleTempVariable($this->tmp_var); + } +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/METAL/FillSlot.php b/lib/phptal/PHPTAL/Php/Attribute/METAL/FillSlot.php new file mode 100644 index 0000000..2dfda3a --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/METAL/FillSlot.php @@ -0,0 +1,148 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * METAL Specification 1.0 + * + * argument ::= Name + * + * Example: + * + * + * + * + *
Links
+ * Good Place
+ * Bad Place
+ * Other Place + *
+ * + * PHPTAL: + * + * 1. evaluate slots + * + * + * + * Good Place
+ * Bad Place
+ * Other Place + * + * slots->links = ob_get_contents(); ob_end_clean(); ? > + * + * 2. call the macro (here not supported) + * + * + * + * + * @package PHPTAL + * @subpackage Php.attribute.metal + * @author Laurent Bedubourg + */ +class PHPTAL_Php_Attribute_METAL_FillSlot extends PHPTAL_Php_Attribute +{ + private static $uid = 0; + private $function_name; + + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + if ($this->shouldUseCallback()) { + $function_base_name = 'slot_'.preg_replace('/[^a-z0-9]/', '_', $this->expression).'_'.(self::$uid++); + $codewriter->doFunction($function_base_name, 'PHPTAL $_thistpl, PHPTAL $tpl'); + $this->function_name = $codewriter->getFunctionPrefix().$function_base_name; + + $codewriter->doSetVar('$ctx', '$tpl->getContext()'); + $codewriter->doInitTranslator(); + } else { + $codewriter->pushCode('ob_start()'); + $this->function_name = null; + } + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + if ($this->function_name !== null) { + $codewriter->doEnd(); + $codewriter->pushCode('$ctx->fillSlotCallback('.$codewriter->str($this->expression).', '.$codewriter->str($this->function_name).', $_thistpl, clone $tpl)'); + } else { + $codewriter->pushCode('$ctx->fillSlot('.$codewriter->str($this->expression).', ob_get_clean())'); + } + } + + // rough guess + const CALLBACK_THRESHOLD = 10000; + + /** + * inspects contents of the element to decide whether callback makes sense + */ + private function shouldUseCallback() + { + // since callback is slightly slower than buffering, + // use callback only for content that is large to offset speed loss by memory savings + return $this->estimateNumberOfBytesOutput($this->phpelement, false) > self::CALLBACK_THRESHOLD; + } + + /** + * @param bool $is_nested_in_repeat true if any parent element has tal:repeat + * + * @return rough guess + */ + private function estimateNumberOfBytesOutput(PHPTAL_Dom_Element $element, $is_nested_in_repeat) + { + // macros don't output anything on their own + if ($element->hasAttributeNS('http://xml.zope.org/namespaces/metal', 'define-macro')) { + return 0; + } + + $estimated_bytes = 2*(3+strlen($element->getQualifiedName())); + + foreach ($element->getAttributeNodes() as $attr) { + $estimated_bytes += 4+strlen($attr->getQualifiedName()); + if ($attr->getReplacedState() === PHPTAL_Dom_Attr::NOT_REPLACED) { + $estimated_bytes += strlen($attr->getValueEscaped()); // this is shoddy for replaced attributes + } + } + + $has_repeat_attr = $element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'repeat'); + + if ($element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'content') || + $element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'replace')) { + // assume that output in loops is shorter (e.g. table rows) than outside (main content) + $estimated_bytes += ($has_repeat_attr || $is_nested_in_repeat) ? 500 : 2000; + } else { + foreach ($element->childNodes as $node) { + if ($node instanceof PHPTAL_Dom_Element) { + $estimated_bytes += $this->estimateNumberOfBytesOutput($node, $has_repeat_attr || $is_nested_in_repeat); + } else { + $estimated_bytes += strlen($node->getValueEscaped()); + } + } + } + + if ($element->hasAttributeNS('http://xml.zope.org/namespaces/metal', 'use-macro')) { + $estimated_bytes += ($has_repeat_attr || $is_nested_in_repeat) ? 500 : 2000; + } + + if ($element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'condition')) { + $estimated_bytes /= 2; // naively assuming 50% chance, that works well with if/else pattern + } + + if ($element->hasAttributeNS('http://xml.zope.org/namespaces/tal', 'repeat')) { + // assume people don't write big nested loops + $estimated_bytes *= $is_nested_in_repeat ? 5 : 10; + } + + return $estimated_bytes; + } +} diff --git a/lib/phptal/PHPTAL/Php/Attribute/METAL/UseMacro.php b/lib/phptal/PHPTAL/Php/Attribute/METAL/UseMacro.php new file mode 100644 index 0000000..83e8144 --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/METAL/UseMacro.php @@ -0,0 +1,135 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * METAL Specification 1.0 + * + * argument ::= expression + * + * Example: + * + *
+ *

+ *


+ * + * PHPTAL: (here not supported) + * + * + * + * + * + * @package PHPTAL + * @subpackage Php.attribute.metal + * @author Laurent Bedubourg + */ +class PHPTAL_Php_Attribute_METAL_UseMacro extends PHPTAL_Php_Attribute +{ + static $ALLOWED_ATTRIBUTES = array( + 'fill-slot'=>'http://xml.zope.org/namespaces/metal', + 'define-macro'=>'http://xml.zope.org/namespaces/metal', + 'define'=>'http://xml.zope.org/namespaces/tal', + ); + + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + $this->pushSlots($codewriter); + + foreach ($this->phpelement->childNodes as $child) { + $this->generateFillSlots($codewriter, $child); + } + + $macroname = strtr($this->expression, '-', '_'); + + // throw error if attempting to define and use macro at same time + // [should perhaps be a TemplateException? but I don't know how to set that up...] + if ($defineAttr = $this->phpelement->getAttributeNodeNS( + 'http://xml.zope.org/namespaces/metal', 'define-macro')) { + if ($defineAttr->getValue() == $macroname) + throw new PHPTAL_TemplateException("Cannot simultaneously define and use macro '$macroname'", + $this->phpelement->getSourceFile(), $this->phpelement->getSourceLine()); + } + + // local macro (no filename specified) and non dynamic macro name + // can be called directly if it's a known function (just generated or seen in previous compilation) + if (preg_match('/^[a-z0-9_]+$/i', $macroname) && $codewriter->functionExists($macroname)) { + $code = $codewriter->getFunctionPrefix() . $macroname . '($_thistpl, $tpl)'; + $codewriter->pushCode($code); + } + // external macro or ${macroname}, use PHPTAL at runtime to resolve it + else { + $code = $codewriter->interpolateTalesVarsInString($this->expression); + $codewriter->pushCode('$tpl->_executeMacroOfTemplate('.$code.', $_thistpl)'); + } + + $this->popSlots($codewriter); + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + } + + /** + * reset template slots on each macro call ? + * + * NOTE: defining a macro and using another macro on the same tag + * means inheriting from the used macro, thus slots are shared, it + * is a little tricky to understand but very natural to use. + * + * For example, we may have a main design.html containing our main + * website presentation with some slots (menu, content, etc...) then + * we may define a member.html macro which use the design.html macro + * for the general layout, fill the menu slot and let caller templates + * fill the parent content slot without interfering. + */ + private function pushSlots(PHPTAL_Php_CodeWriter $codewriter) + { + if (!$this->phpelement->hasAttributeNS('http://xml.zope.org/namespaces/metal', 'define-macro')) { + $codewriter->pushCode('$ctx->pushSlots()'); + } + } + + /** + * generate code that pops macro slots + * (restore slots if not inherited macro) + */ + private function popSlots(PHPTAL_Php_CodeWriter $codewriter) + { + if (!$this->phpelement->hasAttributeNS('http://xml.zope.org/namespaces/metal', 'define-macro')) { + $codewriter->pushCode('$ctx->popSlots()'); + } + } + + /** + * recursively generates code for slots + */ + private function generateFillSlots(PHPTAL_Php_CodeWriter $codewriter, PHPTAL_Dom_Node $phpelement) + { + if (false == ($phpelement instanceof PHPTAL_Dom_Element)) { + return; + } + + // if the tag contains one of the allowed attribute, we generate it + foreach (self::$ALLOWED_ATTRIBUTES as $qname => $uri) { + if ($phpelement->hasAttributeNS($uri, $qname)) { + $phpelement->generateCode($codewriter); + return; + } + } + + foreach ($phpelement->childNodes as $child) { + $this->generateFillSlots($codewriter, $child); + } + } +} diff --git a/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Cache.php b/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Cache.php new file mode 100644 index 0000000..3504a22 --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Cache.php @@ -0,0 +1,97 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + +/** + * phptal:cache (note that's not tal:cache) caches element's HTML for a given time. Time is a number with 'd', 'h', 'm' or 's' suffix. + * There's optional parameter that defines how cache should be shared. By default cache is not sensitive to template's context at all + * - it's shared between all pages that use that template. + * You can add per url to have separate copy of given element for every URL. + * + * You can add per expression to have different cache copy for every different value of an expression (which MUST evaluate to a string). + * Expression cannot refer to variables defined using tal:define on the same element. + * + * NB: + * * phptal:cache blocks can be nested, but outmost block will cache other blocks regardless of their freshness. + * * you cannot use metal:fill-slot inside elements with phptal:cache + * + * Examples: + *
...
+ *
    ...
+ * + * @package PHPTAL + * @subpackage Php.attribute.phptal +*/ +class PHPTAL_Php_Attribute_PHPTAL_Cache extends PHPTAL_Php_Attribute +{ + private $cache_filename_var; + + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + // number or variable name followed by time unit + // optional per expression + if (!preg_match('/^\s*([0-9]+\s*|[a-zA-Z][\/a-zA-Z0-9_]*\s+)([dhms])\s*(?:\;?\s*per\s+([^;]+)|)\s*$/', $this->expression, $matches)) { + throw new PHPTAL_ParserException("Cache attribute syntax error: ".$this->expression, + $this->phpelement->getSourceFile(), $this->phpelement->getSourceLine()); + } + + $cache_len = $matches[1]; + if (!is_numeric($cache_len)) { + $cache_len = $codewriter->evaluateExpression($cache_len); + + if (is_array($cache_len)) throw new PHPTAL_ParserException("Chained expressions in cache length are not supported", + $this->phpelement->getSourceFile(), $this->phpelement->getSourceLine()); + } + switch ($matches[2]) { + case 'd': $cache_len .= '*24'; /* no break */ + case 'h': $cache_len .= '*60'; /* no break */ + case 'm': $cache_len .= '*60'; /* no break */ + } + + $cache_tag = '"'.addslashes( $this->phpelement->getQualifiedName() . ':' . $this->phpelement->getSourceLine()).'"'; + + $cache_per_expression = isset($matches[3])?trim($matches[3]):null; + if ($cache_per_expression == 'url') { + $cache_tag .= '.$_SERVER["REQUEST_URI"]'; + } elseif ($cache_per_expression == 'nothing') { + /* do nothing */ + } elseif ($cache_per_expression) { + $code = $codewriter->evaluateExpression($cache_per_expression); + + if (is_array($code)) throw new PHPTAL_ParserException("Chained expressions in per-cache directive are not supported", + $this->phpelement->getSourceFile(), $this->phpelement->getSourceLine()); + + $cache_tag = '('.$code.')."@".' . $cache_tag; + } + + $this->cache_filename_var = $codewriter->createTempVariable(); + $codewriter->doSetVar($this->cache_filename_var, $codewriter->str($codewriter->getCacheFilesBaseName()).'.md5('.$cache_tag.')' ); + + $cond = '!file_exists('.$this->cache_filename_var.') || time() - '.$cache_len.' >= filemtime('.$this->cache_filename_var.')'; + + $codewriter->doIf($cond); + $codewriter->doEval('ob_start()'); + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + $codewriter->doEval('file_put_contents('.$this->cache_filename_var.', ob_get_flush())'); + $codewriter->doElse(); + $codewriter->doEval('readfile('.$this->cache_filename_var.')'); + $codewriter->doEnd('if'); + + $codewriter->recycleTempVariable($this->cache_filename_var); + } +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Debug.php b/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Debug.php new file mode 100644 index 0000000..d0e9c9b --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Debug.php @@ -0,0 +1,34 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ +/** + * @package PHPTAL + * @subpackage Php.attribute.phptal + * @author Laurent Bedubourg + */ +class PHPTAL_Php_Attribute_PHPTAL_Debug extends PHPTAL_Php_Attribute +{ + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + $this->_oldMode = $codewriter->setDebug(true); + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + $codewriter->setDebug($this->_oldMode); + } + + private $_oldMode; +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Id.php b/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Id.php new file mode 100644 index 0000000..dbee2a9 --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Id.php @@ -0,0 +1,53 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ +/** + * @package PHPTAL + * @subpackage Php.attribute.phptal + * @author Laurent Bedubourg + */ +class PHPTAL_Php_Attribute_PHPTAL_ID extends PHPTAL_Php_Attribute +{ + private $var; + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + // retrieve trigger + $this->var = $codewriter->createTempVariable(); + + $codewriter->doSetVar( + $this->var, + '$tpl->getTrigger('.$codewriter->str($this->expression).')' + ); + + // if trigger found and trigger tells to proceed, we execute + // the node content + $codewriter->doIf($this->var.' && + '.$this->var.'->start('.$codewriter->str($this->expression).', $tpl) === PHPTAL_Trigger::PROCEED'); + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + // end of if PROCEED + $codewriter->doEnd('if'); + + // if trigger found, notify the end of the node + $codewriter->doIf($this->var); + $codewriter->pushCode( + $this->var.'->end('.$codewriter->str($this->expression).', $tpl)' + ); + $codewriter->doEnd('if'); + $codewriter->recycleTempVariable($this->var); + } +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Tales.php b/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Tales.php new file mode 100644 index 0000000..f1fb4d7 --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/PHPTAL/Tales.php @@ -0,0 +1,45 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ +/** + * @package PHPTAL + * @subpackage Php.attribute.phptal + * @author Laurent Bedubourg + */ +class PHPTAL_Php_Attribute_PHPTAL_TALES extends PHPTAL_Php_Attribute +{ + public function before(PHPTAL_Php_CodeWriter $codewriter) + { + $mode = trim($this->expression); + $mode = strtolower($mode); + + if ($mode == '' || $mode == 'default') + $mode = 'tales'; + + if ($mode != 'php' && $mode != 'tales') { + throw new PHPTAL_TemplateException("Unsupported TALES mode '$mode'", + $this->phpelement->getSourceFile(), $this->phpelement->getSourceLine()); + } + + $this->_oldMode = $codewriter->setTalesMode($mode); + } + + public function after(PHPTAL_Php_CodeWriter $codewriter) + { + $codewriter->setTalesMode($this->_oldMode); + } + + private $_oldMode; +} + diff --git a/lib/phptal/PHPTAL/Php/Attribute/TAL/Attributes.php b/lib/phptal/PHPTAL/Php/Attribute/TAL/Attributes.php new file mode 100644 index 0000000..158d079 --- /dev/null +++ b/lib/phptal/PHPTAL/Php/Attribute/TAL/Attributes.php @@ -0,0 +1,213 @@ + + * @author Kornel Lesiński + * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License + * @version SVN: $Id$ + * @link http://phptal.org/ + */ + + +/** + * TAL Specifications 1.4 + * + * argument ::= attribute_statement [';' attribute_statement]* + * attribute_statement ::= attribute_name expression + * attribute_name ::= [namespace ':'] Name + * namespace ::= Name + * + * examples: + * + * + *