diff --git a/Aoe_Static.xml b/Aoe_Static.xml
deleted file mode 100644
index cf69494..0000000
--- a/Aoe_Static.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
- true
- local
-
-
-
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..efe40f6
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, 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
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If 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 convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU 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
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ {one line to give the program's name and a brief idea of what it does.}
+ Copyright (C) {year} {name of author}
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ {project} Copyright (C) {year} {fullname}
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/Readme.md b/Readme.md
new file mode 100644
index 0000000..60f6c7e
--- /dev/null
+++ b/Readme.md
@@ -0,0 +1,5 @@
+# AOE Static
+
+Changelog
+
+* Renamed placeholder class from .placeholder to .as-placeholder (This is a breaking change!)
diff --git a/acl.vcl b/acl.vcl
new file mode 100644
index 0000000..a779add
--- /dev/null
+++ b/acl.vcl
@@ -0,0 +1,4 @@
+acl cache_acl {
+ "127.0.0.1";
+ # insert additional ip's here
+}
diff --git a/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl.php b/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl.php
new file mode 100644
index 0000000..1722ba5
--- /dev/null
+++ b/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl.php
@@ -0,0 +1,37 @@
+_blockGroup = 'aoestatic';
+ $this->_controller = 'adminhtml_customUrl';
+ $this->_headerText = Mage::helper('aoestatic')->__('Urls max-age management');
+
+ parent::__construct();
+
+ if ($this->_isAllowedAction('save')) {
+ $this->_updateButton('add', 'label', Mage::helper('aoestatic')->__('Add new custom url'));
+ } else {
+ $this->_removeButton('add');
+ }
+ }
+
+ /**
+ * Check permission for passed action
+ *
+ * @param string $action
+ * @return bool
+ */
+ protected function _isAllowedAction($action)
+ {
+ return Mage::getSingleton('admin/session')->isAllowed('system/aoestatic_customUrl/' . $action);
+ }
+}
diff --git a/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl/Edit.php b/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl/Edit.php
new file mode 100644
index 0000000..c565f9c
--- /dev/null
+++ b/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl/Edit.php
@@ -0,0 +1,70 @@
+_objectId = 'id';
+ $this->_blockGroup = 'aoestatic';
+ $this->_controller = 'adminhtml_customUrl';
+
+ parent::__construct();
+
+ if ($this->_isAllowedAction('save')) {
+ $this->_updateButton('save', 'label', Mage::helper('aoestatic')->__('Save custom url'));
+ $this->_addButton('saveandcontinue', array(
+ 'label' => Mage::helper('aoestatic')->__('Save and Continue Edit'),
+ 'onclick' => 'saveAndContinueEdit()',
+ 'class' => 'save',
+ ), -100);
+ } else {
+ $this->_removeButton('save');
+ }
+
+ if ($this->_isAllowedAction('delete')) {
+ $this->_updateButton('delete', 'label', Mage::helper('aoestatic')->__('Delete custom url'));
+ } else {
+ $this->_removeButton('delete');
+ }
+
+ $this->_formScripts[] = "
+ function saveAndContinueEdit(){
+ editForm.submit($('edit_form').action+'back/edit/');
+ }
+ ";
+ }
+
+ /**
+ * Retrieve text for header element depending on loaded page
+ *
+ * @return string
+ */
+ public function getHeaderText()
+ {
+ if (Mage::registry('custom_url')->getId()) {
+ return Mage::helper('aoestatic')->__("Edit custom url (ID: %d)",
+ $this->escapeHtml(Mage::registry('custom_url')->getId())
+ );
+ } else {
+ return Mage::helper('aoestatic')->__('New custom url');
+ }
+ }
+
+ /**
+ * Check permission for passed action
+ *
+ * @param string $action
+ * @return bool
+ */
+ protected function _isAllowedAction($action)
+ {
+ return Mage::getSingleton('admin/session')->isAllowed('system/aoestatic_customUrl/' . $action);
+ }
+}
diff --git a/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl/Edit/Form.php b/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl/Edit/Form.php
new file mode 100644
index 0000000..3110f10
--- /dev/null
+++ b/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl/Edit/Form.php
@@ -0,0 +1,93 @@
+setId('custom_url_form');
+ $this->setTitle(Mage::helper('aoestatic')->__('Custom urls'));
+ }
+
+ /**
+ * Prepare form layout
+ *
+ * @return $this
+ */
+ protected function _prepareForm()
+ {
+ /** @var $model Aoe_Static_Model_CustomUrl */
+ $model = Mage::registry('custom_url');
+
+ $form = new Varien_Data_Form(
+ array(
+ 'id' => 'edit_form',
+ 'action' => $this->getData('action'),
+ 'method' => 'post'
+ )
+ );
+
+ // set form data either from model values or from session
+ $formValues = array(
+ 'store_id' => $model->getStoreId(),
+ 'request_path' => $model->getRequestPath(),
+ 'max_age' => $model->getMaxAge(),
+ );
+
+ $fieldset = $form->addFieldset('base_fieldset', array(
+ 'legend' => Mage::helper('aoestatic')->__('Custom urls')
+ ));
+
+ // get store switcher or a hidden field with its id
+ if (!Mage::app()->isSingleStoreMode()) {
+ $stores = Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm();
+ $element = $fieldset->addField('store_id', 'select', array(
+ 'label' => Mage::helper('aoestatic')->__('Store'),
+ 'title' => Mage::helper('aoestatic')->__('Store'),
+ 'class' => 'required-entry',
+ 'name' => 'store_id',
+ 'required' => true,
+ 'values' => $stores,
+ 'value' => $formValues['store_id'],
+ ));
+ $renderer = $this->getLayout()->createBlock('adminhtml/store_switcher_form_renderer_fieldset_element');
+ $element->setRenderer($renderer);
+ } else {
+ $fieldset->addField('store_id', 'hidden', array(
+ 'name' => 'store_id',
+ 'value' => Mage::app()->getStore(true)->getId()
+ ));
+ }
+
+ $fieldset->addField('request_path', 'text', array(
+ 'label' => Mage::helper('aoestatic')->__('Request Path'),
+ 'title' => Mage::helper('aoestatic')->__('Request Path'),
+ 'class' => 'required-entry',
+ 'name' => 'request_path',
+ 'required' => true,
+ 'value' => $formValues['request_path']
+ ));
+
+ $fieldset->addField('max_age', 'text', array(
+ 'label' => Mage::helper('aoestatic')->__('Max Age'),
+ 'title' => Mage::helper('aoestatic')->__('Max Age'),
+ 'class' => 'required-entry validate-digits',
+ 'name' => 'max_age',
+ 'required' => true,
+ 'value' => $formValues['max_age']
+ ));
+
+ $form->setUseContainer(true);
+ $form->setAction(Mage::helper('adminhtml')->getUrl('*/*/save', array('id' => $model->getId())));
+ $this->setForm($form);
+
+ return parent::_prepareForm();
+ }
+}
diff --git a/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl/Grid.php b/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl/Grid.php
new file mode 100644
index 0000000..24e5c96
--- /dev/null
+++ b/app/code/community/Aoe/Static/Block/Adminhtml/CustomUrl/Grid.php
@@ -0,0 +1,129 @@
+setId('custom_url_list_grid');
+ $this->setDefaultSort('custom_url_id');
+ $this->setUseAjax(true);
+ }
+
+ /**
+ * Prepare collection for grid
+ *
+ * @return $this
+ */
+ protected function _prepareCollection()
+ {
+ /** @var $collection Aoe_Static_Model_Resource_CustomUrl_Collection */
+ $collection = Mage::getResourceModel('aoestatic/customUrl_collection');
+
+ $this->setCollection($collection);
+ return parent::_prepareCollection();
+ }
+
+ /**
+ * Return row URL for js event handlers
+ *
+ * @param Aoe_Static_Model_CustomUrl $row
+ * @return string
+ */
+ public function getRowUrl($row)
+ {
+ return $this->getUrl('*/*/edit', array('id' => $row->getId()));
+ }
+
+ /**
+ * Prepare Grid columns
+ *
+ * @return $this
+ */
+ protected function _prepareColumns()
+ {
+ $this->addColumn('custom_url_id', array(
+ 'header' => Mage::helper('aoestatic')->__('ID'),
+ 'width' => '10px',
+ 'index' => 'custom_url_id'
+ ));
+
+ if (!Mage::app()->isSingleStoreMode()) {
+ $this->addColumn('store_id', array(
+ 'header' => Mage::helper('aoestatic')->__('Store View'),
+ 'width' => '200px',
+ 'index' => 'store_id',
+ 'type' => 'store',
+ 'store_view' => true,
+ ));
+ }
+
+ $this->addColumn('request_path', array(
+ 'header' => Mage::helper('aoestatic')->__('Request Path'),
+ 'width' => '80%',
+ 'index' => 'request_path'
+ ));
+ $this->addColumn('max_age', array(
+ 'header' => Mage::helper('aoestatic')->__('Max Age'),
+ 'width' => '50px',
+ 'index' => 'max_age'
+ ));
+
+ $this->addColumn('action',
+ array(
+ 'header' => Mage::helper('aoestatic')->__('Actions'),
+ 'width' => '50px',
+ 'type' => 'action',
+ 'getter' => 'getId',
+ 'actions' => array(
+ array(
+ 'caption' => Mage::helper('aoestatic')->__('Delete'),
+ 'url' => array(
+ 'base' => '*/*/delete',
+ ),
+ 'field' => 'id',
+ 'confirm' => Mage::helper('aoestatic')->__('Are you sure you want to delete custom url?')
+ )
+ ),
+ 'filter' => false,
+ 'sortable' => false,
+ )
+ );
+
+ return parent::_prepareColumns();
+ }
+
+ /**
+ * Prepare grid massaction actions
+ *
+ * @return $this
+ */
+ protected function _prepareMassaction()
+ {
+ $this->setMassactionIdField('custom_url_id');
+ $this->getMassactionBlock()->setFormFieldName('custom_url_ids');
+ $this->getMassactionBlock()->addItem('delete', array(
+ 'label' => Mage::helper('aoestatic')->__('Delete'),
+ 'url' => $this->getUrl('*/*/massDelete'),
+ 'confirm' => Mage::helper('aoestatic')->__('Are you sure you want delete selected custom url(s)?')
+ ));
+
+ return $this;
+ }
+ /**
+ * Grid url getter
+ *
+ * @return string current grid url
+ */
+ public function getGridUrl()
+ {
+ return $this->getUrl('*/*/grid', array('_current' => true));
+ }
+}
diff --git a/app/code/community/Aoe/Static/Block/Adminhtml/Purge.php b/app/code/community/Aoe/Static/Block/Adminhtml/Purge.php
new file mode 100644
index 0000000..06ce966
--- /dev/null
+++ b/app/code/community/Aoe/Static/Block/Adminhtml/Purge.php
@@ -0,0 +1,3 @@
+session)) {
+ $this->session = Mage::getSingleton('customer/session');
+ }
+ return $this->session;
+ }
+
+ /**
+ * Check if there is a logged in customer
+ *
+ * @return bool
+ */
+ public function isLoggedIn() {
+ return $this->getSession()->isLoggedIn();
+ }
+
+ /**
+ * Get customer name
+ *
+ * @return bool|string
+ */
+ public function getCustomerName() {
+ if ($this->isLoggedIn()) {
+ return $this->getSession()->getCustomer()->getName();
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Get cart summary count
+ *
+ * @return int
+ */
+ public function getCartSummaryCount() {
+ // return Mage::helper('checkout/cart')->getSummaryCount();
+ }
+}
diff --git a/app/code/community/Aoe/Static/Block/EsiPlaceholder.php b/app/code/community/Aoe/Static/Block/EsiPlaceholder.php
new file mode 100644
index 0000000..a1ef5cf
--- /dev/null
+++ b/app/code/community/Aoe/Static/Block/EsiPlaceholder.php
@@ -0,0 +1,30 @@
+ $this->getPlaceholderBlockname(),
+ ));
+ # make url relative (TODO: is there a smarter way of doing this?)
+ return str_replace(Mage::getBaseUrl(), '/', $url);
+ }
+
+ public function renderChildren()
+ {
+ return Mage::getStoreConfigFlag('dev/aoestatic/renderEsiPlaceholderChildren');
+ }
+}
diff --git a/code/Block/Placeholder.php b/app/code/community/Aoe/Static/Block/Placeholder.php
similarity index 57%
rename from code/Block/Placeholder.php
rename to app/code/community/Aoe/Static/Block/Placeholder.php
index b0c408e..8d6671a 100644
--- a/code/Block/Placeholder.php
+++ b/app/code/community/Aoe/Static/Block/Placeholder.php
@@ -8,10 +8,8 @@
*/
class Aoe_Static_Block_Placeholder extends Mage_Core_Block_Template
{
-
- /**
- * @var string default template of this block
- */
- protected $_template = 'aoestatic/placeholder.phtml';
-
-}
\ No newline at end of file
+ /**
+ * @var string default template of this block
+ */
+ protected $_template = 'aoestatic/placeholder.phtml';
+}
diff --git a/app/code/community/Aoe/Static/Helper/Data.php b/app/code/community/Aoe/Static/Helper/Data.php
new file mode 100755
index 0000000..8672e1f
--- /dev/null
+++ b/app/code/community/Aoe/Static/Helper/Data.php
@@ -0,0 +1,214 @@
+_config)) {
+ $this->_config = Mage::getModel('aoestatic/config');
+ }
+ return $this->_config;
+ }
+
+ public function __construct() {
+ $this->verboseLogging = Mage::getStoreConfigFlag('dev/aoestatic/verboseLogging');
+ }
+
+ /**
+ * instantiates and caches active adapters
+ *
+ * @return array
+ */
+ protected function _getAdapterInstances()
+ {
+ if (is_null($this->_adapterInstances)) {
+
+ $this->_adapterInstances = array();
+
+ $selectedAdapterKeys = Mage::getStoreConfig('dev/aoestatic/purgeadapter');
+
+ foreach ($this->trimExplode(',', $selectedAdapterKeys) as $key) {
+ $adapters = $this->getConfig()->getAdapters();
+ if (!isset($adapters[$key])) {
+ Mage::throwException('Could not find adapter configuration for adapter "'.$key.'"');
+ }
+
+ $adapter = $adapters[$key];
+ $adapterInstance = Mage::getSingleton($adapter['model']);
+ if (!$adapterInstance instanceof Aoe_Static_Model_Cache_Adapter_Interface) {
+ Mage::throwException('Adapter "'.$key.'" does not implement Aoe_Static_Model_Cache_Adapter_Interface');
+ }
+ $adapterInstance->setConfig($adapter['config']);
+
+ $this->_adapterInstances[$key] = $adapterInstance;
+ }
+ }
+
+ return $this->_adapterInstances;
+ }
+
+ /**
+ * calls purgeAll on all adapter instances
+ *
+ * @return array
+ */
+ public function purgeAll()
+ {
+ // if Varnish is not enabled on admin don't do anything
+ if (!Mage::app()->useCache('aoestatic')) {
+ return array();
+ }
+
+ $result = array();
+ foreach ($this->_getAdapterInstances() as $adapter) {
+ /** @var Aoe_Static_Model_Cache_Adapter_Interface $adapter */
+ $result = array_merge($result, $adapter->purgeAll());
+ }
+ return $result;
+ }
+
+ /**
+ * calls purge on every adapter with given URLs
+ *
+ * @todo names/consts
+ * @param array $urls
+ * @param bool $queue
+ * @return array
+ */
+ public function purge(array $urls, $queue = true)
+ {
+ // if Varnish is not enabled on admin don't do anything
+ if (!Mage::app()->useCache('aoestatic')) {
+ return array();
+ }
+
+ $urls = array_filter($urls);
+
+ $result = array();
+ // queue if async cache is enabled in config and not forced to purge directly
+ if ($this->getConfig()->useAsyncCache() && $queue) {
+ foreach ($urls as $url) {
+ /** @var $asyncCache Aoe_AsyncCache_Model_Asynccache */
+ $asyncCache = Mage::getModel('aoeasynccache/asynccache');
+ $asyncCache->setTstamp(time())
+ ->setMode(Aoe_Static_Helper_Data::MODE_PURGEVARNISHURL)
+ ->setTags($url)
+ ->setStatus(Aoe_AsyncCache_Model_Asynccache::STATUS_PENDING)
+ ->save();
+ }
+ } else {
+ foreach ($this->_getAdapterInstances() as $adapter) {
+ /** @var Aoe_Static_Model_Cache_Adapter_Interface $adapter */
+ $result = array_merge($result, $adapter->purge($urls));
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * purge given tag(s)
+ *
+ * @param string|array $tags
+ * @param bool $withStore
+ * @param bool $queue
+ *
+ * @return array
+ */
+ public function purgeTags($tags, $withStore = false, $queue = true)
+ {
+ // if Varnish is not enabled on admin don't do anything
+ if (!Mage::app()->useCache('aoestatic')) {
+ return array();
+ }
+
+ if (!is_array($tags)) {
+ $tags = array($tags);
+ }
+
+ /** @var Aoe_Static_Model_Cache_Control $cacheControl */
+ $cacheControl = Mage::getSingleton('aoestatic/cache_control');
+ foreach ($tags as $k => $v) {
+ $tags[$k] = $cacheControl->normalizeTag($v, $withStore);
+ }
+
+ $result = array();
+ // queue if async cache is enabled in config and not forced to purge directly
+ if ($this->getConfig()->useAsyncCache() && $queue) {
+ foreach ($tags as $tag) {
+ /** @var $asyncCache Aoe_AsyncCache_Model_Asynccache */
+ $asyncCache = Mage::getModel('aoeasynccache/asynccache');
+ $asyncCache->setTstamp(time())
+ ->setMode(Aoe_Static_Helper_Data::MODE_PURGEVARNISHTAG)
+ ->setTags($tag)
+ ->setStatus(Aoe_AsyncCache_Model_Asynccache::STATUS_PENDING)
+ ->save();
+ }
+ } else {
+ foreach ($this->_getAdapterInstances() as $adapter) {
+ /** @var Aoe_Static_Model_Cache_Adapter_Interface $adapter */
+ $result = array_merge($result, $adapter->purgeTags($tags));
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * trim explode
+ *
+ * @param $delim
+ * @param $string
+ * @param bool $removeEmptyValues
+ * @return array
+ */
+ public function trimExplode($delim, $string, $removeEmptyValues = false)
+ {
+ $explodedValues = explode($delim, $string);
+ $result = array_map('trim', $explodedValues);
+ if ($removeEmptyValues) {
+ $temp = array();
+ foreach ($result as $value) {
+ if ($value !== '') {
+ $temp[] = $value;
+ }
+ }
+ $result = $temp;
+ }
+ return $result;
+ }
+
+ /**
+ *
+ * @param string $message
+ * @param integer $level
+ * @param string $file
+ * @param bool $forceLog
+ */
+ public function log($message, $level = null, $file = '', $forceLog = false) {
+ if ($forceLog || $this->verboseLogging) {
+ Mage::log($message, $level, $file, $forceLog);
+ }
+ }
+}
diff --git a/app/code/community/Aoe/Static/Model/Adminhtml/System/Config/Source/PurgeAdapters.php b/app/code/community/Aoe/Static/Model/Adminhtml/System/Config/Source/PurgeAdapters.php
new file mode 100644
index 0000000..139c4ba
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/Adminhtml/System/Config/Source/PurgeAdapters.php
@@ -0,0 +1,38 @@
+getConfig()->getAdapters();
+
+ $options[] = array(
+ 'value'=> '',
+ 'label'=> Mage::helper('aoestatic')->__('(Purging disabled)')
+ );
+
+ foreach ($adapters as $key => $adapter) {
+ $options[] = array(
+ 'value'=> $key,
+ 'label'=> Mage::helper('aoestatic')->__($key)
+ );
+ }
+
+ Mage::dispatchEvent('aoestatic_purgeadapters_options', array('options' => &$options));
+
+ return $options;
+ }
+
+}
diff --git a/app/code/community/Aoe/Static/Model/Api.php b/app/code/community/Aoe/Static/Model/Api.php
new file mode 100644
index 0000000..94bd92e
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/Api.php
@@ -0,0 +1,42 @@
+purge($urls);
+ return $errors;
+ }
+
+ /**
+ * Purge tags
+ *
+ * @param array $tags
+ * @return array errors
+ */
+ public function purgeTags($tags) {
+ /** @var $helper Aoe_Static_Helper_Data */
+ $helper = Mage::helper('aoestatic');
+ $errors = $helper->purgeTags($tags);
+ return $errors;
+ }
+
+ /**
+ * Purge all
+ *
+ * @return array errors
+ */
+ public function purgeAll() {
+ /** @var $helper Aoe_Static_Helper_Data */
+ $helper = Mage::helper('aoestatic');
+ $errors = $helper->purgeAll();
+ return $errors;
+ }
+}
diff --git a/app/code/community/Aoe/Static/Model/AsyncCacheObserver.php b/app/code/community/Aoe/Static/Model/AsyncCacheObserver.php
new file mode 100644
index 0000000..e0f4a26
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/AsyncCacheObserver.php
@@ -0,0 +1,55 @@
+getData('jobCollection');
+ if (!$jobCollection) {
+ return;
+ }
+ foreach ($jobCollection as $job) {
+ /** @var $job Aoe_AsyncCache_Model_Job */
+ /** @todo name */
+ if (!$job->getIsProcessed() && ($job->getMode() == Aoe_Static_Helper_Data::MODE_PURGEVARNISHURL)) {
+ $startTime = time();
+ $errors = Mage::helper('aoestatic')->purge($job->getTags(), false);
+ $job->setDuration(time() - $startTime);
+ $job->setIsProcessed(true);
+
+ if (!empty($errors)) {
+ foreach ($errors as $error) {
+ Mage::log($error);
+ }
+ }
+
+ Mage::helper('aoestatic')->log(sprintf('[ASYNCCACHE URL] MODE: %s, DURATION: %s sec, TAGS: %s',
+ $job->getMode(),
+ $job->getDuration(),
+ implode(', ', $job->getTags())
+ ));
+ } else if (!$job->getIsProcessed() && ($job->getMode() == Aoe_Static_Helper_Data::MODE_PURGEVARNISHTAG)) {
+ $startTime = time();
+ $errors = Mage::helper('aoestatic')->purgeTags($job->getTags(), 0, false);
+ $job->setDuration(time() - $startTime);
+ $job->setIsProcessed(true);
+
+ if (!empty($errors)) {
+ foreach ($errors as $error) {
+ Mage::log($error);
+ }
+ }
+
+ Mage::helper('aoestatic')->log(sprintf('[ASYNCCACHE TAG] MODE: %s, DURATION: %s sec, TAGS: %s',
+ $job->getMode(),
+ $job->getDuration(),
+ implode(', ', $job->getTags())
+ ));
+ }
+ }
+ }
+}
diff --git a/app/code/community/Aoe/Static/Model/Cache/Adapter/Blackhole.php b/app/code/community/Aoe/Static/Model/Cache/Adapter/Blackhole.php
new file mode 100644
index 0000000..b420ae5
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/Cache/Adapter/Blackhole.php
@@ -0,0 +1,53 @@
+snsTopic)) {
+ $this->snsTopic = Mage::getStoreConfig('dev/aoestatic/snsTopic');
+ if (empty($this->snsTopic)) {
+ throw new Exception('Invalid SNS topic');
+ }
+ }
+ return $this->snsTopic;
+ }
+
+ public function getSnsClient()
+ {
+ if (is_null($this->snsClient)) {
+
+ $file = Mage::getBaseDir('lib') . DS . 'AwsSdk' . DS . 'autoload.php';
+ if (!is_file($file)) {
+ throw new Exception('Please install Mage_AwsSdk');
+ }
+ require_once $file;
+
+ // use EC2 instance profile of ENV vars to configure the client
+ $this->snsClient = new \Aws\Sns\SnsClient([
+ 'version' => '2010-03-31',
+ 'region' => Mage::getStoreConfig('dev/aoestatic/snsRegion')
+ ]);
+ }
+ return $this->snsClient;
+ }
+
+ protected function sendRequests(array $actions)
+ {
+ Mage::log('[Aoe_Static SNS] Publish SNS message');
+ $this->getSnsClient()->publish([
+ 'Message' => json_encode($actions),
+ 'Subject' => 'Aoe_Static',
+ 'TopicArn' => $this->getSnsTopic(),
+ ]);
+ return array();
+ }
+
+}
diff --git a/app/code/community/Aoe/Static/Model/Cache/Adapter/Varnish.php b/app/code/community/Aoe/Static/Model/Cache/Adapter/Varnish.php
new file mode 100644
index 0000000..f85fff2
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/Cache/Adapter/Varnish.php
@@ -0,0 +1,162 @@
+varnishServers)) {
+ $serverConfig = Mage::getStoreConfig('dev/aoestatic/servers');
+ if (strpos($serverConfig, ',') !== false) {
+ // old format - comma-separated list of servers
+ $this->varnishServers = Mage::helper('aoestatic')->trimExplode(",", $serverConfig, true);
+ } else {
+ // new format - newline-separated list of servers
+ $this->varnishServers = Mage::helper('aoestatic')->trimExplode("\n", $serverConfig, true);
+ }
+ }
+ return $this->varnishServers;
+ }
+
+ /**
+ * Purges all cache on all Varnish servers.
+ *
+ * @return array errors if any
+ */
+ public function purgeAll()
+ {
+ return $this->purge(array('R:.*'));
+ }
+
+ /**
+ * Purge an array of urls on all varnish servers.
+ *
+ * @param array $urls
+ * @return array with all errors
+ */
+ public function purge(array $urls)
+ {
+ $actions = [];
+
+ // Separate regex ('R:...') from plain urls
+ $regexPatterns = array();
+ foreach ($urls as $k => $url) {
+ if(strpos($url, 'R:') === 0) {
+ unset($urls[$k]);
+ $regexPatterns[] = substr($url, 2);
+ } else {
+ $actions[] = [
+ 'method' => 'PURGE',
+ 'path' => $url,
+ 'headers' => []
+ ];
+ }
+ }
+
+ if (!empty($regexPatterns)) {
+ $regexPatterns = '((' . implode(')|(', $regexPatterns) . '))';
+ $actions[] = [
+ 'method' => 'BAN',
+ 'path' => '/',
+ 'headers' => ['X-Url' => $regexPatterns]
+ ];
+ }
+
+ return $this->sendRequests($actions);
+ }
+
+ public function purgeTags(array $tags)
+ {
+ // Tag delimiter
+ $td = str_replace(' ', '\x20', preg_quote(Aoe_Static_Model_Cache_Control::TAG_DELIMITER));
+
+ // Part delimiter
+ $pd = str_replace(' ', '\x20', preg_quote(Aoe_Static_Model_Cache_Control::PART_DELIMITER));
+
+ foreach ($tags as $k => $tag) {
+ if (strpos($tag, 'R:') === 0) {
+ $tag = substr($tag, 2);
+ } else {
+ $tag = preg_quote($tag) . "({$pd}[^{$td}]+)?";
+ }
+ $tags[$k] = $tag;
+ }
+
+ $regex = "(?U)(^|{$td})((" . implode(')|(', $tags) . "))($|{$td})";
+
+ return $this->sendRequests([[
+ 'method' => 'BAN',
+ 'path' => '/',
+ 'headers' => ['X-Tags' => $regex]
+ ]]);
+ }
+
+ protected function sendRequests(array $actions)
+ {
+ // Init curl handler
+ $curlHandlers = array(); // keep references for clean up
+ $multiHandler = curl_multi_init();
+
+ foreach ($actions as $action) {
+ foreach ($this->getVarnishServers() as $varnishServer) {
+ $curlHandler = curl_init();
+ curl_setopt($curlHandler, CURLOPT_URL, $varnishServer . '/' . $action['path']);
+ curl_setopt($curlHandler, CURLOPT_CUSTOMREQUEST, $action['method']);
+ curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1);
+ curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, 0);
+ curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, 0);
+ if (count($action['headers'])) {
+ $headers = [];
+ foreach ($action['headers'] as $key => $value) {
+ $headers[] = "$key: $value";
+ }
+ curl_setopt($curlHandler, CURLOPT_HTTPHEADER, $headers);
+ }
+ curl_multi_add_handle($multiHandler, $curlHandler);
+ $curlHandlers[] = $curlHandler;
+ }
+ }
+
+ do {
+ curl_multi_exec($multiHandler, $active);
+ } while ($active);
+
+ $errors = array();
+ // Error handling and clean up
+ foreach ($curlHandlers as $curlHandler) {
+ $info = curl_getinfo($curlHandler);
+
+ if (curl_errno($curlHandler)) {
+ $errors[] = "Cannot purge tag {$info['url']} due to error" . curl_error($curlHandler);
+ } else if ($info['http_code'] != 200 && $info['http_code'] != 404) {
+ $errors[] = "Cannot purge tag {$info['url']}, http code: {$info['http_code']}. curl error: " . curl_error($curlHandler);
+ }
+
+ curl_multi_remove_handle($multiHandler, $curlHandler);
+ curl_close($curlHandler);
+ }
+ curl_multi_close($multiHandler);
+
+ return $errors;
+ }
+
+ /**
+ * sets varnish server urls
+ *
+ * @param string|array $config
+ */
+ public function setConfig($config)
+ {
+ // This adapter reads its configuration from core_config_data instead
+ }
+}
diff --git a/app/code/community/Aoe/Static/Model/Cache/Control.php b/app/code/community/Aoe/Static/Model/Cache/Control.php
new file mode 100755
index 0000000..3f95bd5
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/Cache/Control.php
@@ -0,0 +1,201 @@
+_enabled = true;
+ return $this;
+ }
+
+ /**
+ * @return $this
+ */
+ public function disable()
+ {
+ $this->_enabled = false;
+ return $this;
+ }
+
+ /**
+ * @return boolean
+ */
+ public function isEnabled()
+ {
+ return $this->_enabled;
+ }
+
+ /**
+ * computes minimum max-age
+ *
+ * @param int|array $maxAge
+ */
+ public function addMaxAge($maxAge)
+ {
+ if (!is_array($maxAge)) {
+ $maxAge = array($maxAge);
+ }
+
+ foreach ($maxAge as $timestamp) {
+ if ($timestamp > 0 && (!$this->_maxAge || ($timestamp < $this->_maxAge))) {
+ $this->_maxAge = $timestamp;
+ }
+ }
+ }
+
+ /**
+ * loads specific max-age from database
+ *
+ * @param $request Mage_Core_Controller_Request_Http
+ */
+ public function addCustomUrlMaxAge($request)
+ {
+ // apply custom max-age from db
+ $urls = array($request->getRequestString());
+ $alias = $request->getAlias(Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS);
+ if ($alias) {
+ $urls[] = $alias;
+ }
+ /** @var $customUrlModel Aoe_Static_Model_CustomUrl */
+ $customUrlModel = Mage::getModel('aoestatic/customUrl');
+ $customUrlModel->setStoreId(Mage::app()->getStore()->getId());
+ $customUrlModel->loadByRequestPath($urls);
+
+ if ($customUrlModel->getId() && $customUrlModel->getMaxAge()) {
+ $this->addMaxAge($customUrlModel->getMaxAge());
+ }
+ }
+
+ /**
+ * adds tag(s) to current cache
+ *
+ * @param $tags array|string
+ * @return $this
+ */
+ public function addTag($tags)
+ {
+ if (!is_array($tags)) {
+ $tags = array($tags);
+ }
+
+ foreach ($tags as $tag) {
+ $tag = $this->normalizeTag($tag, true);
+ if (!isset($this->_tags[$tag])) {
+ $this->_tags[$tag] = 0;
+ }
+ $this->_tags[$tag]++;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Parse the requested tag and return a clean version
+ *
+ * @param string $tag
+ * @param bool $withStore
+ *
+ * @return string
+ */
+ public function normalizeTag($tag, $withStore = false)
+ {
+ if(is_array($tag)) {
+ $tag = implode(self::PART_DELIMITER, $tag);
+ }
+
+ $tag = str_replace(array("\r\n", "\r", "\n", self::TAG_DELIMITER), '_', strtoupper(trim($tag)));
+
+ if ($withStore) {
+ $tag .= self::PART_DELIMITER . Mage::app()->getStore()->getId();
+ }
+
+ return $tag;
+ }
+
+ /**
+ * applies cache-headers if enabled is true (default)
+ *
+ * @return $this
+ */
+ public function applyCacheHeaders()
+ {
+ if ($this->_enabled && $this->_maxAge) {
+ $maxAge = (int) $this->_maxAge;
+ $response = Mage::app()->getResponse();
+ $response->setHeader('Cache-Control', 'max-age=' . $maxAge, true);
+ $response->setHeader('Expires', gmdate("D, d M Y H:i:s", time() + $maxAge) . ' GMT', true);
+ $response->setHeader('X-Tags', implode(self::TAG_DELIMITER, array_keys($this->_tags)));
+ $response->setHeader('X-Aoestatic', 'cache', true);
+ $response->setHeader('X-Aoestatic-Lifetime', (int) $maxAge, true);
+ }
+
+ return $this;
+ }
+
+ /**
+ * get current category layer
+ *
+ * @return Mage_Catalog_Model_Layer
+ */
+ protected function _getLayer()
+ {
+ $layer = Mage::registry('current_layer');
+ if ($layer) {
+ return $layer;
+ }
+ return Mage::getSingleton('catalog/layer');
+ }
+
+ /**
+ * collect various possible tags from current products and category/layer pages
+ *
+ * @return $this
+ */
+ public function collectTags()
+ {
+ $tags = array();
+ $product = Mage::registry('product');
+ if ($product) {
+ $tags[] = 'product-' . $product->getId();
+ //add child products tags
+ if ($product->getTypeId() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) {
+ $childProductsIds = $product->getTypeInstance()->getUsedProductIds();
+ foreach($childProductsIds as $id) {
+ $tags[] = 'product-' . $id;
+ }
+ }
+ }
+ if (($layer = $this->_getLayer()) && ($layer->getCurrentCategory()->getId() != $layer->getCurrentStore()->getRootCategoryId()) && ($layer->apply()->getProductCollection())) {
+ /** @var Mage_Catalog_Model_Layer $layer */
+ $ids = $layer->getProductCollection()->getLoadedIds();
+ foreach ($ids as $id) {
+ $tags[] = 'product-' . $id;
+ }
+ }
+ if (Mage::registry('current_category')) {
+ /** @var Mage_Catalog_Model_Category $currentCategory */
+ $currentCategory = Mage::registry('current_category');
+ $tags[] = 'category-' . $currentCategory->getId();
+ }
+ $this->addTag($tags);
+ return $this;
+ }
+}
diff --git a/app/code/community/Aoe/Static/Model/Cache/Marker.php b/app/code/community/Aoe/Static/Model/Cache/Marker.php
new file mode 100644
index 0000000..7802435
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/Cache/Marker.php
@@ -0,0 +1,98 @@
+_config = Mage::getSingleton('aoestatic/config');
+ }
+
+ public function addMarkerValues($markers)
+ {
+ if (!is_array($markers)) {
+ $markers = array($markers);
+ }
+
+ $this->_markersValues = array_merge($this->_markersValues, $markers);
+ }
+
+ /**
+ * Replaces markers in the $value, saves calculated value to the local cache
+ *
+ * @param string $value
+ * @return string
+ */
+ public function replaceMarkers($value)
+ {
+ $matches = array();
+ preg_match_all('|###[^#]+###|', $value, $matches);
+ $markersWithoutValues = array_diff($matches[0], array_keys($this->_markersValues));
+ foreach($markersWithoutValues as $marker) {
+ $this->_markersValues[$marker] = $this->getMarkerValue($marker);
+ }
+ $value = str_replace(array_keys($this->_markersValues), array_values($this->_markersValues), $value);
+ return $value;
+ }
+
+ /**
+ * Returns value of a given marker
+ *
+ * @param string $marker
+ * @return string
+ */
+ public function getMarkerValue($marker)
+ {
+ $markerValue = $marker;
+ if (isset($this->_markersValues[$marker]) && $this->_markersValues[$marker] !== NULL) {
+ $markerValue = $this->_markersValues[$marker];
+ } elseif ($this->_config->getMarkerCallback($marker)) {
+ $markerValue = $this->executeCallback($this->_config->getMarkerCallback($marker));
+ }
+ return (string)$markerValue;
+ }
+
+ /**
+ * Executes method defined in the marker callback configuration and returns the result
+ *
+ * @param string $callbackString
+ * @return mixed
+ */
+ public function executeCallback($callbackString)
+ {
+ $result = "";
+ try {
+ if ($callbackString) {
+ if (!preg_match(Mage_Cron_Model_Observer::REGEX_RUN_MODEL, (string)$callbackString, $run)) {
+ Mage::throwException('Invalid model/method definition, expecting "model/class::method".');
+ }
+ if (!($model = Mage::getModel($run[1])) || !method_exists($model, $run[2])) {
+ Mage::throwException('Invalid callback: %s::%s does not exist', $run[1], $run[2]);
+ }
+ $callback = array($model, $run[2]);
+ $arguments = array();
+ }
+ if (empty($callback)) {
+ Mage::throwException(Mage::helper('cron')->__('No callbacks found for marker'));
+ }
+ $result = call_user_func_array($callback, $arguments);
+ } catch (Exception $e) {
+ Mage::logException($e);
+ }
+ return $result;
+ }
+
+}
diff --git a/app/code/community/Aoe/Static/Model/Config.php b/app/code/community/Aoe/Static/Model/Config.php
new file mode 100644
index 0000000..ac20853
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/Config.php
@@ -0,0 +1,144 @@
+';
+
+ /**
+ * @var null|array
+ */
+ protected $_markers = null;
+
+ /**
+ * Class constructor
+ * load cache configuration
+ *
+ * @param string $sourceData Source data
+ * @SuppressWarnings
+ */
+ public function __construct($sourceData = null)
+ {
+ $tags = array(self::CACHE_TAG);
+ $useCache = Mage::app()->useCache('config');
+ $this->setCacheId(self::CACHE_ID);
+ $this->setCacheTags($tags);
+ if ($useCache && ($cache = Mage::app()->loadCache(self::CACHE_ID))) {
+ parent::__construct($cache);
+ } else {
+ parent::__construct(self::CONFIGURATION_TEMPLATE);
+ Mage::getConfig()->loadModulesConfiguration(self::CONFIGURATION_FILENAME, $this);
+ if ($useCache) {
+ $xmlString = $this->getXmlString();
+ Mage::app()->saveCache($xmlString, self::CACHE_ID, $tags);
+ }
+ }
+ }
+
+ /**
+ * Get action configuration
+ *
+ * @param string $fullActionName Full action name
+ * @return false|Mage_Core_Model_Config_Element
+ */
+ public function getActionConfiguration($fullActionName)
+ {
+ $configuration = $this->getNode('aoe_static/' . $fullActionName);
+ if (!$configuration || (1 == $configuration->disabled)) {
+
+ return false;
+ }
+ $use = (string) $configuration->use;
+ if ($use) {
+ $configuration = $this->getActionConfiguration($use);
+ }
+
+ return $configuration;
+ }
+
+ /**
+ * @return Varien_Simplexml_Element
+ */
+ public function getMarkersCallbackConfiguration()
+ {
+ if (is_null($this->_markers)) {
+ $this->_markers = $this->getNode('aoe_static/default/markers');
+ }
+
+ return $this->_markers;
+ }
+
+ /**
+ * Get callback string like some_module/fooclass::getValue for a given marker name
+ * @param string $marker Marker string
+ * @return string callback
+ */
+ public function getMarkerCallback($marker)
+ {
+ $callback = '';
+ $configuration = $this->getMarkersCallbackConfiguration();
+ $markerWithoutHash = str_replace('#', '',$marker);
+ if (isset($configuration->$markerWithoutHash->valueCallback)) {
+ $callback = (string) $configuration->$markerWithoutHash->valueCallback;
+ }
+
+ return $callback;
+ }
+
+ /**
+ * fetch configured adapters
+ *
+ * @return array
+ */
+ public function getAdapters()
+ {
+ $adapters = $this->getNode('aoe_static_purging/adapters');
+ if (!$adapters) {
+
+ return array();
+ }
+
+ return $adapters->asArray();
+ }
+
+ /**
+ * @return bool
+ */
+ public function useAsyncCache()
+ {
+ return Mage::getStoreConfigFlag('dev/aoestatic/use_aoe_asynccache');
+ }
+
+ /**
+ * @return bool
+ */
+ public function isLoadCurrentProduct()
+ {
+ return Mage::getStoreConfigFlag('dev/aoestatic/load_current_product');
+ }
+}
diff --git a/app/code/community/Aoe/Static/Model/CustomUrl.php b/app/code/community/Aoe/Static/Model/CustomUrl.php
new file mode 100755
index 0000000..713b38a
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/CustomUrl.php
@@ -0,0 +1,67 @@
+_init('aoestatic/customUrl');
+ }
+
+ /**
+ * Load url max-age information for request
+ * If $path is array - we must load possible records and choose one matching earlier record in array
+ *
+ * @param array|string $path
+ * @return $this
+ */
+ public function loadByRequestPath($path)
+ {
+ $this->setId(null);
+ $this->_getResource()->loadByRequestPath($this, $path);
+ $this->_afterLoad();
+ $this->setOrigData();
+ $this->_hasDataChanges = false;
+ return $this;
+ }
+
+ /**
+ * Delete custom urls with given ids
+ *
+ * @param array $customUrlIds
+ * @return $this
+ */
+ public function deleteCustomUrls(array $customUrlIds)
+ {
+ $this->getResource()->deleteCustomUrls($customUrlIds);
+ }
+
+ /**
+ * purge URL from static cache to make sure the max-age is correct set for the cache server
+ *
+ * @return $this
+ */
+ protected function _afterSave()
+ {
+ $url = $this->getRequestPath();
+ if (Mage::getStoreConfig('web/url/use_store')) {
+ $url = Mage::app()->getStore($this->getStoreId())->getCode() . '/' . $url;
+ }
+
+ Mage::helper('aoestatic')->purge(array($url));
+
+ return $this;
+ }
+}
diff --git a/app/code/community/Aoe/Static/Model/Index/Observer.php b/app/code/community/Aoe/Static/Model/Index/Observer.php
new file mode 100644
index 0000000..fb104ea
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/Index/Observer.php
@@ -0,0 +1,161 @@
+
+ * @license none none
+ * @link www.aoe.com
+ */
+
+class Aoe_Static_Model_Index_Observer
+{
+
+ /**
+ * Invalidate the cache on receiving full reindex events
+ *
+ * @param Varien_Event_Observer $observer The observer
+ * @return Aoe_Static_Model_Index_Observer
+ */
+ public function invalidateCacheAfterFullReindex($observer)
+ {
+ Mage::app()->getCacheInstance()->invalidateType(array('aoestatic'));
+ }
+
+ /**
+ * Clean product cache after partial reindex event
+ *
+ * @param Varien_Event_Observer $observer The observer
+ * @return Aoe_Static_Model_Index_Observer
+ */
+ public function cleanProductsCacheAfterPartialReindex($observer)
+ {
+ if (!$this->_useAoeStaticCache()) {
+ return $this;
+ }
+
+ $entityIds = $observer->getEvent()->getProductIds();
+ if (!is_array($entityIds) || empty($entityIds)) {
+ return $this;
+ }
+
+ $skippableProductIds = Mage::registry(Aoe_Static_Model_Observer::REGISTRY_SKIPPABLE_NAME);
+ if (null == $skippableProductIds) {
+ $skippableProductIds = [];
+ }
+
+ $tags = [];
+ foreach ($entityIds as $_entityId) {
+ if (in_array($_entityId, $skippableProductIds)) {
+ continue;
+ }
+
+ $tags[] = $this->_getCacheControl()->normalizeTag(['product', $_entityId]);
+ }
+
+ if (!empty($tags)) {
+ $helper = $this->_getDataHelper();
+ $helper->purgeTags($tags);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Clean categories cache after partial reindex event
+ *
+ * @param Varien_Event_Observer $observer The observer
+ * @return Aoe_Static_Model_Index_Observer
+ */
+ public function cleanCategoriesCacheAfterPartialReindex($observer)
+ {
+ if (!$this->_useAoeStaticCache()) {
+ return $this;
+ }
+
+ $entityIds = $observer->getEvent()->getCategoryIds();
+ if (!is_array($entityIds) || empty($entityIds)) {
+ return $this;
+ }
+
+ $tags = [];
+ foreach ($entityIds as $_entityId) {
+ $tags[] = $this->_getCacheControl()->normalizeTag(['category', $_entityId]);
+ }
+
+ $helper = $this->_getDataHelper();
+ $helper->purgeTags($tags);
+
+ return $this;
+ }
+
+ /**
+ * Clean cache by tags created on partial reindexes
+ *
+ * @param Varien_Event_Observer $observer The observer
+ * @return Aoe_Static_Model_Index_Observer
+ */
+ public function cleanCacheByTags($observer)
+ {
+ if (!$this->_useAoeStaticCache()) {
+ return $this;
+ }
+
+ $tags = $observer->getEvent()->getTags();
+ if (empty($tags)) {
+ return $this;
+ }
+
+ $purgeTags = [];
+ foreach ($tags as $_tag) {
+ $tagFields = explode('_', $_tag);
+ if (3 == count($tagFields)) {
+ if (in_array($tagFields[1], array('product', 'category'))) {
+ $purgeTags[] = $this->_getCacheControl()->normalizeTag(array($tagFields[1], $tagFields[2]));
+ }
+ }
+ }
+
+ if (empty($purgeTags)) {
+ return $this;
+ }
+
+ $this->_getDataHelper()->purgeTags($purgeTags);
+
+ return $this;
+ }
+
+ /**
+ * Determine if aoestatic is enabled as cache
+ *
+ * @return boolean
+ */
+ protected function _useAoeStaticCache()
+ {
+ return Mage::app()->useCache('aoestatic');
+ }
+
+ /**
+ * Get the modules data helper
+ *
+ * @return Aoe_Static_Helper_Data
+ */
+ protected function _getDataHelper()
+ {
+ return Mage::helper('aoestatic');
+ }
+
+ /**
+ * Get cache control singleton
+ *
+ * @return Aoe_Static_Model_Cache_Control
+ */
+ protected function _getCacheControl()
+ {
+ return Mage::getSingleton('aoestatic/cache_control');
+ }
+
+}
diff --git a/app/code/community/Aoe/Static/Model/Observer.php b/app/code/community/Aoe/Static/Model/Observer.php
new file mode 100755
index 0000000..f010e07
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/Observer.php
@@ -0,0 +1,469 @@
+_config = Mage::getSingleton('aoestatic/config');
+ }
+
+ /**
+ * Set custom headers and cookies
+ *
+ * @param Varien_Event_Observer $observer
+ * @return Aoe_Static_Model_Observer
+ */
+ public function processPostDispatch(Varien_Event_Observer $observer)
+ {
+ //Check if caching is enabled for this dispatch
+ if (!Mage::getSingleton('aoestatic/cache_control')->isEnabled()) {
+ return $this;
+ }
+
+ // check if we have messages to display
+ $this->messagesToShow = $this->checkForMessages();
+
+ /* @var $event Varien_Event */
+ $event = $observer->getEvent();
+ /* @var $controllerAction Mage_Core_Controller_Varien_Action */
+ $controllerAction = $event->getControllerAction();
+ $fullActionName = $controllerAction->getFullActionName();
+
+ /* @var $response Mage_Core_Controller_Response_Http */
+ $response = $controllerAction->getResponse();
+
+ // gather information for replace array
+ $customerName = '';
+ $loggedIn = '0';
+ $session = Mage::getSingleton('customer/session');
+ /* @var $session Mage_Customer_Model_Session */
+ if ($session->isLoggedIn()) {
+ $loggedIn = '1';
+ $customerName = Mage::helper('core')->escapeHtml(trim($session->getCustomer()->getName()));
+ }
+
+ /** @var Aoe_Static_Model_Cache_Marker $cacheMarker */
+ $cacheMarker = Mage::getSingleton('aoestatic/cache_marker');
+ $cacheMarker->addMarkerValues(array(
+ '###FULLACTIONNAME###' => $fullActionName,
+ '###CUSTOMERNAME###' => $customerName,
+ '###ISLOGGEDIN###' => $loggedIn,
+ '###NUMBEROFITEMSINCART###' => Mage::helper('checkout/cart')->getSummaryCount(),
+ ));
+
+ // apply default configuration in any case
+ $defaultConf = $this->_config->getActionConfiguration('default');
+ if ($defaultConf) {
+ $this->applyConf($defaultConf, $response);
+ }
+
+ // check if there is a configured configuration for this full action name
+ $conf = $this->_config->getActionConfiguration($fullActionName);
+ if (!$conf) {
+ // load the "uncached" configuration if no other configuration was found
+ $conf = $this->_config->getActionConfiguration('uncached');
+ }
+
+ $request = $controllerAction->getRequest();
+ // apply the configuration
+ if ($conf && $request->isDispatched()) {
+ $this->applyConf($conf, $response);
+ }
+
+ if (!$this->messagesToShow) {
+ /** @var Aoe_Static_Model_Cache_Control $cacheControl */
+ $cacheControl = Mage::getSingleton('aoestatic/cache_control');
+ $cacheControl->addCustomUrlMaxAge($controllerAction->getRequest());
+ $cacheControl->collectTags();
+ $cacheControl->applyCacheHeaders();
+ }
+
+ if(Mage::getStoreConfigFlag('dev/aoestatic/debug')) {
+ $response->setHeader('X-Aoestatic-Debug', 'true');
+ }
+
+ return $this;
+ }
+
+ /**
+ * Apply configuration (set headers and cookies)
+ *
+ * @param Mage_Core_Model_Config_Element $conf
+ * @param Mage_Core_Controller_Response_Http $response
+ */
+ protected function applyConf(Mage_Core_Model_Config_Element $conf, Mage_Core_Controller_Response_Http $response)
+ {
+ /** @var Aoe_Static_Model_Cache_Marker $cacheMarker */
+ $cacheMarker = Mage::getSingleton('aoestatic/cache_marker');
+ if (property_exists($conf, 'headers')) {
+ foreach ($conf->headers->children() as $key => $value) {
+ // skip aoestatic header if we have messages to display
+ if ($this->messagesToShow && ($key == 'aoestatic')) {
+ continue;
+ }
+ $value = $cacheMarker->replaceMarkers($value);
+ $response->setHeader($key, $value, true);
+ }
+ }
+ if (property_exists($conf, 'cookies') && $conf->cookies) {
+ $cookie = Mage::getModel('core/cookie');
+ /* @var $cookie Mage_Core_Model_Cookie */
+ foreach ($conf->cookies->children() as $name => $cookieConf) {
+ if (1 == $cookieConf->disabled) {
+ continue;
+ }
+ $scope = $cookieConf->scope ? (string) $cookieConf->scope : 'customer';
+ $value = (string) $cookieConf->value;
+ $value = $cacheMarker->replaceMarkers($value);
+ $period = $cookieConf->period ? (string) $cookieConf->period : null;
+ $path = $cookieConf->path ? (string) $cookieConf->path : null;
+ $domain = $cookieConf->domain ? (string) $cookieConf->domain : null;
+ $secure = $cookieConf->secure ? filter_var($cookieConf->secure, FILTER_VALIDATE_BOOLEAN) : null;
+ $httponly = $cookieConf->httponly ? filter_var($cookieConf->httponly, FILTER_VALIDATE_BOOLEAN) : null;
+
+ $scopePart = '';
+ if (!in_array($scope, array('customer', 'global', 'website', 'store'))) {
+ Mage::log("[AOE_Static::applyConf] Invalid scope '$scope'", Zend_Log::ERR);
+ } else {
+ if ($scope == 'customer') {
+ $customerScope = (int) Mage::getStoreConfig('customer/account_share/scope');
+ $scope = $customerScope == 0 ? 'global' : 'website';
+ }
+ if ($scope == 'global') {
+ $scopePart = 'g';
+ } elseif ($scope == 'website') {
+ $scopePart = 'w'.Mage::app()->getWebsite()->getId();
+ } elseif ($scope == 'store') {
+ $scopePart = 's'.Mage::app()->getStore()->getId();
+ }
+ }
+
+ $name = 'aoestatic_' . $scopePart . '_' . $name;
+
+ $cookie->set($name, $value, $period, $path, $domain, $secure, $httponly);
+ }
+ }
+ if (property_exists($conf, 'cache') && $conf->cache) {
+ Mage::getSingleton('aoestatic/cache_control')->addMaxAge($conf->cache->maxage);
+ }
+ }
+
+ /**
+ * Add layout handle 'aoestatic_cacheable' or 'aoestatic_notcacheable'
+ *
+ * @param Varien_Event_Observer $observer
+ */
+ public function beforeLoadLayout(Varien_Event_Observer $observer)
+ {
+ /** @var Mage_Core_Model_Layout $layout */
+ $layout = $observer->getLayout();
+ if (!$layout instanceof Mage_Core_Model_Layout) {
+ return;
+ }
+
+ /** @var Mage_Core_Controller_Varien_Action $action */
+ $action = $observer->getAction();
+ if (!$action instanceof Mage_Core_Controller_Varien_Action) {
+ return;
+ }
+
+ $this->checkForMessages();
+
+ $layout->getUpdate()->addHandle($this->getHandles($action->getFullActionName()));
+ }
+
+ /**
+ * Checks if there are messages to display
+ *
+ * @return bool
+ */
+ protected function checkForMessages()
+ {
+ if (
+ (false === $this->messagesToShow) &&
+ (Mage::app()->getLayout()->getMessagesBlock()->getMessageCollection()->count() > 0)
+ ) {
+ $this->messagesToShow = true;
+ }
+ return $this->messagesToShow;
+ }
+
+ /**
+ * collect tags
+ *
+ * @param Varien_Event_Observer $observer
+ */
+ public function coreBlockAbstractToHtmlAfter(Varien_Event_Observer $observer)
+ {
+ $block = $observer->getBlock();
+
+ if ($block instanceof Mage_Cms_Block_Block && $block->getBlock()) {
+ Mage::getSingleton('aoestatic/cache_control')->addTag('block-' . $block->getBlock()->getId());
+ } else if ($block instanceof Mage_Cms_Block_Page) {
+ Mage::getSingleton('aoestatic/cache_control')->addTag('page-' . ($block->getPageId() ?: ($block->getPage() ? $block->getPage()->getId() : Mage::getSingleton('cms/page')->getId())));
+ } else if (($block instanceof Mage_Catalog_Block_Product_Abstract) && $block->getProductCollection()) {
+ $tags = array();
+ foreach ($block->getProductCollection()->getLoadedIds() as $id) {
+ $tags[] = 'product-' . $id;
+ }
+ Mage::getSingleton('aoestatic/cache_control')->addTag($tags);
+ }
+ }
+
+ /**
+ * manual cache purging of specified URLs
+ *
+ * @param Varien_Event_Observer $event
+ */
+ public function controllerActionPredispatchAdminhtmlCacheIndex(Varien_Event_Observer $event)
+ {
+ /** @var Mage_Core_Controller_Request_Http $request */
+ $request = $event->getControllerAction()->getRequest();
+
+ if ($purgeUrls = $request->getParam('aoe_purge_urls')) {
+ $purgeUrls = array_map('trim', explode("\n", trim($purgeUrls)));
+
+ foreach (Mage::helper('aoestatic')->purge($purgeUrls, false) as $message) {
+ Mage::getSingleton('adminhtml/session')->addNotice($message);
+ }
+
+ /** @var Mage_Core_Controller_Response_Http $response */
+ $response = $event->getControllerAction()->getResponse();
+ $response->setRedirect(Mage::getModel('adminhtml/url')->getUrl('*/cache/index', array()));
+ $response->sendResponse();
+ exit;
+ }
+
+ if ($purgeTags = $request->getParam('aoe_purge_tags')) {
+ $purgeTags = array_map('trim', explode("\n", trim($purgeTags)));
+
+ foreach (Mage::helper('aoestatic')->purgeTags($purgeTags) as $message) {
+ Mage::getSingleton('adminhtml/session')->addNotice($message);
+ }
+
+ /** @var Mage_Core_Controller_Response_Http $response */
+ $response = $event->getControllerAction()->getResponse();
+ $response->setRedirect(Mage::getModel('adminhtml/url')->getUrl('*/cache/index', array()));
+ $response->sendResponse();
+ exit;
+ }
+ }
+
+ /**
+ * @see Mage_Core_Model_Cache
+ *
+ * @param Mage_Core_Model_Observer $observer
+ * @return Aoe_Static_Model_Observer
+ */
+ public function catalogCategorySaveCommitAfter($observer)
+ {
+ /** @var $category Mage_Catalog_Model_Category */
+ $category = $observer->getCategory();
+ if ($category->getData('include_in_menu')) {
+ // notify user that varnish needs to be refreshed
+ Mage::app()->getCacheInstance()->invalidateType(array('aoestatic'));
+ }
+ return $this;
+ }
+
+ /**
+ * Observer for cataloginventory_stock_item_save_after
+ * checking for product going out of stock
+ *
+ * This is needed for catching product availability change after it was sold out
+ *
+ * @param Varien_Event_Observer $observer
+ */
+ public function productOutOfStock($observer) {
+ $stockItem = $observer->getItem();
+ if (! $stockItem instanceof Mage_CatalogInventory_Model_Stock_Item) {
+ return;
+ }
+ $originalStockData = $stockItem->getOrigData('is_in_stock');
+
+ if ((!is_null($originalStockData)
+ && $stockItem->getIsInStock() != $originalStockData
+ && $stockItem->getProductId() > 0)
+ || $stockItem->getStockStatusChangedAuto()
+ ) {
+ $tagsToPurge = array();
+ /** @var $helper Aoe_Static_Helper_Data */
+ $helper = Mage::helper('aoestatic');
+ $tagsToPurge[] = 'product-' . $stockItem->getProductId();
+ $categoryIds = Mage::getModel('catalog/product')->setId($stockItem->getProductId())->getCategoryIds();
+ foreach($categoryIds as $id) {
+ $tagsToPurge[] = 'category-' . $id;
+ }
+ $helper->purgeTags($tagsToPurge);
+ }
+ }
+
+ /**
+ * shows message in case admin session exists
+ *
+ * @param string $type message type (error/success/notice)
+ * @param string $message actual message
+ * @return bool
+ */
+ protected function _addSessionMessage($type, $message)
+ {
+ if (!Mage::registry('_singleton/adminhtml/session')) {
+ return false;
+ }
+
+ if ($type == 'error') {
+ Mage::getSingleton('adminhtml/session')->addError($message);
+ } else if ($type == 'success') {
+ Mage::getSingleton('adminhtml/session')->addSuccess($message);
+ } else {
+ Mage::getSingleton('adminhtml/session')->addNotice($message);
+ }
+ return true;
+ }
+
+ /**
+ * Listens to application_clean_cache event and gets notified when a product/category/cms model is saved
+ *
+ * @param $observer Mage_Core_Model_Observer
+ * @return Aoe_Static_Model_Observer
+ */
+ public function applicationCleanCache($observer)
+ {
+ // if Varnish is not enabled on admin don't do anything
+ if (!Mage::app()->useCache('aoestatic')) {
+ return $this;
+ }
+
+ /** @var Aoe_Static_Helper_Data $helper */
+ $helper = Mage::helper('aoestatic');
+ $tags = $observer->getTags();
+ $tags = array_filter(array_unique((array)$tags));
+
+ // check if we should process tags from product which has no relevant changes
+ $skippableProductIds = Mage::registry(self::REGISTRY_SKIPPABLE_NAME);
+ if (null !== $skippableProductIds) {
+ foreach ((array) $tags as $tag) {
+ if (preg_match('/^catalog_product_(\d+)?/', $tag, $match)) {
+ if (isset($match[1]) && in_array($match[1], $skippableProductIds)) {
+ return $this;
+ }
+ }
+ }
+ }
+
+ if (empty($tags)) {
+ $errors = $helper->purgeAll();
+ if (!empty($errors)) {
+ $this->_addSessionMessage('error', $helper->__("Static Purge failed"));
+ } else {
+ $this->_addSessionMessage('success', $helper->__("Static Purge succeed"));
+ }
+
+ return $this;
+ }
+
+ $purgetags = array();
+
+ /** @var Aoe_Static_Model_Cache_Control $cacheControl */
+ $cacheControl = Mage::getSingleton('aoestatic/cache_control');
+
+ // compute the urls for affected entities
+ foreach ($tags as $tag) {
+ //catalog_product_100 or catalog_category_186
+ $tag_fields = explode('_', $tag);
+ if (count($tag_fields) == 3) {
+ if (in_array($tag_fields[1], array('product', 'category', 'page', 'block'))) {
+ $purgetags[] = $cacheControl->normalizeTag(array($tag_fields[1], $tag_fields[2]), false);
+ }
+ }
+ }
+
+ if (!empty($purgetags)) {
+ $errors = $helper->purgeTags($purgetags);
+ if (!empty($errors)) {
+ $this->_addSessionMessage('error', $helper->__("Some Static purges failed: ") . implode(" ", $errors));
+ } else {
+ $count = count($purgetags);
+ if ($count > 5) {
+ $purgetags = array_slice($purgetags, 0, 5);
+ $purgetags[] = '...';
+ $purgetags[] = $helper->__("(Total number of purged urls: %d)", $count);
+ }
+ $this->_addSessionMessage('success', $helper->__("Tag purges have been submitted successfully: ") . implode(" ", $purgetags));
+ }
+ }
+ return $this;
+ }
+
+ public function controllerActionPredispatchAdminhtmlCacheMassRefresh(Varien_Event_Observer $observer)
+ {
+ /** @var Mage_Core_Controller_Request_Http $request */
+ $request = $observer->getControllerAction()->getRequest();
+ $types = $request->getParam('types');
+
+ if (is_array($types) && in_array('aoestatic', $types)) {
+ foreach (Mage::helper('aoestatic')->purgeAll() as $message) {
+ Mage::getSingleton('adminhtml/session')->addNotice($message);
+ }
+ }
+ }
+
+ /**
+ * Generate a list of additional layout handles based on the current full action name
+ *
+ * @param string $fullActionName
+ *
+ * @return string[]
+ */
+ protected function getHandles($fullActionName)
+ {
+ $handles = array();
+
+ // apply default configuration first
+ $conf = $this->_config->getActionConfiguration('default');
+ if ($conf && isset($conf->handles) && $conf->handles instanceof Mage_Core_Model_Config_Element) {
+ foreach($conf->handles->children() as $handle => $node) {
+ $enabled = !(isset($node['disabled']) && (bool)(string)$node['disabled']);
+ $handles[$handle] = $enabled;
+ }
+ }
+
+ // check if there is a configuration for this full action name
+ $conf = $this->_config->getActionConfiguration($fullActionName);
+ if (!$conf) {
+ // load the "uncached" configuration if no other configuration was found
+ $conf = $this->_config->getActionConfiguration('uncached');
+ }
+ if ($conf && isset($conf->handles) && $conf->handles instanceof Mage_Core_Model_Config_Element) {
+ foreach($conf->handles->children() as $handle => $node) {
+ $enabled = !(isset($node['disabled']) && (bool)(string)$node['disabled']);
+ $handles[$handle] = $enabled;
+ }
+ }
+
+ // Filter using the enabled/disabled flag and then grab the remaining array keys
+ $handles = array_keys(array_filter($handles));
+
+ return $handles;
+ }
+}
diff --git a/app/code/community/Aoe/Static/Model/Resource/CustomUrl.php b/app/code/community/Aoe/Static/Model/Resource/CustomUrl.php
new file mode 100644
index 0000000..f636e33
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/Resource/CustomUrl.php
@@ -0,0 +1,123 @@
+_init('aoestatic/custom_url', 'custom_url_id');
+ }
+
+ /**
+ * Initialize array fields
+ *
+ * @return $this
+ */
+ protected function _initUniqueFields()
+ {
+ $this->_uniqueFields = array(
+ array(
+ 'field' => array('request_path','store_id'),
+ 'title' => Mage::helper('aoestatic')->__('Request Path for Specified Store'),
+ )
+ );
+ return $this;
+ }
+
+ /**
+ * Retrieve select object for load object data
+ *
+ * @param string $field
+ * @param mixed $value
+ * @param Aoe_Static_Model_CustomUrl $object
+ * @return Zend_Db_Select
+ */
+ protected function _getLoadSelect($field, $value, $object)
+ {
+ /** @var $select Varien_Db_Select */
+ $select = parent::_getLoadSelect($field, $value, $object);
+
+ if (!is_null($object->getStoreId())) {
+ $select->where('store_id IN(?)', array(Mage_Core_Model_App::ADMIN_STORE_ID, $object->getStoreId()));
+ $select->order('store_id ' . Varien_Db_Select::SQL_DESC);
+ $select->limit(1);
+ }
+
+ return $select;
+ }
+
+ /**
+ * Load max-age information for given custom url
+ * If $path is array - we must load all possible records and choose one matching earlier record in array
+ *
+ * @param Aoe_Static_Model_CustomUrl $object
+ * @param array|string $path
+ * @return $this
+ */
+ public function loadByRequestPath(Aoe_Static_Model_CustomUrl $object, $path)
+ {
+ if (!is_array($path)) {
+ $path = array($path);
+ }
+
+ $pathBind = array();
+ foreach ($path as $key => $url) {
+ $pathBind['path' . $key] = $url;
+ }
+ // Form select
+ $adapter = $this->_getReadAdapter();
+ $select = $adapter->select()
+ ->from($this->getMainTable())
+ ->where('request_path IN (:' . implode(', :', array_flip($pathBind)) . ')')
+ ->where('store_id IN(?)', array(Mage_Core_Model_App::ADMIN_STORE_ID, (int)$object->getStoreId()));
+
+ $items = $adapter->fetchAll($select, $pathBind);
+
+ // Go through all found records and choose one with lowest penalty - earlier path in array, concrete store
+ $mapPenalty = array_flip(array_values($path)); // we got mapping array(path => index), lower index - better
+ $currentPenalty = null;
+ $foundItem = null;
+ foreach ($items as $item) {
+ if (!array_key_exists($item['request_path'], $mapPenalty)) {
+ continue;
+ }
+ $penalty = $mapPenalty[$item['request_path']] << 1 + ($item['store_id'] ? 0 : 1);
+ if (!$foundItem || $currentPenalty > $penalty) {
+ $foundItem = $item;
+ $currentPenalty = $penalty;
+ if (!$currentPenalty) {
+ break; // Found best matching item with zero penalty, no reason to continue
+ }
+ }
+ }
+
+ // Set data and finish loading
+ if ($foundItem) {
+ $object->setData($foundItem);
+ }
+
+ // Finish
+ $this->unserializeFields($object);
+ $this->_afterLoad($object);
+
+ return $this;
+ }
+
+ /**
+ * Delete custom urls with given ids
+ *
+ * @param array $customUrlIds
+ * @return $this
+ */
+ public function deleteCustomUrls(array $customUrlIds)
+ {
+ $this->_getWriteAdapter()->delete($this->getMainTable(),
+ array('custom_url_id IN(?)' => $customUrlIds)
+ );
+
+ return $this;
+ }
+}
diff --git a/app/code/community/Aoe/Static/Model/Resource/CustomUrl/Collection.php b/app/code/community/Aoe/Static/Model/Resource/CustomUrl/Collection.php
new file mode 100644
index 0000000..8724ddc
--- /dev/null
+++ b/app/code/community/Aoe/Static/Model/Resource/CustomUrl/Collection.php
@@ -0,0 +1,34 @@
+_init('aoestatic/customUrl');
+ }
+
+ /**
+ * Filter collections by stores
+ *
+ * @param mixed $store
+ * @param bool $withAdmin
+ * @return $this
+ */
+ public function addStoreFilter($store, $withAdmin = true)
+ {
+ if (!is_array($store)) {
+ $store = array(Mage::app()->getStore($store)->getId());
+ }
+ if ($withAdmin) {
+ $store[] = 0;
+ }
+
+ $this->addFieldToFilter('store_id', array('in' => $store));
+
+ return $this;
+ }
+}
diff --git a/app/code/community/Aoe/Static/controllers/Adminhtml/Aoestatic/CustomUrlController.php b/app/code/community/Aoe/Static/controllers/Adminhtml/Aoestatic/CustomUrlController.php
new file mode 100644
index 0000000..6dc5964
--- /dev/null
+++ b/app/code/community/Aoe/Static/controllers/Adminhtml/Aoestatic/CustomUrlController.php
@@ -0,0 +1,247 @@
+loadLayout()
+ ->_setActiveMenu('system/aoestatic_customUrl')
+ ->_addBreadcrumb(
+ Mage::helper('aoestatic')->__('System'),
+ Mage::helper('aoestatic')->__('System')
+ )
+ ->_addBreadcrumb(
+ Mage::helper('aoestatic')->__('Urls max-age management'),
+ Mage::helper('aoestatic')->__('Urls max-age management')
+ );
+ return $this;
+ }
+
+ /**
+ * Index action
+ */
+ public function indexAction()
+ {
+ $this->_title($this->__('System'))
+ ->_title($this->__('Urls max-age management'));
+
+ $this->_initAction();
+ $this->renderLayout();
+ }
+
+ /**
+ * Create new custom url
+ */
+ public function newAction()
+ {
+ // the same form is used to create and edit
+ $this->_forward('edit');
+ }
+
+ /**
+ * Edit custom url
+ */
+ public function editAction()
+ {
+ $this->_title($this->__('System'))
+ ->_title($this->__('Urls max-age management'));
+
+ /** @var $model Aoe_Static_Model_CustomUrl */
+ $model = Mage::getModel('aoestatic/customUrl');
+
+ $customUrlId = $this->getRequest()->getParam('id');
+ if ($customUrlId) {
+ $model->load($customUrlId);
+
+ if (!$model->getId()) {
+ $this->_getSession()->addError(
+ Mage::helper('aoestatic')->__('Custom url does not exist.')
+ );
+ $this->_redirect('*/*/');
+ return;
+ }
+ // prepare title
+ $breadCrumb = Mage::helper('aoestatic')->__('Edit custom url (ID: %d)', $model->getId());
+ } else {
+ $breadCrumb = Mage::helper('aoestatic')->__('New Item');
+ }
+
+ // Init breadcrumbs
+ $this->_title($breadCrumb);
+ $this->_initAction()->_addBreadcrumb($breadCrumb, $breadCrumb);
+
+ $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
+ if (!empty($data)) {
+ $model->addData($data);
+ }
+
+ Mage::register('custom_url', $model);
+
+ $this->renderLayout();
+ }
+
+ /**
+ * Save action
+ */
+ public function saveAction()
+ {
+ $redirectPath = '*/*';
+ $redirectParams = array();
+
+ // check if data sent
+ $data = $this->getRequest()->getPost();
+ if ($data) {
+ // init model and set data
+ /** @var $model Aoe_Static_Model_CustomUrl */
+ $model = Mage::getModel('aoestatic/customUrl');
+
+ // if custom url exists, try to load it
+ $customUrlId = $this->getRequest()->getParam('id');
+ if ($customUrlId) {
+ $model->load($customUrlId);
+ }
+
+ $model->addData($data);
+
+ try {
+ $hasError = false;
+
+ // save the data
+ $model->save();
+
+ // display success message
+ $this->_getSession()->addSuccess(
+ Mage::helper('aoestatic')->__('Custom url has been saved.')
+ );
+
+ // check if 'Save and Continue'
+ if ($this->getRequest()->getParam('back')) {
+ $redirectPath = '*/*/edit';
+ $redirectParams = array('id' => $model->getId());
+ }
+ } catch (Mage_Core_Exception $e) {
+ $hasError = true;
+ $this->_getSession()->addError($e->getMessage());
+ } catch (Exception $e) {
+ $hasError = true;
+ $this->_getSession()->addException($e,
+ Mage::helper('aoestatic')->__('An error occurred while saving custom url.')
+ );
+ }
+
+ if ($hasError) {
+ $this->_getSession()->setFormData($data);
+ $redirectPath = '*/*/edit';
+ $redirectParams = array('id' => $this->getRequest()->getParam('id'));
+ }
+ }
+
+ $this->_redirect($redirectPath, $redirectParams);
+ }
+
+ /**
+ * Delete action
+ */
+ public function deleteAction()
+ {
+ // check if we know what should be deleted
+ $customUrlId = $this->getRequest()->getParam('id');
+ if ($customUrlId) {
+ try {
+ // init model and delete
+ /** @var $model Aoe_Static_Model_CustomUrl */
+ $model = Mage::getModel('aoestatic/customUrl');
+ $model->load($customUrlId);
+ if (!$model->getId()) {
+ Mage::throwException(Mage::helper('aoestatic')->__('Unable to find a custom url.'));
+ }
+ $model->delete();
+
+ // display success message
+ $this->_getSession()->addSuccess(
+ Mage::helper('aoestatic')->__('Custom url has been deleted.')
+ );
+ } catch (Mage_Core_Exception $e) {
+ $this->_getSession()->addError($e->getMessage());
+ } catch (Exception $e) {
+ $this->_getSession()->addException($e,
+ Mage::helper('aoestatic')->__('An error occurred while deleting custom url.')
+ );
+ }
+ }
+
+ // go to grid
+ $this->_redirect('*/*/');
+ }
+
+ /**
+ * Check the permission to run it
+ *
+ * @return boolean
+ */
+ protected function _isAllowed()
+ {
+ switch ($this->getRequest()->getActionName()) {
+ case 'new':
+ case 'save':
+ return Mage::getSingleton('admin/session')->isAllowed('system/aoestatic_customUrl/save');
+ break;
+ case 'delete':
+ return Mage::getSingleton('admin/session')->isAllowed('system/aoestatic_customUrl/delete');
+ break;
+ default:
+ return Mage::getSingleton('admin/session')->isAllowed('system/aoestatic_customUrl');
+ break;
+ }
+ }
+
+ /**
+ * Grid ajax action
+ */
+ public function gridAction()
+ {
+ $this->loadLayout();
+ $this->renderLayout();
+ }
+
+ /**
+ * Mass delete action
+ */
+ public function massDeleteAction()
+ {
+ $customUrlIds = $this->getRequest()->getParam('custom_url_ids');
+ if (!is_array($customUrlIds)) {
+ $this->_getSession()->addError(
+ Mage::helper('aoestatic')->__('Please select custom url(s) to delete.')
+ );
+ } else {
+ if (!empty($customUrlIds)) {
+ try {
+ /** @var Aoe_Static_Model_CustomUrl $customUrlModel */
+ $customUrlModel = Mage::getModel('aoestatic/customUrl');
+ $customUrlModel->deleteCustomUrls($customUrlIds);
+ $this->_getSession()->addSuccess(
+ Mage::helper('aoestatic')->__('Total of %d custom url(s) have been deleted.', count($customUrlIds))
+ );
+ } catch (Mage_Core_Exception $e) {
+ $this->_getSession()->addError($e->getMessage());
+ } catch (Exception $e) {
+ $this->_getSession()->addException($e,
+ Mage::helper('aoestatic')->__('An error occurred while deleting custom url(s).')
+ );
+ }
+ }
+ }
+ $this->_redirectReferer();
+ }
+}
diff --git a/app/code/community/Aoe/Static/controllers/CallController.php b/app/code/community/Aoe/Static/controllers/CallController.php
new file mode 100644
index 0000000..9b8b643
--- /dev/null
+++ b/app/code/community/Aoe/Static/controllers/CallController.php
@@ -0,0 +1,162 @@
+getLayout();
+ foreach ($blocks as $id => $requestedBlockName) {
+ $tmpBlock = $layout->getBlock($requestedBlockName);
+ if ($tmpBlock) {
+ $result[$id] = $tmpBlock->toHtml();
+ } else {
+ $result[$id] = 'BLOCK NOT FOUND';
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * Index action. This action is called by an ajax request
+ *
+ * @return void
+ * @author Fabrizio Branca
+ */
+ public function indexAction()
+ {
+ // if (!$this->getRequest()->isXmlHttpRequest()) { Mage::throwException('This is not an XmlHttpRequest'); }
+ $response = array();
+ //$response['sid'] = Mage::getModel('core/session')->getEncryptedSessionId();
+
+ if ($currentProductId = $this->getRequest()->getParam('currentProductId')) {
+ /** @var Mage_Reports_Model_Product_Index_Viewed $report */
+ $report = Mage::getModel('reports/product_index_viewed');
+ $report->setProductId($currentProductId)
+ ->save()
+ ->calculate();
+
+ /** @var Mage_Catalog_Model_Session $session */
+ $session = Mage::getSingleton('catalog/session');
+ $session->setLastViewedProductId($currentProductId);
+
+ if ($this->getConfig()->isLoadCurrentProduct()) {
+ /** @var Mage_Catalog_Model_Product $product */
+ $product = Mage::getModel('catalog/product');
+ $product
+ ->setStoreId(Mage::app()->getStore()->getId())
+ ->load($currentProductId);
+ if ($product->getId()) {
+ Mage::register('product', $product);
+ Mage::register('current_product', $product);
+ }
+ }
+ }
+
+ $this->loadLayout();
+
+ // get blocks
+ $requestedBlockNames = $this->getRequest()->getParam('getBlocks');
+ if ($requestedBlockNames) {
+ $response['blocks'] = $this->_renderBlocks($requestedBlockNames);
+ }
+
+ // get messages
+ $messages = array();
+ foreach ($this->_sessions as $sessionStorage) {
+ if (!isset($messages[$sessionStorage])) {
+ $messages[$sessionStorage] = array();
+ }
+ foreach (Mage::getSingleton($sessionStorage)->getMessages(true)->getItems() as $message) {
+ $type = $message->getType();
+ if (!isset($messages[$sessionStorage][$type])) {
+ $messages[$sessionStorage][$type] = array();
+ }
+ $messages[$sessionStorage][$type][] = $message->getCode();
+ }
+ }
+ $response['messages'] = $messages;
+
+ $this->getResponse()->setBody(Zend_Json::encode($response));
+ }
+
+ /**
+ * The same as Index action, but strips out the session_id and doesn't return messages
+ *
+ * @return void
+ */
+ public function secureAction()
+ {
+ $this->loadLayout();
+
+ $response = array();
+ $requestedBlockNames = $this->getRequest()->getParam('getBlocks');
+ if ($requestedBlockNames) {
+ $response['blocks'] = $this->_renderBlocks($requestedBlockNames);
+ }
+
+ // strip SID from responses
+ $sid = Mage::getModel('core/session')->getEncryptedSessionId();
+ foreach ($response['blocks'] as $id => &$content) {
+ $content = str_replace($sid, '__NO_SID__', $content);
+ }
+
+ $this->getResponse()->setBody(Zend_Json::encode($response));
+ }
+
+ /**
+ * @return Aoe_Static_Model_Config
+ */
+ public function getConfig()
+ {
+ if (!$this->_config) {
+ /** @var Aoe_Static_Model_Config $config */
+ $config = Mage::getSingleton('aoestatic/config');
+
+ $this->setConfig($config);
+ }
+
+ return $this->_config;
+ }
+
+ /**
+ * @param Aoe_Static_Model_Config $config Config
+ * @return $this
+ */
+ public function setConfig(Aoe_Static_Model_Config $config)
+ {
+ $this->_config = $config;
+
+ return $this;
+ }
+}
diff --git a/app/code/community/Aoe/Static/controllers/EsiController.php b/app/code/community/Aoe/Static/controllers/EsiController.php
new file mode 100644
index 0000000..55a84ff
--- /dev/null
+++ b/app/code/community/Aoe/Static/controllers/EsiController.php
@@ -0,0 +1,32 @@
+loadLayout();
+ $blockName = $this->getRequest()->getParam('block');
+ $block = $this->getLayout()->getBlock($blockName); /* @var $block Mage_Core_Block_Abstract */
+ $response = $block ? $block->toHtml() : 'BLOCK NOT FOUND';
+
+ if ($block && $block->getMaxAge()) {
+ /** @var Aoe_Static_Model_Cache_Control $cacheControl */
+ $cacheControl = Mage::getSingleton('aoestatic/cache_control');
+ $cacheControl->addMaxAge($block->getMaxAge());
+ $cacheControl->addTag($block->getBanTags());
+ $cacheControl->applyCacheHeaders();
+ }
+
+ $this->getResponse()->setBody($response);
+ }
+}
diff --git a/app/code/community/Aoe/Static/etc/adminhtml.xml b/app/code/community/Aoe/Static/etc/adminhtml.xml
new file mode 100755
index 0000000..e56a0f5
--- /dev/null
+++ b/app/code/community/Aoe/Static/etc/adminhtml.xml
@@ -0,0 +1,40 @@
+
+
+
+
+
+
+
+
+
+
+ Manage Urls max-age
+ 0
+
+
+ Save Url
+ 0
+
+
+ Delete Url
+ 10
+
+
+
+
+
+
+
+
+
+
diff --git a/app/code/community/Aoe/Static/etc/aoe_static.xml b/app/code/community/Aoe/Static/etc/aoe_static.xml
new file mode 100644
index 0000000..f3d8d41
--- /dev/null
+++ b/app/code/community/Aoe/Static/etc/aoe_static.xml
@@ -0,0 +1,135 @@
+
+
+
+
+
+
+
+
+
+ ###FULLACTIONNAME###
+
+
+
+
+
+
+
+
+
+
+
+
+
+ no-store, no-cache, must-revalidate, post-check=0, pre-check=0
+ ###ISLOGGEDIN###
+
+
+
+ customer
+ ###ISLOGGEDIN###
+ 3600
+
+ 0
+
+
+ customer
+ ###CUSTOMERNAME###
+ 3600
+
+ 0
+
+
+ customer
+ ###NUMBEROFITEMSINCART###
+ 3600
+
+ 0
+
+
+
+
+
+
+
+
+
+
+
+ 0
+
+ 86400
+
+
+ cache
+ 86400
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ aoestatic/cache_adapter_varnish
+
+
+
+ aoestatic/cache_adapter_blackhole
+
+
+
+ aoestatic/cache_adapter_sns
+
+
+
+
+
+
diff --git a/app/code/community/Aoe/Static/etc/api.xml b/app/code/community/Aoe/Static/etc/api.xml
new file mode 100644
index 0000000..f2aa037
--- /dev/null
+++ b/app/code/community/Aoe/Static/etc/api.xml
@@ -0,0 +1,42 @@
+
+
+
+
+
+ aoestatic/api
+ Aoe Static API
+ aoestatic/aoestatic
+
+
+ Purge URLs
+ aoestatic/aoestatic/purge
+
+
+ Purge Tags
+ aoestatic/aoestatic/purgeTags
+
+
+ Purge All
+ aoestatic/aoestatic/purgeAll
+
+
+
+
+
+
+
+ Aoe Static API
+
+ Purge URLs
+
+
+ Purge Tags
+
+
+ Purge All
+
+
+
+
+
+
diff --git a/app/code/community/Aoe/Static/etc/config.xml b/app/code/community/Aoe/Static/etc/config.xml
new file mode 100755
index 0000000..1cc8ec8
--- /dev/null
+++ b/app/code/community/Aoe/Static/etc/config.xml
@@ -0,0 +1,315 @@
+
+
+
+
+ 0.2.2
+
+
+
+
+
+
+ Aoe_Static_Block
+
+
+
+
+ Aoe_Static_Model
+ aoestatic_resource
+
+
+ Aoe_Static_Model_Resource
+
+
+