diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..a60639d7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/db/log/*.log +/db/sql/*.bak +/vendor/ +/ruckusing.conf.local.php diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..33afc678 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,18 @@ +## Changelog ## + + +### 0.0 ### +* Init repo and files + + +### 0.1 ### +Initial release + +* Add shortcode for tests lists: wptlist +* Edit tests, answers (global), scales, results and categories through admin +* Edit tests questions and scores (question -> answer -> scale -> score value) +* Show test page, allowing to redefine it's template if needed +* Allow to send test form only when all questions selected +* Show test results by scales totals +* Add eysenck personality inventory example + diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..21feb205 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,595 @@ +GNU GENERAL PUBLIC LICENSE +========================== + +_Version 3, 29 June 2007_ +_Copyright © 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. + + + Copyright (C) + + 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: + + Copyright (C) + 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-DEV.md b/README-DEV.md new file mode 100644 index 00000000..5d00db0b --- /dev/null +++ b/README-DEV.md @@ -0,0 +1,11 @@ +# Wp-testing for developer + +## To regenerate README.md + +Changes should be in readme.txt, which then generates README.md by this: + + vendor/bin/wp2md convert < readme.txt > README.md + +* Validator is at http://wordpress.org/plugins/about/validator/ +* Template is at https://wordpress.org/plugins/about/readme.txt +* Good howto is at http://www.smashingmagazine.com/2011/11/23/improve-wordpress-plugins-readme-txt/ diff --git a/README.md b/README.md new file mode 100644 index 00000000..d482ad32 --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# Wp-testing # + +**Contributors:** ustimenko +**Donate link:** http://ustimen.co/ +**Tags:** psychological, testing, test, quiz +**Requires at least:** 3.2 +**Tested up to:** 3.9 +**Stable tag:** 0.1 +**License:** GPLv3 +**License URI:** http://www.gnu.org/licenses/gpl-3.0.html + +Helps to create psychological tests. + +## Installation ## + +1. Download plugin archive. +1. Unzip it. +1. Upload it to your plugins directory. It will create a 'wp-content/plugins/wp-testing/' directory. +1. Activate the plugin through the 'Plugins' menu in WordPress. + +## Requirements ## + +* WordPress version **3.2** or higher. +* PHP version **5.2.4** or higher. +* MySQL version **5.0** or higher. diff --git a/composer.json b/composer.json new file mode 100644 index 00000000..12d77d3c --- /dev/null +++ b/composer.json @@ -0,0 +1,35 @@ +{ + "name": "garex/wp-testing", + "description": "Helps to create psychological tests", + "type": "wordpress-plugin", + "license": "GPLv3", + "authors": [{ + "name": "Ustimenko Alexander", + "email": "a@ustimen.co" + } + ], + "require": { + "composer/installers": "~1.0.0" + , "xrstf/composer-php52": "1.*" + , "ruckusing/ruckusing-migrations": "~1.0" + , "flourish/flourish": "0.9.*@dev" + }, + "require-dev": { + }, + "scripts": { + "post-install-cmd": [ + "xrstf\\Composer52\\Generator::onPostInstallCmd" + ], + "post-update-cmd": [ + "xrstf\\Composer52\\Generator::onPostInstallCmd" + ], + "post-autoload-dump": [ + "xrstf\\Composer52\\Generator::onPostInstallCmd" + ] + }, + "autoload": { + "classmap": [ + "src/" + ] + } +} diff --git a/css/admin.css b/css/admin.css new file mode 100644 index 00000000..76f9d7ea --- /dev/null +++ b/css/admin.css @@ -0,0 +1,21 @@ +table.wpt_questions { + width: 100%; +} + +.wpt_questions .wpt_title input { + width: 100%; +} + +.wpt_questions .wpt_number { + width: 1em; + text-align: right; +} + +.wpt_questions .wpt_scale { + text-align: center; +} + +.wpt_questions .wpt_scale input { + text-align: center; + width: 100%; +} diff --git a/css/public.css b/css/public.css new file mode 100644 index 00000000..e7dd4d1a --- /dev/null +++ b/css/public.css @@ -0,0 +1,69 @@ +.wpt_test .question { + margin-bottom: 1.25em; +} + +.wpt_test .question .title { + font-weight: bold; +} + +.wpt_test .question .title .number { + font-weight: normal; + display: inline-block; + width: 3em; + margin-left: -3.5em; + padding-right: 0.5em; + text-align: right; +} + +.wpt_test .answer { + padding-top: 0.25em; + padding-left: 0.5em; +} + +.wpt_test .answer label { + margin-left: 0.25em; +} + +.wpt_test .answer input { + margin-top: -2px; + vertical-align: middle; +} + +.wpt_test .button { + margin-top: 0.75em; +} + +.wpt_test .button.disabled { + opacity: 0.5; +} + +.wpt_test .get_results .meter, +.wpt_test .get_results .meter > span { + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + position: relative; +} +.wpt_test .get_results .meter { + height: 1.5em; + margin-bottom: 1em; + padding: 2px 1px; + border: 1px solid highlight; +} +.wpt_test .get_results .meter > span { + display: block; + height: 100%; + background: highlight; + overflow: hidden; +} +.wpt_test .get_results .scale.scores { + padding-left: 7px; + padding-top: 2px; + font-weight: bold; + position: absolute; + z-index: 1; +} + +.wpt_test .get_results .content { + color: gray; +} diff --git a/db/log/empty b/db/log/empty new file mode 100644 index 00000000..d3d1e691 --- /dev/null +++ b/db/log/empty @@ -0,0 +1,83 @@ +Aug 31 09:20:56 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:20:56 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:20:56 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:20:56 [info] CREATE TABLE `wp_t_tests` ( +`id` int(11) UNSIGNED auto_increment NOT NULL, +`title` varchar(255), + PRIMARY KEY (`id`)) DEFAULT CHARSET=utf8; +Aug 31 09:20:56 [info] INSERT INTO wp_t_schema_migrations (version) VALUES ('20140831002425') +Aug 31 09:21:27 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:21:27 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:21:27 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:21:27 [info] DROP TABLE IF EXISTS `wp_t_tests` +Aug 31 09:21:27 [info] DELETE FROM wp_t_schema_migrations WHERE version = '20140831002425' +Aug 31 09:21:28 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:21:28 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:21:28 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:21:28 [info] CREATE TABLE `wp_t_tests` ( +`id` int(11) UNSIGNED auto_increment NOT NULL, +`title` varchar(255), + PRIMARY KEY (`id`)) DEFAULT CHARSET=utf8; +Aug 31 09:21:28 [info] INSERT INTO wp_t_schema_migrations (version) VALUES ('20140831002425') +Aug 31 09:21:30 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:21:30 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:21:30 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:21:30 [info] DROP TABLE IF EXISTS `wp_t_tests` +Aug 31 09:21:30 [info] DELETE FROM wp_t_schema_migrations WHERE version = '20140831002425' +Aug 31 09:24:43 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:24:43 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:24:43 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:24:43 [info] CREATE TABLE `wp_t_tests` ( +`id` int(11) UNSIGNED auto_increment NOT NULL, +`title` varchar(255), + PRIMARY KEY (`id`)) DEFAULT CHARSET=utf8; +Aug 31 09:24:43 [info] INSERT INTO wp_t_schema_migrations (version) VALUES ('20140831002425') +Aug 31 09:24:45 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:24:45 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:24:45 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:24:45 [info] DROP TABLE IF EXISTS `wp_t_tests` +Aug 31 09:24:45 [info] DELETE FROM wp_t_schema_migrations WHERE version = '20140831002425' +Aug 31 09:28:12 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:28:12 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:28:12 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:28:12 [info] CREATE TABLE `wp_t_tests` ( +`id` int(11) UNSIGNED auto_increment NOT NULL, +`title` varchar(255), + PRIMARY KEY (`id`)) DEFAULT CHARSET=utf8; +Aug 31 09:28:12 [info] INSERT INTO wp_t_schema_migrations (version) VALUES ('20140831002425') +Aug 31 09:29:50 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:29:50 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:29:50 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:29:50 [info] DROP TABLE IF EXISTS `wp_t_tests` +Aug 31 09:29:50 [info] DELETE FROM wp_t_schema_migrations WHERE version = '20140831002425' +Aug 31 09:30:01 [info] CREATE TABLE `wp_t_schema_migrations` ( +`version` varchar(255)) DEFAULT CHARSET=utf8; +Aug 31 09:30:01 [info] CREATE UNIQUE INDEX idx_wp_t_schema_migrations_version ON `wp_t_schema_migrations`(`version`) +Aug 31 09:30:01 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:30:01 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:30:01 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:30:01 [info] CREATE TABLE `wp_t_tests` ( +`id` int(11) UNSIGNED auto_increment NOT NULL, +`title` varchar(255), + PRIMARY KEY (`id`)) DEFAULT CHARSET=utf8; +Aug 31 09:30:01 [info] INSERT INTO wp_t_schema_migrations (version) VALUES ('20140831002425') +Aug 31 09:32:59 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:32:59 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:32:59 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:32:59 [info] DROP TABLE IF EXISTS `wp_t_tests` +Aug 31 09:32:59 [info] DELETE FROM wp_t_schema_migrations WHERE version = '20140831002425' +Aug 31 09:32:59 [info] DROP TABLE IF EXISTS `wp_t_schema_migrations` +Aug 31 09:33:08 [info] CREATE TABLE `wp_t_schema_migrations` ( +`version` varchar(255)) DEFAULT CHARSET=utf8; +Aug 31 09:33:08 [info] CREATE UNIQUE INDEX idx_wp_t_schema_migrations_version ON `wp_t_schema_migrations`(`version`) +Aug 31 09:33:08 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:33:08 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:33:08 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:33:08 [info] CREATE TABLE `wp_t_tests` ( +`id` int(11) UNSIGNED auto_increment NOT NULL, +`title` varchar(255), + PRIMARY KEY (`id`)) DEFAULT CHARSET=utf8; +Aug 31 09:33:08 [info] INSERT INTO wp_t_schema_migrations (version) VALUES ('20140831002425') +Aug 31 09:35:46 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:35:46 [info] SELECT version FROM wp_t_schema_migrations +Aug 31 09:35:46 [info] SELECT version FROM wp_t_schema_migrations diff --git a/db/migrations/wp_testing/20140831002425_CreateTestsTable.php b/db/migrations/wp_testing/20140831002425_CreateTestsTable.php new file mode 100644 index 00000000..bfee5090 --- /dev/null +++ b/db/migrations/wp_testing/20140831002425_CreateTestsTable.php @@ -0,0 +1,16 @@ +create_table(WPT_DB_PREFIX . 'tests'); + $t->column('title', 'string'); + $t->finish(); + } + + public function down() + { + $this->drop_table(WPT_DB_PREFIX . 'tests'); + } +} diff --git a/db/migrations/wp_testing/20140831142817_CreateTestEntities.php b/db/migrations/wp_testing/20140831142817_CreateTestEntities.php new file mode 100644 index 00000000..2e81f865 --- /dev/null +++ b/db/migrations/wp_testing/20140831142817_CreateTestEntities.php @@ -0,0 +1,116 @@ +drop_table(WPT_DB_PREFIX . 'tests'); + + $this + ->createEntityTable('scales') + ->finishTable() + ->createEntityTable('tests') + ->finishTable() + ->createManyToManyTable('scales', 'tests') + ->finishTable() + ->createEntityTable('parameters') + ->addForeignKeyTo('scales') + ->finishTable() + ->createEntityTable('questions') + ->addForeignKeyTo('tests') + ->finishTable() + ->createEntityTable('answers') + ->addForeignKeyTo('questions') + ->finishTable() + ->createManyToManyTable('answers', 'parameters') + ->finishTable() + ; + + $this->executeBuffered(); + } + + public function down() + { + $this->drop_table(WPT_DB_PREFIX . 'answers_parameters'); + $this->drop_table(WPT_DB_PREFIX . 'answers'); + $this->drop_table(WPT_DB_PREFIX . 'questions'); + $this->drop_table(WPT_DB_PREFIX . 'scales_tests'); + $this->drop_table(WPT_DB_PREFIX . 'tests'); + $this->drop_table(WPT_DB_PREFIX . 'parameters'); + $this->drop_table(WPT_DB_PREFIX . 'scales'); + } + + protected function createTable($name, array $options = array()) + { + $this->currentTableName = $name; + $this->currentTable = $this->create_table(WPT_DB_PREFIX . $this->currentTableName, $options); + return $this; + } + + protected function createEntityTable($name) + { + $this->createTable($name); + $notNull = array('null' => false); + $this->currentTable->column('title', 'string', $notNull); + $this->currentTable->column('created', 'datetime', $notNull); + $this->currentTable->column('modified', 'datetime', $notNull); + return $this; + } + + protected function createManyToManyTable($from, $to) + { + $pk = array('primary_key' => true); + return $this + ->createTable($from . '_' . $to, array('id' => false)) + ->addForeignKeyTo($from, $pk)->addForeignKeyTo($to, $pk); + } + + protected function addForeignKeyTo($name, $options = array()) + { + $singularName = preg_replace('/s$/', '', $name); + $this->currentTable->column($singularName . '_id', 'integer', array( + 'unsigned' => true, + 'null' => false, + ) + $options); + $prefix = WPT_DB_PREFIX; + $this->buffer(" + ALTER TABLE {$prefix}{$this->currentTableName} + ADD CONSTRAINT fk_{$this->currentTableName}_{$name} + FOREIGN KEY ({$singularName}_id) + REFERENCES {$prefix}{$name} (id) + ON DELETE RESTRICT + ON UPDATE RESTRICT, + ADD INDEX fk_{$this->currentTableName}_{$name} ({$singularName}_id) + "); + return $this; + } + + protected function finishTable() + { + $this->currentTable->finish(); + return $this; + } + + protected function buffer($query) + { + $this->queriesBuffer[] = $query; + } + + protected function executeBuffered() + { + foreach ($this->queriesBuffer as $query) { + $this->execute($query); + } + + $this->queriesBuffer = array(); + } +} diff --git a/db/migrations/wp_testing/20140831155940_AddHelloWorldTest.php b/db/migrations/wp_testing/20140831155940_AddHelloWorldTest.php new file mode 100644 index 00000000..5477e850 --- /dev/null +++ b/db/migrations/wp_testing/20140831155940_AddHelloWorldTest.php @@ -0,0 +1,82 @@ +execute(' + INSERT INTO ' . WPT_DB_PREFIX . 'scales (id, title, created, modified) + VALUES (1, "Correct?", NOW(), NOW()); + + INSERT INTO ' . WPT_DB_PREFIX . 'parameters (id, title, created, modified, scale_id) + VALUES (1, "Yes", NOW(), NOW(), 1); + INSERT INTO ' . WPT_DB_PREFIX . 'parameters (id, title, created, modified, scale_id) + VALUES (2, "No", NOW(), NOW(), 1); + + INSERT INTO ' . WPT_DB_PREFIX . 'tests (id, title, created, modified) + VALUES (1, "Hello world!", NOW(), NOW()); + + INSERT INTO ' . WPT_DB_PREFIX . 'scales_tests (scale_id, test_id) + VALUES (1, 1); + + INSERT INTO ' . WPT_DB_PREFIX . 'questions (id, title, created, modified, test_id) + VALUES (1, "2 + 2 = 5", NOW(), NOW(), 1); + INSERT INTO ' . WPT_DB_PREFIX . 'questions (id, title, created, modified, test_id) + VALUES (2, "Sun in the sky", NOW(), NOW(), 1); + INSERT INTO ' . WPT_DB_PREFIX . 'questions (id, title, created, modified, test_id) + VALUES (3, "The world is mine", NOW(), NOW(), 1); + + INSERT INTO ' . WPT_DB_PREFIX . 'answers (id, title, created, modified, question_id) + VALUES (1, "Yes", NOW(), NOW(), 1); + INSERT INTO ' . WPT_DB_PREFIX . 'answers (id, title, created, modified, question_id) + VALUES (2, "No", NOW(), NOW(), 1); + INSERT INTO ' . WPT_DB_PREFIX . 'answers (id, title, created, modified, question_id) + VALUES (3, "Yes", NOW(), NOW(), 2); + INSERT INTO ' . WPT_DB_PREFIX . 'answers (id, title, created, modified, question_id) + VALUES (4, "No", NOW(), NOW(), 2); + INSERT INTO ' . WPT_DB_PREFIX . 'answers (id, title, created, modified, question_id) + VALUES (5, "Yes", NOW(), NOW(), 3); + INSERT INTO ' . WPT_DB_PREFIX . 'answers (id, title, created, modified, question_id) + VALUES (6, "No", NOW(), NOW(), 3); + + INSERT INTO ' . WPT_DB_PREFIX . 'answers_parameters (answer_id, parameter_id) + VALUES (1, 2); + INSERT INTO ' . WPT_DB_PREFIX . 'answers_parameters (answer_id, parameter_id) + VALUES (2, 1); + INSERT INTO ' . WPT_DB_PREFIX . 'answers_parameters (answer_id, parameter_id) + VALUES (3, 1); + INSERT INTO ' . WPT_DB_PREFIX . 'answers_parameters (answer_id, parameter_id) + VALUES (4, 2); + INSERT INTO ' . WPT_DB_PREFIX . 'answers_parameters (answer_id, parameter_id) + VALUES (5, 1); + INSERT INTO ' . WPT_DB_PREFIX . 'answers_parameters (answer_id, parameter_id) + VALUES (6, 2); + '); + } + + public function down() + { + $this + ->clearTable('answers_parameters') + ->clearTable('answers') + ->clearTable('questions') + ->clearTable('tests') + ->clearTable('parameters') + ->clearTable('scales_tests') + ->clearTable('scales') + ; + } + + protected function clearTable($name) + { + if ($this->get_adapter() instanceof Ruckusing_Adapter_MySQL_Base) { + $this->execute('SET FOREIGN_KEY_CHECKS=0'); + $this->execute('TRUNCATE TABLE ' . WPT_DB_PREFIX . $name); + $this->execute('SET FOREIGN_KEY_CHECKS=1'); + } else { + $this->execute('DELETE FROM ' . WPT_DB_PREFIX . $name); + } + return $this; + } + +} diff --git a/db/migrations/wp_testing/20140913080127_DropExperimentTables.php b/db/migrations/wp_testing/20140913080127_DropExperimentTables.php new file mode 100644 index 00000000..74a6d1b9 --- /dev/null +++ b/db/migrations/wp_testing/20140913080127_DropExperimentTables.php @@ -0,0 +1,20 @@ +drop_table(WPT_DB_PREFIX . 'answers_parameters'); + $this->drop_table(WPT_DB_PREFIX . 'answers'); + $this->drop_table(WPT_DB_PREFIX . 'questions'); + $this->drop_table(WPT_DB_PREFIX . 'scales_tests'); + $this->drop_table(WPT_DB_PREFIX . 'tests'); + $this->drop_table(WPT_DB_PREFIX . 'parameters'); + $this->drop_table(WPT_DB_PREFIX . 'scales'); + } + + public function down() + { + // nothing here. it's backward incompatible action + } +} diff --git a/db/migrations/wp_testing/20140913082248_AddQuestionsTable.php b/db/migrations/wp_testing/20140913082248_AddQuestionsTable.php new file mode 100644 index 00000000..1e0b1c55 --- /dev/null +++ b/db/migrations/wp_testing/20140913082248_AddQuestionsTable.php @@ -0,0 +1,41 @@ +create_table(WPT_DB_PREFIX . 'questions', array( + 'id' => false, + )); + $table->column('question_id', 'biginteger', array( + 'unsigned' => true, + 'null' => false, + 'primary_key' => true, + 'auto_increment' => true, + )); + $table->column('test_id', 'biginteger', array( + 'unsigned' => true, + 'null' => false, + )); + $table->column('question_title', 'text', array( + 'null' => false, + )); + $table->finish(); + $global_prefix = WP_DB_PREFIX; + $plugin_prefix = WPT_DB_PREFIX; + $this->execute(" + ALTER TABLE {$plugin_prefix}questions + ADD CONSTRAINT fk_question_test + FOREIGN KEY (test_id) + REFERENCES {$global_prefix}posts (ID) + ON DELETE CASCADE + ON UPDATE CASCADE, + ADD INDEX fk_question_test (test_id) + "); + } + + public function down() + { + $this->drop_table(WPT_DB_PREFIX . 'questions'); + } +} diff --git a/db/migrations/wp_testing/20140916030608_AddTestScoresTable.php b/db/migrations/wp_testing/20140916030608_AddTestScoresTable.php new file mode 100644 index 00000000..0ecec834 --- /dev/null +++ b/db/migrations/wp_testing/20140916030608_AddTestScoresTable.php @@ -0,0 +1,56 @@ +create_table(WPT_DB_PREFIX . 'scores', array( + 'id' => false, + )); + $pkOptions = array( + 'unsigned' => true, + 'null' => false, + 'primary_key' => true, + ); + $table->column('answer_id', 'biginteger', $pkOptions); + $table->column('question_id', 'biginteger', $pkOptions); + $table->column('scale_id', 'biginteger', $pkOptions); + $table->column('score_value', 'tinyinteger', array( + 'null' => false, + 'default' => 0, + )); + $table->finish(); + + $global_prefix = WP_DB_PREFIX; + $plugin_prefix = WPT_DB_PREFIX; + $this->execute(" + ALTER TABLE {$plugin_prefix}scores + + ADD CONSTRAINT fk_score_answer + FOREIGN KEY (answer_id) + REFERENCES {$global_prefix}terms (term_id) + ON DELETE CASCADE + ON UPDATE CASCADE, + ADD INDEX fk_score_answer (answer_id), + + ADD CONSTRAINT fk_score_question + FOREIGN KEY (question_id) + REFERENCES {$plugin_prefix}questions (question_id) + ON DELETE CASCADE + ON UPDATE CASCADE, + ADD INDEX fk_score_question (question_id), + + ADD CONSTRAINT fk_score_scale + FOREIGN KEY (scale_id) + REFERENCES {$global_prefix}terms (term_id) + ON DELETE CASCADE + ON UPDATE CASCADE, + ADD INDEX fk_score_scale (scale_id) + "); + } + + public function down() + { + $this->drop_table(WPT_DB_PREFIX . 'scores'); + } +} diff --git a/db/migrations/wp_testing/20140925023344_AddPassingsTables.php b/db/migrations/wp_testing/20140925023344_AddPassingsTables.php new file mode 100644 index 00000000..9646cdd1 --- /dev/null +++ b/db/migrations/wp_testing/20140925023344_AddPassingsTables.php @@ -0,0 +1,95 @@ +create_table(WPT_DB_PREFIX . 'passings', array( + 'id' => false, + )); + $table->column('passing_id', 'biginteger', array( + 'unsigned' => true, + 'null' => false, + 'primary_key' => true, + 'auto_increment' => true, + )); + $table->column('test_id', 'biginteger', array( + 'unsigned' => true, + 'null' => false, + )); + $table->column('respondent_id', 'biginteger', array( + 'unsigned' => true, + )); + $table->column('created', 'datetime', array( + 'null' => false, + )); + $table->column('modified', 'datetime', array( + 'null' => false, + )); + $table->finish(); + + $global_prefix = WP_DB_PREFIX; + $plugin_prefix = WPT_DB_PREFIX; + $this->execute(" + ALTER TABLE {$plugin_prefix}passings + + ADD CONSTRAINT fk_passing_test + FOREIGN KEY (test_id) + REFERENCES {$global_prefix}posts (ID) + ON DELETE CASCADE + ON UPDATE CASCADE, + ADD INDEX fk_passing_test (test_id), + + ADD CONSTRAINT fk_passing_respondent + FOREIGN KEY (respondent_id) + REFERENCES {$global_prefix}users (ID) + ON DELETE CASCADE + ON UPDATE CASCADE, + ADD INDEX fk_passing_respondent (respondent_id) + "); + + $table = $this->create_table(WPT_DB_PREFIX . 'passing_answers', array( + 'id' => false, + )); + $pkOptions = array( + 'unsigned' => true, + 'null' => false, + 'primary_key' => true, + ); + $table->column('answer_id', 'biginteger', $pkOptions); + $table->column('question_id', 'biginteger', $pkOptions); + $table->column('passing_id', 'biginteger', $pkOptions); + $table->finish(); + + $this->execute(" + ALTER TABLE {$plugin_prefix}passing_answers + + ADD CONSTRAINT fk_passing_answer_answer + FOREIGN KEY (answer_id) + REFERENCES {$global_prefix}terms (term_id) + ON DELETE CASCADE + ON UPDATE CASCADE, + ADD INDEX fk_passing_answer_answer (answer_id), + + ADD CONSTRAINT fk_passing_answer_question + FOREIGN KEY (question_id) + REFERENCES {$plugin_prefix}questions (question_id) + ON DELETE CASCADE + ON UPDATE CASCADE, + ADD INDEX fk_passing_answer_question (question_id), + + ADD CONSTRAINT fk_passing_answer_passing + FOREIGN KEY (passing_id) + REFERENCES {$plugin_prefix}passings (passing_id) + ON DELETE CASCADE + ON UPDATE CASCADE, + ADD INDEX fk_passing_answer_passing (passing_id) + "); + } + + public function down() + { + $this->drop_table(WPT_DB_PREFIX . 'passing_answers'); + $this->drop_table(WPT_DB_PREFIX . 'passings'); + } +} diff --git a/db/migrations/wp_testing/20140928160013_AddExampleTest.php b/db/migrations/wp_testing/20140928160013_AddExampleTest.php new file mode 100644 index 00000000..a72763a0 --- /dev/null +++ b/db/migrations/wp_testing/20140928160013_AddExampleTest.php @@ -0,0 +1,219 @@ +execute(" + INSERT INTO $posts ( + post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, + post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, + post_modified, post_modified_gmt, post_content_filtered, post_parent, guid, menu_order, + post_type, post_mime_type, comment_count + ) VALUES ( + 1, NOW(), NOW(), 'The Eysenck Personality Inventory (EPI) measures two pervasive, independent dimensions of personality, Extraversion-Introversion and Neuroticism-Stability, which account for most of the variance in the personality domain. Each form contains 57 \"Yes-No\" items with no repetition of items. The inclusion of a falsification scale provides for the detection of response distortion. The traits measured are Extraversion-Introversion and Neuroticism. When you fill out Eysenck’s Personality Inventory (EPI) you get three scores.\r\n
    \r\n
  • The ‘lie score’ is out of 9. It measures how socially desirable you are trying to be in your answers.Those who score 5 or more on this scale are probably trying to make themselves look good and are not being totally honest in their responses.
  • \r\n
  • The ‘E score’ is out of 24 and measures how much of an extrovert you are.
  • \r\n
  • The ‘N score’ is out of 24 and measures how neurotic you are.
  • \r\n
\r\nTo interpret the scores, your E score and your N score are plotted on a graph from which you can read your personality characteristics. The nearer the outside of the circle you are, the more marked are the personality traits. Please note that the EPI is a very simplistic type of personality measurement scale, so if you have come out as a personality that does not match what you thought before you took the test, you are probably right and the test is probably wrong!\r\n\r\n\"EPI\r\n

Instructions

\r\nHere are some questions regarding the way you behave, feel and act. Each question has radio buttons to answer YES or NO. Try to decide whether YES or NO represents your usual way of acting or feeling. Then check those radio named YES or NO. Work quickly, and don’t spend too much time over any question, we want your first reaction, not a long drawn-out thought process. The whole questionnaire shouldn’t take more than a few minutes. Be sure not to omit any questions. Start now, work quickly and remember to answer every question. There are no right or wrong answers, and this isn’t a test of intelligence or ability, but simply a measure of the way you behave.', 'Eysenck’s Personality Inventory (EPI) (Extroversion/Introversion)', '', 'publish', 'closed', 'closed', '', 'eysencks-personality-inventory-epi-extroversionintroversion', '', '', NOW(), NOW(), '', 0, UUID(), 0, 'wpt_test', '', 0); + + INSERT INTO $terms (name, slug, term_group) VALUES + ('Yes', 'answer-yes', 0), + ('No', 'answer-no', 0), + ('Extraversion/Introversion', 'scale-extraversion-introversion', 0), + ('Neuroticism/Stability', 'scale-neuroticism-stability', 0), + ('Lie', 'scale-lie', 0); + "); + + $testId = $this->field("SELECT ID FROM $posts WHERE post_type = 'wpt_test' ORDER BY ID DESC LIMIT 1"); + $yesId = $this->field("SELECT term_id FROM $terms WHERE slug = 'answer-yes' LIMIT 1"); + $noId = $this->field("SELECT term_id FROM $terms WHERE slug = 'answer-no' LIMIT 1"); + $eiId = $this->field("SELECT term_id FROM $terms WHERE slug = 'scale-extraversion-introversion' LIMIT 1"); + $nsId = $this->field("SELECT term_id FROM $terms WHERE slug = 'scale-neuroticism-stability' LIMIT 1"); + $lieId = $this->field("SELECT term_id FROM $terms WHERE slug = 'scale-lie' LIMIT 1"); + + $this->execute(" + INSERT INTO $termTaxonomy (term_id, taxonomy, description, parent, count) VALUES + ($yesId, 'wpt_answer', '', 0, 1), + ($noId, 'wpt_answer', '', 0, 1), + ($eiId, 'wpt_scale', 'Extraversion is characterized by being outgoing, talkative, high on positive affect (feeling good), and in need of external stimulation. According to Eysenck\'s arousal theory of extraversion, there is an optimal level of cortical arousal, and performance deteriorates as one becomes more or less aroused than this optimal level. Arousal can be measured by skin conductance, brain waves or sweating. At very low and very high levels of arousal, performance is low, but at a better mid-level of arousal, performance is maximized.\r\n\r\nExtraverts, according to Eysenck\'s theory, are chronically under-aroused and bored and are therefore in need of external stimulation to bring them up to an optimal level of performance. About 16 percent of the population tend to fall in this range.\r\n\r\nIntroverts, on the other hand, (also about 16 percent of the population) are chronically over-aroused and jittery and are therefore in need of peace and quiet to bring them up to an optimal level of performance.\r\n\r\nMost people (about 68 percent of the population) fall in the midrange of the extraversion/introversion continuum, an area referred to as ambiversion.', 0, 1), + ($nsId, 'wpt_scale', 'Neuroticism or emotionality is characterized by high levels of negative affect such as depression and anxiety. Neuroticism, according to Eysenck\'s theory, is based on activation thresholds in the sympathetic nervous system or visceral brain. This is the part of the brain that is responsible for the fight-or-flight response in the face of danger. Activation can be measured by heart rate, blood pressure, cold hands, sweating and muscular tension (especially in the forehead).\r\n\r\nNeurotic people — who have low activation thresholds, and unable to inhibit or control their emotional reactions, experience negative affect (fight-or-flight) in the face of very minor stressors — are easily nervous or upset.\r\n\r\nEmotionally stable people — who have high activation thresholds and good emotional control, experience negative affect only in the face of very major stressors — are calm and collected under pressure.', 0, 1), + ($lieId, 'wpt_scale', 'It measures how socially desirable you are trying to be in your answers. Those who score 5 or more on this scale are probably trying to make themselves look good and are not being totally honest in their responses.', 0, 1); + "); + $this->execute(" + INSERT INTO $termRelashionships (object_id, term_taxonomy_id, term_order) VALUES + ($testId, (SELECT term_taxonomy_id FROM $termTaxonomy WHERE term_id = $yesId), 1), + ($testId, (SELECT term_taxonomy_id FROM $termTaxonomy WHERE term_id = $noId), 2), + ($testId, (SELECT term_taxonomy_id FROM $termTaxonomy WHERE term_id = $eiId), 1), + ($testId, (SELECT term_taxonomy_id FROM $termTaxonomy WHERE term_id = $nsId), 2), + ($testId, (SELECT term_taxonomy_id FROM $termTaxonomy WHERE term_id = $lieId), 3); + + INSERT INTO $questions (test_id, question_title) VALUES + ($testId, 'Do you often long for excitement?'), + ($testId, 'Do you often need understanding friends to cheer you up?'), + ($testId, 'Are you usually carefree?'), + ($testId, 'Do you find it very hard to take no for an answer?'), + ($testId, 'Do you stop and think things over before doing anything?'), + ($testId, 'If you say you will do something do you always keep your promise, no matter how inconvenient it might be to do so?'), + ($testId, 'Do your moods go up and down?'), + ($testId, 'Do you generally do and say things quickly without stopping to think?'), + ($testId, 'Do you ever feel ‘just miserable’ for no good reason?'), + ($testId, 'Would you do almost anything for a dare?'), + ($testId, 'Do you suddenly feel shy when you want to talk to an attractive stranger?'), + ($testId, 'Once in a while do you lose your temper and get angry?'), + ($testId, 'Do you often do things on the spur of the moment?'), + ($testId, 'Do you often worry about things you should have done or said?'), + ($testId, 'Generally do you prefer reading to meeting people?'), + ($testId, 'Are your feelings rather easily hurt?'), + ($testId, 'Do you like going out a lot?'), + ($testId, 'Do you occasionally have thoughts and ideas that you would not like otherpeople to know about?'), + ($testId, 'Are you sometimes bubbling over with energy and sometimes very sluggish?'), + ($testId, 'Do you prefer to have few but special friends?'), + ($testId, 'Do you daydream a lot?'), + ($testId, 'When people shout at you do you shout back?'), + ($testId, 'Are you often troubled about feelings of guilt?'), + ($testId, 'Are all your habits good and desirable ones?'), + ($testId, 'Can you usually let yourself go and enjoy yourself a lot at a lively party?'), + ($testId, 'Would you call yourself tense or ‘highly strung’?'), + ($testId, 'Do other people think of you as being very lively?'), + ($testId, 'After you have done something important, do you come away feelingyou could have done better?'), + ($testId, 'Are you mostly quiet when you are with other people?'), + ($testId, 'Do you sometimes gossip?'), + ($testId, 'Do ideas run through your head so that you cannot sleep?'), + ($testId, 'If there is something you want to know about, would you rather look it upin a book than talk to someone about it?'), + ($testId, 'Do you get palpitations or thumping in your hear?'), + ($testId, 'Do you like the kind of work that you need to pay close attention to?'), + ($testId, 'Do you get attacks of shaking or trembling?'), + ($testId, 'Would you always declare everything at customs, even if you knewyou could never be found out?'), + ($testId, 'Do you hate being with a crowd who play jokes on one another?'), + ($testId, 'Are you an irritable person?'), + ($testId, 'Do you like doing things in which you have to act quickly?'), + ($testId, 'Do you worry about awful things that might happen?'), + ($testId, 'Are you slow and unhurried in the way you move?'), + ($testId, 'Have you ever been late for an appointment or work?'), + ($testId, 'Do you have many nightmares?'), + ($testId, 'Do you like talking to people so much that you never miss a chance of talking toa stranger?'), + ($testId, 'Are you troubled by aches and pains?'), + ($testId, 'Would you be very unhappy if you could not see lots of people most of the time?'), + ($testId, 'Would you call yourself a nervous person?'), + ($testId, 'Of all the people you know, are there some whom you definitely do not like?'), + ($testId, 'Would you say that you were fairly self-confident?'), + ($testId, 'Are you easily hurt when people find fault with you or your work?'), + ($testId, 'Do you find it hard to really enjoy yourself at a lively party?'), + ($testId, 'Are you troubled by feelings of inferiority?'), + ($testId, 'Can you easily get some life into a dull party?'), + ($testId, 'Do you sometimes talk about things you know nothing about?'), + ($testId, 'Do you worry about your health?'), + ($testId, 'Do you like playing pranks on others?'), + ($testId, 'Do you suffer from sleeplessness?'); + + INSERT INTO $scores (answer_id, question_id, scale_id, score_value) VALUES + ($yesId, 1, $eiId, 1), + ($yesId, 2, $nsId, 1), + ($yesId, 3, $eiId, 1), + ($yesId, 4, $nsId, 1), + ($noId, 5, $eiId, 1), + ($yesId, 6, $lieId, 1), + ($yesId, 7, $nsId, 1), + ($yesId, 8, $eiId, 1), + ($yesId, 9, $nsId, 1), + ($yesId, 10, $eiId, 1), + ($yesId, 11, $nsId, 1), + ($noId, 12, $lieId, 1), + ($yesId, 13, $eiId, 1), + ($yesId, 14, $nsId, 1), + ($noId, 15, $eiId, 1), + ($yesId, 16, $nsId, 1), + ($yesId, 17, $eiId, 1), + ($noId, 18, $lieId, 1), + ($yesId, 19, $nsId, 1), + ($noId, 20, $eiId, 1), + ($yesId, 21, $nsId, 1), + ($yesId, 22, $eiId, 1), + ($yesId, 23, $nsId, 1), + ($yesId, 24, $lieId, 1), + ($yesId, 25, $eiId, 1), + ($yesId, 26, $nsId, 1), + ($yesId, 27, $eiId, 1), + ($yesId, 28, $nsId, 1), + ($noId, 29, $eiId, 1), + ($noId, 30, $lieId, 1), + ($yesId, 31, $nsId, 1), + ($noId, 32, $eiId, 1), + ($yesId, 33, $nsId, 1), + ($noId, 34, $eiId, 1), + ($yesId, 35, $nsId, 1), + ($yesId, 36, $lieId, 1), + ($noId, 37, $eiId, 1), + ($yesId, 38, $nsId, 1), + ($yesId, 39, $eiId, 1), + ($yesId, 40, $nsId, 1), + ($noId, 41, $eiId, 1), + ($noId, 42, $lieId, 1), + ($yesId, 43, $nsId, 1), + ($yesId, 44, $eiId, 1), + ($yesId, 45, $nsId, 1), + ($yesId, 46, $eiId, 1), + ($yesId, 47, $nsId, 1), + ($noId, 48, $lieId, 1), + ($yesId, 49, $eiId, 1), + ($yesId, 50, $nsId, 1), + ($noId, 51, $eiId, 1), + ($yesId, 52, $nsId, 1), + ($yesId, 53, $eiId, 1), + ($noId, 54, $lieId, 1), + ($yesId, 55, $nsId, 1), + ($yesId, 56, $eiId, 1), + ($yesId, 57, $nsId, 1); + "); + } + + /** + * Select first field value + * + * @param string $sql the query to run + * + * @return string + */ + protected function field($sql) + { + $result = $this->select_one($sql); + if (empty($result)) { + return null; + } + return reset($result); + } + + public function down() + { + $posts = WP_DB_PREFIX . 'posts'; + $terms = WP_DB_PREFIX . 'terms'; + $termTaxonomy = WP_DB_PREFIX . 'term_taxonomy'; + $termRelashionships = WP_DB_PREFIX . 'term_relationships'; + $questions = WPT_DB_PREFIX . 'questions'; + $scores = WPT_DB_PREFIX . 'scores'; + + $this->execute(" + SET FOREIGN_KEY_CHECKS = 0; + TRUNCATE TABLE $scores; + TRUNCATE TABLE $questions; + SET FOREIGN_KEY_CHECKS = 1; + DELETE FROM $terms WHERE term_id IN ( + SELECT term_id FROM $termTaxonomy WHERE taxonomy LIKE 'wpt\_%' + ); + DELETE FROM $termRelashionships WHERE term_taxonomy_id IN ( + SELECT term_taxonomy_id FROM $termTaxonomy WHERE taxonomy LIKE 'wpt\_%' + ); + DELETE FROM $termTaxonomy WHERE taxonomy LIKE 'wpt\_%'; + DELETE FROM $posts WHERE post_parent IN ( + SELECT ID FROM (SELECT ID FROM $posts WHERE post_type = 'wpt_test') inn + ); + DELETE FROM $posts WHERE post_type = 'wpt_test'; + "); + } +} diff --git a/db/sql/add-eysenk-example.sql b/db/sql/add-eysenk-example.sql new file mode 100644 index 00000000..6edca00f --- /dev/null +++ b/db/sql/add-eysenk-example.sql @@ -0,0 +1,136 @@ +SET FOREIGN_KEY_CHECKS = 0; +TRUNCATE TABLE wp_t_scores; +TRUNCATE TABLE wp_t_questions; +SET FOREIGN_KEY_CHECKS = 1; +SHOW TABLE STATUS LIKE 'wp\_t\_%'; + +SELECT * FROM wp_posts WHERE post_type = 'wpt_test'; + +SET @test_id := (SELECT ID FROM wp_posts WHERE post_type = 'wpt_test' AND post_title = 'Eysenck’s Personality Inventory (EPI) (Extroversion/Introversion)' ORDER BY ID DESC LIMIT 1); +INSERT INTO wp_t_questions (test_id, question_title) VALUES +(@test_id, 'Do you often long for excitement?'), +(@test_id, 'Do you often need understanding friends to cheer you up?'), +(@test_id, 'Are you usually carefree?'), +(@test_id, 'Do you find it very hard to take no for an answer?'), +(@test_id, 'Do you stop and think things over before doing anything?'), +(@test_id, 'If you say you will do something do you always keep your promise,no matter how inconvenient it might be to do so?'), +(@test_id, 'Do your moods go up and down?'), +(@test_id, 'Do you generally do and say things quickly without stopping to think?'), +(@test_id, 'Do you ever feel ‘just miserable’ for no good reason?'), +(@test_id, 'Would you do almost anything for a dare?'), +(@test_id, 'Do you suddenly feel shy when you want to talk to an attractive stranger?'), +(@test_id, 'Once in a while do you lose your temper and get angry?'), +(@test_id, 'Do you often do things on the spur of the moment?'), +(@test_id, 'Do you often worry about things you should have done or said?'), +(@test_id, 'Generally do you prefer reading to meeting people?'), +(@test_id, 'Are your feelings rather easily hurt?'), +(@test_id, 'Do you like going out a lot?'), +(@test_id, 'Do you occasionally have thoughts and ideas that you would not like otherpeople to know about?'), +(@test_id, 'Are you sometimes bubbling over with energy and sometimes very sluggish?'), +(@test_id, 'Do you prefer to have few but special friends?'), +(@test_id, 'Do you daydream a lot?'), +(@test_id, 'When people shout at you do you shout back?'), +(@test_id, 'Are you often troubled about feelings of guilt?'), +(@test_id, 'Are all your habits good and desirable ones?'), +(@test_id, 'Can you usually let yourself go and enjoy yourself a lot at a lively party?'), +(@test_id, 'Would you call yourself tense or ‘highly strung’?'), +(@test_id, 'Do other people think of you as being very lively?'), +(@test_id, 'After you have done something important, do you come away feelingyou could have done better?'), +(@test_id, 'Are you mostly quiet when you are with other people?'), +(@test_id, 'Do you sometimes gossip?'), +(@test_id, 'Do ideas run through your head so that you cannot sleep?'), +(@test_id, 'If there is something you want to know about, would you rather look it upin a book than talk to someone about it?'), +(@test_id, 'Do you get palpitations or thumping in your hear?'), +(@test_id, 'Do you like the kind of work that you need to pay close attention to?'), +(@test_id, 'Do you get attacks of shaking or trembling?'), +(@test_id, 'Would you always declare everything at customs, even if you knewyou could never be found out?'), +(@test_id, 'Do you hate being with a crowd who play jokes on one another?'), +(@test_id, 'Are you an irritable person?'), +(@test_id, 'Do you like doing things in which you have to act quickly?'), +(@test_id, 'Do you worry about awful things that might happen?'), +(@test_id, 'Are you slow and unhurried in the way you move?'), +(@test_id, 'Have you ever been late for an appointment or work?'), +(@test_id, 'Do you have many nightmares?'), +(@test_id, 'Do you like talking to people so much that you never miss a chance of talking toa stranger?'), +(@test_id, 'Are you troubled by aches and pains?'), +(@test_id, 'Would you be very unhappy if you could not see lots of people most of the time?'), +(@test_id, 'Would you call yourself a nervous person?'), +(@test_id, 'Of all the people you know, are there some whom you definitely do not like?'), +(@test_id, 'Would you say that you were fairly self-confident?'), +(@test_id, 'Are you easily hurt when people find fault with you or your work?'), +(@test_id, 'Do you find it hard to really enjoy yourself at a lively party?'), +(@test_id, 'Are you troubled by feelings of inferiority?'), +(@test_id, 'Can you easily get some life into a dull party?'), +(@test_id, 'Do you sometimes talk about things you know nothing about?'), +(@test_id, 'Do you worry about your health?'), +(@test_id, 'Do you like playing pranks on others?'), +(@test_id, 'Do you suffer from sleeplessness?') + +; +SELECT * FROM wp_t_questions; + +SET @yes_id := (SELECT term_id FROM wp_terms WHERE name = 'Yes' ORDER BY term_id DESC); +SET @no_id := (SELECT term_id FROM wp_terms WHERE name = 'No' ORDER BY term_id DESC); +SET @ei_id := (SELECT term_id FROM wp_terms WHERE name = 'Extraversion/Introversion' ORDER BY term_id DESC); +SET @ns_id := (SELECT term_id FROM wp_terms WHERE name = 'Neuroticism/Stability' ORDER BY term_id DESC); +SET @l_id := (SELECT term_id FROM wp_terms WHERE name = 'Lie' ORDER BY term_id DESC); + +INSERT INTO wp_t_scores (answer_id, question_id, scale_id, score_value) VALUES +(@yes_id, 1, @ei_id, 1), +(@yes_id, 2, @ns_id, 1), +(@yes_id, 3, @ei_id, 1), +(@yes_id, 4, @ns_id, 1), +(@no_id, 5, @ei_id, 1), +(@yes_id, 6, @l_id, 1), +(@yes_id, 7, @ns_id, 1), +(@yes_id, 8, @ei_id, 1), +(@yes_id, 9, @ns_id, 1), +(@yes_id, 10, @ei_id, 1), +(@yes_id, 11, @ns_id, 1), +(@no_id, 12, @l_id, 1), +(@yes_id, 13, @ei_id, 1), +(@yes_id, 14, @ns_id, 1), +(@no_id, 15, @ei_id, 1), +(@yes_id, 16, @ns_id, 1), +(@yes_id, 17, @ei_id, 1), +(@no_id, 18, @l_id, 1), +(@yes_id, 19, @ns_id, 1), +(@no_id, 20, @ei_id, 1), +(@yes_id, 21, @ns_id, 1), +(@yes_id, 22, @ei_id, 1), +(@yes_id, 23, @ns_id, 1), +(@yes_id, 24, @l_id, 1), +(@yes_id, 25, @ei_id, 1), +(@yes_id, 26, @ns_id, 1), +(@yes_id, 27, @ei_id, 1), +(@yes_id, 28, @ns_id, 1), +(@no_id, 29, @ei_id, 1), +(@no_id, 30, @l_id, 1), +(@yes_id, 31, @ns_id, 1), +(@no_id, 32, @ei_id, 1), +(@yes_id, 33, @ns_id, 1), +(@no_id, 34, @ei_id, 1), +(@yes_id, 35, @ns_id, 1), +(@yes_id, 36, @l_id, 1), +(@no_id, 37, @ei_id, 1), +(@yes_id, 38, @ns_id, 1), +(@yes_id, 39, @ei_id, 1), +(@yes_id, 40, @ns_id, 1), +(@no_id, 41, @ei_id, 1), +(@no_id, 42, @l_id, 1), +(@yes_id, 43, @ns_id, 1), +(@yes_id, 44, @ei_id, 1), +(@yes_id, 45, @ns_id, 1), +(@yes_id, 46, @ei_id, 1), +(@yes_id, 47, @ns_id, 1), +(@no_id, 48, @l_id, 1), +(@yes_id, 49, @ei_id, 1), +(@yes_id, 50, @ns_id, 1), +(@no_id, 51, @ei_id, 1), +(@yes_id, 52, @ns_id, 1), +(@yes_id, 53, @ei_id, 1), +(@no_id, 54, @l_id, 1), +(@yes_id, 55, @ns_id, 1), +(@yes_id, 56, @ei_id, 1), +(@yes_id, 57, @ns_id, 1) +; diff --git a/db/sql/drop-all.sql b/db/sql/drop-all.sql new file mode 100644 index 00000000..ae07b81a --- /dev/null +++ b/db/sql/drop-all.sql @@ -0,0 +1,10 @@ +set FOREIGN_KEY_CHECKS = 0; +drop table if exists `wp_testing`.`wp_t_answers`; +drop table if exists `wp_testing`.`wp_t_answers_parameters`; +drop table if exists `wp_testing`.`wp_t_parameters`; +drop table if exists `wp_testing`.`wp_t_questions`; +drop table if exists `wp_testing`.`wp_t_scales`; +drop table if exists `wp_testing`.`wp_t_scales_tests`; +drop table if exists `wp_testing`.`wp_t_schema_migrations`; +drop table if exists `wp_testing`.`wp_t_tests`; +set FOREIGN_KEY_CHECKS = 1; diff --git a/db/sql/extract-migration-into-example.sql b/db/sql/extract-migration-into-example.sql new file mode 100644 index 00000000..950a15db --- /dev/null +++ b/db/sql/extract-migration-into-example.sql @@ -0,0 +1,21 @@ +SELECT * FROM wp_terms WHERE term_id IN ( + SELECT term_id FROM wp_term_taxonomy WHERE taxonomy LIKE 'wpt\_%' +); +SELECT * FROM wp_term_relationships WHERE term_taxonomy_id IN ( + SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE taxonomy LIKE 'wpt\_%' +); +SELECT * FROM wp_term_taxonomy WHERE taxonomy LIKE 'wpt\_%'; + +DELETE FROM wp_term_relationships WHERE term_taxonomy_id NOT IN ( + SELECT term_taxonomy_id FROM wp_term_taxonomy +); + +SELECT ID FROM wp_posts WHERE post_type = 'wpt_test' ORDER BY ID DESC LIMIT 1; + +DELETE FROM wp_posts WHERE post_parent IN ( + SELECT ID FROM wp_posts WHERE post_type = 'wpt_test' +); + +-- @see prev. SQL for: +-- wp_t_questions +-- wp_t_scores \ No newline at end of file diff --git a/db/sql/generate-phpdoc.sql b/db/sql/generate-phpdoc.sql new file mode 100644 index 00000000..91cc0eef --- /dev/null +++ b/db/sql/generate-phpdoc.sql @@ -0,0 +1,18 @@ +-- SELECT * FROM wp_testing.wp_t_test; + +set @db := 'wp_testing'; +set @global_prefix := 'wp_'; +set @prefix := concat(@global_prefix, 't_'); + +select isc.column_name, isc.data_type +from information_schema.columns as isc +join ( + select 'get' as op + union select 'set' + union select 'encode' + union select 'prepare' + union select 'inspect' +) as ops +where isc.table_schema = @db +and isc.table_name = concat(@prefix, 'test') +; diff --git a/db/sql/get-scales-from-wp-terms.sql b/db/sql/get-scales-from-wp-terms.sql new file mode 100644 index 00000000..797fff1c --- /dev/null +++ b/db/sql/get-scales-from-wp-terms.sql @@ -0,0 +1,34 @@ +SELECT * FROM wp_terms +WHERE term_id IN ( + SELECT term_id FROM wp_term_taxonomy WHERE taxonomy = 'wpt_scale' +) +; + +SELECT * FROM wp_term_relationships where object_id = 40 order by term_order; + +SELECT * FROM wp_testing.wp_term_taxonomy; +SELECT * FROM wp_testing.wp_term_relationships; + +SELECT + * +FROM wp_terms +LEFT JOIN wp_term_relationships ON wp_terms.term_id = wp_term_relationships.term_taxonomy_id +-- LEFT JOIN wp_posts ON wp_term_relationships.object_id = wp_posts.id +WHERE wp_terms.term_id = 24 +-- WHERE wp_posts.id = 40 +-- GROUP BY wp_terms.term_id , wp_terms.name , wp_terms.slug , wp_terms.term_group +ORDER BY wp_terms.term_id ASC; + + +SELECT + wp_term_taxonomy . * +FROM + wp_term_taxonomy + LEFT JOIN + wp_term_relationships ON wp_term_taxonomy.term_id = wp_term_relationships.term_taxonomy_id + LEFT JOIN + wp_posts ON wp_term_relationships.object_id = wp_posts.id +WHERE + wp_posts.id = 40 +-- GROUP BY wp_term_taxonomy.term_taxonomy_id , wp_term_taxonomy.term_id , wp_term_taxonomy.taxonomy , wp_term_taxonomy.description , wp_term_taxonomy.parent , wp_term_taxonomy.count +ORDER BY wp_term_taxonomy.term_taxonomy_id ASC; \ No newline at end of file diff --git a/db/sql/get-scores.sql b/db/sql/get-scores.sql new file mode 100644 index 00000000..d2d092fa --- /dev/null +++ b/db/sql/get-scores.sql @@ -0,0 +1,5 @@ +SELECT * FROM wp_terms; +SELECT * FROM wp_t_questions; +INSERT INTO wp_t_scores (answer_id, question_id, scale_id, score_value) VALUES ('25', '21', '15', '1'); +INSERT INTO wp_t_scores (answer_id, question_id, scale_id, score_value) VALUES ('25', '23', '15', '1'); +SELECT * FROM wp_t_scores; \ No newline at end of file diff --git a/db/sql/manual-add-questions.sql b/db/sql/manual-add-questions.sql new file mode 100644 index 00000000..5e5dd62b --- /dev/null +++ b/db/sql/manual-add-questions.sql @@ -0,0 +1,8 @@ +select * from wp_posts where ID = 40; +select * from wp_posts where ID = 68; +select * from wp_t_questions; + +TRUNCATE `wp_t_questions`; +INSERT INTO `wp_t_questions` (`test_id`, `question_title`) VALUES ('40', 'one'); +INSERT INTO `wp_t_questions` (`test_id`, `question_title`) VALUES ('40', 'two'); +INSERT INTO `wp_t_questions` (`test_id`, `question_title`) VALUES ('40', 'three'); diff --git a/db/sql/wp-testing.mwb b/db/sql/wp-testing.mwb new file mode 100644 index 00000000..8784b162 Binary files /dev/null and b/db/sql/wp-testing.mwb differ diff --git a/img/EPI-scales.png b/img/EPI-scales.png new file mode 100644 index 00000000..22e3d6a6 Binary files /dev/null and b/img/EPI-scales.png differ diff --git a/js/test-pass-fill-form.js b/js/test-pass-fill-form.js new file mode 100644 index 00000000..ddab6448 --- /dev/null +++ b/js/test-pass-fill-form.js @@ -0,0 +1,24 @@ +jQuery(document).ready(function($) { + var form = $('#wpt-test-form'); + + if (0 == form.length) { + return; + } + + var button = form.find('.button'); + button.addClass('disabled').attr('disabled', 'disabled'); + + var questions = []; + form.find('input:radio').each(function() { + questions.push($(this).attr('name')); + }); + questions = _.uniq(questions); + + form.find('input:radio').change(function() { + if (form.find('input:radio:checked').length < questions.length) { + return; + } + button.removeAttr('disabled').removeClass('disabled'); + }); + +}); diff --git a/js/test-pass-get-results.js b/js/test-pass-get-results.js new file mode 100644 index 00000000..8f5aae4e --- /dev/null +++ b/js/test-pass-get-results.js @@ -0,0 +1,3 @@ +jQuery(document).ready(function($) { + // nothing hia +}); diff --git a/js/vendor/lodash/lodash.compat.min.js b/js/vendor/lodash/lodash.compat.min.js new file mode 100644 index 00000000..d03b6ba6 --- /dev/null +++ b/js/vendor/lodash/lodash.compat.min.js @@ -0,0 +1,61 @@ +/** + * @license + * Lo-Dash 2.4.1 (Custom Build) lodash.com/license | Underscore.js 1.5.2 underscorejs.org/LICENSE + * Build: `lodash -o ./dist/lodash.compat.js` + */ +;(function(){function n(n,t,e){e=(e||0)-1;for(var r=n?n.length:0;++ei||typeof a=="undefined")return 1;if(ae?0:e);++r=_&&a===n,f=[];if(l){var c=o(r);c?(a=t,r=c):l=false}for(;++ua(r,c)&&f.push(c);return l&&p(r),f}function ot(n,t,e,r){r=(r||0)-1; +for(var u=n?n.length:0,o=[];++r=_&&l===n,h=u||g?i():s;for(g&&(h=o(h),l=t);++al(h,y))&&((u||g)&&h.push(y),s.push(v))}return g?(c(h.k),p(h)):u&&c(h),s}function ct(n){return function(t,e,r){var u={}; +if(e=v.createCallback(e,r,3),qe(t)){r=-1;for(var o=t.length;++rk;k++)r+="n='"+e.h[k]+"';if((!(r&&x[n])&&m.call(t,n))",e.j||(r+="||(!x[n]&&t[n]!==A[n])"),r+="){"+e.g+"}"; +r+="}"}return(e.b||Le.nonEnumArgs)&&(r+="}"),r+=e.c+";return E",n("d,j,k,m,o,p,q,s,v,A,B,y,I,J,L",t+r+"}")(tt,q,ce,we,d,dt,qe,kt,Q.f,pe,X,$e,M,se,he)}function gt(n){return Ve[n]}function ht(){var t=(t=v.indexOf)===zt?n:t;return t}function vt(n){return typeof n=="function"&&ve.test(n)}function yt(n){var t,e;return!n||he.call(n)!=G||(t=n.constructor,jt(t)&&!(t instanceof t))||!Le.argsClass&&dt(n)||!Le.nodeClass&&f(n)?false:Le.ownLast?(nr(n,function(n,t,r){return e=we.call(r,t),false}),false!==e):(nr(n,function(n,t){e=t +}),typeof e=="undefined"||we.call(n,e))}function mt(n){return He[n]}function dt(n){return n&&typeof n=="object"&&typeof n.length=="number"&&he.call(n)==T||false}function bt(n,t,e){var r=We(n),u=r.length;for(t=tt(t,e,3);u--&&(e=r[u],false!==t(n[e],e,n)););return n}function _t(n){var t=[];return nr(n,function(n,e){jt(n)&&t.push(e)}),t.sort()}function wt(n){for(var t=-1,e=We(n),r=e.length,u={};++te?Be(0,o+e):e)||0,qe(n)?a=-1o&&(o=i)}}else t=null==t&&kt(n)?r:v.createCallback(t,e,3),Xe(n,function(n,e,r){e=t(n,e,r),e>u&&(u=e,o=n)});return o}function Rt(n,t,e,r){var u=3>arguments.length;if(t=v.createCallback(t,r,4),qe(n)){var o=-1,a=n.length;for(u&&(e=n[++o]);++oarguments.length; +return t=v.createCallback(t,r,4),Nt(n,function(n,r,o){e=u?(u=false,n):t(e,n,r,o)}),e}function Tt(n){var t=-1,e=n?n.length:0,r=Zt(typeof e=="number"?e:0);return Dt(n,function(n){var e=lt(0,++t);r[t]=r[e],r[e]=n}),r}function $t(n,t,e){var r;if(t=v.createCallback(t,e,3),qe(n)){e=-1;for(var u=n.length;++er?Be(0,u+r):r||0}else if(r)return r=Kt(t,e),t[r]===e?r:-1;return n(t,e,r)}function qt(n,t,e){if(typeof t!="number"&&null!=t){var r=0,u=-1,o=n?n.length:0;for(t=v.createCallback(t,e,3);++u>>1,e(n[r])e?0:e);++t=h;m?(u&&(u=me(u)),c=a,o=n.apply(i,r)):u||(u=Ce(y,h))}return m&&l?l=me(l):l||t===p||(l=Ce(v,t)),e&&(m=true,o=n.apply(i,r)),!m||l||u||(r=i=null),o}}function Ht(n){return n}function Ut(n,t,e){var r=true,u=t&&_t(t);t&&(e||u.length)||(null==e&&(e=t),o=y,t=n,n=v,u=_t(t)),false===e?r=false:xt(e)&&"chain"in e&&(r=e.chain);var o=n,a=jt(o);Dt(u,function(e){var u=n[e]=t[e];a&&(o.prototype[e]=function(){var t=this.__chain__,e=this.__wrapped__,a=[e];if(je.apply(a,arguments),a=u.apply(n,a),r||t){if(e===a&&xt(a))return this; +a=new o(a),a.__chain__=t}return a})})}function Qt(){}function Xt(n){return function(t){return t[n]}}function Yt(){return this.__wrapped__}e=e?ut.defaults(Z.Object(),e,ut.pick(Z,R)):Z;var Zt=e.Array,ne=e.Boolean,te=e.Date,ee=e.Function,re=e.Math,ue=e.Number,oe=e.Object,ae=e.RegExp,ie=e.String,le=e.TypeError,fe=[],ce=e.Error.prototype,pe=oe.prototype,se=ie.prototype,ge=e._,he=pe.toString,ve=ae("^"+ie(he).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),ye=re.ceil,me=e.clearTimeout,de=re.floor,be=ee.prototype.toString,_e=vt(_e=oe.getPrototypeOf)&&_e,we=pe.hasOwnProperty,je=fe.push,xe=pe.propertyIsEnumerable,Ce=e.setTimeout,ke=fe.splice,Ee=fe.unshift,Oe=function(){try{var n={},t=vt(t=oe.defineProperty)&&t,e=t(n,n,n)&&t +}catch(r){}return e}(),Se=vt(Se=oe.create)&&Se,Ae=vt(Ae=Zt.isArray)&&Ae,Ie=e.isFinite,De=e.isNaN,Ne=vt(Ne=oe.keys)&&Ne,Be=re.max,Pe=re.min,Re=e.parseInt,Fe=re.random,Te={};Te[$]=Zt,Te[L]=ne,Te[z]=te,Te[K]=ee,Te[G]=oe,Te[W]=ue,Te[J]=ae,Te[M]=ie;var $e={};$e[$]=$e[z]=$e[W]={constructor:true,toLocaleString:true,toString:true,valueOf:true},$e[L]=$e[M]={constructor:true,toString:true,valueOf:true},$e[q]=$e[K]=$e[J]={constructor:true,toString:true},$e[G]={constructor:true},function(){for(var n=F.length;n--;){var t,e=F[n]; +for(t in $e)we.call($e,t)&&!we.call($e[t],e)&&($e[t][e]=false)}}(),y.prototype=v.prototype;var Le=v.support={};!function(){var n=function(){this.x=1},t={0:1,length:1},r=[];n.prototype={valueOf:1,y:1};for(var u in new n)r.push(u);for(u in arguments);Le.argsClass=he.call(arguments)==T,Le.argsObject=arguments.constructor==oe&&!(arguments instanceof Zt),Le.enumErrorProps=xe.call(ce,"message")||xe.call(ce,"name"),Le.enumPrototypes=xe.call(n,"prototype"),Le.funcDecomp=!vt(e.WinRTError)&&B.test(g),Le.funcNames=typeof ee.name=="string",Le.nonEnumArgs=0!=u,Le.nonEnumShadows=!/valueOf/.test(r),Le.ownLast="x"!=r[0],Le.spliceObjects=(fe.splice.call(t,0,1),!t[0]),Le.unindexedChars="xx"!="x"[0]+oe("x")[0]; +try{Le.nodeClass=!(he.call(document)==G&&!({toString:0}+""))}catch(o){Le.nodeClass=true}}(1),v.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:I,variable:"",imports:{_:v}},Se||(nt=function(){function n(){}return function(t){if(xt(t)){n.prototype=t;var r=new n;n.prototype=null}return r||e.Object()}}());var ze=Oe?function(n,t){U.value=t,Oe(n,"__bindData__",U)}:Qt;Le.argsClass||(dt=function(n){return n&&typeof n=="object"&&typeof n.length=="number"&&we.call(n,"callee")&&!xe.call(n,"callee")||false +});var qe=Ae||function(n){return n&&typeof n=="object"&&typeof n.length=="number"&&he.call(n)==$||false},Ke=st({a:"z",e:"[]",i:"if(!(B[typeof z]))return E",g:"E.push(n)"}),We=Ne?function(n){return xt(n)?Le.enumPrototypes&&typeof n=="function"||Le.nonEnumArgs&&n.length&&dt(n)?Ke(n):Ne(n):[]}:Ke,Ge={a:"g,e,K",i:"e=e&&typeof K=='undefined'?e:d(e,K,3)",b:"typeof u=='number'",v:We,g:"if(e(t[n],n,g)===false)return E"},Je={a:"z,H,l",i:"var a=arguments,b=0,c=typeof l=='number'?2:a.length;while(++b":">",'"':""","'":"'"},He=wt(Ve),Ue=ae("("+We(He).join("|")+")","g"),Qe=ae("["+We(Ve).join("")+"]","g"),Xe=st(Ge),Ye=st(Je,{i:Je.i.replace(";",";if(c>3&&typeof a[c-2]=='function'){var e=d(a[--c-1],a[c--],2)}else if(c>2&&typeof a[c-1]=='function'){e=a[--c]}"),g:"E[n]=e?e(E[n],t[n]):t[n]"}),Ze=st(Je),nr=st(Ge,Me,{j:false}),tr=st(Ge,Me); +jt(/x/)&&(jt=function(n){return typeof n=="function"&&he.call(n)==K});var er=_e?function(n){if(!n||he.call(n)!=G||!Le.argsClass&&dt(n))return false;var t=n.valueOf,e=vt(t)&&(e=_e(t))&&_e(e);return e?n==e||_e(n)==e:yt(n)}:yt,rr=ct(function(n,t,e){we.call(n,e)?n[e]++:n[e]=1}),ur=ct(function(n,t,e){(we.call(n,e)?n[e]:n[e]=[]).push(t)}),or=ct(function(n,t,e){n[e]=t}),ar=Bt,ir=vt(ir=te.now)&&ir||function(){return(new te).getTime()},lr=8==Re(j+"08")?Re:function(n,t){return Re(kt(n)?n.replace(D,""):n,t||0)}; +return v.after=function(n,t){if(!jt(t))throw new le;return function(){return 1>--n?t.apply(this,arguments):void 0}},v.assign=Ye,v.at=function(n){var t=arguments,e=-1,r=ot(t,true,false,1),t=t[2]&&t[2][t[1]]===n?1:r.length,u=Zt(t);for(Le.unindexedChars&&kt(n)&&(n=n.split(""));++e=_&&o(r?e[r]:s)))}var f=e[0],h=-1,v=f?f.length:0,y=[];n:for(;++h(m?t(m,g):l(s,g))){for(r=u,(m||s).push(g);--r;)if(m=a[r],0>(m?t(m,g):l(e[r],g)))continue n;y.push(g) +}}for(;u--;)(m=a[u])&&p(m);return c(a),c(s),y},v.invert=wt,v.invoke=function(n,t){var e=s(arguments,2),r=-1,u=typeof t=="function",o=n?n.length:0,a=Zt(typeof o=="number"?o:0);return Dt(n,function(n){a[++r]=(u?t:n[t]).apply(n,e)}),a},v.keys=We,v.map=Bt,v.mapValues=function(n,t,e){var r={};return t=v.createCallback(t,e,3),tr(n,function(n,e,u){r[e]=t(n,e,u)}),r},v.max=Pt,v.memoize=function(n,t){if(!jt(n))throw new le;var e=function(){var r=e.cache,u=t?t.apply(this,arguments):b+arguments[0];return we.call(r,u)?r[u]:r[u]=n.apply(this,arguments) +};return e.cache={},e},v.merge=function(n){var t=arguments,e=2;if(!xt(n))return n;if("number"!=typeof t[2]&&(e=t.length),3e?Be(0,r+e):Pe(e,r-1))+1);r--;)if(n[r]===t)return r;return-1},v.mixin=Ut,v.noConflict=function(){return e._=ge,this},v.noop=Qt,v.now=ir,v.parseInt=lr,v.random=function(n,t,e){var r=null==n,u=null==t;return null==e&&(typeof n=="boolean"&&u?(e=n,n=1):u||typeof t!="boolean"||(e=t,u=true)),r&&u&&(t=1),n=+n||0,u?(t=n,n=0):t=+t||0,e||n%1||t%1?(e=Fe(),Pe(n+e*(t-n+parseFloat("1e-"+((e+"").length-1))),t)):lt(n,t)},v.reduce=Rt,v.reduceRight=Ft,v.result=function(n,t){if(n){var e=n[t]; +return jt(e)?n[t]():e}},v.runInContext=g,v.size=function(n){var t=n?n.length:0;return typeof t=="number"?t:We(n).length},v.some=$t,v.sortedIndex=Kt,v.template=function(n,t,e){var r=v.templateSettings;n=ie(n||""),e=Ze({},e,r);var u,o=Ze({},e.imports,r.imports),r=We(o),o=Et(o),i=0,l=e.interpolate||N,f="__p+='",l=ae((e.escape||N).source+"|"+l.source+"|"+(l===I?O:N).source+"|"+(e.evaluate||N).source+"|$","g");n.replace(l,function(t,e,r,o,l,c){return r||(r=o),f+=n.slice(i,c).replace(P,a),e&&(f+="'+__e("+e+")+'"),l&&(u=true,f+="';"+l+";\n__p+='"),r&&(f+="'+((__t=("+r+"))==null?'':__t)+'"),i=c+t.length,t +}),f+="';",l=e=e.variable,l||(e="obj",f="with("+e+"){"+f+"}"),f=(u?f.replace(x,""):f).replace(C,"$1").replace(E,"$1;"),f="function("+e+"){"+(l?"":e+"||("+e+"={});")+"var __t,__p='',__e=_.escape"+(u?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+f+"return __p}";try{var c=ee(r,"return "+f).apply(h,o)}catch(p){throw p.source=f,p}return t?c(t):(c.source=f,c)},v.unescape=function(n){return null==n?"":ie(n).replace(Ue,mt)},v.uniqueId=function(n){var t=++m;return ie(null==n?"":n)+t +},v.all=St,v.any=$t,v.detect=It,v.findWhere=It,v.foldl=Rt,v.foldr=Ft,v.include=Ot,v.inject=Rt,Ut(function(){var n={};return tr(v,function(t,e){v.prototype[e]||(n[e]=t)}),n}(),false),v.first=Lt,v.last=function(n,t,e){var r=0,u=n?n.length:0;if(typeof t!="number"&&null!=t){var o=u;for(t=v.createCallback(t,e,3);o--&&t(n[o],o,n);)r++}else if(r=t,null==r||e)return n?n[u-1]:h;return s(n,Be(0,u-r))},v.sample=function(n,t,e){return n&&typeof n.length!="number"?n=Et(n):Le.unindexedChars&&kt(n)&&(n=n.split("")),null==t||e?n?n[lt(0,n.length-1)]:h:(n=Tt(n),n.length=Pe(Be(0,t),n.length),n) +},v.take=Lt,v.head=Lt,tr(v,function(n,t){var e="sample"!==t;v.prototype[t]||(v.prototype[t]=function(t,r){var u=this.__chain__,o=n(this.__wrapped__,t,r);return u||null!=t&&(!r||e&&typeof t=="function")?new y(o,u):o})}),v.VERSION="2.4.1",v.prototype.chain=function(){return this.__chain__=true,this},v.prototype.toString=function(){return ie(this.__wrapped__)},v.prototype.value=Yt,v.prototype.valueOf=Yt,Xe(["join","pop","shift"],function(n){var t=fe[n];v.prototype[n]=function(){var n=this.__chain__,e=t.apply(this.__wrapped__,arguments); +return n?new y(e,n):e}}),Xe(["push","reverse","sort","unshift"],function(n){var t=fe[n];v.prototype[n]=function(){return t.apply(this.__wrapped__,arguments),this}}),Xe(["concat","slice","splice"],function(n){var t=fe[n];v.prototype[n]=function(){return new y(t.apply(this.__wrapped__,arguments),this.__chain__)}}),Le.spliceObjects||Xe(["pop","shift","splice"],function(n){var t=fe[n],e="splice"==n;v.prototype[n]=function(){var n=this.__chain__,r=this.__wrapped__,u=t.apply(r,arguments);return 0===r.length&&delete r[0],n||e?new y(u,n):u +}}),v}var h,v=[],y=[],m=0,d={},b=+new Date+"",_=75,w=40,j=" \t\x0B\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000",x=/\b__p\+='';/g,C=/\b(__p\+=)''\+/g,E=/(__e\(.*?\)|\b__t\))\+'';/g,O=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,S=/\w*$/,A=/^\s*function[ \n\r\t]+\w/,I=/<%=([\s\S]+?)%>/g,D=RegExp("^["+j+"]*0+(?=.$)"),N=/($^)/,B=/\bthis\b/,P=/['\n\r\t\u2028\u2029\\]/g,R="Array Boolean Date Error Function Math Number Object RegExp String _ attachEvent clearTimeout isFinite isNaN parseInt setTimeout".split(" "),F="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "),T="[object Arguments]",$="[object Array]",L="[object Boolean]",z="[object Date]",q="[object Error]",K="[object Function]",W="[object Number]",G="[object Object]",J="[object RegExp]",M="[object String]",V={}; +V[K]=false,V[T]=V[$]=V[L]=V[z]=V[W]=V[G]=V[J]=V[M]=true;var H={leading:false,maxWait:0,trailing:false},U={configurable:false,enumerable:false,value:null,writable:false},Q={a:"",b:null,c:"",d:"",e:"",v:null,g:"",h:null,support:null,i:"",j:false},X={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false},Y={"\\":"\\","'":"'","\n":"n","\r":"r","\t":"t","\u2028":"u2028","\u2029":"u2029"},Z=X[typeof window]&&window||this,nt=X[typeof exports]&&exports&&!exports.nodeType&&exports,tt=X[typeof module]&&module&&!module.nodeType&&module,et=tt&&tt.exports===nt&&nt,rt=X[typeof global]&&global; +!rt||rt.global!==rt&&rt.window!==rt||(Z=rt);var ut=g();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(Z._=ut, define(function(){return ut})):nt&&tt?et?(tt.exports=ut)._=ut:nt._=ut:Z._=ut}).call(this); \ No newline at end of file diff --git a/ruckusing.conf.php b/ruckusing.conf.php new file mode 100644 index 00000000..fbba3128 --- /dev/null +++ b/ruckusing.conf.php @@ -0,0 +1,27 @@ + array( + 'development' => array( + 'type' => 'mysql', + 'host' => 'localhost', + 'port' => 3306, + 'database' => 'wordpress', + 'user' => 'root', + 'password' => '', + 'charset' => 'utf8', + ), + ), + 'db_dir' => $databaseDirectory, + 'migrations_dir' => array('default' => $databaseDirectory . DIRECTORY_SEPARATOR . 'migrations'), + 'log_dir' => $databaseDirectory . DIRECTORY_SEPARATOR . 'log', +); diff --git a/src/Doer/AbstractDoer.php b/src/Doer/AbstractDoer.php new file mode 100644 index 00000000..e532a4a4 --- /dev/null +++ b/src/Doer/AbstractDoer.php @@ -0,0 +1,47 @@ +wp = $wp; + $this->registerScripts(); + } + + /** + * Register common used scripts for future dependencies + */ + protected function registerScripts() + { + $this->wp + ->registerPluginScript('lodash', 'js/vendor/lodash/lodash.compat.min.js', array(), '2.4.1') + ; + } + + protected function output($__template, $__params = array()) + { + if (substr($__template, -4) != '.php') { + $__template = dirname(dirname(__FILE__)) . '/Template/' . $__template . '.php'; + } + extract($__params, EXTR_SKIP); + include $__template; + } + + protected function render($__template, $__params = array()) + { + ob_start(); + $this->output($__template, $__params); + return ob_get_clean(); + } + + protected function isPost() + { + return fRequest::isPost(); + } +} diff --git a/src/Doer/ShortcodeProcessor.php b/src/Doer/ShortcodeProcessor.php new file mode 100644 index 00000000..5128b333 --- /dev/null +++ b/src/Doer/ShortcodeProcessor.php @@ -0,0 +1,14 @@ +findAllPublished(); + return $this->render('Shortcode/list', array( + 'tests' => $tests, + 'wp' => $this->wp, + )); + } +} diff --git a/src/Doer/TestEditor.php b/src/Doer/TestEditor.php new file mode 100644 index 00000000..5bfd432e --- /dev/null +++ b/src/Doer/TestEditor.php @@ -0,0 +1,50 @@ +wp + ->addMetaBox('wpt_edit_questions', 'Edit Questions', array($this, 'renderEditQuestions'), 'wpt_test') + ->addMetaBox('wpt_add_questions', 'Add New Questions', array($this, 'renderAddQuestions'), 'wpt_test') + ->addAction('save_post', array($this, 'saveTest'), 10, 3) + ; + } + + public function renderEditQuestions(WP_Post $item) + { + $this->wp->enqueuePluginStyle('wpt_admin', 'css/admin.css'); + $test = new WpTesting_Model_Test($item); + $this->output('Test/Editor/edit-questions', array( + 'scales' => $test->buildScales(), + 'questions' => $test->buildQuestions(), + 'prefix' => $test->getQuestionsPrefix(), + 'scorePrefix' => $test->getScorePrefix(), + 'isWarnOfSettings' => $test->isWarnOfSettings(), + )); + } + + public function renderAddQuestions(WP_Post $item) + { + $this->wp->enqueuePluginStyle('wpt_admin', 'css/admin.css'); + $test = new WpTesting_Model_Test($item); + $this->output('Test/Editor/add-questions', array( + 'addNewCount' => 10, + 'startFrom' => $test->buildQuestions()->count(), + 'scales' => $test->buildScales(), + 'prefix' => $test->getQuestionsPrefix(), + )); + } + + public function saveTest($id, WP_Post $item, $isUpdate) + { + $test = new WpTesting_Model_Test($item); + if (!$test->getId()) { + return; + } + $test->populateQuestions(true); + $test->store(true); + } + +} diff --git a/src/Doer/TestPasser.php b/src/Doer/TestPasser.php new file mode 100644 index 00000000..1f81e4db --- /dev/null +++ b/src/Doer/TestPasser.php @@ -0,0 +1,52 @@ +wp->getQuery()->get_queried_object(); + if ($object instanceof WP_Post && $object->post_type == 'wpt_test') { + $this->test = new WpTesting_Model_Test($object); + $this->wp->addFilter('the_content', array($this, 'renderTestContent')); + } + return $this; + } + + public function renderTestContent($content) + { + $action = $this->isPost() ? 'get-results' : 'fill-form'; + $template = $this->wp->locateTemplate('entry-content-wpt-test-' . $action . '.php'); + $template = ($template) ? $template : 'Test/Passer/' . $action; + + if ($this->isPost()) { + $passing = new WpTesting_Model_Passing(); + $passing->populate($this->test); + $params = array( + 'content' => $content, + 'test' => $this->test, + 'passing' => $passing, + 'scales' => $passing->calculateScalesTotals(), + ); + } else { + $params = array( + 'content' => $content, + 'test' => $this->test, + 'questions' => $this->test->buildQuestions(), + ); + } + + $this->wp + ->enqueuePluginStyle('wpt_public', 'css/public.css') + ->enqueuePluginScript('wpt_test_pass_' . $action, 'js/test-pass-' . $action . '.js', array('jquery', 'lodash'), false, true) + ; + + return $this->render($template, $params); + } + +} diff --git a/src/Doer/WordPressEntitiesRegistrator.php b/src/Doer/WordPressEntitiesRegistrator.php new file mode 100644 index 00000000..daf796a5 --- /dev/null +++ b/src/Doer/WordPressEntitiesRegistrator.php @@ -0,0 +1,94 @@ +registerPostType('wpt_test', array( + 'labels' => $this->generateLabels('test'), + 'description' => 'Instrument to measure unobserved constructs (latent variables). Typically it is a series of tasks or problems that the respondent has to solve.', + 'public' => true, + 'menu_position' => 5, + 'menu_icon' => 'dashicons-editor-paste-text', + 'supports' => array( + 'title', + 'editor', + 'thumbnail', + 'comments', + ), + 'taxonomies' => array( + 'wpt_answer', + 'wpt_scale', + 'wpt_result', + 'wpt_category', + ), + 'has_archive' => true, + 'rewrite' => array( + 'slug' => 'test', + 'pages' => false, + ), + 'can_export' => true, + )); + + $this + ->addTaxonomy('answer') + ->addTaxonomy('scale') + ->addTaxonomy('result') + ->addTaxonomy('category', array( + 'labels' => $this->generateLabels('category', 'categories'), + 'public' => true, + 'show_in_nav_menus' => true, + 'rewrite' => array( + 'slug' => 'test-category', + ), + )) + ; + + $this->wp->getRewrite()->flush_rules(); + } + + protected function generateLabels($name, $pluralName = null) + { + $name = ucfirst($name); + $pluralName = ($pluralName) ? $pluralName : $name . 's'; + $pluralName = ucfirst($pluralName); + return array( + 'name' => "Test $pluralName", + 'singular_name' => "Test $name", + 'add_new_item' => "Add New $name", + 'edit_item' => "Edit $name", + 'view_item' => "View $name", + 'search_items' => "Search $pluralName", + 'parent_item_colon' => "Parent $name:", + + 'menu_name' => "$pluralName", + 'all_items' => "All $pluralName", + 'update_item' => "Update $name", + 'new_item_name' => "New $name Name", + 'parent_item' => "Parent $name", + + 'new_item' => "New $name", + 'not_found' => "No $pluralName found", + 'not_found_in_trash' => "No $pluralName found in Trash", + ); + } + + protected function addTaxonomy($name, $parameters = array()) + { + $this->wp->registerTaxonomy('wpt_' . $name, array('wpt_test'), $parameters + array( + 'hierarchical' => true, + 'labels' => $this->generateLabels($name), + 'public' => false, + 'show_ui' => true, + 'show_admin_column' => true, + 'query_var' => true, + 'sort' => true, + )); + + return $this; + } + +} diff --git a/src/Facade.php b/src/Facade.php new file mode 100644 index 00000000..fb8ac594 --- /dev/null +++ b/src/Facade.php @@ -0,0 +1,297 @@ +wp = $wp; + $this->registerWordPressHooks(); + } + + public function onPluginActivate() + { + $this->migrateDatabase(array(__FILE__, 'db:migrate')); + $this->registerWordPressEntities(); + } + + public function onPluginDeactivate() + { + // do nothing currently + } + + public static function onPluginUninstall() + { + $adapter = $this->migrateDatabase(array(__FILE__, 'db:migrate', 'VERSION=0')); + $adapter->drop_table(RUCKUSING_TS_SCHEMA_TBL_NAME); + $adapter->logger->close(); + } + + public function shortcodeList() + { + return $this->getShortcodeProcessor()->getList(); + } + + protected function registerWordPressHooks() + { + $class = get_class($this); + $this->wp + ->registerActivationHook( array($this, 'onPluginActivate')) + ->registerDeactivationHook( array($this, 'onPluginDeactivate')) + ->registerUninstallHook( array($class, 'onPluginUninstall')) + ->addAction('init', array($this, 'registerWordPressEntities')) + ->addShortcode('wptlist', array($this, 'shortcodeList')) + ->addAction('admin_init', array($this, 'setupTestEditor')) + ->addFilter('single_template', array($this, 'setupTestPasser')) + ; + } + + public function registerWordPressEntities() + { + if ($this->isWordPressEntitiesRegistered) { + return; + } + + require_once dirname(__FILE__) . '/Doer/AbstractDoer.php'; + require_once dirname(__FILE__) . '/Doer/WordPressEntitiesRegistrator.php'; + new WpTesting_Doer_WordPressEntitiesRegistrator($this->wp); + + $this->isWordPressEntitiesRegistered = true; + } + + public function setupTestEditor() + { + $this->getTestEditor()->customizeUi(); + } + + public function setupTestPasser($template) + { + $this->getTestPasser()->addContentFilter(); + return $template; + } + + protected function getShortcodeProcessor() + { + if (!is_null($this->shortcodeProcessor)) { + return $this->shortcodeProcessor; + } + + $this->setupORM(); + require_once dirname(__FILE__) . '/Doer/AbstractDoer.php'; + require_once dirname(__FILE__) . '/Doer/ShortcodeProcessor.php'; + $this->shortcodeProcessor = new WpTesting_Doer_ShortcodeProcessor($this->wp); + + return $this->shortcodeProcessor; + } + + protected function getTestEditor() + { + if (!is_null($this->testEditor)) { + return $this->testEditor; + } + + $this->setupORM(); + require_once dirname(__FILE__) . '/Doer/AbstractDoer.php'; + require_once dirname(__FILE__) . '/Doer/TestEditor.php'; + $this->testEditor = new WpTesting_Doer_TestEditor($this->wp); + + return $this->testEditor; + } + + protected function getTestPasser() + { + if (!is_null($this->testPasser)) { + return $this->testPasser; + } + + $this->setupORM(); + require_once dirname(__FILE__) . '/Doer/AbstractDoer.php'; + require_once dirname(__FILE__) . '/Doer/TestPasser.php'; + $this->testPasser = new WpTesting_Doer_TestPasser($this->wp); + + return $this->testPasser; + } + + protected function setupORM() + { + if ($this->isOrmSettedUp) { + return; + } + $this->autoloadComposer(); + $this->defineConstants(); + + // Extract port from host. See wpdb::db_connect + $port = null; + $host = $this->wp->getDbHost(); + if (preg_match('/^(.+):(\d+)$/', trim($host), $m)) { + $host = $m[1]; + $port = $m[2]; + } + $database = new fDatabase('mysql', $this->wp->getDbName(), $this->wp->getDbUser(), $this->wp->getDbPassword(), $host, $port); + // $database->enableDebugging(true); + fORMDatabase::attach($database); + + require_once dirname(__FILE__) . '/Model/AbstractModel.php'; + require_once dirname(__FILE__) . '/Model/Test.php'; + require_once dirname(__FILE__) . '/Model/Question.php'; + require_once dirname(__FILE__) . '/Model/Taxonomy.php'; + require_once dirname(__FILE__) . '/Model/AbstractTerm.php'; + require_once dirname(__FILE__) . '/Model/Answer.php'; + require_once dirname(__FILE__) . '/Model/Scale.php'; + require_once dirname(__FILE__) . '/Model/Score.php'; + require_once dirname(__FILE__) . '/Model/Passing.php'; + require_once dirname(__FILE__) . '/Model/PassingAnswer.php'; + require_once dirname(__FILE__) . '/Query/AbstractQuery.php'; + require_once dirname(__FILE__) . '/Query/Test.php'; + + fORM::mapClassToTable('WpTesting_Model_Test', WP_DB_PREFIX . 'posts'); + fORM::mapClassToTable('WpTesting_Model_Question', WPT_DB_PREFIX . 'questions'); + fORM::mapClassToTable('WpTesting_Model_Taxonomy', WP_DB_PREFIX . 'term_taxonomy'); + fORM::mapClassToTable('WpTesting_Model_Answer', WP_DB_PREFIX . 'terms'); + fORM::mapClassToTable('WpTesting_Model_Scale', WP_DB_PREFIX . 'terms'); + fORM::mapClassToTable('WpTesting_Model_Score', WPT_DB_PREFIX . 'scores'); + fORM::mapClassToTable('WpTesting_Model_Passing', WPT_DB_PREFIX . 'passings'); + fORM::mapClassToTable('WpTesting_Model_PassingAnswer', WPT_DB_PREFIX . 'passing_answers'); + + fGrammar::addSingularPluralRule('Taxonomy', 'Taxonomy'); + fGrammar::addSingularPluralRule('Score', 'Score'); + $schema = fORMSchema::retrieve('name:default'); + $schema->setColumnInfoOverride(null, WP_DB_PREFIX . 'term_relationships', 'term_order'); + $schema->setKeysOverride(array( + array( + 'column' => 'object_id', + 'foreign_table' => WP_DB_PREFIX . 'posts', + 'foreign_column' => 'id', + 'on_delete' => 'cascade', + 'on_update' => 'cascade', + ), + array( + 'column' => 'term_taxonomy_id', + 'foreign_table' => WP_DB_PREFIX . 'term_taxonomy', + 'foreign_column' => 'term_taxonomy_id', + 'on_delete' => 'cascade', + 'on_update' => 'cascade', + ), + ), WP_DB_PREFIX . 'term_relationships', 'foreign'); + + $schema->setKeysOverride(array( + array( + 'column' => 'term_id', + 'foreign_table' => WP_DB_PREFIX . 'terms', + 'foreign_column' => 'term_id', + 'on_delete' => 'cascade', + 'on_update' => 'cascade', + ), + ), WP_DB_PREFIX . 'term_taxonomy', 'foreign'); + + $this->isOrmSettedUp = true; + } + + /** + * @param array $argv + * @return Ruckusing_Adapter_Interface + */ + protected function migrateDatabase($argv) + { + $this->autoloadComposer(); + $this->defineConstants(); + + $runnerReflection = new ReflectionClass('Ruckusing_FrameworkRunner'); + defined('RUCKUSING_SCHEMA_TBL_NAME') or define('RUCKUSING_SCHEMA_TBL_NAME', WPT_DB_PREFIX . 'schema_info'); + defined('RUCKUSING_TS_SCHEMA_TBL_NAME') or define('RUCKUSING_TS_SCHEMA_TBL_NAME', WPT_DB_PREFIX . 'schema_migrations'); + defined('RUCKUSING_WORKING_BASE') or define('RUCKUSING_WORKING_BASE', dirname(dirname(__FILE__))); + defined('RUCKUSING_BASE') or define('RUCKUSING_BASE', dirname(dirname(dirname($runnerReflection->getFileName())))); + + $databaseDirectory = RUCKUSING_WORKING_BASE . DIRECTORY_SEPARATOR . 'db'; + $config = array( + 'db' => array( + 'development' => array( + 'type' => DB_TYPE, + 'host' => reset(explode(':', $this->wp->getDbHost())), + 'port' => next(explode(':', $this->wp->getDbHost() . ':3306')), + 'database' => $this->wp->getDbName(), + 'user' => $this->wp->getDbUser(), + 'password' => $this->wp->getDbPassword(), + 'charset' => $this->wp->getDbCharset(), + ), + ), + 'db_dir' => $databaseDirectory, + 'migrations_dir' => array('default' => $databaseDirectory . DIRECTORY_SEPARATOR . 'migrations'), + 'log_dir' => $databaseDirectory . DIRECTORY_SEPARATOR . 'log', + ); + + $runner = new Ruckusing_FrameworkRunner($config, $argv); + restore_error_handler(); + restore_exception_handler(); + $runner->execute(); + + /* @var $adapter Ruckusing_Adapter_Interface */ + $adapter = $runner->get_adapter(); + $adapter->logger = new Ruckusing_Util_Logger($config['log_dir'] . DIRECTORY_SEPARATOR . 'development.log'); + return $adapter; + } + + protected function autoloadComposer() + { + // 1. Try to find composer.json + $composerFullName = null; + foreach (array($this->wp->getAbsPath(), dirname(dirname($this->wp->getPluginDir()))) as $path) { + $candidateFile = $path . DIRECTORY_SEPARATOR . 'composer.json'; + if (file_exists($candidateFile)) { + $composerFullName = $candidateFile; + break; + } + } + + // 2. Not found? Use default php52 generated autoloader + if (!$composerFullName) { + $autoloadPath = implode(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)), 'vendor', 'autoload_52.php')); + require_once ($autoloadPath); + return; + } + + // 3. Found? Determine vendor dirname and load autoload file + $vendorDirectory = 'vendor'; + if (function_exists('json_decode')) { + $composerJson = json_decode(file_get_contents($composerFullName), true); + if (!empty($composerJson['config']['vendor-dir'])) { + $vendorDirectory = $composerJson['config']['vendor-dir']; + } + } + + $autoloadPath = implode(DIRECTORY_SEPARATOR, array(dirname($composerFullName), $vendorDirectory, 'autoload.php')); + require_once ($autoloadPath); + } + + protected function defineConstants() + { + defined('WP_DB_PREFIX') or define('WP_DB_PREFIX', $this->wp->getTablePrefix()); + defined('WPT_DB_PREFIX') or define('WPT_DB_PREFIX', WP_DB_PREFIX . 't_'); + defined('DB_TYPE') or define('DB_TYPE', 'mysql'); + } + +} diff --git a/src/Model/AbstractModel.php b/src/Model/AbstractModel.php new file mode 100644 index 00000000..52ef7d8c --- /dev/null +++ b/src/Model/AbstractModel.php @@ -0,0 +1,98 @@ + real_name) + * + * @var array + */ + protected $columnAliases = array(); + + + /** + * Generates phpdoc for class + * @return string + */ + public function reflectPhpDoc() + { + $signatures = array(); + + $class = get_class($this); + $table = fORM::tablize($class); + $schema = fORMSchema::retrieve($class); + foreach ($schema->getColumnInfo($table) as $column => $columnInfo) { + $camelizedColumn = fGrammar::camelize($column, TRUE); + + // Get and set methods + $fixedType = $columnInfo['type']; + if ($fixedType == 'blob') { + $fixedType = 'string'; + } + if ($fixedType == 'varchar') { + $fixedType = 'string'; + } + if ($fixedType == 'date') { + $fixedType = 'fDate|string'; + } + if ($fixedType == 'timestamp') { + $fixedType = 'fTimestamp|string'; + } + if ($fixedType == 'time') { + $fixedType = 'fTime|string'; + } + $firstFixedType = reset(explode('|', $fixedType)); + + $signatures[] = $this->generateMagicMethodPhpDoc( + 'get' . $camelizedColumn, array(), $firstFixedType, "Gets the current value of $column"); + $signatures[] = $this->generateMagicMethodPhpDoc( + 'set' . $camelizedColumn, array($fixedType => $column), $class, "Sets the value for $column"); + } + + return $signatures; + } + + protected function generateMagicMethodPhpDoc($methodName, $params, $returnType, $comment) + { + $paramsDoc = array(); + foreach ($params as $type => $name) { + $paramsDoc[] = "$type \$$name"; + } + $paramsDoc = implode(', ', $paramsDoc); + $commentDoc = preg_replace('/\s+/', ' ', $comment); + return " * @method $returnType $methodName() $methodName($paramsDoc) $commentDoc"; + } + + protected function loadFromResult($result, $ignore_identity_map=FALSE) + { + $row = $result->current(); + foreach ($row as $key => $value) { + $row[strtolower($key)] = $value; + } + return parent::loadFromResult(new ArrayIterator(array($row)), $ignore_identity_map); + } + + /** + * @see fActiveRecord::get() + */ + protected function get($column) + { + if (isset($this->columnAliases[$column])) { + $column = $this->columnAliases[$column]; + } + return parent::get($column); + } + + /** + * @see fActiveRecord::set() + */ + protected function set($column, $value) + { + if (isset($this->columnAliases[$column])) { + $column = $this->columnAliases[$column]; + } + return parent::set($column, $value); + } +} \ No newline at end of file diff --git a/src/Model/AbstractTerm.php b/src/Model/AbstractTerm.php new file mode 100644 index 00000000..38b201fc --- /dev/null +++ b/src/Model/AbstractTerm.php @@ -0,0 +1,35 @@ + 'term_id', + 'title' => 'name', + ); + + /** + * Abbreviration of title + * + * @return string + */ + public function getAbbr() + { + return mb_substr($this->getTitle(), 0, 1, 'UTF-8'); + } + + public function getDescription() + { + /* @var $result fRecordset */ + $result = $this->buildWpTesting_Model_Taxonomy(); + if (!$result->count()) { + return null; + } + return $result->getRecord(0)->getDescription(); + } + +} diff --git a/src/Model/Answer.php b/src/Model/Answer.php new file mode 100644 index 00000000..f20f560c --- /dev/null +++ b/src/Model/Answer.php @@ -0,0 +1,5 @@ +setTestId($test->getId()); + parent::populate(true); + + $answers = $this->buildAnswers(); + foreach ($test->buildQuestions() as $i => $question) { + $answers[$i]->setQuestionId($question->getId()); + } + + return $this; + } + + /** + * @return WpTesting_Model_PassingAnswer[] + */ + public function buildAnswers() + { + return $this->buildWpTesting_Model_PassingAnswers(); + } + + /** + * @return WpTesting_Model_Scales[] + */ + public function calculateScalesTotals() + { + $results = array(); + + foreach ($this->buildAnswers() as $passingAnswer) { + $scores = $passingAnswer->createQuestion()->getScoresByAnswer($passingAnswer->createAnswer()); + foreach ($scores as $score) { /* @var $score WpTesting_Model_Score */ + $scale = $score->createScale(); + if (empty($results[$scale->getId()])) { + $results[$scale->getId()] = $scale->resetScore(); + } + $results[$scale->getId()]->addScore($score); + } + } + + if (empty($results)) { + return $results; + } + + // Calculate scales global totals (not from respondent answers) + $globalTotals = array(); + /* @var $test WpTesting_Model_Test */ + $test = $passingAnswer->createQuestion()->createTest(); + foreach ($test->buildQuestions() as $i => $question) { + foreach ($question->buildScores() as $score) { + $scale = $score->createScale(); + if (!isset($results[$scale->getId()])) { + continue; + } + if (!isset($globalTotals[$scale->getId()])) { + $globalTotals[$scale->getId()] = $scale->resetScore(); + } + $globalTotals[$scale->getId()]->addScore($score); + } + } + + foreach ($results as $id => $result) { + $results[$id]->setTotalScale($globalTotals[$id]); + } + + return $results; + } + +} diff --git a/src/Model/PassingAnswer.php b/src/Model/PassingAnswer.php new file mode 100644 index 00000000..c8d687d6 --- /dev/null +++ b/src/Model/PassingAnswer.php @@ -0,0 +1,38 @@ +loadFromResult(new ArrayIterator(array($values)), true); + } + } + + /** + * @return WpTesting_Model_Question + */ + public function createQuestion() + { + return $this->createWpTesting_Model_Question(); + } + + /** + * @return WpTesting_Model_Answer + */ + public function createAnswer() + { + return $this->createWpTesting_Model_Answer(); + } +} diff --git a/src/Model/Question.php b/src/Model/Question.php new file mode 100644 index 00000000..58c350bb --- /dev/null +++ b/src/Model/Question.php @@ -0,0 +1,102 @@ + 'question_title', + 'id' => 'question_id', + ); + + /** + * @var WpTesting_Model_Score[] + */ + protected $scores = null; + + /** + * @var WpTesting_Model_Answer[] + */ + protected $answers = array(); + + /** + * @param fRecordSet $answers + * @return WpTesting_Model_Question + */ + public function setAnswers(fRecordSet $answers) + { + if (count($answers) == 0 || !($answers[0] instanceof WpTesting_Model_Answer)) { + return $this; + } + $this->answers = $answers; + return $this; + } + + public function getAnswers() + { + return $this->answers; + } + + /** + * Get score anyway (even if it doesn't exists) + * + * @param WpTesting_Model_Answer $answer + * @param WpTesting_Model_Scale $scale + * @return WpTesting_Model_Score + */ + public function getScoreByAnswerAndScale(WpTesting_Model_Answer $answer, WpTesting_Model_Scale $scale) + { + $result = $this->buildScoresOnce()->filter(array( + 'getAnswerId=' => $answer->getId(), + 'getScaleId=' => $scale->getId(), + )); + if ($result->count()) { + return $result->getRecord(0); + } + return new WpTesting_Model_Score(); + } + + /** + * Get scores by answer + * + * @param WpTesting_Model_Answer $answer + * @return WpTesting_Model_Score[] + */ + public function getScoresByAnswer(WpTesting_Model_Answer $answer) + { + return $this->buildScoresOnce()->filter(array( + 'getAnswerId=' => $answer->getId(), + )); + } + + /** + * @return WpTesting_Model_Test + */ + public function createTest() + { + return $this->createWpTesting_Model_Test(); + } + + /** + * @return WpTesting_Model_Score[] + */ + public function buildScores() + { + return $this->buildScoresOnce(); + } + + /** + * @return fRecordSet of WpTesting_Model_Score + */ + protected function buildScoresOnce() + { + if (is_null($this->scores)) { + $this->scores = $this->buildWpTesting_Model_Score(); + } + return $this->scores; + } + +} diff --git a/src/Model/Scale.php b/src/Model/Scale.php new file mode 100644 index 00000000..657c87e5 --- /dev/null +++ b/src/Model/Scale.php @@ -0,0 +1,53 @@ +scoreTotal = 0; + return $this; + } + + public function addScore(WpTesting_Model_Score $score) + { + $this->scoreTotal += $score->getValue(); + return $this; + } + + public function getScoresTotal() + { + return $this->scoreTotal; + } + + public function getScoresTotalPercent() + { + $totalTotal = $this->getTotalScale()->getScoresTotal(); + if (!$totalTotal) { + return 0; + } + return round($this->scoreTotal / $totalTotal * 100); + } + + public function setTotalScale(WpTesting_Model_Scale $scale) + { + $this->totalScale = $scale; + } + + public function getTotalScale() + { + if ($this->totalScale instanceof WpTesting_Model_Scale) { + return $this->totalScale; + } + return new WpTesting_Model_Scale(); + } + +} diff --git a/src/Model/Score.php b/src/Model/Score.php new file mode 100644 index 00000000..5dad3050 --- /dev/null +++ b/src/Model/Score.php @@ -0,0 +1,26 @@ + 'score_value', + ); + + public function getValueWithoutZeros() + { + $value = $this->getValue(); + return empty($value) ? '' : $value; + } + + /** + * @return WpTesting_Model_Scale + */ + public function createScale() + { + return $this->createWpTesting_Model_Scale('scale_id'); + } +} diff --git a/src/Model/Taxonomy.php b/src/Model/Taxonomy.php new file mode 100644 index 00000000..bc273c1e --- /dev/null +++ b/src/Model/Taxonomy.php @@ -0,0 +1,10 @@ + 'ID', + 'title' => 'post_title', + 'created' => 'post_date', + 'modified' => 'post_modified', + ); + + /** + * @var WpTesting_Model_Taxonomy[] + */ + protected $taxonomies = null; + + public function __construct($key = null) + { + if ($key instanceof WP_Post) { + if ($key->post_type != 'wpt_test') { + $this->values['ID'] = null; + return; + } + $postAsArray = (array)$key; + unset($postAsArray['filter']); + return parent::__construct(new ArrayIterator(array($postAsArray))); + } + return parent::__construct($key); + } + + /** + * @return WpTesting_Model_Question[] + */ + public function buildQuestions() + { + $answers = $this->buildAnswers(); + $questions = $this->buildWpTesting_Model_Questions(); + if (count($answers)) { + foreach ($questions as $question) { /* @var $question WpTesting_Model_Question */ + $question->setAnswers($answers); + } + } + return $questions; + } + + /** + * @return WpTesting_Model_Scale[] + */ + public function buildScales() + { + return fRecordSet::build('WpTesting_Model_Scale', array( + 'term_id=' => $this->getTermIdFromFilteredTaxonomies('wpt_scale'), + )); + } + + /** + * @return WpTesting_Model_Answer[] + */ + protected function buildAnswers() + { + return fRecordSet::build('WpTesting_Model_Answer', array( + 'term_id=' => $this->getTermIdFromFilteredTaxonomies('wpt_answer'), + )); + } + + /** + * @return WpTesting_Model_Taxonomy[] + */ + protected function buildTaxonomies() + { + return $this->buildWpTesting_Model_Taxonomy(); + } + + /** + * @return fRecordSet of WpTesting_Model_Taxonomy + */ + protected function buildTaxonomiesOnce() + { + if (is_null($this->taxonomies)) { + $this->taxonomies = $this->buildTaxonomies(); + } + return $this->taxonomies; + } + + /** + * Filter related taxonomies and return term id from they + * @param string $taxonomy One of wpt_answer|wpt_scale|wpt_result|wpt_category + * @return array + */ + protected function getTermIdFromFilteredTaxonomies($taxonomy) + { + $ids = array(); + foreach ($this->buildTaxonomiesOnce()->filter(array('getTaxonomy=' => $taxonomy)) as $taxonomy) { + $ids[] = $taxonomy->getTermId(); + } + return $ids; + } + + public function getQuestionsPrefix() + { + return fORMRelated::determineRequestFilter('WpTesting_Model_Test', 'WpTesting_Model_Question', 'test_id'); + } + + public function getScorePrefix() + { + return $this->getQuestionsPrefix() . + fORMRelated::determineRequestFilter('WpTesting_Model_Question', 'WpTesting_Model_Score', 'question_id'); + } + + /** + * @see http://stackoverflow.com/questions/10303714/php-max-input-vars + * @return boolean + */ + public function isWarnOfSettings() + { + $scalesCount = count($this->buildScales()); + if (!$scalesCount) { + return false; + } + $questions = $this->buildQuestions(); + $questionsCount = count($questions); + if (!$questionsCount) { + return false; + } + $answersCount = count($questions[0]->getAnswers()); + if (!$answersCount) { + return false; + } + + $iniKeys = array( + 'max_input_vars', + 'suhosin.get.max_vars', + 'suhosin.post.max_vars', + 'suhosin.request.max_vars', + ); + $values = array(); + foreach ($iniKeys as $iniKey) { + $value = ini_get($iniKey); + if ($value !== false) { + $values[] = (int)$value; + } + } + + return $scalesCount * $questionsCount * $answersCount * 3 > (min($values) - 150); + } + + /** + * @param bool $isRecursive + * @return WpTesting_Model_Test + */ + public function populateQuestions($isRecursive = false) + { + $this->populateWpTesting_Model_Questions($isRecursive); + $table = fORM::tablize('WpTesting_Model_Question'); + $questions =& $this->related_records[$table]['test_id']['record_set']; + $questions = $questions->filter(array('getTitle!=' => '')); + return $this; + } + + /** + * Export as WP native content entity object + * + * @return WP_Post + */ + public function toWpPost() + { + $post = new WP_Post(new stdClass()); + $post->filter = 'raw'; + foreach ($this->values as $key => $value) { + $post->$key = (string)$value; + } + return $post; + } +} diff --git a/src/Query/AbstractQuery.php b/src/Query/AbstractQuery.php new file mode 100644 index 00000000..95657fc5 --- /dev/null +++ b/src/Query/AbstractQuery.php @@ -0,0 +1,25 @@ +modelName = str_replace('_Query_', '_Model_', get_class($this)); + } + + public static function create($className = __CLASS__) + { + return new $className(); + } + + /** + * @return WpTesting_Model_AbstractModel[] + */ + public function findAll() + { + return fRecordSet::build($this->modelName); + } + +} \ No newline at end of file diff --git a/src/Query/Test.php b/src/Query/Test.php new file mode 100644 index 00000000..79c42832 --- /dev/null +++ b/src/Query/Test.php @@ -0,0 +1,41 @@ +findAllByParams(); + } + + /** + * @return WpTesting_Query_Test[] + */ + public function findAllPublished() + { + return $this->findAllByParams(array( + 'post_status=' => 'publish', + )); + } + + /** + * @param array $where + * @return WpTesting_Query_Test[] + */ + protected function findAllByParams(array $where = array()) + { + return fRecordSet::build($this->modelName, array( + 'post_type=' => 'wpt_test', + ) + $where); + } +} \ No newline at end of file diff --git a/src/Template/Shortcode/list.php b/src/Template/Shortcode/list.php new file mode 100644 index 00000000..776af303 --- /dev/null +++ b/src/Template/Shortcode/list.php @@ -0,0 +1,5 @@ +
    + +
  1. getTitle() ?>
  2. + +
diff --git a/src/Template/Test/Editor/add-questions.php b/src/Template/Test/Editor/add-questions.php new file mode 100644 index 00000000..f3a73c1b --- /dev/null +++ b/src/Template/Test/Editor/add-questions.php @@ -0,0 +1,21 @@ + + + + $scale): /* @var $scale WpTesting_Model_Scale */ ?> + + + + + + + + + +
+ getTitle() ?> +
+ * + + + +
\ No newline at end of file diff --git a/src/Template/Test/Editor/edit-questions.php b/src/Template/Test/Editor/edit-questions.php new file mode 100644 index 00000000..654a5495 --- /dev/null +++ b/src/Template/Test/Editor/edit-questions.php @@ -0,0 +1,66 @@ + +
+

Settings of your server are too low — form values could be cropped!

+ +

Add this into your php.ini:

+
+    max_input_vars=5000
+    suhosin.get.max_vars=5000
+    suhosin.post.max_vars=5000
+    suhosin.request.max_vars=5000
+ + .. or .htaccess + +
+    php_value max_input_vars 5000
+    php_value suhosin.get.max_vars 5000
+    php_value suhosin.post.max_vars 5000
+    php_value suhosin.request.max_vars 5000
+ + .. and reload (restart) server. +
+ + + + + $scale): /* @var $scale WpTesting_Model_Scale */ ?> + + + + $question): /* @var $question WpTesting_Model_Question */ ?> + + + + + + getAnswers() as $a => $answer): /* @var $answer WpTesting_Model_Answer */ ?> + + + $scale): /* @var $scale WpTesting_Model_Scale */ ?> + getScoreByAnswerAndScale($answer, $scale) ?> + + + + + + + +
+ getTitle() ?> +
+ + + + +
getTitle() ?> + + + +
\ No newline at end of file diff --git a/src/Template/Test/Passer/fill-form.php b/src/Template/Test/Passer/fill-form.php new file mode 100644 index 00000000..ee88d0ba --- /dev/null +++ b/src/Template/Test/Passer/fill-form.php @@ -0,0 +1,47 @@ + +
+ +
+ +
+ +
+ + $question): /* @var $question WpTesting_Model_Question */ ?> + +
+ +
+ .getTitle() ?> +
+ + + getAnswers() as $answer): /* @var $answer WpTesting_Model_Answer */ ?> + getId() . '-answer-' . $answer->getId() ?> + +
+ + + + + +
+ + + +
+ + + + + +
+ +
diff --git a/src/Template/Test/Passer/get-results.php b/src/Template/Test/Passer/get-results.php new file mode 100644 index 00000000..9ea5655d --- /dev/null +++ b/src/Template/Test/Passer/get-results.php @@ -0,0 +1,38 @@ + +
+ +
+ +

+ + + +

getTitle() ?>

+ +
+ getScoresTotal() ?> getTotalScale()->getScoresTotal() ?> +
+
+ +
+ +

getDescription()) ?>

+ + + +
+ +
+ +
+ +
+ +
diff --git a/src/WordPressFacade.php b/src/WordPressFacade.php new file mode 100644 index 00000000..91dc2ac5 --- /dev/null +++ b/src/WordPressFacade.php @@ -0,0 +1,337 @@ +pluginFile = $pluginFile; + } + + public function getDbHost() + { + return DB_HOST; + } + + public function getDbName() + { + return DB_NAME; + } + + public function getDbUser() + { + return DB_USER; + } + + public function getDbPassword() + { + return DB_PASSWORD; + } + + public function getTablePrefix() + { + return $GLOBALS['table_prefix']; + } + + public function getDbCharset() + { + return DB_CHARSET; + } + + /** + * Absolute path to the WordPress directory. + */ + public function getAbsPath() + { + return ABSPATH; + } + + /** + * Allows for the plugins directory to be moved from the default location. + * + * @since 2.6.0 + */ + public function getPluginDir() + { + return WP_PLUGIN_DIR; + } + + /** + * Holds the WordPress Rewrite object for creating pretty URLs + * + * @since 1.5.0 + * @return WP_Rewrite + */ + public function getRewrite() + { + return $GLOBALS['wp_rewrite']; + } + + /** + * WordPress Query API + * + * @since 1.5.0 + * + * @return WP_Query + */ + public function getQuery() + { + return $GLOBALS['wp_query']; + } + + /** + * Enqueue a CSS stylesheet related to plugin path. + * + * @since 2.6.0 + * + * @param string $name Name of the stylesheet. + * @param string $pluginRelatedPath + * @return WpTesting_WordPressFacade + */ + public function enqueuePluginStyle($name, $pluginRelatedPath) + { + wp_enqueue_style($name, plugins_url($pluginRelatedPath, $this->pluginFile)); + return $this; + } + + /** + * Enqueue an JS script related to plugin path. + * + * @since 2.6.0 + * + * @param string $name Name of the script. + * @param string $pluginRelatedPath + * @param array $dependencies Optional. An array of registered handles this script depends on. Default empty array. + * @param string $version Optional. String specifying the script version number, if it has one. This parameter is used to ensure that the correct version is sent to the client regardless of caching, and so should be included if a version number is available and makes sense for the script. + * @param string $isInFooter Optional. Whether to enqueue the script before or before . Default 'false'. Accepts 'false' or 'true'. + * @return WpTesting_WordPressFacade + */ + public function enqueuePluginScript($name, $pluginRelatedPath, array $dependencies = array(), $version = false, $isInFooter = false) + { + $path = plugins_url($pluginRelatedPath, $this->pluginFile); + wp_enqueue_script($name, $path, $dependencies, $version, $isInFooter); + return $this; + } + + + /** + * Register an JS script related to plugin path. + * + * Mainly to use in later dependencies. + * + * @since 2.6.0 + * + * @param string $name Name of the script. + * @param string $pluginRelatedPath + * @param array $dependencies Optional. An array of registered handles this script depends on. Default empty array. + * @param string $version Optional. String specifying the script version number, if it has one. This parameter is used to ensure that the correct version is sent to the client regardless of caching, and so should be included if a version number is available and makes sense for the script. + * @param string $isInFooter Optional. Whether to enqueue the script before or before . Default 'false'. Accepts 'false' or 'true'. + * @return WpTesting_WordPressFacade + */ + public function registerPluginScript($name, $pluginRelatedPath, array $dependencies = array(), $version = false, $isInFooter = false) + { + $path = plugins_url($pluginRelatedPath, $this->pluginFile); + wp_register_script($name, $path, $dependencies, $version, $isInFooter); + return $this; + } + + /** + * Retrieve the name of the highest priority template file that exists. + * + * @since 2.7.0 + * + * @param string|array $templateNames Template file(s) to search for, in order. + * @param string $isLoad If true the template file will be loaded if it is found. + * @param string $isRequireOnce Whether to require_once or require. Default true. Has no effect if $isLoad is false. + * @return string The template filename if one is located. + */ + public function locateTemplate($templateNames, $isLoad = false, $isRequireOnce = true ) + { + return locate_template($templateNames, $isLoad, $isRequireOnce); + } + + /** + * Retrieve full permalink for post by ID or current post + * + * @since 1.0.0 + * + * @param number|WP_Post $id + * @param string $isLeaveName + * @return string|bool + */ + public function getPermalink($id = 0, $isLeaveName = false) + { + return get_permalink($id, $isLeaveName); + } + + /** + * Hooks a function on to a specific action. + * + * @since 1.2.0 + * @link http://codex.wordpress.org/Function_Reference/add_action + * + * @param string $tag The name of the action to which the $function is hooked. + * @param callback $function The name of the function you wish to be called. + * @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action. + * @param int $functionArgsCount optional. The number of arguments the function accept (default 1). + * @return WpTesting_WordPressFacade + */ + public function addAction($tag, callable $function, $priority = 10, $functionArgsCount = 1) + { + add_action($tag, $function, $priority, $functionArgsCount); + return $this; + } + + /** + * Hooks a function or method to a specific filter action. + * + * @since 0.71 + * + * @param string $tag The name of the action to which the $function is hooked. + * @param callback $function The name of the function you wish to be called. + * @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action. + * @param int $functionArgsCount optional. The number of arguments the function accept (default 1). + * @return WpTesting_WordPressFacade + */ + public function addFilter($tag, callable $function, $priority = 10, $functionArgsCount = 1) + { + add_filter($tag, $function, $priority, $functionArgsCount); + return $this; + } + + /** + * Add hook for shortcode tag. + * + * @since 2.5.0 + * @link http://codex.wordpress.org/Function_Reference/add_shortcode + * + * @param string $tag Shortcode tag to be searched in post content. + * @param callable $function Hook to run when shortcode is found. + * @return WpTesting_WordPressFacade + */ + public function addShortcode($tag, callable $function) + { + add_shortcode($tag, $function); + return $this; + } + + /** + * Add a meta box to an edit form. + * + * @since 2.5.0 + * + * @param string $id String for use in the 'id' attribute of tags. + * @param string $title Title of the meta box. + * @param callable $function Function that fills the box with the desired content. + * The function should echo its output. + * @param string|WP_Screen $screen Optional. The screen on which to show the box (like a post + * type, 'link', or 'comment'). Default is the current screen. + * @param string $context Optional. The context within the screen where the boxes + * should display. Available contexts vary from screen to + * screen. Post edit screen contexts include 'normal', 'side', + * and 'advanced'. Comments screen contexts include 'normal' + * and 'side'. Menus meta boxes (accordion sections) all use + * the 'side' context. Global default is 'advanced'. + * @param string $priority Optional. The priority within the context where the boxes + * should show ('high', 'low'). Default 'default'. + * @param array $functionArgs Optional. Data that should be set as the $args property + * of the box array (which is the second parameter passed + * to your callback). Default null. + * @return WpTesting_WordPressFacade + */ + public function addMetaBox($id, $title, callable $function, $screen = null, $context = 'advanced', $priority = 'default', $functionArgs = null) + { + add_meta_box($id, $title, $function, $screen, $context, $priority, $functionArgs); + return $this; + } + + /** + * Register a post type. Do not use before init. + * + * @since 2.9.0 + * @link http://codex.wordpress.org/Function_Reference/register_post_type + * + * @param string $name Post type key, must not exceed 20 characters. + * @param array $parameters + * @return WpTesting_WordPressFacade + */ + public function registerPostType($name, $parameters = array()) + { + register_post_type($name, $parameters); + return $this; + } + + /** + * Create or modify a taxonomy object. Do not use before init. + * + * @since 2.3.0 + * @link http://codex.wordpress.org/Function_Reference/register_taxonomy + * + * @param string $name Taxonomy key, must not exceed 32 characters. + * @param array|string $objectType Name of the object type(s) for the taxonomy object. + * @param array|string $parameters + * @return WpTesting_WordPressFacade + */ + public function registerTaxonomy($name, $objectType, $parameters = array()) + { + register_taxonomy($name, $objectType, $parameters); + return $this; + } + + /** + * Set the activation hook for a plugin. + * + * @since 2.0.0 + * @link http://codex.wordpress.org/Function_Reference/register_activation_hook + * + * @param callback $function the function hooked for action. + * @return WpTesting_WordPressFacade + */ + public function registerActivationHook(callable $function) + { + register_activation_hook($this->pluginFile, $function); + return $this; + } + + /** + * Set the deactivation hook for a plugin. + * + * @since 2.0.0 + * @link http://codex.wordpress.org/Function_Reference/register_deactivation_hook + * + * @param callback $function the function hooked for action. + * @return WpTesting_WordPressFacade + */ + public function registerDeactivationHook(callable $function) + { + register_deactivation_hook($this->pluginFile, $function); + return $this; + } + + /** + * Set the uninstallation hook for a plugin. + * + * @since 2.7.0 + * @link http://codex.wordpress.org/Function_Reference/register_uninstall_hook + * + * @param callback $function the function hooked for action. + * @return WpTesting_WordPressFacade + */ + public function registerUninstallHook(callable $function) + { + register_uninstall_hook($this->pluginFile, $function); + return $this; + } +} \ No newline at end of file diff --git a/wp-testing.php b/wp-testing.php new file mode 100644 index 00000000..cc8af151 --- /dev/null +++ b/wp-testing.php @@ -0,0 +1,17 @@ +