commit ee215165eaa550b362f03533b643299fcd3f231f Author: Daniel Barros Date: Thu Dec 7 11:06:50 2023 -0300 Adicionando arquivos diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + 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.md b/README.md new file mode 100644 index 0000000..2706201 --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# H5P Moodle Plugin + +Create and add rich content inside your LMS for free. Some examples of what you +get with H5P are Interactive Video, Quizzes, Collage and Timeline. + +## Usage + +If you intend to use the repository directly in production, make sure that you're using the "Stable" branch, as this is the production branch. +There are no guarantees for the state of the other branches at any given time. +Also make sure that all submodules are pulled as well using: + +``` +git submodule update --init +``` + +## Description + +One of the great benefits with using H5P is that it gives you access to lots of +different [interactive content types](https://h5p.org/content-types-and-applications). + +Another great benefit with H5P is that it allows you to easily share and reuse +content. To reuse content, you just download the H5P you would like to edit and +make your changes – e.g. translate to a new language or adjust it to a new +situation. + +H5P is: + +* Open Source +* Free to Use +* HTML5 +* Responsive + +The H5P community is actively contributing to improve H5P. Updates and new +features are continuously made available on the community portal +[H5P.org](https://h5p.org). + +View our [setup for Moodle](https://h5p.org/moodle) to get information on how +to get started with H5P. + +### GDPR Compliance +Information useful to help you achieve GDPR compliance while using this plugin +can be found at [H5P.org's GDPR Compliance](https://h5p.org/plugin-gdpr-compliance) page. + +### Development Version +Warning! Never use the development version in production, there are no guarantees for which state the development branches are in at a given time. + +Inside your `moodle/mod` folder you run the following command: +``` +git clone -b master https://github.com/h5p/h5p-moodle-plugin.git hvp && cd hvp && git submodule update --init +``` + +### Enabling The Plugin +In Moodle, go to administrator -> plugin overview, and press 'Update database'. + +## Settings +Settings can be found at: Site Administration -> Plugins -> Activity Modules -> H5P + +## Contributing +Feel free to contribute by: +* Submitting translations to the [Moodle AMOS translator](https://lang.moodle.org/local/amos/view.php) +* Testing and creating issues. But remember to check if the issues is already +reported before creating a new one. Perhaps you can contribute to an already +existing issue? +* Solving issues and submitting code through Pull Requests to the 'master' branch or on a separate feature branch. diff --git a/ajax.php b/ajax.php new file mode 100644 index 0000000..f3cc298 --- /dev/null +++ b/ajax.php @@ -0,0 +1,506 @@ +. +/** + * Responsible for handling AJAX requests related to H5P. + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +use mod_hvp\framework; + +define('AJAX_SCRIPT', true); +require(__DIR__ . '/../../config.php'); +require_once($CFG->libdir . '/filelib.php'); +require_once("locallib.php"); + +require_login(); + +$action = required_param('action', PARAM_ALPHA); +switch($action) { + + /* + * Handle user data reporting + * + * Type: HTTP POST + * + * Parameters: + * - content_id + * - data_type + * - sub_content_id + */ + case 'contentsuserdata': + \mod_hvp\content_user_data::handle_ajax(); + break; + + /* + * Handle restricting H5P libraries + * + * Type: HTTP GET + * + * Parameters: + * - library_id + * - restrict (0 or 1) + * - token + */ + case 'restrictlibrary': + + // Check permissions. + $context = \context_system::instance(); + if (!has_capability('mod/hvp:restrictlibraries', $context)) { + \H5PCore::ajaxError(get_string('nopermissiontorestrict', 'hvp')); + http_response_code(403); + break; + } + + $libraryid = required_param('library_id', PARAM_INT); + $restrict = required_param('restrict', PARAM_INT); + + if (!\H5PCore::validToken('library_' . $libraryid, required_param('token', PARAM_RAW))) { + \H5PCore::ajaxError(get_string('invalidtoken', 'hvp')); + exit; + } + + hvp_restrict_library($libraryid, $restrict); + header('Cache-Control: no-cache'); + header('Content-Type: application/json'); + echo json_encode(array( + 'url' => (new moodle_url('/mod/hvp/ajax.php', array( + 'action' => 'restrict_library', + 'token' => \H5PCore::createToken('library_' . $libraryid), + 'restrict' => ($restrict === '1' ? 0 : 1), + 'library_id' => $libraryid + )))->out(false))); + break; + + /* + * Collecting data needed by H5P content upgrade + * + * Type: HTTP GET + * + * Parameters: + * - library (Format: ///) + */ + case 'getlibrarydataforupgrade': + + // Check permissions. + $context = \context_system::instance(); + if (!has_capability('mod/hvp:updatelibraries', $context)) { + \H5PCore::ajaxError(get_string('nopermissiontoupgrade', 'hvp')); + http_response_code(403); + break; + } + + $library = required_param('library', PARAM_TEXT); + $library = explode('/', substr($library, 1)); + + if (count($library) !== 3) { + http_response_code(422); + return; + } + + $library = hvp_get_library_upgrade_info($library[0], $library[1], $library[2]); + + header('Cache-Control: no-cache'); + header('Content-Type: application/json'); + print json_encode($library); + + break; + + /* + * Saving upgraded content, and returning next batch to process + * + * Type: HTTP POST + * + * Parameters: + * - library_id + */ + case 'libraryupgradeprogress': + // Check upgrade permissions. + $context = \context_system::instance(); + if (!has_capability('mod/hvp:updatelibraries', $context)) { + \H5PCore::ajaxError(get_string('nopermissiontoupgrade', 'hvp')); + http_response_code(403); + break; + } + + // Because of a confirmed bug in PHP, filter_input(INPUT_SERVER, ...) + // will return null on some versions of FCGI/PHP (5.4 and probably + // older versions as well), ref. https://bugs.php.net/bug.php?id=49184. + if ($_SERVER['REQUEST_METHOD'] === 'POST') { + $libraryid = required_param('library_id', PARAM_INT); + $out = hvp_content_upgrade_progress($libraryid); + header('Cache-Control: no-cache'); + header('Content-Type: application/json'); + print json_encode($out); + } else { + // Only allow POST. + http_response_code(405); + } + break; + + /* + * Handle set finished / storing grades + * + * Type: HTTP GET + * + * Parameters: + * - contentId + * - score + * - maxScore + */ + case 'setfinished': + \mod_hvp\user_grades::handle_ajax(); + break; + + /* + * Saves a dynamically graded grade to the gradebook + * + * Type: HTTP POST + * + * Parameters: + * - subcontent_id + * - score + */ + case 'updatesubcontentscore': + \mod_hvp\user_grades::handle_dynamic_grading(); + break; + + /* + * Returns a grade + * + * Type: HTTP GET + * + * Parameters: + * - subcontent_id + */ + case 'getsubcontentscore': + \mod_hvp\user_grades::return_subcontent_grade(); + break; + + /* + * Provide data for results view + * + * Type: HTTP GET + * + * Parameters: + * int content_id + * int offset + * int limit + * int sortBy + * int sortDir + * string[] filters + */ + case 'results': + $results = new \mod_hvp\results(); + $results->print_results(); + break; + + /* + * Load list of libraries or details for library. + * + * Parameters: + * string machineName + * int majorVersion + * int minorVersion + */ + case 'libraries': + if (!framework::has_editor_access('nopermissiontoviewcontenttypes')) { + break; + } + + // Get parameters. + $name = optional_param('machineName', '', PARAM_TEXT); + $major = optional_param('majorVersion', 0, PARAM_INT); + $minor = optional_param('minorVersion', 0, PARAM_INT); + $editor = framework::instance('editor'); + $language = optional_param('default-language', null, PARAM_RAW); + + if (!empty($name)) { + $editor->ajax->action(H5PEditorEndpoints::SINGLE_LIBRARY, $name, + $major, $minor, framework::get_language(), '', '', $language); + + new \mod_hvp\event( + 'library', null, + null, null, + $name, $major . '.' . $minor + ); + } else { + $editor->ajax->action(H5PEditorEndpoints::LIBRARIES); + } + + break; + + /* + * Load content type cache list to display available libraries in hub + */ + case 'contenttypecache': + if (!framework::has_editor_access('nopermissiontoviewcontenttypes')) { + break; + } + + $editor = framework::instance('editor'); + $editor->ajax->action(H5PEditorEndpoints::CONTENT_TYPE_CACHE); + break; + + /* + * Handle file upload through the editor. + * + * Parameters: + * int contentId + * int contextId + */ + case 'files': + $token = required_param('token', PARAM_RAW); + $contentid = required_param('contentId', PARAM_INT); + if (!framework::has_editor_access('nopermissiontouploadfiles')) { + break; + } + + $editor = framework::instance('editor'); + $editor->ajax->action(H5PEditorEndpoints::FILES, $token, $contentid); + break; + + /* + * Handle file upload through the editor. + * + * Parameters: + * raw token + * raw contentTypeUrl + */ + case 'libraryinstall': + $token = required_param('token', PARAM_RAW); + $machinename = required_param('id', PARAM_TEXT); + $editor = framework::instance('editor'); + $editor->ajax->action(H5PEditorEndpoints::LIBRARY_INSTALL, $token, $machinename); + break; + + /* + * Install libraries from h5p and retrieve content json + * + * Parameters: + * file h5p + */ + case 'libraryupload': + $token = required_param('token', PARAM_RAW); + if (!framework::has_editor_access('nopermissiontouploadcontent')) { + break; + } + + $editor = framework::instance('editor'); + $uploadpath = $_FILES['h5p']['tmp_name']; + $contentid = optional_param('contentId', 0, PARAM_INT); + $editor->ajax->action(H5PEditorEndpoints::LIBRARY_UPLOAD, $token, $uploadpath, $contentid); + break; + + /* + * Record xAPI result from view + */ + case 'xapiresult': + \mod_hvp\xapi_result::handle_ajax(); + break; + + case 'translations': + if (!framework::has_editor_access('nopermissiontogettranslations')) { + break; + } + $language = required_param('language', PARAM_RAW); + $editor = framework::instance('editor'); + $editor->ajax->action(H5PEditorEndpoints::TRANSLATIONS, $language); + break; + + /* + * Handle filtering of parameters through AJAX. + */ + case 'filter': + $token = required_param('token', PARAM_RAW); + $libraryparameters = required_param('libraryParameters', PARAM_RAW); + + if (!framework::has_editor_access('nopermissiontouploadfiles')) { + break; + } + + $editor = framework::instance('editor'); + $editor->ajax->action(H5PEditorEndpoints::FILTER, $token, $libraryparameters); + break; + + /* + * Handle filtering of parameters through AJAX. + */ + case 'contenthubmetadatacache': + if (!framework::has_editor_access('nopermissiontoviewcontenthubcache')) { + break; + } + $editor = framework::instance('editor'); + $editor->ajax->action(H5PEditorEndpoints::CONTENT_HUB_METADATA_CACHE, framework::get_language()); + break; + + case 'contenthubregistration': + // Check permission. + $context = \context_system::instance(); + if (!has_capability('mod/hvp:contenthubregistration', $context)) { + \H5PCore::ajaxError(get_string('contenthub:nopermissions', 'hvp'), 'NO_PERMISSION', 403); + return; + } + + $token = required_param('_token', PARAM_RAW); + + if (!H5PCore::validToken('contentHubRegistration', $token)) { + H5PCore::ajaxError('Invalid token', 'INVALID_TOKEN', 401); + return; + } + $logo = isset($_FILES['logo']) ? $_FILES['logo'] : null; + + $formdata = [ + 'name' => required_param('name', PARAM_TEXT), + 'email' => required_param('email', PARAM_EMAIL), + 'description' => optional_param('description', '', PARAM_TEXT), + 'contact_person' => optional_param('contact_person', '', PARAM_TEXT), + 'phone' => optional_param('phone', '', PARAM_TEXT), + 'address' => optional_param('address', '', PARAM_TEXT), + 'city' => optional_param('city', '', PARAM_TEXT), + 'zip' => optional_param('zip', '', PARAM_TEXT), + 'country' => optional_param('country', '', PARAM_TEXT), + 'remove_logo' => optional_param('remove_logo', '', PARAM_BOOL), + ]; + + $core = framework::instance(); + $result = $core->hubRegisterAccount($formdata, $logo); + + if ($result['success'] === false) { + $core->h5pF->setErrorMessage($result['message']); + H5PCore::ajaxError($result['message'], $result['error_code'], $result['status_code']); + return; + } + + $core->h5pF->setInfoMessage($result['message']); + H5PCore::ajaxSuccess($result['message']); + break; + + /* + * Handle filtering of parameters through AJAX. + */ + case 'getcontent': + $token = required_param('token', PARAM_RAW); + $hubid = required_param('hubId', PARAM_INT); + + $editor = \mod_hvp\framework::instance('editor'); + $editor->ajax->action(H5PEditorEndpoints::GET_HUB_CONTENT, $token, $hubid, null); + break; + + /* + * Handle publishing of content to the H5P OER Hub. + */ + case 'share': + if ($_SERVER['REQUEST_METHOD'] !== 'POST') { + http_response_code(405); + } + $token = required_param('_token', PARAM_RAW); + $id = required_param('id', PARAM_INT); + + if (!\H5PCore::validToken('share_' . $id, $token)) { + \H5PCore::ajaxError(get_string('invalidtoken', 'hvp')); + break; + } + + $data = array( + 'title' => required_param('title', PARAM_RAW), + 'language' => required_param('language', PARAM_RAW), + 'license' => required_param('license', PARAM_RAW), + 'license_version' => required_param('license_version', PARAM_RAW), + 'level' => optional_param('level', null, PARAM_RAW), + 'disciplines' => optional_param_array('disciplines', null, PARAM_RAW), + 'keywords' => optional_param_array('keywords', null, PARAM_RAW), + 'summary' => optional_param('summary', null, PARAM_RAW), + 'description' => optional_param('description', null, PARAM_RAW), + 'screenshot_alt_texts' => optional_param_array('screenshot_alt_texts', null, PARAM_RAW), + 'remove_screenshots' => optional_param_array('remove_screenshots', null, PARAM_RAW), + 'remove_icon' => optional_param('remove_icon', null, PARAM_RAW), + 'age' => optional_param('age', null, PARAM_RAW), + ); + + // Load content. + $core = \mod_hvp\framework::instance(); + $cm = get_coursemodule_from_id('hvp', $id); + $content = $core->loadContent($cm->instance); + + // Update Hub status for content before proceeding. + $newstate = hvp_update_hub_status($content); + $synced = $newstate !== false ? $newstate : intval($content['synced']); + + if ($synced === \H5PContentHubSyncStatus::WAITING) { + \H5PCore::ajaxError(get_string('contentissyncing', 'hvp')); + break; + } + + // Create URL. + $data['download_url'] = hvp_create_hub_export_url($cm->id, $content); + + // Get file size. + $slug = $content['slug'] ? $content['slug'] . '-' : ''; + $filecontext = context_course::instance($cm->course); + $file = get_file_storage()->get_file($filecontext->id, 'mod_hvp', 'exports', 0, '/', "{$slug}{$content['id']}.h5p"); + if (!$file) { + \H5PCore::ajaxError(get_string('noexport', 'hvp')); + break; + } + $size = $file->get_filesize(); + $data['size'] = empty($size) ? -1 : $size; + + // Add the icon and any screenshots. + $files = array( + 'icon' => !empty($_FILES['icon']) ? $_FILES['icon'] : null, + 'screenshots' => !empty($_FILES['screenshots']) ? $_FILES['screenshots'] : null, + ); + + try { + $isedit = !empty($content['contentHubId']); + $updatecontent = $synced === \H5PContentHubSyncStatus::NOT_SYNCED && $isedit; + if ($updatecontent) { + // Node has been edited since the last time it was published. + $data['resync'] = 1; + } + $result = $core->hubPublishContent($data, $files, $isedit ? $content['contentHubId'] : null); + + $fields = array( + 'shared' => 1, // Content is always shared after sharing or editing. + ); + if (!$isedit) { + $fields['hub_id'] = $result->content->id; + // Sync will not happen on 'edit info', only for 'publish' or 'sync'. + $fields['synced'] = \H5PContentHubSyncStatus::WAITING; + } else if ($updatecontent) { + $fields['synced'] = \H5PContentHubSyncStatus::WAITING; + } + + // Store the content hub id. + $core->h5pF->updateContentFields($cm->instance, $fields); + + H5PCore::ajaxSuccess(); + } catch (Exception $e) { + H5PCore::ajaxError(!empty($e->errors) ? $e->errors : $e->getMessage()); + } + + break; + + /* + * Throw error if AJAX isnt handeled + */ + default: + throw new coding_exception('Unhandled AJAX'); + break; +} diff --git a/amd/build/communicator.min.js b/amd/build/communicator.min.js new file mode 100644 index 0000000..25419cf --- /dev/null +++ b/amd/build/communicator.min.js @@ -0,0 +1 @@ +define([],function(){var a=function(){this._actionHandlers={},this.registerEventListeners()};return a.prototype._actionHandlers={},a.prototype.on=function(a,b){this._actionHandlers[a]=b},a.prototype.send=function(a,b){void 0===b&&(b={}),b.context="h5p",b.action=a,window.parent.postMessage(b,"*")},a.prototype.registerEventListeners=function(){var a=this;window.addEventListener("message",function(b){window.parent===b.source&&"h5p"===b.data.context&&void 0!==a._actionHandlers[b.data.action]&&a._actionHandlers[b.data.action](b.data)},!1)},new a}); \ No newline at end of file diff --git a/amd/build/contenthubregistration.min.js b/amd/build/contenthubregistration.min.js new file mode 100644 index 0000000..8facaa9 --- /dev/null +++ b/amd/build/contenthubregistration.min.js @@ -0,0 +1,2 @@ +define ("mod_hvp/contenthubregistration",[],function(){return{init:function init(){var a=H5PSettings;a.container=document.getElementById("h5p-hub-registration");H5PHub.createRegistrationUI(a)}}}); +//# sourceMappingURL=contenthubregistration.min.js.map diff --git a/amd/build/contenthubregistration.min.js.map b/amd/build/contenthubregistration.min.js.map new file mode 100644 index 0000000..f21897d --- /dev/null +++ b/amd/build/contenthubregistration.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/contenthubregistration.js"],"names":["define","init","settings","H5PSettings","container","document","getElementById","H5PHub","createRegistrationUI"],"mappings":"AAAAA,OAAM,kCAAC,EAAD,CAAK,UAAY,CACrB,MAAO,CACLC,IAAI,CAAE,eAAY,CAEhB,GAAMC,CAAAA,CAAQ,CAAGC,WAAjB,CACAD,CAAQ,CAACE,SAAT,CAAqBC,QAAQ,CAACC,cAAT,CAAwB,sBAAxB,CAArB,CACAC,MAAM,CAACC,oBAAP,CAA4BN,CAA5B,CACD,CANI,CAQR,CATK,CAAN","sourcesContent":["define([], function () {\n return {\n init: function () {\n // Moodle complains if you pass in settings through init (js_call_amd) since they are too large\n const settings = H5PSettings;\n settings.container = document.getElementById('h5p-hub-registration');\n H5PHub.createRegistrationUI(settings);\n },\n };\n});\n"],"file":"contenthubregistration.min.js"} \ No newline at end of file diff --git a/amd/build/embed.min.js b/amd/build/embed.min.js new file mode 100644 index 0000000..fdd34ed --- /dev/null +++ b/amd/build/embed.min.js @@ -0,0 +1 @@ +define(["jquery","mod_hvp/communicator"],function(a,b){a(document).ready(function(){a(".h5p-iframe").ready(function(){var a=document.querySelector(".h5p-iframe"),c=a.contentWindow.H5P;if(c&&c.instances&&c.instances[0]){var d,e=c.instances[0],f=!1;b.on("ready",function(){b.send("hello")}),b.on("hello",function(){f=!0,a.contentDocument.body.style.overflow="hidden",document.body.classList.add("h5p-resizing"),c.trigger(e,"resize")}),b.on("resizePrepared",function(){b.send("resize",{scrollHeight:a.contentDocument.body.scrollHeight})}),b.on("resize",function(){c.trigger(e,"resize")}),c.on(e,"resize",function(){c.isFullscreen||(clearTimeout(d),d=setTimeout(function(){f?b.send("prepareResize",{scrollHeight:a.contentDocument.body.scrollHeight,clientHeight:a.contentDocument.body.clientHeight}):b.send("hello")},0))}),c.trigger(e,"resize")}})})}); \ No newline at end of file diff --git a/amd/src/communicator.js b/amd/src/communicator.js new file mode 100644 index 0000000..308b774 --- /dev/null +++ b/amd/src/communicator.js @@ -0,0 +1,79 @@ +// This file is part of Moodle - http://moodle.org/ +// +// Moodle 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. +// +// Moodle 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 Moodle. If not, see . + +define([], function() { + + /** + * When embedded the communicator helps talk to the parent page. + * This is a copy of the H5P.communicator, which we need to communicate in this context + */ + var H5PEmbedCommunicator = function() { + this._actionHandlers = {}; + this.registerEventListeners(); + }; + + /** @type {Object} Maps actions to functions. */ + H5PEmbedCommunicator.prototype._actionHandlers = {}; + + /** + * Register action listener. + * + * @param {string} action What you are waiting for + * @param {function} handler What you want done + */ + H5PEmbedCommunicator.prototype.on = function(action, handler) { + this._actionHandlers[action] = handler; + }; + + /** + * Send a message to the all mighty father. + * + * @param {string} action + * @param {Object} [data] payload + */ + H5PEmbedCommunicator.prototype.send = function(action, data) { + if (data === undefined) { + data = {}; + } + data.context = 'h5p'; + data.action = action; + + // Parent origin can be anything. + window.parent.postMessage(data, '*'); + }; + + + /** + * Register event listeners for the communicator. + * + * @method registerEventListeners + */ + H5PEmbedCommunicator.prototype.registerEventListeners = function() { + var self = this; + // Register message listener. + window.addEventListener('message', function receiveMessage(event) { + if (window.parent !== event.source || event.data.context !== 'h5p') { + return; // Only handle messages from parent and in the correct context. + } + + if (self._actionHandlers[event.data.action] !== undefined) { + self._actionHandlers[event.data.action](event.data); + } + }, false); + }; + + return new H5PEmbedCommunicator(); + +}); diff --git a/amd/src/contenthubregistration.js b/amd/src/contenthubregistration.js new file mode 100644 index 0000000..7d549f9 --- /dev/null +++ b/amd/src/contenthubregistration.js @@ -0,0 +1,10 @@ +define([], function () { + return { + init: function () { + // Moodle complains if you pass in settings through init (js_call_amd) since they are too large + const settings = H5PSettings; + settings.container = document.getElementById('h5p-hub-registration'); + H5PHub.createRegistrationUI(settings); + }, + }; +}); diff --git a/amd/src/embed.js b/amd/src/embed.js new file mode 100644 index 0000000..77ddbfe --- /dev/null +++ b/amd/src/embed.js @@ -0,0 +1,90 @@ +// This file is part of Moodle - http://moodle.org/ +// +// Moodle 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. +// +// Moodle 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 Moodle. If not, see . + +define(['jquery', 'mod_hvp/communicator'], function($, H5PEmbedCommunicator) { + + // Wait for instances to be initialize. + $(document).ready(function() { + $('.h5p-iframe').ready(function() { + var iFrame = document.querySelector('.h5p-iframe'); + var H5P = iFrame.contentWindow.H5P; + + // Check for H5P instances. + if (!H5P || !H5P.instances || !H5P.instances[0]) { + return; + } + + var resizeDelay; + var instance = H5P.instances[0]; + var parentIsFriendly = false; + + // Handle that the resizer is loaded after the iframe. + H5PEmbedCommunicator.on('ready', function() { + H5PEmbedCommunicator.send('hello'); + }); + + // Handle hello message from our parent window. + H5PEmbedCommunicator.on('hello', function() { + // Initial setup/handshake is done. + parentIsFriendly = true; + + // Hide scrollbars for correct size. + iFrame.contentDocument.body.style.overflow = 'hidden'; + + document.body.classList.add('h5p-resizing'); + + // Content need to be resized to fit the new iframe size. + H5P.trigger(instance, 'resize'); + }); + + // When resize has been prepared tell parent window to resize. + H5PEmbedCommunicator.on('resizePrepared', function() { + H5PEmbedCommunicator.send('resize', { + scrollHeight: iFrame.contentDocument.body.scrollHeight + }); + }); + + H5PEmbedCommunicator.on('resize', function() { + H5P.trigger(instance, 'resize'); + }); + + H5P.on(instance, 'resize', function() { + if (H5P.isFullscreen) { + return; // Skip iframe resize. + } + + // Use a delay to make sure iframe is resized to the correct size. + clearTimeout(resizeDelay); + resizeDelay = setTimeout(function() { + // Only resize if the iframe can be resized. + if (parentIsFriendly) { + H5PEmbedCommunicator.send('prepareResize', + { + scrollHeight: iFrame.contentDocument.body.scrollHeight, + clientHeight: iFrame.contentDocument.body.clientHeight + } + ); + } else { + H5PEmbedCommunicator.send('hello'); + } + }, 0); + }); + + // Trigger initial resize for instance. + H5P.trigger(instance, 'resize'); + }); + }); + +}); diff --git a/autoloader.php b/autoloader.php new file mode 100644 index 0000000..e18a92b --- /dev/null +++ b/autoloader.php @@ -0,0 +1,80 @@ +. + +/** + * References files that should be automatically loaded + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +defined('MOODLE_INTERNAL') || die(); + +/** + * A simple autoloader which makes it easy to load classes when you need them. + * + * @param string $class name + */ +function hvp_autoloader($class) { + global $CFG; + static $classmap; + if (!isset($classmap)) { + $classmap = array( + // Core. + 'H5PCore' => 'library/h5p.classes.php', + 'H5PFrameworkInterface' => 'library/h5p.classes.php', + 'H5PContentValidator' => 'library/h5p.classes.php', + 'H5PValidator' => 'library/h5p.classes.php', + 'H5PStorage' => 'library/h5p.classes.php', + 'H5PExport' => 'library/h5p.classes.php', + 'H5PDevelopment' => 'library/h5p-development.class.php', + 'H5PFileStorage' => 'library/h5p-file-storage.interface.php', + 'H5PDefaultStorage' => 'library/h5p-default-storage.class.php', + 'H5PEventBase' => 'library/h5p-event-base.class.php', + 'H5PMetadata' => 'library/h5p-metadata.class.php', + + // Editor. + 'H5peditor' => 'editor/h5peditor.class.php', + 'H5PEditorAjax' => 'editor/h5peditor-ajax.class.php', + 'H5PEditorAjaxInterface' => 'editor/h5peditor-ajax.interface.php', + 'H5peditorFile' => 'editor/h5peditor-file.class.php', + 'H5peditorStorage' => 'editor/h5peditor-storage.interface.php', + + // Reporting. + 'H5PReport' => 'reporting/h5p-report.class.php', + 'H5PReportXAPIData' => 'reporting/h5p-report-xapi-data.class.php', + 'ChoiceProcessor' => 'reporting/type-processors/choice-processor.class.php', + 'CompoundProcessor' => 'reporting/type-processors/compound-processor.class.php', + 'FillInProcessor' => 'reporting/type-processors/fill-in-processor.class.php', + 'LongChoiceProcessor' => 'reporting/type-processors/long-choice-processor.class.php', + 'MatchingProcessor' => 'reporting/type-processors/matching-processor.class.php', + 'TrueFalseProcessor' => 'reporting/type-processors/true-false-processor.class.php', + 'IVOpenEndedQuestionProcessor' => 'reporting/type-processors/iv-open-ended-question-processor.class.php', + 'TypeProcessor' => 'reporting/type-processors/type-processor.class.php', + 'DocumentationToolProcessor' => 'reporting/type-processors/compound/documentation-tool-processor.class.php', + 'GoalsPageProcessor' => 'reporting/type-processors/compound/goals-page-processor.class.php', + 'GoalsAssessmentPageProcessor' => 'reporting/type-processors/compound/goals-assessment-page-processor.class.php', + 'StandardPageProcessor' => 'reporting/type-processors/compound/standard-page-processor.class.php', + + // Plugin specific classes are loaded by Moodle. + ); + } + + if (isset($classmap[$class])) { + require_once($CFG->dirroot . '/mod/hvp/' . $classmap[$class]); + } +} +spl_autoload_register('hvp_autoloader'); diff --git a/backup/moodle2/backup_hvp_activity_task.class.php b/backup/moodle2/backup_hvp_activity_task.class.php new file mode 100644 index 0000000..1f728fe --- /dev/null +++ b/backup/moodle2/backup_hvp_activity_task.class.php @@ -0,0 +1,90 @@ +. + +/** + * Defines backup_hvp_activity_task class + * + * @package mod_hvp + * @category backup + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +require_once($CFG->dirroot . '/mod/hvp/backup/moodle2/backup_hvp_stepslib.php'); + +/** + * Provides the steps to perform one complete backup of a H5P instance + * + * @copyright 2018 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class backup_hvp_activity_task extends backup_activity_task { + + /** + * No specific settings for this activity + */ + protected function define_my_settings() { + } + + /** + * Defines a backup step to store the instance data in the hvp.xml file + */ + protected function define_my_steps() { + global $CFG; + + // Add hvp activity data and content files. + $this->add_step(new backup_hvp_activity_structure_step('hvp_structure', 'hvp.xml')); + + // Allow user to override library backup. + $backuplibraries = !(isset($CFG->mod_hvp_backup_libraries) && $CFG->mod_hvp_backup_libraries === '0'); + + // Exclude hvp libraries step for local 'imports'. + if ($backuplibraries && backup_controller_dbops::backup_includes_files($this->plan->get_backupid())) { + + // Note that this step will only run once per backup as it generates + // a shared resource. + $this->add_step(new backup_hvp_libraries_structure_step('hvp_libraries', 'hvp_libraries.xml')); + } + } + + /** + * Encodes URLs to the index.php and view.php scripts + * + * @param string $content some HTML text that eventually contains URLs to the activity instance scripts + * @return string the content with the URLs encoded + */ + static public function encode_content_links($content) { + global $CFG; + + $base = preg_quote($CFG->wwwroot, "/"); + + // Link to the list of glossaries. + $search = "/(".$base."\/mod\/hvp\/index.php\?id\=)([0-9]+)/"; + $content = preg_replace($search, '$@HVPINDEX*$2@$', $content); + + // Link to hvp view by module id. + $search = "/(".$base."\/mod\/hvp\/view.php\?id\=)([0-9]+)/"; + $content = preg_replace($search, '$@HVPVIEWBYID*$2@$', $content); + + // Link to hvp embed by module id. + $search = "/(".$base."\/mod\/hvp\/embed.php\?id\=)([0-9]+)/"; + $content = preg_replace($search, '$@HVPEMBEDBYID*$2@$', $content); + + return $content; + } +} diff --git a/backup/moodle2/backup_hvp_stepslib.php b/backup/moodle2/backup_hvp_stepslib.php new file mode 100644 index 0000000..398ea08 --- /dev/null +++ b/backup/moodle2/backup_hvp_stepslib.php @@ -0,0 +1,248 @@ +. + +/** + * Defines backup structure steps for both hvp content and hvp libraries. + * + * @package mod_hvp + * @category backup + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +/** + * Define the complete hvp structure for backup, with file and id annotations + * + * @copyright 2018 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class backup_hvp_activity_structure_step extends backup_activity_structure_step { + + /** + * Defines backup element's structure + * + * @return backup_nested_element + * @throws base_element_struct_exception + * @throws base_step_exception + */ + protected function define_structure() { + + // To know if we are including user info. + $userinfo = $this->get_setting_value('userinfo'); + + // Define each element separated. + $hvp = new backup_nested_element('hvp', array('id'), array( + 'name', + 'machine_name', + 'major_version', + 'minor_version', + 'intro', + 'introformat', + 'json_content', + 'embed_type', + 'disable', + 'content_type', + 'source', + 'year_from', + 'year_to', + 'license_version', + 'changes', + 'license_extras', + 'author_comments', + 'slug', + 'timecreated', + 'timemodified', + 'authors', + 'license', + 'completionpass' + )); + + // User data. + $entries = new backup_nested_element('content_user_data'); + $contentuserdata = new backup_nested_element('entry', array( + 'user_id', // Annotated. + 'sub_content_id' + ), array( + 'data_id', + 'data', + 'preloaded', + 'delete_on_content_change', + )); + + // Build the tree. + + $hvp->add_child($entries); + $entries->add_child($contentuserdata); + + // Define sources. + + // Uses library name and version instead of main_library_id. + $hvp->set_source_sql(' + SELECT h.id, + hl.machine_name, + hl.major_version, + hl.minor_version, + h.name, + h.intro, + h.introformat, + h.json_content, + h.embed_type, + h.disable, + h.content_type, + h.slug, + h.timecreated, + h.timemodified, + h.authors, + h.source, + h.year_from, + h.year_to, + h.license_version, + h.changes, + h.license_extras, + h.author_comments, + h.license, + h.completionpass + FROM {hvp} h + JOIN {hvp_libraries} hl ON hl.id = h.main_library_id + WHERE h.id = ?', array(backup::VAR_ACTIVITYID)); + + // All the rest of elements only happen if we are including user info. + if ($userinfo) { + $contentuserdata->set_source_table('hvp_content_user_data', array('hvp_id' => backup::VAR_PARENTID)); + } + + // Define id annotations. + $contentuserdata->annotate_ids('user', 'user_id'); + // In an ideal world we would use the main_library_id and annotate that + // but since we cannot know the required dependencies of the content + // without parsing json_content and crawling the libraries_libraries + // (library dependencies) table it's much easier to just include all + // installed libraries. + + // Define file annotations. + $hvp->annotate_files('mod_hvp', 'intro', null, null); + $hvp->annotate_files('mod_hvp', 'content', null, null); + + // Return the root element (hvp), wrapped into standard activity structure. + return $this->prepare_activity_structure($hvp); + } +} + +/** + * Backup h5p libraries. + * + * Structure step in charge of constructing the hvp_libraries.xml file for + * all the H5P libraries. + * + * @copyright 2018 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class backup_hvp_libraries_structure_step extends backup_structure_step { + + /** + * Determines if backup step should be executed + * + * @return bool + * @throws backup_step_exception + */ + protected function execute_condition() { + $fullpath = $this->task->get_taskbasepath(); + if (empty($fullpath)) { + throw new backup_step_exception('backup_structure_step_undefined_fullpath'); + } + + // Modify filename to use a globally shared file for all libraries. + $this->filename = "../{$this->filename}"; + + // Append the filename to the full path. + $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; + + // Determine if already generated. + return !file_exists($fullpath); + } + + /** + * Defines the structure to be executed by this backup step + * + * @return backup_nested_element + * @throws base_element_struct_exception + * @throws dml_exception + */ + protected function define_structure() { + // Libraries. + $libraries = new backup_nested_element('hvp_libraries'); + $library = new backup_nested_element('library', array('id'), array( + 'title', + 'machine_name', + 'major_version', + 'minor_version', + 'patch_version', + 'runnable', + 'fullscreen', + 'embed_types', + 'preloaded_js', + 'preloaded_css', + 'drop_library_css', + 'semantics', + 'restricted', + 'tutorial_url', + 'add_to', + 'metadata' + )); + + // Library translations. + $translations = new backup_nested_element('translations'); + $translation = new backup_nested_element('translation', array( + 'language_code' + ), array( + 'language_json' + )); + + // Library dependencies. + $dependencies = new backup_nested_element('dependencies'); + $dependency = new backup_nested_element('dependency', array( + 'required_library_id' + ), array( + 'dependency_type' + )); + + // Build the tree. + $libraries->add_child($library); + + $library->add_child($translations); + $translations->add_child($translation); + + $library->add_child($dependencies); + $dependencies->add_child($dependency); + + // Define sources. + + $library->set_source_table('hvp_libraries', array()); + + $translation->set_source_table('hvp_libraries_languages', array('library_id' => backup::VAR_PARENTID)); + + $dependency->set_source_table('hvp_libraries_libraries', array('library_id' => backup::VAR_PARENTID)); + + // Define file annotations. + $context = \context_system::instance(); + $library->annotate_files('mod_hvp', 'libraries', null, $context->id); + + // Return root element. + return $libraries; + } +} diff --git a/backup/moodle2/restore_hvp_activity_task.class.php b/backup/moodle2/restore_hvp_activity_task.class.php new file mode 100644 index 0000000..c425dad --- /dev/null +++ b/backup/moodle2/restore_hvp_activity_task.class.php @@ -0,0 +1,115 @@ +. + +/** + * Describe how H5P activites are to be restored from backup + * + * @package mod_hvp + * @category backup + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +require_once($CFG->dirroot . '/mod/hvp/backup/moodle2/restore_hvp_stepslib.php'); // Because it exists (must). + +/** + * Hvp restore task that provides all the settings and steps to perform one complete restore of the activity. + * + * @copyright 2018 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class restore_hvp_activity_task extends restore_activity_task { + + /** + * Define (add) particular settings this activity can have + */ + protected function define_my_settings() { + // No particular settings for this activity. + } + + /** + * Define (add) particular steps this activity can have + */ + protected function define_my_steps() { + // Add H5P libraries. + $this->add_step(new restore_hvp_libraries_structure_step('hvp_structure', 'hvp_libraries.xml')); + + // Add H5P content. + $this->add_step(new restore_hvp_activity_structure_step('hvp_structure', 'hvp.xml')); + } + + /** + * Define the contents in the activity that must be + * processed by the link decoder + */ + static public function define_decode_contents() { + $contents = array(); + + $contents[] = new restore_decode_content('hvp', array('intro'), 'hvp'); + + return $contents; + } + + /** + * Define the decoding rules for links belonging + * to the activity to be executed by the link decoder + */ + static public function define_decode_rules() { + $rules = array(); + + $rules[] = new restore_decode_rule('HVPVIEWBYID', '/mod/hvp/view.php?id=$1', 'course_module'); + $rules[] = new restore_decode_rule('HVPINDEX', '/mod/hvp/index.php?id=$1', 'course'); + $rules[] = new restore_decode_rule('HVPEMBEDBYID', '/mod/hvp/embed.php?id=$1', 'course_module'); + + return $rules; + } + + /** + * Define the restore log rules that will be applied + * by the {@link restore_logs_processor} when restoring + * hvp logs. It must return one array + * of {@link restore_log_rule} objects + */ + static public function define_restore_log_rules() { + $rules = array(); + + $rules[] = new restore_log_rule('hvp', 'add', 'view.php?id={course_module}', '{hvp}'); + $rules[] = new restore_log_rule('hvp', 'update', 'view.php?id={course_module}', '{hvp}'); + $rules[] = new restore_log_rule('hvp', 'view', 'view.php?id={course_module}', '{hvp}'); + + return $rules; + } + + /** + * Define the restore log rules that will be applied + * by the {@link restore_logs_processor} when restoring + * course logs. It must return one array + * of {@link restore_log_rule} objects + * + * Note this rules are applied when restoring course logs + * by the restore final task, but are defined here at + * activity level. All them are rules not linked to any module instance (cmid = 0) + */ + static public function define_restore_log_rules_for_course() { + $rules = array(); + + $rules[] = new restore_log_rule('hvp', 'view all', 'index.php?id={course}', null); + + return $rules; + } +} diff --git a/backup/moodle2/restore_hvp_stepslib.php b/backup/moodle2/restore_hvp_stepslib.php new file mode 100644 index 0000000..75c4930 --- /dev/null +++ b/backup/moodle2/restore_hvp_stepslib.php @@ -0,0 +1,372 @@ +. + +/** + * Restore structure step for both hvp content and hvp libraries + * + * @package mod_hvp + * @category backup + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +/** + * Structure step to restore one H5P activity + * + * @copyright 2018 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class restore_hvp_activity_structure_step extends restore_activity_structure_step { + + /** + * Defines restore element's structure + * + * @return array + * @throws base_step_exception + */ + protected function define_structure() { + $paths = array(); + $userinfo = $this->get_setting_value('userinfo'); + + // Restore activities. + $paths[] = new restore_path_element('hvp', '/activity/hvp'); + + if ($userinfo) { + // Restore content state. + $paths[] = new restore_path_element('content_user_data', '/activity/hvp/content_user_data/entry'); + } + + // Return the paths wrapped into standard activity structure. + return $this->prepare_activity_structure($paths); + } + + /** + * Process H5P, inserting the record into the database. + * + * @param $data + * + * @throws base_step_exception + * @throws dml_exception + */ + protected function process_hvp($data) { + global $DB; + + $data = (object) $data; + $data->course = $this->get_courseid(); + $data->main_library_id = \restore_hvp_libraries_structure_step::get_library_id($data); + + $data->timecreated = $this->apply_date_offset($data->timecreated); + $data->timemodified = $this->apply_date_offset($data->timemodified); + + // Insert the hvp record. + $newitemid = $DB->insert_record('hvp', $data); + // Immediately after inserting "activity" record, call this. + $this->apply_activity_instance($newitemid); + } + + /** + * Process and inserts content user data. + * + * @param $data + * + * @throws dml_exception + */ + protected function process_content_user_data($data) { + global $DB; + + $data = (object) $data; + $data->user_id = $this->get_mappingid('user', $data->user_id); + $data->hvp_id = $this->get_new_parentid('hvp'); + + $DB->insert_record('hvp_content_user_data', $data); + } + + /** + * Additional work that needs to be done after steps executions. + */ + protected function after_execute() { + // Add files for intro field. + $this->add_related_files('mod_hvp', 'intro', null); + + // Add hvp related files. + $this->add_related_files('mod_hvp', 'content', 'hvp'); + } +} + +/** + * Structure step to restore H5P libraries + * + * @copyright 2018 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class restore_hvp_libraries_structure_step extends restore_activity_structure_step { + + /** + * Determines if library should be restored. + * + * @return bool + * @throws backup_step_exception + */ + protected function execute_condition() { + static $librariesrestored; + + // Prevent this step from running more than once + // since all hvp_libraries.xml files are the same. + if (!empty($librariesrestored)) { + return false; + } + $librariesrestored = true; + + // Get full path to activity backup location. + $fullpath = $this->task->get_taskbasepath(); + if (empty($fullpath)) { + throw new backup_step_exception('backup_structure_step_undefined_fullpath'); + } + $fullpath = rtrim($fullpath, '/'); + + // Check for the activity's local hvp_libraries.xml file. + if (file_exists("{$fullpath}/{$this->filename}")) { + // Use that. + return true; + } + + // Look for a global hvp_libraries.xml file. + if (file_exists("{$fullpath}/../{$this->filename}")) { + // Use it. + $this->filename = "../{$this->filename}"; + return true; + } + + // Not able to find a hvp_libraries.xml, skip restore and let the admin + // be responsible for providing the approperiate libraries. + // (Could also be using Import which doesn't need libraries). + return false; + } + + /** + * Defines how library should be restored. + * + * @return array + */ + protected function define_structure() { + $paths = array(); + + // Restore libraries first. + $paths[] = new restore_path_element('hvp_library', '/hvp_libraries/library'); + + // Add translations. + $paths[] = new restore_path_element('hvp_library_translation', '/hvp_libraries/library/translations/translation'); + + // ... and dependencies. + $paths[] = new restore_path_element('hvp_library_dependency', '/hvp_libraries/library/dependencies/dependency'); + + // Return the paths wrapped into standard activity structure. + return $this->prepare_activity_structure($paths); + } + + /** + * Process and insert library record. + * + * @param $data + * + * @throws dml_exception + * @throws restore_step_exception + */ + protected function process_hvp_library($data) { + global $DB; + + $data = (object)$data; + $oldid = $data->id; + unset($data->id); + + $libraryid = self::get_library_id($data); + if (!$libraryid) { + // There is no updating of libraries. If an older patch version exists + // on the site that one will be used instead of the new one in the backup. + // This is due to the default behavior when files are restored in Moodle. + + // Restore library. + $libraryid = $DB->insert_record('hvp_libraries', $data); + + // Update libraries cache. + self::get_library_id($data, $libraryid); + } + + // Keep track of libraries for translations and dependencies. + $this->set_mapping('hvp_library', $oldid, $libraryid); + + // Update any dependencies that require this library. + $this->update_missing_dependencies($oldid, $libraryid); + } + + /** + * Process and inserts translations for library. + * + * @param $data + * + * @throws dml_exception + */ + protected function process_hvp_library_translation($data) { + global $DB; + + $data = (object) $data; + $data->library_id = $this->get_new_parentid('hvp_library'); + + // Check that translations doesn't exists. + $translation = $DB->get_record_sql( + 'SELECT id + FROM {hvp_libraries_languages} + WHERE library_id = ? + AND language_code = ?', + array($data->library_id, + $data->language_code) + ); + + if (empty($translation)) { + // Only restore translations if library has been restored. + $DB->insert_record('hvp_libraries_languages', $data); + } + } + + /** + * Process and inserts library dependencies. + * + * @param $data + * + * @throws dml_exception + */ + protected function process_hvp_library_dependency($data) { + global $DB; + + $data = (object) $data; + $data->library_id = $this->get_new_parentid('hvp_library'); + + $newlibraryid = $this->get_mappingid('hvp_library', $data->required_library_id); + if ($newlibraryid) { + $data->required_library_id = $newlibraryid; + + // Check that the dependency doesn't exists. + $dependency = $DB->get_record_sql( + 'SELECT id + FROM {hvp_libraries_libraries} + WHERE library_id = ? + AND required_library_id = ?', + [ + $data->library_id, + $data->required_library_id, + ] + ); + if (empty($dependency)) { + $DB->insert_record('hvp_libraries_libraries', $data); + } + } else { + // The required dependency hasn't been restored yet. We need to add this dependency later. + $this->update_missing_dependencies($data->required_library_id, null, $data); + } + } + + /** + * Additional work that is executed after library restoration steps. + * + * @throws dml_exception + */ + protected function after_execute() { + // Add files for libraries. + $context = \context_system::instance(); + $this->add_related_files('mod_hvp', 'libraries', null, $context->id); + } + + /** + * Cache to reduce queries. + * + * @param $library + * @param null $set + * + * @return mixed + * @throws dml_exception + */ + public static function get_library_id(&$library, $set = null) { + static $keytoid; + global $DB; + + $key = $library->machine_name . ' ' . $library->major_version . '.' . $library->minor_version; + if (is_null($keytoid)) { + $keytoid = array(); + } + if ($set !== null) { + $keytoid[$key] = $set; + } else if (!isset($keytoid[$key])) { + $lib = $DB->get_record_sql( + 'SELECT id + FROM {hvp_libraries} + WHERE machine_name = ? + AND major_version = ? + AND minor_version = ?', + array($library->machine_name, + $library->major_version, + $library->minor_version) + ); + + // Non existing = false. + $keytoid[$key] = (empty($lib) ? false : $lib->id); + } + + return $keytoid[$key]; + } + + /** + * Keep track of missing dependencies since libraries aren't inserted + * in any special order + * + * @param $oldid + * @param $newid + * @param null $setmissing + * + * @throws dml_exception + */ + private function update_missing_dependencies($oldid, $newid, $setmissing = null) { + static $missingdeps; + global $DB; + + if (is_null($missingdeps)) { + $missingdeps = array(); + } + + if ($setmissing !== null) { + $missingdeps[$oldid][] = $setmissing; + } else if (isset($missingdeps[$oldid])) { + foreach ($missingdeps[$oldid] as $missingdep) { + $missingdep->required_library_id = $newid; + + // Check that the dependency doesn't exists. + $dependency = $DB->get_record_sql( + 'SELECT id + FROM {hvp_libraries_libraries} + WHERE library_id = ? + AND required_library_id = ?', + array($missingdep->library_id, + $missingdep->required_library_id) + ); + if (empty($dependency)) { + $DB->insert_record('hvp_libraries_libraries', $missingdep); + } + } + unset($missingdeps[$oldid]); + } + } +} diff --git a/classes/admin_setting_html.php b/classes/admin_setting_html.php new file mode 100644 index 0000000..a03f618 --- /dev/null +++ b/classes/admin_setting_html.php @@ -0,0 +1,76 @@ +. + +defined('MOODLE_INTERNAL') || die(); + +/** + * No setting - just html + * Note: since admin_setting is not namespaced, this can not be namespaced and put into a class + */ +class admin_setting_html extends admin_setting { + + private $hubinfo; + + /** + * not a setting, just html + * + * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. + */ + public function __construct($name, $translation, $hubinfo) { + $this->nosave = true; + $this->hubinfo = $hubinfo; + parent::__construct($name, $translation, '', ''); + } + + /** + * Always returns true + * @return bool Always returns true + */ + public function get_setting() { + return true; + } + + /** + * Always returns true + * @return bool Always returns true + */ + public function get_defaultsetting() { + return true; + } + + /** + * Never write settings + * @return string Always returns an empty string + */ + public function write_setting($data) { + // Do not write any setting. + return ''; + } + + /** + * Returns an HTML string + * @return string Returns an HTML string + */ + public function output_html($data, $query = '') { + global $OUTPUT; + $registrationurl = new moodle_url('/mod/hvp/content_hub_registration.php'); + if ($this->hubinfo === false) { + $this->hubinfo = (object) []; + } + $this->hubinfo->registrationurl = $registrationurl->out(false); + return $OUTPUT->render_from_template('mod_hvp/content_hub_registration_box', $this->hubinfo); + } +} \ No newline at end of file diff --git a/classes/content_hub_service.php b/classes/content_hub_service.php new file mode 100644 index 0000000..64fc040 --- /dev/null +++ b/classes/content_hub_service.php @@ -0,0 +1,56 @@ +. +namespace mod_hvp; + +use Exception; +use moodle_url; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Service for communicating with the content hub + * + * @package mod_hvp + * @copyright 2020 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class content_hub_service { + + /** + * Get settings for content hub registration UI + * + * @return array + * @throws Exception + */ + public static function get_registration_ui_settings() { + $core = framework::instance(); + $registrationurl = new moodle_url('/mod/hvp/ajax.php', [ + 'action' => 'contenthubregistration', + ]); + $accountsettingsurl = new moodle_url('/admin/settings.php?section=modsettinghvp'); + + return [ + 'registrationURL' => $registrationurl->out(true), + 'accountSettingsUrl' => $accountsettingsurl->out(true), + 'token' => $core::createToken('contentHubRegistration'), + 'l10n' => $core->getLocalization(), + 'licenseAgreementTitle' => get_string('contenthub:licenseagreementtitle', 'hvp'), + 'licenseAgreementDescription' => get_string('contenthub:licenseagreementdescription', 'hvp'), + 'licenseAgreementMainText' => get_string('contenthub:licenseagreementmaintext', 'hvp'), + 'accountInfo' => $core->hubAccountInfo(), + ]; + } +} diff --git a/classes/content_type_cache_form.php b/classes/content_type_cache_form.php new file mode 100644 index 0000000..c07d82b --- /dev/null +++ b/classes/content_type_cache_form.php @@ -0,0 +1,61 @@ +. +/** + * \mod_hvp\content_type_cache_form class + * + * @package mod_hvp + * @copyright 2017 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +namespace mod_hvp; + +defined('MOODLE_INTERNAL') || die(); + +global $CFG; +require_once($CFG->libdir . '/formslib.php'); + +/** + * Form to update the content type cache that mirrors the available libraries in the H5P hub. + * + * @package mod_hvp + * @copyright 2017 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class content_type_cache_form extends \moodleform { + + /** + * Define form elements + */ + public function definition() { + // Get form. + $mform = $this->_form; + + // Get and format date. + $lastupdate = get_config('mod_hvp', 'content_type_cache_updated_at'); + + $dateformatted = $lastupdate ? \userdate($lastupdate) : get_string('ctcacheneverupdated', 'hvp'); + + // Add last update info. + $mform->addElement('static', 'lastupdate', + get_string('ctcachelastupdatelabel', 'hvp'), $dateformatted); + + $mform->addElement('static', 'lastupdatedescription', '', + get_string('ctcachedescription', 'hvp')); + + // Update cache button. + $this->add_action_buttons(false, get_string('ctcachebuttonlabel', 'hvp')); + } +} diff --git a/classes/content_user_data.php b/classes/content_user_data.php new file mode 100644 index 0000000..8b2dc63 --- /dev/null +++ b/classes/content_user_data.php @@ -0,0 +1,256 @@ +. + +/** + * The mod_hvp content user data. + * + * @package mod_hvp + * @since Moodle 2.7 + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Class content_user_data handles user data and corresponding db operations. + * + * @package mod_hvp + * @copyright 2018 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class content_user_data { + + /** + * Retrieves ajax parameters for content and update or delete + * user data depending on params. + * + * @throws \coding_exception + * @throws \dml_exception + */ + public static function handle_ajax() { + // Query String Parameters. + $contentid = required_param('content_id', PARAM_INT); + $dataid = required_param('data_type', PARAM_RAW); + $subcontentid = required_param('sub_content_id', PARAM_INT); + + // Form Data. + $data = optional_param('data', null, PARAM_RAW); + $preload = optional_param('preload', null, PARAM_INT); + $invalidate = optional_param('invalidate', null, PARAM_INT); + + if ($contentid === null || $dataid === null || $subcontentid === null) { + // Missing parameters. + \H5PCore::ajaxError(get_string('missingparameters', 'hvp')); + return; + } + + // Saving data. + if ($data !== null && $preload !== null && $invalidate !== null) { + self::store_data($contentid, $subcontentid, $dataid, $data, $preload, $invalidate); + } else { + self::fetch_existing_data($contentid, $subcontentid, $dataid); + } + } + + + /** + * Stores content user data + * + * @param $contentid + * @param $subcontentid + * @param $dataid + * @param $data + * @param $preload + * @param $invalidate + * + * @throws \coding_exception + * @throws \dml_exception + */ + private static function store_data($contentid, $subcontentid, $dataid, $data, $preload, $invalidate) { + // Validate token. + if (!\H5PCore::validToken('contentuserdata', required_param('token', PARAM_RAW))) { + \H5PCore::ajaxError(get_string('invalidtoken', 'hvp')); + return; + } + + if ($contentid === 0) { + $context = \context::instance_by_id(required_param('contextId', PARAM_RAW)); + } else { + // Load course module for content to get context. + $cm = get_coursemodule_from_instance('hvp', $contentid); + if (!$cm) { + \H5PCore::ajaxError('No such content'); + http_response_code(404); + return; + } + $context = \context_module::instance($cm->id); + } + + // Check permissions. + if (!has_capability('mod/hvp:savecontentuserdata', $context)) { + \H5PCore::ajaxError(get_string('nopermissiontosavecontentuserdata', 'hvp')); + http_response_code(403); + return; + } + + if ($data === '0') { + // Delete user data. + self::delete_user_data($contentid, $subcontentid, $dataid); + } else { + // Save user data. + self::save_user_data($contentid, $subcontentid, $dataid, $preload, $invalidate, $data); + } + \H5PCore::ajaxSuccess(); + } + + /** + * Return existing content user data + * + * @param $contentid + * @param $subcontentid + * @param $dataid + * + * @throws \dml_exception + */ + private static function fetch_existing_data($contentid, $subcontentid, $dataid) { + // Fetch user data. + $userdata = self::get_user_data($contentid, $subcontentid, $dataid); + \H5PCore::ajaxSuccess($userdata ? $userdata->data : null); + } + + /** + * Get user data for content. + * + * @param $contentid + * @param $subcontentid + * @param $dataid + * + * @return mixed + * @throws \dml_exception + */ + public static function get_user_data($contentid, $subcontentid, $dataid) { + global $DB, $USER; + + $result = $DB->get_record('hvp_content_user_data', array( + 'user_id' => $USER->id, + 'hvp_id' => $contentid, + 'sub_content_id' => $subcontentid, + 'data_id' => $dataid + ) + ); + + return $result; + } + + /** + * Save user data for specific content in database. + * + * @param $contentid + * @param $subcontentid + * @param $dataid + * @param $preload + * @param $invalidate + * @param $data + * + * @throws \dml_exception + */ + public static function save_user_data($contentid, $subcontentid, $dataid, $preload, $invalidate, $data) { + global $DB, $USER; + + // Determine if we should update or insert. + $update = self::get_user_data($contentid, $subcontentid, $dataid); + + // Wash values to ensure 0 or 1. + $preload = ($preload === '0' || $preload === 0) ? 0 : 1; + $invalidate = ($invalidate === '0' || $invalidate === 0) ? 0 : 1; + + // New data to be inserted. + $newdata = (object)array( + 'user_id' => $USER->id, + 'hvp_id' => $contentid, + 'sub_content_id' => $subcontentid, + 'data_id' => $dataid, + 'data' => $data, + 'preloaded' => $preload, + 'delete_on_content_change' => $invalidate + ); + + // Does not exist. + if ($update === false) { + // Insert new data. + $DB->insert_record('hvp_content_user_data', $newdata); + } else { + // Get old data id. + $newdata->id = $update->id; + + // Update old data. + $DB->update_record('hvp_content_user_data', $newdata); + } + } + + /** + * Delete user data with specific content from database + * + * @param $contentid + * @param $subcontentid + * @param $dataid + * + * @throws \dml_exception + */ + public static function delete_user_data($contentid, $subcontentid, $dataid) { + global $DB, $USER; + + $DB->delete_records('hvp_content_user_data', array( + 'user_id' => $USER->id, + 'hvp_id' => $contentid, + 'sub_content_id' => $subcontentid, + 'data_id' => $dataid + )); + } + + /** + * Load user data for specific content + * + * @param $contentid + * + * @return array User data for specific content if found, else null + * @throws \dml_exception + */ + public static function load_pre_loaded_user_data($contentid) { + global $DB, $USER; + + $preloadeduserdata = array( + 'state' => '{}' + ); + + $results = $DB->get_records('hvp_content_user_data', array( + 'user_id' => $USER->id, + 'hvp_id' => $contentid, + 'sub_content_id' => 0, + 'preloaded' => 1 + )); + + // Get data for data ids. + foreach ($results as $contentuserdata) { + $preloadeduserdata[$contentuserdata->data_id] = $contentuserdata->data; + } + + return $preloadeduserdata; + } +} diff --git a/classes/curl.php b/classes/curl.php new file mode 100644 index 0000000..2230848 --- /dev/null +++ b/classes/curl.php @@ -0,0 +1,59 @@ +. + +/** + * The mod_hvp content user data. + * + * @package mod_hvp + * @since Moodle 3.10 + * @copyright 2020 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; + +use curl as moodlecurl; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Override Moodle's curl class to provide proper PUT support. + * + * @package mod_hvp + * @copyright 2020 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class curl extends moodlecurl { + + /** + * @inheritdoc + */ + public function post($url, $params = '', $options = array()) { + $options['CURLOPT_POST'] = 1; + $options['CURLOPT_POSTFIELDS'] = $params; + return $this->request($url, $options); + } + + /** + * @inheritdoc + */ + public function put($url, $params = '', $options = array()) { + $options['CURLOPT_CUSTOMREQUEST'] = 'PUT'; + $options['CURLOPT_POSTFIELDS'] = $params; + return $this->request($url, $options); + } + +} diff --git a/classes/editor_ajax.php b/classes/editor_ajax.php new file mode 100644 index 0000000..ef20764 --- /dev/null +++ b/classes/editor_ajax.php @@ -0,0 +1,180 @@ +. + +/** + * \mod_hvp\editor_ajax class + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; + +defined('MOODLE_INTERNAL') || die(); + +require_once(__DIR__ . '/../autoloader.php'); + +/** + * Moodle's implementation of the H5P Editor Ajax interface. + * Makes it possible for the editor's core ajax functionality to communicate with the + * database used by Moodle. + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class editor_ajax implements \H5PEditorAjaxInterface { + + /** + * Gets latest library versions that exists locally + * + * @return array Latest version of all local libraries + * @throws \dml_exception + */ + // @codingStandardsIgnoreLine + public function getLatestLibraryVersions() { + global $DB; + + $maxmajorversionsql = " + SELECT hl.machine_name, MAX(hl.major_version) AS major_version + FROM {hvp_libraries} hl + WHERE hl.runnable = 1 + GROUP BY hl.machine_name"; + + $maxminorversionsql = " + SELECT hl2.machine_name, hl2.major_version, MAX(hl2.minor_version) AS minor_version + FROM ({$maxmajorversionsql}) hl1 + JOIN {hvp_libraries} hl2 + ON hl1.machine_name = hl2.machine_name + AND hl1.major_version = hl2.major_version + GROUP BY hl2.machine_name, hl2.major_version"; + + return $DB->get_records_sql(" + SELECT hl4.id, hl4.machine_name, hl4.title, hl4.major_version, + hl4.minor_version, hl4.patch_version, hl4.has_icon, hl4.restricted + FROM {hvp_libraries} hl4 + JOIN ({$maxminorversionsql}) hl3 + ON hl4.machine_name = hl3.machine_name + AND hl4.major_version = hl3.major_version + AND hl4.minor_version = hl3.minor_version" + ); + } + + /** + * Get locally stored Content Type Cache. If machine name is provided + * it will only get the given content type from the cache + * + * @param null $machinename + * + * @return array|mixed|null|object Returns results from querying the database + * @throws \dml_exception + */ + // @codingStandardsIgnoreLine + public function getContentTypeCache($machinename = null) { + global $DB; + + if ($machinename) { + return $DB->get_record_sql( + "SELECT id, is_recommended + FROM {hvp_libraries_hub_cache} + WHERE machine_name = ?", + array($machinename) + ); + } + + return $DB->get_records("hvp_libraries_hub_cache"); + } + + /** + * Gets recently used libraries for the current author + * + * @return array machine names. The first element in the array is the + * most recently used. + */ + // @codingStandardsIgnoreLine + public function getAuthorsRecentlyUsedLibraries() { + global $DB; + global $USER; + $recentlyused = array(); + + $results = $DB->get_records_sql( + "SELECT library_name, max(created_at) AS max_created_at + FROM {hvp_events} + WHERE type='content' AND sub_type = 'create' AND user_id = ? + GROUP BY library_name + ORDER BY max_created_at DESC", array($USER->id)); + + foreach ($results as $row) { + $recentlyused[] = $row->library_name; + } + + return $recentlyused; + } + + /** + * Checks if the provided token is valid for this endpoint + * + * @param string $token The token that will be validated for. + * + * @return bool True if successful validation + */ + // @codingStandardsIgnoreLine + public function validateEditorToken($token) { + return \H5PCore::validToken('editorajax', $token); + } + + /** + * Get translations for a language for a list of libraries + * + * @param array $libraries An array of libraries, in the form " . + * @param string $language_code + * + * @return array + * @throws \dml_exception + */ + public function getTranslations($libraries, $language_code) { + global $DB; + + $translations = array(); + + foreach ($libraries as $library) { + $parsedLib = \H5PCore::libraryFromString($library); + + $sql = " + SELECT language_json + FROM {hvp_libraries} lib + LEFT JOIN {hvp_libraries_languages} lang + ON lib.id = lang.library_id + WHERE lib.machine_name = :machine_name AND + lib.major_version = :major_version AND + lib.minor_version = :minor_version AND + lang.language_code = :language_code"; + $translation = $DB->get_field_sql($sql, array( + 'machine_name' => $parsedLib['machineName'], + 'major_version' => $parsedLib['majorVersion'], + 'minor_version' => $parsedLib['minorVersion'], + 'language_code' => $language_code, + )); + + if ($translation !== false) { + $translations[$library] = $translation; + } + } + + return $translations; + } +} diff --git a/classes/editor_framework.php b/classes/editor_framework.php new file mode 100644 index 0000000..4822f3b --- /dev/null +++ b/classes/editor_framework.php @@ -0,0 +1,355 @@ +. + +/** + * \mod_hvp\framework class + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; + +use H5peditorFile; + +defined('MOODLE_INTERNAL') || die(); + +require_once(__DIR__ . '/../autoloader.php'); + +/** + * Moodle's implementation of the H5P Editor framework interface. + * Makes it possible for the editor's core library to communicate with the + * database used by Moodle. + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class editor_framework implements \H5peditorStorage { + + /** + * Load language file(JSON) from database. + * This is used to translate the editor fields(title, description etc.) + * + * @param string $name The machine readable name of the library(content type) + * @param int $major Major part of version number + * @param int $minor Minor part of version number + * @param string $lang Language code + * @return string Translation in JSON format + */ + // @codingStandardsIgnoreLine + public function getLanguage($name, $major, $minor, $lang) { + global $DB; + + // Load translation field from DB. + return $DB->get_field_sql( + "SELECT hlt.language_json + FROM {hvp_libraries_languages} hlt + JOIN {hvp_libraries} hl ON hl.id = hlt.library_id + WHERE hl.machine_name = ? + AND hl.major_version = ? + AND hl.minor_version = ? + AND hlt.language_code = ? + ", array( + $name, + $major, + $minor, + $lang + ) + ); + } + + /** + * "Callback" for mark the given file as a permanent file. + * Used when saving content that has new uploaded files. + * + * @param int $fileid + */ + // @codingStandardsIgnoreLine + public function keepFile($fileid) { + global $DB; + + // Remove from tmpfiles. + $DB->delete_records('hvp_tmpfiles', array( + 'id' => $fileid + )); + } + + /** + * Decides which content types the editor should have. + * + * Two usecases: + * 1. No input, will list all the available content types. + * 2. Libraries supported are specified, load additional data and verify + * that the content types are available. Used by e.g. the Presentation Tool + * Editor that already knows which content types are supported in its + * slides. + * + * @param array $libraries List of library names + version to load info for + * @return array List of all libraries loaded + */ + // @codingStandardsIgnoreLine + public function getLibraries($libraries = null) { + global $DB; + + $contextid = required_param('contextId', PARAM_RAW); + $superuser = has_capability('mod/hvp:userestrictedlibraries', + \context::instance_by_id($contextid)); + + if ($libraries !== null) { + // Get details for the specified libraries only. + $librarieswithdetails = array(); + foreach ($libraries as $library) { + // Look for library. + $details = $DB->get_record_sql( + "SELECT title, + runnable, + restricted, + tutorial_url, + metadata_settings + FROM {hvp_libraries} + WHERE machine_name = ? + AND major_version = ? + AND minor_version = ? + AND semantics IS NOT NULL + ", array( + $library->name, + $library->majorVersion, + $library->minorVersion + ) + ); + if ($details) { + // Library found, add details to list. + $library->tutorialUrl = $details->tutorial_url; + $library->title = $details->title; + $library->runnable = $details->runnable; + $library->restricted = $superuser ? false : ($details->restricted === '1' ? true : false); + $library->metadataSettings = json_decode($details->metadata_settings); + $librarieswithdetails[] = $library; + } + } + + // Done, return list with library details. + return $librarieswithdetails; + } + + // Load all libraries. + $libraries = array(); + $librariesresult = $DB->get_records_sql( + "SELECT id, + machine_name AS name, + title, + major_version, + minor_version, + tutorial_url, + restricted, + metadata_settings + FROM {hvp_libraries} + WHERE runnable = 1 + AND semantics IS NOT NULL + ORDER BY title" + ); + foreach ($librariesresult as $library) { + // Remove unique index. + unset($library->id); + + // Convert snakes to camels. + $library->majorVersion = (int) $library->major_version; + unset($library->major_version); + $library->minorVersion = (int) $library->minor_version; + unset($library->minor_version); + if (!empty($library->tutorial_url)) { + $library->tutorialUrl = $library->tutorial_url; + } + unset($library->tutorial_url); + + $library->metadataSettings = json_decode($library->metadata_settings); + unset($library->metadata_settings); + + // Make sure we only display the newest version of a library. + foreach ($libraries as $key => $existinglibrary) { + if ($library->name === $existinglibrary->name) { + // Found library with same name, check versions. + if ( ( $library->majorVersion === $existinglibrary->majorVersion && + $library->minorVersion > $existinglibrary->minorVersion ) || + ( $library->majorVersion > $existinglibrary->majorVersion ) ) { + // This is a newer version. + $existinglibrary->isOld = true; + } else { + // This is an older version. + $library->isOld = true; + } + } + } + + // Check to see if content type should be restricted. + $library->restricted = $superuser ? false : ($library->restricted === '1' ? true : false); + + // Add new library. + $libraries[] = $library; + } + return $libraries; + } + + /** + * Allow for other plugins to decide which styles and scripts are attached. + * This is useful for adding and/or modifing the functionality and look of + * the content types. + * + * @param array $files + * List of files as objects with path and version as properties + * @param array $libraries + * List of libraries indexed by machineName with objects as values. The objects + * have majorVersion and minorVersion as properties. + */ + // @codingStandardsIgnoreLine + public function alterLibraryFiles(&$files, $libraries) { + global $PAGE; + + // Refactor dependency list. + $librarylist = array(); + foreach ($libraries as $dependency) { + $librarylist[$dependency['machineName']] = array( + 'majorVersion' => $dependency['majorVersion'], + 'minorVersion' => $dependency['minorVersion'] + ); + } + + $contextid = required_param('contextId', PARAM_INT); + $context = \context::instance_by_id($contextid); + + $PAGE->set_context($context); + $renderer = $PAGE->get_renderer('mod_hvp'); + + $embedtype = 'editor'; + $renderer->hvp_alter_scripts($files['scripts'], $librarylist, $embedtype); + $renderer->hvp_alter_styles($files['styles'], $librarylist, $embedtype); + } + + /** + * Saves a file or moves it temporarily. This is often necessary in order to + * validate and store uploaded or fetched H5Ps. + * + * @param string $data Uri of data that should be saved as a temporary file + * @param boolean $movefile Can be set to TRUE to move the data instead of saving it + * + * @return bool|object Returns false if saving failed or an object with path + * of the directory and file that is temporarily saved + */ + // @codingStandardsIgnoreLine + public static function saveFileTemporarily($data, $movefile = false) { + global $CFG; + + // Generate local tmp file path. + $uniqueh5pid = uniqid('hvp-'); + $filename = $uniqueh5pid . '.h5p'; + $directory = $CFG->tempdir . DIRECTORY_SEPARATOR . $uniqueh5pid; + $filepath = $directory . DIRECTORY_SEPARATOR . $filename; + + if (!is_dir($directory)) { + mkdir($directory, 0777, true); + } + + // Move file or save data to new file so core can validate H5P. + if ($movefile) { + move_uploaded_file($data, $filepath); + } else { + file_put_contents($filepath, $data); + } + + // Add folder and file paths to H5P Core. + $interface = framework::instance('interface'); + $interface->getUploadedH5pFolderPath($directory); + $interface->getUploadedH5pPath($directory . DIRECTORY_SEPARATOR . $filename); + + return (object) array( + 'dir' => $directory, + 'fileName' => $filename + ); + } + + /** + * Marks a file for later cleanup, useful when files are not instantly cleaned + * up. E.g. for files that are uploaded through the editor. + * + * @param int $file Id of file that should be cleaned up + * @param int|null $contentid Content id of file + */ + // @codingStandardsIgnoreLine + public static function markFileForCleanup($file, $contentid = null) { + global $DB; + + // Let H5P Core clean up. + if ($contentid) { + return; + } + + // Track temporary files for later cleanup. + $DB->insert_record_raw('hvp_tmpfiles', array( + 'id' => $file + ), false, false, true); + } + + /** + * Clean up temporary files + * + * @param string $filepath Path to file or directory + */ + // @codingStandardsIgnoreLine + public static function removeTemporarilySavedFiles($filepath) { + if (is_dir($filepath)) { + \H5PCore::deleteFileTree($filepath); + } else { + @unlink($filepath); + } + } + + /** + * Load a list of available language codes from the database. + * + * @param string $machineName The machine readable name of the library(content type) + * @param int $majorVersion Major part of version number + * @param int $minorVersion Minor part of version number + * + * @return array List of possible language codes + * @throws \dml_exception + */ + public function getAvailableLanguages($machineName, $majorVersion, $minorVersion) { + global $DB; + + $sql = "SELECT language_code + FROM {hvp_libraries_languages} hlt + JOIN {hvp_libraries} hl + ON hl.id = hlt.library_id + WHERE hl.machine_name = :machinename + AND hl.major_version = :major + AND hl.minor_version = :minor"; + + $results = $DB->get_records_sql($sql, array( + 'machinename' => $machineName, + 'major' => $majorVersion, + 'minor' => $minorVersion, + )); + + $codes = array('en'); // Semantics is 'en' by default. + foreach ($results as $result) { + $codes[] = $result->language_code; + } + + return $codes; + } +} diff --git a/classes/event.php b/classes/event.php new file mode 100644 index 0000000..664b4b8 --- /dev/null +++ b/classes/event.php @@ -0,0 +1,98 @@ +. + +/** + * The mod_hvp event logger, makes it easy to track events throughout + * the H5P system. + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; +defined('MOODLE_INTERNAL') || die(); + +class event extends \H5PEventBase { + private $user; + + /** + * @inheritdoc + */ + public function __construct($type, $subtype = null, $contentid = null, + $contenttitle = null, $libraryname = null, $libraryversion = null) { + global $USER; + + // Track the who initiated the event. + $this->user = $USER->id; + + parent::__construct($type, $subtype, $contentid, $contenttitle, $libraryname, $libraryversion); + } + + /** + * Store the event. + * + * @return int Event ID + */ + protected function save() { + global $DB; + + // Get data in array format without null values. + $data = $this->getDataArray(); + + // Add user. + $data['user_id'] = $this->user; + + return $DB->insert_record('hvp_events', $data); + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + protected function saveStats() { + global $DB; + $type = $this->type . ' ' . $this->sub_type; + + // Grab current counter to check if it exists. + $id = $DB->get_field_sql( + "SELECT id + FROM {hvp_counters} + WHERE type = ? + AND library_name = ? + AND library_version = ?", + array($type, $this->library_name, $this->library_version) + ); + + if ($id === false) { + // No counter found, insert new one. + $DB->insert_record('hvp_counters', array( + 'type' => $type, + 'library_name' => $this->library_name, + 'library_version' => $this->library_version, + 'num' => 1 + )); + } else { + // Update num+1. + $DB->execute( + "UPDATE {hvp_counters} + SET num = num + 1 + WHERE id = ?", + array($id) + ); + } + } +} diff --git a/classes/event/attempt_submitted.php b/classes/event/attempt_submitted.php new file mode 100644 index 0000000..8392b24 --- /dev/null +++ b/classes/event/attempt_submitted.php @@ -0,0 +1,46 @@ +. + +/** + * Attempt submitted event + * + * @package mod_hvp + * @copyright 2020 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp\event; + +defined('MOODLE_INTERNAL') || die(); + +/** + * The mod_hvp instance list viewed event class. + * + * @package mod_hvp + * @copyright @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class attempt_submitted extends \core\event\base +{ + + /** + * @inheritDoc + */ + protected function init() { + $this->data['crud'] = 'u'; + $this->data['edulevel'] = self::LEVEL_PARTICIPATING; + } +} diff --git a/classes/event/course_module_instance_list_viewed.php b/classes/event/course_module_instance_list_viewed.php new file mode 100644 index 0000000..17387fd --- /dev/null +++ b/classes/event/course_module_instance_list_viewed.php @@ -0,0 +1,39 @@ +. + +/** + * The mod_hvp instance list viewed event. + * + * @package mod_hvp + * @copyright @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp\event; + +defined('MOODLE_INTERNAL') || die(); + +/** + * The mod_hvp instance list viewed event class. + * + * @package mod_hvp + * @copyright @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class course_module_instance_list_viewed extends \core\event\course_module_instance_list_viewed +{ + // No code required here as the parent class handles it all. +} diff --git a/classes/event/course_module_viewed.php b/classes/event/course_module_viewed.php new file mode 100644 index 0000000..694b61e --- /dev/null +++ b/classes/event/course_module_viewed.php @@ -0,0 +1,47 @@ +. + +/** + * The mod_hvp course module viewed event. + * + * @package mod_hvp + * @copyright @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp\event; + +defined('MOODLE_INTERNAL') || die(); + +/** + * The mod_hvp course module viewed event class. + * + * @package mod_hvp + * @copyright @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class course_module_viewed extends \core\event\course_module_viewed +{ + + /** + * Set basic properties for the event. + */ + protected function init() { + $this->data['objecttable'] = 'hvp'; + $this->data['crud'] = 'r'; + $this->data['edulevel'] = self::LEVEL_PARTICIPATING; + } +} diff --git a/classes/file_storage.php b/classes/file_storage.php new file mode 100644 index 0000000..4fd2dc1 --- /dev/null +++ b/classes/file_storage.php @@ -0,0 +1,912 @@ +. + +/** + * The mod_hvp file storage + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; +defined('MOODLE_INTERNAL') || die(); +require_once($CFG->dirroot . '/mod/hvp/library/h5p-file-storage.interface.php'); + +/** + * The mod_hvp file storage class. + * + * @package mod_hvp + * @since Moodle 2.7 + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * + * @SuppressWarnings(PHPMD.TooManyPublicMethods) + * @SuppressWarnings(PHPMD.ExcessiveClassComplexity) + */ +class file_storage implements \H5PFileStorage { + + /** + * Store the library folder. + * + * @param array $library + * Library properties + */ + // @codingStandardsIgnoreLine + public function saveLibrary($library) { + // Libraries are stored in a system context. + $context = \context_system::instance(); + $options = array( + 'contextid' => $context->id, + 'component' => 'mod_hvp', + 'filearea' => 'libraries', + 'itemid' => 0, + 'filepath' => '/' . \H5PCore::libraryToFolderName($library) . '/', + ); + + // Remove any old existing library files. + self::deleteFileTree($context->id, $options['filearea'], $options['filepath']); + + // Move library folder. + self::readFileTree($library['uploadDirectory'], $options); + } + + /** + * Store the content folder. + * + * @param string $source + * Path on file system to content directory. + * @param array $content + * Content properties + */ + // @codingStandardsIgnoreLine + public function saveContent($source, $content) { + // Remove any old content. + $this->deleteContent($content); + + // Contents are stored in a course context. + $context = \context_module::instance($content['coursemodule']); + $options = array( + 'contextid' => $context->id, + 'component' => 'mod_hvp', + 'filearea' => 'content', + 'itemid' => $content['id'], + 'filepath' => '/', + ); + + // Move content folder. + self::readFileTree($source, $options); + } + + /** + * Remove content folder. + * + * @param array $content + * Content properties + */ + // @codingStandardsIgnoreLine + public function deleteContent($content) { + $context = \context_module::instance($content['coursemodule']); + self::deleteFileTree($context->id, 'content', '/', $content['id']); + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function cloneContent($id, $newid) { + // Not implemented in Moodle. + } + + /** + * Get path to a new unique tmp folder. + * + * @return string Path + */ + // @codingStandardsIgnoreLine + public function getTmpPath() { + global $CFG; + + return $CFG->tempdir . uniqid('/hvp-'); + } + + /** + * Fetch content folder and save in target directory. + * + * @param int $id + * Content identifier + * @param string $target + * Where the content folder will be saved + */ + // @codingStandardsIgnoreLine + public function exportContent($id, $target) { + $cm = \get_coursemodule_from_instance('hvp', $id); + $context = \context_module::instance($cm->id); + self::exportFileTree($target, $context->id, 'content', '/', $id); + } + + /** + * Fetch library folder and save in target directory. + * + * @param array $library + * Library properties + * @param string $target + * Where the library folder will be saved + */ + // @codingStandardsIgnoreLine + public function exportLibrary($library, $target) { + $folder = \H5PCore::libraryToFolderName($library); + $context = \context_system::instance(); + self::exportFileTree("{$target}/{$folder}", $context->id, 'libraries', "/{$folder}/"); + } + + /** + * Save export in file system + * + * @param string $source + * Path on file system to temporary export file. + * @param string $filename + * Name of export file. + */ + // @codingStandardsIgnoreLine + public function saveExport($source, $filename) { + global $COURSE; + + // Remove old export. + $this->deleteExport($filename); + + // Create record. + $context = \context_course::instance($COURSE->id); + $record = array( + 'contextid' => $context->id, + 'component' => 'mod_hvp', + 'filearea' => 'exports', + 'itemid' => 0, + 'filepath' => '/', + 'filename' => $filename + ); + + // Store new export. + $fs = get_file_storage(); + $fs->create_file_from_pathname($record, $source); + } + + /** + * Get file object for given export file. + * + * @param string $filename + * @return stdClass Moodle file object + */ + // @codingStandardsIgnoreLine + private function getExportFile($filename) { + global $COURSE; + $context = \context_course::instance($COURSE->id); + + // Check if file exists. + $fs = get_file_storage(); + return $fs->get_file($context->id, 'mod_hvp', 'exports', 0, '/', $filename); + } + + /** + * Removes given export file + * + * @param string $filename + */ + // @codingStandardsIgnoreLine + public function deleteExport($filename) { + $file = $this->getExportFile($filename); + if ($file) { + // Remove old export. + $file->delete(); + } + } + + /** + * Check if the given export file exists + * + * @param string $filename + * @return boolean + */ + // @codingStandardsIgnoreLine + public function hasExport($filename) { + return !!$this->getExportFile($filename); + } + + /** + * Will concatenate all JavaScrips and Stylesheets into two files in order + * to improve page performance. + * + * @param array $files + * A set of all the assets required for content to display + * @param string $key + * Hashed key for cached asset + */ + // @codingStandardsIgnoreLine + public function cacheAssets(&$files, $key) { + $context = \context_system::instance(); + $fs = get_file_storage(); + + foreach ($files as $type => $assets) { + if (empty($assets)) { + continue; + } + + $content = ''; + foreach ($assets as $asset) { + // Find location of asset. + $location = array(); + preg_match('/^\/(libraries|development)(.+\/)([^\/]+)$/', $asset->path, $location); + + // Locate file. + $file = $fs->get_file($context->id, 'mod_hvp', $location[1], 0, $location[2], $location[3]); + + // Get file content and concatenate. + if ($type === 'scripts') { + $content .= $file->get_content() . ";\n"; + } else { + // Rewrite relative URLs used inside stylesheets. + $content .= preg_replace_callback( + '/url\([\'"]?([^"\')]+)[\'"]?\)/i', + function ($matches) use ($location) { + if (preg_match("/^(data:|([a-z0-9]+:)?\/)/i", $matches[1]) === 1) { + return $matches[0]; // Not relative, skip. + } + return 'url("../' . $location[1] . $location[2] . $matches[1] . '")'; + }, + $file->get_content()) . "\n"; + } + } + + // Create new file for cached assets. + $ext = ($type === 'scripts' ? 'js' : 'css'); + $fileinfo = array( + 'contextid' => $context->id, + 'component' => 'mod_hvp', + 'filearea' => 'cachedassets', + 'itemid' => 0, + 'filepath' => '/', + 'filename' => "{$key}.{$ext}" + ); + + // Store concatenated content. + $fs->create_file_from_string($fileinfo, $content); + $files[$type] = array((object) array( + 'path' => "/cachedassets/{$key}.{$ext}", + 'version' => '' + )); + } + } + + /** + * Will check if there are cache assets available for content. + * + * @param string $key + * Hashed key for cached asset + * @return array + */ + // @codingStandardsIgnoreLine + public function getCachedAssets($key) { + $context = \context_system::instance(); + $fs = get_file_storage(); + + $files = array(); + + $js = $fs->get_file($context->id, 'mod_hvp', 'cachedassets', 0, '/', "{$key}.js"); + if ($js) { + $files['scripts'] = array((object) array( + 'path' => "/cachedassets/{$key}.js", + 'version' => '' + )); + } + + $css = $fs->get_file($context->id, 'mod_hvp', 'cachedassets', 0, '/', "{$key}.css"); + if ($css) { + $files['styles'] = array((object) array( + 'path' => "/cachedassets/{$key}.css", + 'version' => '' + )); + } + + return empty($files) ? null : $files; + } + + /** + * Remove the aggregated cache files. + * + * @param array $keys + * The hash keys of removed files + */ + // @codingStandardsIgnoreLine + public function deleteCachedAssets($keys) { + $context = \context_system::instance(); + $fs = get_file_storage(); + + foreach ($keys as $hash) { + foreach (array('js', 'css') as $type) { + $cachedasset = $fs->get_file($context->id, 'mod_hvp', 'cachedassets', 0, '/', "{$hash}.{$type}"); + if ($cachedasset) { + $cachedasset->delete(); + } + } + } + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function getContent($filepath) { + // Grab context and file storage. + $context = \context_system::instance(); + $fs = get_file_storage(); + + // Find location of file. + $location = []; + preg_match('/^\/(libraries|development|cachedassets)(.*\/)([^\/]+)$/', $filepath, $location); + + // Locate file. + $file = $fs->get_file($context->id, 'mod_hvp', $location[1], 0, $location[2], $location[3]); + if (!$file) { + throw new \file_serving_exception( + 'Could not retrieve the requested file, check your file permissions.' + ); + } + + // Return content. + return $file->get_content(); + } + + /** + * Save files uploaded through the editor. + * + * @param \H5peditorFile $file + * @param int $contentid + * @param \stdClass $contextid Course Context ID + * + * @return int + */ + // @codingStandardsIgnoreLine + public function saveFile($file, $contentid, $contextid = null) { + global $CFG; + + if ($contentid !== 0) { + // Grab cm context. + $cm = \get_coursemodule_from_instance('hvp', $contentid); + $context = \context_module::instance($cm->id); + $contextid = $context->id; + } else if ($contextid === null) { + // Check for context id in params. + $contextid = optional_param('contextId', null, PARAM_INT); + $context = \context::instance_by_id($contextid); + } + + if (!$context) { + \H5PCore::ajaxError(get_string('invalidcontext', 'error')); + return; + } + + $maxsize = get_max_upload_file_size($CFG->maxbytes); + // Check size of each uploaded file and scan for viruses. + foreach ($_FILES as $uploadedfile) { + $filename = clean_param($uploadedfile['name'], PARAM_FILE); + + if (!has_capability('moodle/course:ignorefilesizelimits', $context)) { + if ($uploadedfile['size'] > $maxsize) { + \H5PCore::ajaxError(get_string('maxbytesfile', 'error', ['file' => $filename, 'size' => display_size($maxsize)])); + return; + } + } + \core\antivirus\manager::scan_file($uploadedfile['tmp_name'], $filename, true); + } + + // Files not yet related to any activities are stored in a course context + // These are temporary files and should not be part of backups. + + $record = array( + 'contextid' => $contextid, + 'component' => 'mod_hvp', + 'filearea' => $contentid === 0 ? 'editor' : 'content', + 'itemid' => $contentid, + 'filepath' => '/' . $file->getType() . 's/', + 'filename' => $file->getName() + ); + $fs = get_file_storage(); + $storedfile = $fs->create_file_from_pathname($record, $_FILES['file']['tmp_name']); + + return $storedfile->get_id(); + } + + /** + * Copy a file from another content or editor tmp dir. + * Used when copy pasting content in H5P. + * + * @param string $file path + name + * @param string|int $fromid Content ID or 'editor' string + * @param stdClass $tocontent Target Content + */ + // @codingStandardsIgnoreLine + public function cloneContentFile($file, $fromid, $tocontent) { + + // Determine source file area and item id. + if ($fromid === 'editor') { + $sourcefilearea = 'editor'; + if (empty($tocontent->instance)) { + $sourceitemid = \context_course::instance($tocontent->course); + } else { + $sourceitemid = \context_module::instance($tocontent->coursemodule); + } + } else { + $sourcefilearea = 'content'; + $sourceitemid = $fromid; + }; + + // Check to see if source exist. + $sourcefile = $this->getFile($sourcefilearea, $sourceitemid, $file); + if ($sourcefile === false) { + return; // Nothing to copy from. + } + + // Check to make sure source doesn't exist already. + if ($this->getFile('content', $tocontent, $file) !== false) { + return; // File exists, no need to copy. + } + + // Grab context for CM. + $context = \context_module::instance($tocontent->coursemodule); + + // Create new file record. + $record = [ + 'contextid' => $context->id, + 'component' => 'mod_hvp', + 'filearea' => 'content', + 'itemid' => $tocontent->id, + 'filepath' => $this->getFilepath($file), + 'filename' => $this->getFilename($file), + ]; + $fs = get_file_storage(); + $fs->create_file_from_storedfile($record, $sourcefile); + } + + /** + * Checks to see if content has the given file. + * Used when saving content. + * + * @param string $file path + name + * @param stdClass $content + * @return string|int File ID or null if not found + */ + // @codingStandardsIgnoreLine + public function getContentFile($file, $content) { + $file = $this->getFile('content', $content, $file); + return ($file === false ? null : $file->get_id()); + } + + /** + * Remove content files that are no longer used. + * Used when saving content. + * + * @param string $file path + name + * @param stdClass $content + */ + // @codingStandardsIgnoreLine + public function removeContentFile($file, $content) { + $file = $this->getFile('content', $content, $file); + if ($file !== false) { + $file->delete(); + } + } + + /** + * Copies files from tmp folder to Moodle storage. + * + * @param string $source + * Path to source directory + * @param array $options + * For Moodle's file record + * @throws \Exception Unable to copy + */ + // @codingStandardsIgnoreLine + private static function readFileTree($source, $options) { + $dir = opendir($source); + if ($dir === false) { + trigger_error('Unable to open directory ' . $source, E_USER_WARNING); + throw new \Exception('unabletocopy'); + } + + while (false !== ($file = readdir($dir))) { + if (($file != '.') && ($file != '..') && $file != '.git' && $file != '.gitignore') { + if (is_dir($source . DIRECTORY_SEPARATOR . $file)) { + $suboptions = $options; + $suboptions['filepath'] .= $file . '/'; + self::readFileTree($source . '/' . $file, $suboptions); + } else { + $record = $options; + $record['filename'] = $file; + $fs = get_file_storage(); + $fs->create_file_from_pathname($record, $source . '/' . $file); + } + } + } + closedir($dir); + } + + /** + * Copies files from Moodle storage to temporary folder. + * + * @param string $target + * Path to temporary folder + * @param int $contextid + * Moodle context where the files are found + * @param string $filearea + * Moodle file area + * @param string $filepath + * Moodle file path + * @param int $itemid + * Optional Moodle item ID + */ + // @codingStandardsIgnoreLine + private static function exportFileTree($target, $contextid, $filearea, $filepath, $itemid = 0) { + // Make sure target folder exists. + if (!file_exists($target)) { + mkdir($target, 0777, true); + } + + // Read source files. + $fs = get_file_storage(); + $files = $fs->get_directory_files($contextid, 'mod_hvp', $filearea, $itemid, $filepath, true); + + foreach ($files as $file) { + // Correct target path for file. + $path = $target . str_replace($filepath, '/', $file->get_filepath()); + + if ($file->is_directory()) { + // Create directory. + $path = rtrim($path, '/'); + if (!file_exists($path)) { + mkdir($path, 0777, true); + } + } else { + // Copy file. + $file->copy_content_to($path . $file->get_filename()); + } + } + } + + /** + * Recursive removal of given filepath. + * + * @param int $contextid + * @param string $filearea + * @param string $filepath + * @param int $itemid + */ + // @codingStandardsIgnoreLine + private static function deleteFileTree($contextid, $filearea, $filepath, $itemid = 0) { + $fs = get_file_storage(); + if ($filepath === '/') { + // Remove complete file area. + $fs->delete_area_files($contextid, 'mod_hvp', $filearea, $itemid); + return; + } + + // Look up files and remove. + $files = $fs->get_directory_files($contextid, 'mod_hvp', $filearea, $itemid, $filepath, true); + foreach ($files as $file) { + $file->delete(); + } + + // Remove root dir. + $file = $fs->get_file($contextid, 'mod_hvp', $filearea, $itemid, $filepath, '.'); + if ($file) { + $file->delete(); + } + } + + /** + * Help make it easy to load content files. + * + * @param string $filearea + * @param int|object $itemid + * @param string $file path + name + * + * @return \stored_file|bool + */ + // @codingStandardsIgnoreLine + private function getFile($filearea, $itemid, $file) { + if ($filearea === 'editor') { + // Itemid is actually cm or course context. + $context = $itemid; + $itemid = 0; + } else if (is_object($itemid)) { + // Grab CM context from item. + $context = \context_module::instance($itemid->coursemodule); + $itemid = $itemid->id; + } else { + // Use item ID to find CM context. + $cm = \get_coursemodule_from_instance('hvp', $itemid); + $context = \context_module::instance($cm->id); + } + + // Load file. + $fs = get_file_storage(); + return $fs->get_file($context->id, 'mod_hvp', $filearea, $itemid, $this->getFilepath($file), $this->getFilename($file)); + } + + /** + * Extract Moodle compatible filepath + * + * @param string $file + * @return string With slashes + */ + // @codingStandardsIgnoreLine + private function getFilepath($file) { + return '/' . dirname($file) . '/'; + } + + /** + * Extract filename from filepath string + * + * @param string $file + * @return string Without slashes + */ + // @codingStandardsIgnoreLine + private function getFilename($file) { + return basename($file); + } + + /** + * Checks if a file exists + * + * @method fileExists + * @param string $filearea [description] + * @param string $filepath [description] + * @param string $filename [description] + * @return boolean + */ + // @codingStandardsIgnoreLine + public static function fileExists($contextid, $filearea, $filepath, $filename) { + // Check if file exists. + $fs = get_file_storage(); + return ($fs->get_file($contextid, 'mod_hvp', $filearea, 0, $filepath, $filename) !== false); + } + + /** + * Check if server setup has write permission to + * the required folders + * + * @return bool true if server has the proper write access + */ + // @codingStandardsIgnoreLine + public function hasWriteAccess() { + global $CFG; + + if (!is_dir($CFG->dataroot)) { + trigger_error('Path is not a directory ' . $CFG->dataroot, E_USER_WARNING); + return false; + } + + if (!is_writable($CFG->dataroot)) { + trigger_error('Unable to write to ' . $CFG->dataroot . ' – check directory permissions –', E_USER_WARNING); + return false; + } + + return true; + } + + /** + * Copy a content from one directory to another. Defaults to cloning + * content from the current temporary upload folder to the editor path. + * + * @param string $source path to source directory + * @param string $contentid path of target directory. Defaults to editor path + * + * @return object|null Object containing h5p json and content json data + */ + // @codingStandardsIgnoreLine + public function moveContentDirectory($source, $contentid = null) { + if ($source === null) { + return null; + } + + // Default to 0 (editor). + if (!isset($contentid)) { + $contentid = 0; + } + + // Find content context. + if ($contentid > 0) { + // Grab cm context. + $cm = \get_coursemodule_from_instance('hvp', $contentid); + $context = \context_module::instance($cm->id); + $contextid = $context->id; + } + + // Get context from parameters. + if (!isset($contextid)) { + $contextid = required_param('contextId', PARAM_INT); + } + + // Get h5p and content json. + $contentsource = $source . DIRECTORY_SEPARATOR . 'content'; + + // Move all temporary content files to editor. + $contentfiles = array_diff(scandir($contentsource), array('.', '..', 'content.json')); + foreach ($contentfiles as $file) { + if (is_dir("{$contentsource}/{$file}")) { + self::moveFileTree("{$contentsource}/{$file}", $contextid, $contentid); + } else { + self::moveFile("{$contentsource}/{$file}", $contextid, $contentid); + } + } + + // TODO: Return list of all files so they can be marked as temporary. JI-366. + } + + /** + * Move a single file to editor + * + * @param string $sourcefile Path to source fil + * @param int $contextid Id of context + * @param int $contentid Id of content, 0 if editor + */ + // @codingStandardsIgnoreLine + private static function moveFile($sourcefile, $contextid, $contentid) { + $fs = get_file_storage(); + + $pathparts = pathinfo($sourcefile); + $filename = $pathparts['basename']; + $filepath = $pathparts['dirname']; + $foldername = basename($filepath); + + if ($contentid > 0) { + // Create file record for content. + $record = array( + 'contextid' => $contextid, + 'component' => 'mod_hvp', + 'filearea' => $contentid > 0 ? 'content' : 'editor', + 'itemid' => $contentid, + 'filepath' => '/' . $foldername . '/', + 'filename' => $filename + ); + } else { + // Create file record for editor. + $record = array( + 'contextid' => $contextid, + 'component' => 'mod_hvp', + 'filearea' => 'editor', + 'itemid' => 0, + 'filepath' => '/' . $foldername . '/', + 'filename' => $filename + ); + } + + $sourcedata = file_get_contents($sourcefile); + + // Check if file already exists. + $fileexists = $fs->file_exists($record['contextid'], 'mod_hvp', + $record['filearea'], $record['itemid'], $record['filepath'], + $record['filename'] + ); + + if ($fileexists) { + // Delete it to make sure that it is replaced with correct content. + $file = $fs->get_file($record['contextid'], 'mod_hvp', + $record['filearea'], $record['itemid'], $record['filepath'], + $record['filename'] + ); + if ($file) { + $file->delete(); + } + } + + $fs->create_file_from_string($record, $sourcedata); + } + + /** + * Move a complete file tree to the editor + * + * @param string $sourcefiletree Path of file tree that should be moved + * @param int $contextid Id of context + * @param int $contentid Id of content, 0 for editor + * + * @throws \Exception + */ + // @codingStandardsIgnoreLine + private static function moveFileTree($sourcefiletree, $contextid, $contentid) { + $dir = opendir($sourcefiletree); + if ($dir === false) { + trigger_error('Unable to open directory ' . $sourcefiletree, E_USER_WARNING); + throw new \Exception('unabletocopy'); + } + + while (false !== ($file = readdir($dir))) { + if (($file != '.') && ($file != '..') && $file != '.git' && $file != '.gitignore') { + if (is_dir("{$sourcefiletree}/{$file}")) { + self::moveFileTree("{$sourcefiletree}/{$file}", $contextid, $contentid); + } else { + self::moveFile("{$sourcefiletree}/{$file}", $contextid, $contentid); + } + } + } + closedir($dir); + } + + /** + * Check if the library has a presave.js in the root folder + * + * @param string $libraryname + * @param string $developmentpath + * + * @return bool + */ + // @codingStandardsIgnoreLine + public function hasPresave($libraryname, $developmentpath = null) { + // TODO: Implement. + return false; + } + + /** + * Check if upgrades script exist for library. + * + * @param string $machineName + * @param int $majorVersion + * @param int $minorVersion + * @return string Relative path + */ + // @codingStandardsIgnoreLine + public function getUpgradeScript($machinename, $majorversion, $minorversion) { + $context = \context_system::instance(); + $fs = get_file_storage(); + $area = 'libraries'; + $path = "/{$machinename}-{$majorversion}.{$minorversion}/"; + $file = 'upgrades.js'; + if ($fs->get_file($context->id, 'mod_hvp', $area, 0, $path, $file)) { + return "/{$area}{$path}{$file}"; + } else { + return null; + } + } + + /** + * Store the given stream into the given file. + * + * @param string $path + * @param string $file + * @param resource $stream + * + * @return bool + */ + // @codingStandardsIgnoreLine + public function saveFileFromZip($path, $file, $stream) { + $filepath = $path . '/' . $file; + + // Make sure the directory exists first. + $matches = array(); + preg_match('/(.+)\/[^\/]*$/', $filepath, $matches); + // Recursively make directories. + if (!file_exists($matches[1])) { + mkdir($matches[1], 0777, true); + } + + // Store in local storage folder. + return file_put_contents($filepath, $stream); + } + + // @codingStandardIgnoreLine + public function deleteLibrary($library) { + // TODO: Implement deleteLibrary() method. + } +} diff --git a/classes/framework.php b/classes/framework.php new file mode 100644 index 0000000..fc7ab69 --- /dev/null +++ b/classes/framework.php @@ -0,0 +1,1920 @@ +. + +/** + * \mod_hvp\framework class + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; + +defined('MOODLE_INTERNAL') || die(); + +global $CFG; +require_once(__DIR__ . '/../autoloader.php'); +require_once($CFG->libdir . '/filelib.php'); +require_once($CFG->libdir . '/adminlib.php'); + +/** + * Moodle's implementation of the H5P framework interface. + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * + * @SuppressWarnings(PHPMD) + */ +class framework implements \H5PFrameworkInterface { + + /** + * Get type of hvp instance + * + * @param string $type Type of hvp instance to get + * @return \H5PContentValidator|\H5PCore|\H5PStorage|\H5PValidator|\mod_hvp\framework|\H5peditor + */ + public static function instance($type = null) { + global $CFG; + static $interface, $core, $editor, $editorinterface, $editorajaxinterface; + + if (!isset($interface)) { + $interface = new \mod_hvp\framework(); + + // Support alternate file storage class defined in $CFG. + if (!empty($CFG->mod_hvp_file_storage_class)) { + $fsclass = $CFG->mod_hvp_file_storage_class; + } else { + $fsclass = '\mod_hvp\file_storage'; + } + + $fs = new $fsclass(); + + $context = \context_system::instance(); + $root = view_assets::getsiteroot(); + $url = "{$root}/pluginfile.php/{$context->id}/mod_hvp"; + + $language = self::get_language(); + + $export = !(isset($CFG->mod_hvp_export) && $CFG->mod_hvp_export === '0'); + + $core = new \H5PCore($interface, $fs, $url, $language, $export); + $core->aggregateAssets = !(isset($CFG->mod_hvp_aggregate_assets) && $CFG->mod_hvp_aggregate_assets === '0'); + } + + switch ($type) { + case 'validator': + return new \H5PValidator($interface, $core); + case 'storage': + return new \H5PStorage($interface, $core); + case 'contentvalidator': + return new \H5PContentValidator($interface, $core); + case 'interface': + return $interface; + case 'editor': + if (empty($editorinterface)) { + $editorinterface = new \mod_hvp\editor_framework(); + } + + if (empty($editorajaxinterface)) { + $editorajaxinterface = new editor_ajax(); + } + + if (empty($editor)) { + $editor = new \H5peditor($core, $editorinterface, $editorajaxinterface); + } + return $editor; + case 'core': + default: + return $core; + } + } + + /** + * Check if the current user has editor access, if not then return the + * given error message. + * + * @param string $error + * @return boolean + */ + public static function has_editor_access($error) { + $context = \context::instance_by_id(required_param('contextId', PARAM_RAW)); + $cap = ($context->contextlevel === CONTEXT_COURSE ? 'addinstance' : 'manage'); + + if (!has_capability("mod/hvp:$cap", $context)) { + \H5PCore::ajaxError(get_string($error, 'hvp')); + http_response_code(403); + return false; + } + + return true; + } + + /** + * Get current H5P language code. + * + * @return string Language Code + */ + public static function get_language() { + static $map; + + if (empty($map)) { + // Create mapping for "converting" language codes. + $map = array( + 'no' => 'nb' + ); + } + + // Get current language in Moodle. + $language = str_replace('_', '-', strtolower(\current_language())); + + // Try to map. + return isset($map[$language]) ? $map[$language] : $language; + } + + /** + * Implements getPlatformInfo + */ + // @codingStandardsIgnoreLine + public function getPlatformInfo() { + global $CFG; + + return array( + 'name' => 'Moodle', + 'version' => $CFG->version, + 'h5pVersion' => get_component_version('mod_hvp'), + ); + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function fetchExternalData($url, $data = null, $blocking = true, $stream = null, $alldata = false, $headers = array(), $files = array(), $method = 'POST') { + global $CFG; + + if (!empty($files)) { + $curldata = array(); + foreach ($data as $key => $value) { + if (empty($value)) { + continue; // Skip empty values. + } + if (is_array($value)) { + foreach ($value as $i => $subvalue) { + $curldata["{$key}[{$i}]"] = $subvalue; + } + } else { + $curldata[$key] = $value; + } + } + + foreach ($files as $name => $file) { + if ($file === null) { + continue; + } else if (is_array($file['name'])) { + // Array of files uploaded (multiple). + for ($i = 0; $i < count($file['name']); $i ++) { + $curldata["{$name}[{$i}]"] = new \CurlFile($file['tmp_name'][$i], $file['type'][$i], $file['name'][$i]); + } + } else { + // Single file. + $curldata[$name] = new \CurlFile($file['tmp_name'], $file['type'], $file['name']); + } + } + } else if (!empty($data)) { + // Application/x-www-form-urlencoded. + $curldata = format_postdata_for_curlcall($data); + } + + $options = array( + 'CURLOPT_SSL_VERIFYPEER' => true, + 'CURLOPT_CONNECTTIMEOUT' => 20, + 'CURLOPT_FOLLOWLOCATION' => 1, + 'CURLOPT_MAXREDIRS' => 5, + 'CURLOPT_RETURNTRANSFER' => true, + 'CURLOPT_NOBODY' => false, + 'CURLOPT_TIMEOUT' => 300, + ); + + if ($stream !== null) { + // Download file. + @set_time_limit(0); + + // Generate local tmp file path. + $localfolder = make_temp_directory(uniqid('hvp-')); + $localpath = $localfolder . '.h5p'; + + // Add folder and file paths to H5P Core. + $interface = self::instance('interface'); + $interface->getUploadedH5pFolderPath($localfolder); + $interface->getUploadedH5pPath($localpath); + + $stream = fopen($localpath, 'w'); + $options['CURLOPT_FILE'] = $stream; + } + + $curl = new curl(); + + // Massage headers to work with curl. + foreach ($headers as $key => $value) { + $curl->setHeader(is_numeric($key) ? $value : "$key: $value"); + } + + if (empty($data) || $method === 'GET') { + $response = $curl->get($url, array(), $options); + } else if ($method === 'POST') { + $response = $curl->post($url, $curldata, $options); + } else if ($method === 'PUT') { + $response = $curl->put($url, $curldata, $options); + } + + if ($stream !== null) { + fclose($stream); + @chmod($localpath, $CFG->filepermissions); + } + + $errorno = $curl->get_errno(); + // Error handling. + if ($errorno) { + if ($alldata) { + $response = null; + } else { + $this->setErrorMessage($response, 'failed-fetching-external-data'); + + return false; + } + } + + if ($alldata) { + $info = $curl->get_info(); + + return [ + 'status' => intval($info['http_code']), + 'data' => empty($response) ? null : $response, + 'headers' => $curl->get_raw_response(), + ]; + } else { + return $response; + } + } + + /** + * Implements setLibraryTutorialUrl + * + * Set the tutorial URL for a library. All versions of the library is set + * + * @param string $libraryname + * @param string $url + */ + // @codingStandardsIgnoreLine + public function setLibraryTutorialUrl($libraryname, $url) { + global $DB; + + $DB->execute("UPDATE {hvp_libraries} SET tutorial_url = ? WHERE machine_name = ?", array($url, $libraryname)); + } + + /** + * Implements setErrorMessage + * + * @param string $message translated error message + * @param string $code + */ + // @codingStandardsIgnoreLine + public function setErrorMessage($message, $code = null) { + if ($message !== null) { + self::messages('error', $message, $code); + } + } + + /** + * Implements setInfoMessage + */ + // @codingStandardsIgnoreLine + public function setInfoMessage($message) { + if ($message !== null) { + self::messages('info', $message); + } + } + + /** + * Store messages until they can be printed to the current user + * + * @param string $type Type of messages, e.g. 'info' or 'error' + * @param string $newmessage Optional + * @param string $code + * @return array Array of stored messages + */ + public static function messages($type, $newmessage = null, $code = null) { + static $m = 'mod_hvp_messages'; + + if ($newmessage === null) { + // Return and reset messages. + $messages = isset($_SESSION[$m][$type]) ? $_SESSION[$m][$type] : array(); + unset($_SESSION[$m][$type]); + if (empty($_SESSION[$m])) { + unset($_SESSION[$m]); + } + return $messages; + } + + // We expect to get out an array of strings when getting info + // and an array of objects when getting errors for consistency across platforms. + // This implementation should be improved for consistency across the data type returned here. + if ($type === 'error') { + $_SESSION[$m][$type][] = (object)array( + 'code' => $code, + 'message' => $newmessage + ); + } else { + $_SESSION[$m][$type][] = $newmessage; + } + } + + /** + * Simple print of given messages. + * + * @param string $type One of error|info + * @param array $messages + */ + // @codingStandardsIgnoreLine + public static function printMessages($type, $messages) { + global $OUTPUT; + foreach ($messages as $message) { + $out = $type === 'error' ? $message->message : $message; + print $OUTPUT->notification($out, ($type === 'error' ? 'notifyproblem' : 'notifymessage')); + } + } + + /** + * Implements getMessages + */ + // @codingStandardsIgnoreLine + public function getMessages($type) { + return self::messages($type); + } + + /** + * Implements t + */ + public function t($message, $replacements = array()) { + static $translationsmap; + + if (empty($translationsmap)) { + // Create mapping. + // @codingStandardsIgnoreStart + $translationsmap = [ + 'Your PHP version does not support ZipArchive.' => 'noziparchive', + 'The file you uploaded is not a valid HTML5 Package (It does not have the .h5p file extension)' => 'noextension', + 'The file you uploaded is not a valid HTML5 Package (We are unable to unzip it)' => 'nounzip', + 'Could not parse the main h5p.json file' => 'noparse', + 'The main h5p.json file is not valid' => 'nojson', + 'Invalid content folder' => 'invalidcontentfolder', + 'Could not find or parse the content.json file' => 'nocontent', + 'Library directory name must match machineName or machineName-majorVersion.minorVersion (from library.json). (Directory: %directoryName , machineName: %machineName, majorVersion: %majorVersion, minorVersion: %minorVersion)' => 'librarydirectoryerror', + 'A valid content folder is missing' => 'missingcontentfolder', + 'A valid main h5p.json file is missing' => 'invalidmainjson', + 'Missing required library @library' => 'missinglibrary', + "Note that the libraries may exist in the file you uploaded, but you're not allowed to upload new libraries. Contact the site administrator about this." => 'missinguploadpermissions', + 'Invalid library name: %name' => 'invalidlibraryname', + 'Could not find library.json file with valid json format for library %name' => 'missinglibraryjson', + 'Invalid semantics.json file has been included in the library %name' => 'invalidsemanticsjson', + 'Invalid language file %file in library %library' => 'invalidlanguagefile', + 'Invalid language file %languageFile has been included in the library %name' => 'invalidlanguagefile2', + 'The file "%file" is missing from library: "%name"' => 'missinglibraryfile', + 'The system was unable to install the %component component from the package, it requires a newer version of the H5P plugin. This site is currently running version %current, whereas the required version is %required or higher. You should consider upgrading and then try again.' => 'missingcoreversion', + "Invalid data provided for %property in %library. Boolean expected." => 'invalidlibrarydataboolean', + "Invalid data provided for %property in %library" => 'invalidlibrarydata', + "Can't read the property %property in %library" => 'invalidlibraryproperty', + 'The required property %property is missing from %library' => 'missinglibraryproperty', + 'Illegal option %option in %library' => 'invalidlibraryoption', + 'Added %new new H5P library and updated %old old one.' => 'addedandupdatedss', + 'Added %new new H5P library and updated %old old ones.' => 'addedandupdatedsp', + 'Added %new new H5P libraries and updated %old old one.' => 'addedandupdatedps', + 'Added %new new H5P libraries and updated %old old ones.' => 'addedandupdatedpp', + 'Added %new new H5P library.' => 'addednewlibrary', + 'Added %new new H5P libraries.' => 'addednewlibraries', + 'Updated %old H5P library.' => 'updatedlibrary', + 'Updated %old H5P libraries.' => 'updatedlibraries', + 'Missing dependency @dep required by @lib.' => 'missingdependency', + 'Provided string is not valid according to regexp in semantics. (value: \"%value\", regexp: \"%regexp\")' => 'invalidstring', + 'File "%filename" not allowed. Only files with the following extensions are allowed: %files-allowed.' => 'invalidfile', + 'Invalid selected option in multi-select.' => 'invalidmultiselectoption', + 'Invalid selected option in select.' => 'invalidselectoption', + 'H5P internal error: unknown content type "@type" in semantics. Removing content!' => 'invalidsemanticstype', + 'Copyright information' => 'copyrightinfo', + 'Title' => 'title', + 'Author' => 'author', + 'Year(s)' => 'years', + 'Year' => 'year', + 'Source' => 'source', + 'License' => 'license', + 'Undisclosed' => 'undisclosed', + 'Attribution 4.0' => 'attribution', + 'Attribution-ShareAlike 4.0' => 'attributionsa', + 'Attribution-NoDerivs 4.0' => 'attributionnd', + 'Attribution-NonCommercial 4.0' => 'attributionnc', + 'Attribution-NonCommercial-ShareAlike 4.0' => 'attributionncsa', + 'Attribution-NonCommercial-NoDerivs 4.0' => 'attributionncnd', + 'Attribution' => 'noversionattribution', + 'Attribution-ShareAlike' => 'noversionattributionsa', + 'Attribution-NoDerivs' => 'noversionattributionnd', + 'Attribution-NonCommercial' => 'noversionattributionnc', + 'Attribution-NonCommercial-ShareAlike' => 'noversionattributionncsa', + 'Attribution-NonCommercial-NoDerivs' => 'noversionattributionncnd', + 'General Public License v3' => 'gpl', + 'Public Domain' => 'pd', + 'Public Domain Dedication and Licence' => 'pddl', + 'Public Domain Mark' => 'pdm', + 'Public Domain Mark (PDM)' => 'pdm', + 'Copyright' => 'copyrightstring', + 'Unable to create directory.' => 'unabletocreatedir', + 'Unable to get field type.' => 'unabletogetfieldtype', + "File type isn't allowed." => 'filetypenotallowed', + 'Invalid field type.' => 'invalidfieldtype', + 'Invalid image file format. Use jpg, png or gif.' => 'invalidimageformat', + 'File is not an image.' => 'filenotimage', + 'Invalid audio file format. Use mp3 or wav.' => 'invalidaudioformat', + 'Invalid video file format. Use mp4 or webm.' => 'invalidvideoformat', + 'Could not save file.' => 'couldnotsave', + 'Could not copy file.' => 'couldnotcopy', + 'The mbstring PHP extension is not loaded. H5P need this to function properly' => 'missingmbstring', + 'The version of the H5P library %machineName used in this content is not valid. Content contains %contentLibrary, but it should be %semanticsLibrary.' => 'wrongversion', + 'The H5P library %library used in the content is not valid' => 'invalidlibrarynamed', + 'Your PHP version is outdated. H5P requires version 5.2 to function properly. Version 5.6 or later is recommended.' => 'oldphpversion', + 'Your PHP max upload size is quite small. With your current setup, you may not upload files larger than %number MB. This might be a problem when trying to upload H5Ps, images and videos. Please consider to increase it to more than 5MB.' => 'maxuploadsizetoosmall', + 'Your PHP max post size is quite small. With your current setup, you may not upload files larger than %number MB. This might be a problem when trying to upload H5Ps, images and videos. Please consider to increase it to more than 5MB' => 'maxpostsizetoosmall', + 'Your server does not have SSL enabled. SSL should be enabled to ensure a secure connection with the H5P hub.' => 'sslnotenabled', + 'H5P hub communication has been disabled because one or more H5P requirements failed.' => 'hubcommunicationdisabled', + 'When you have revised your server setup you may re-enable H5P hub communication in H5P Settings.' => 'reviseserversetupandretry', + 'A problem with the server write access was detected. Please make sure that your server can write to your data folder.' => 'nowriteaccess', + 'Your PHP max upload size is bigger than your max post size. This is known to cause issues in some installations.' => 'uploadsizelargerthanpostsize', + 'Library cache was successfully updated!' => 'ctcachesuccess', + 'No content types were received from the H5P Hub. Please try again later.' => 'ctcachenolibraries', + "Couldn't communicate with the H5P Hub. Please try again later." => 'ctcacheconnectionfailed', + 'The hub is disabled. You can re-enable it in the H5P settings.' => 'hubisdisabled', + 'File not found on server. Check file upload settings.' => 'filenotfoundonserver', + 'Invalid security token.' => 'invalidtoken', + 'No content type was specified.' => 'nocontenttype', + 'The chosen content type is invalid.' => 'invalidcontenttype', + 'You do not have permission to install content types. Contact the administrator of your site.' => 'installdenied', + 'You do not have permission to install content types.' => 'installdenied', + 'Validating h5p package failed.' => 'validatingh5pfailed', + 'Failed to download the requested H5P.' => 'failedtodownloadh5p', + 'A post message is required to access the given endpoint' => 'postmessagerequired', + 'Could not get posted H5P.' => 'invalidh5ppost', + 'Site could not be registered with the hub. Please contact your site administrator.' => 'sitecouldnotberegistered', + 'The H5P Hub has been disabled until this problem can be resolved. You may still upload libraries through the "H5P Libraries" page.' => 'hubisdisableduploadlibraries', + 'Your site was successfully registered with the H5P Hub.' => 'successfullyregisteredwithhub', + 'You have been provided a unique key that identifies you with the Hub when receiving new updates. The key is available for viewing in the "H5P Settings" page.' => 'sitekeyregistered', + 'Fullscreen' => 'fullscreen', + 'Disable fullscreen' => 'disablefullscreen', + 'Download' => 'download', + 'Rights of use' => 'copyright', + 'Embed' => 'embed', + 'Size' => 'size', + 'Show advanced' => 'showadvanced', + 'Hide advanced' => 'hideadvanced', + 'Include this script on your website if you want dynamic sizing of the embedded content:' => 'resizescript', + 'Close' => 'close', + 'Thumbnail' => 'thumbnail', + 'No copyright information available for this content.' => 'nocopyright', + 'Download this content as a H5P file.' => 'downloadtitle', + 'View copyright information for this content.' => 'copyrighttitle', + 'View the embed code for this content.' => 'embedtitle', + 'Visit H5P.org to check out more cool content.' => 'h5ptitle', + 'This content has changed since you last used it.' => 'contentchanged', + "You'll be starting over." => 'startingover', + 'by' => 'by', + 'Show more' => 'showmore', + 'Show less' => 'showless', + 'Sublevel' => 'sublevel', + 'Confirm action' => 'confirmdialogheader', + 'Please confirm that you wish to proceed. This action is not reversible.' => 'confirmdialogbody', + 'Cancel' => 'cancellabel', + 'Confirm' => 'confirmlabel', + '4.0 International' => 'licenseCC40', + '3.0 Unported' => 'licenseCC30', + '2.5 Generic' => 'licenseCC25', + '2.0 Generic' => 'licenseCC20', + '1.0 Generic' => 'licenseCC10', + 'General Public License' => 'licenseGPL', + 'Version 3' => 'licenseV3', + 'Version 2' => 'licenseV2', + 'Version 1' => 'licenseV1', + 'CC0 1.0 Universal (CC0 1.0) Public Domain Dedication' => 'licenseCC010', + 'CC0 1.0 Universal' => 'licenseCC010U', + 'License Version' => 'licenseversion', + 'Creative Commons' => 'creativecommons', + 'Attribution' => 'ccattribution', + 'Attribution (CC BY)' => 'ccattribution', + 'Attribution-ShareAlike' => 'ccattributionsa', + 'Attribution-ShareAlike (CC BY-SA)' => 'ccattributionsa', + 'Attribution-NoDerivs' => 'ccattributionnd', + 'Attribution-NoDerivs (CC BY-ND)' => 'ccattributionnd', + 'Attribution-NonCommercial' => 'ccattributionnc', + 'Attribution-NonCommercial (CC BY-NC)' => 'ccattributionnc', + 'Attribution-NonCommercial-ShareAlike' => 'ccattributionncsa', + 'Attribution-NonCommercial-ShareAlike (CC BY-NC-SA)' => 'ccattributionncsa', + 'Attribution-NonCommercial-NoDerivs' => 'ccattributionncnd', + 'Attribution-NonCommercial-NoDerivs (CC BY-NC-ND)' => 'ccattributionncnd', + 'Public Domain Dedication' => 'ccpdd', + 'Public Domain Dedication (CC0)' => 'ccpdd', + 'Years (from)' => 'yearsfrom', + 'Years (to)' => 'yearsto', + "Author's name" => 'authorname', + "Author's role" => 'authorrole', + 'Editor' => 'editor', + 'Licensee' => 'licensee', + 'Originator' => 'originator', + 'Any additional information about the license' => 'additionallicenseinfo', + 'License Extras' => 'licenseextras', + 'Changelog' => 'changelog', + 'Content Type' => 'contenttype', + 'Question' => 'question', + 'Date' => 'date', + 'Changed by' => 'changedby', + 'Description of change' => 'changedescription', + 'Photo cropped, text changed, etc.' => 'changeplaceholder', + 'Additional Information' => 'additionalinfo', + 'Author comments' => 'authorcomments', + 'Comments for the editor of the content (This text will not be published as a part of copyright info)' => 'authorcommentsdescription', + 'Reuse' => 'reuse', + 'Reuse Content' => 'reusecontent', + 'Reuse this content.' => 'reusedescription', + 'Content is copied to the clipboard' => 'contentcopied', + 'Connection lost. Results will be stored and sent when you regain connection.' => 'connectionlost', + 'Connection reestablished.' => 'connectionreestablished', + 'Attempting to submit stored results.' => 'resubmitscores', + 'Your connection to the server was lost' => 'offlinedialogheader', + 'We were unable to send information about your completion of this task. Please check your internet connection.' => 'offlinedialogbody', + 'Retrying in :num....' => 'offlinedialogretrymessage', + 'Retry now' => 'offlinedialogretrybuttonlabel', + 'Successfully submitted results.' => 'offlinesuccessfulsubmit', + 'Sharing :title' => 'maintitle', + 'Edit info for :title' => 'editinfotitle', + 'Back' => 'back', + 'Next' => 'next', + 'Review info' => 'reviewinfo', + 'Share' => 'share', + 'Save changes' => 'savechanges', + 'Register on the H5P Hub' => 'registeronhub', + 'Required Info' => 'requiredinfo', + 'Optional Info' => 'optionalinfo', + 'Review & Share' => 'reviewandshare', + 'Review & Save' => 'reviewandsave', + 'Shared' => 'shared', + 'Step :step of :total' => 'currentstep', + 'All content details can be edited after sharing' => 'sharingnote', + 'Select a license for your content' => 'licensedescription', + 'Select a license version' => 'licenseversiondescription', + 'Disciplines' => 'disciplinelabel', + 'You can select multiple disciplines' => 'disciplinedescription', + 'You can select up to :numDisciplines disciplines' => 'disciplinelimitreachedmessage', + 'Type to search for disciplines' =>'searchplaceholder', + 'in' => 'in', + 'Dropdown button' => 'dropdownbutton', + 'Remove :chip from the list' => 'removechip', + 'Add keywords' => 'keywordsplaceholder', + 'Keywords' => 'keywords', + 'You can add multiple keywords separated by commas. Press "Enter" or "Add" to confirm keywords' => 'keywordsdescription', + 'Alt text' => 'alttext', + 'Please review the info below before you share' => 'reviewmessage', + 'Sub-content (images, questions etc.) will be shared under :license unless otherwise specified in the authoring tool' => 'subcontentwarning', + 'Disciplines' => 'disciplines', + 'Short description' => 'shortdescription', + 'Long description' => 'longdescription', + 'Icon' => 'icon', + 'Screenshots' => 'screenshots', + 'Help me choose a license' => 'helpchoosinglicense', + 'Share failed.' => 'sharefailed', + 'Editing failed.' => 'editingfailed', + 'Something went wrong, please try to share again.' => 'sharetryagain', + 'Please wait...' => 'pleasewait', + 'Language' => 'language', + 'Level' => 'level', + 'Short description of your content' => 'shortdescriptionplaceholder', + 'Long description of your content' => 'longdescriptionplaceholder', + 'Description' => 'description', + '640x480px. If not selected content will use category icon' => 'icondescription', + 'Add up to five screenshots of your content' => 'screenshotsdescription', + 'Submitted!' => 'submitted', + 'Is now submitted to H5P Hub' => 'isnowsubmitted', + 'A change has been submited for' => 'changehasbeensubmitted', + 'Your content will normally be available in the Hub within one business day.' => 'contentavailable', + 'Your content will update soon' => 'contentupdatesoon', + 'Content License Info' => 'contentlicensetitle', + 'Click on a specific license to get info about proper usage' => 'licensedialogdescription', + 'Publisher' => 'publisherfieldtitle', + 'This will display as the "Publisher name" on shared content' => 'publisherfielddescription', + 'Email Address' => 'emailaddress', + 'Publisher description' => 'publisherdescription', + 'This will be displayed under "Publisher info" on shared content' => 'publisherdescriptiontext', + 'Contact Person' => 'contactperson', + 'Phone' => 'phone', + 'Address' => 'address', + 'City' => 'city', + 'Zip' => 'zip', + 'Country' => 'country', + 'Organization logo or avatar' => 'logouploadtext', + 'I accept the terms of use' => 'acceptterms', + 'You have successfully registered an account on the H5P Hub' => 'successfullyregistred', + 'You account details can be changed' => 'successfullyregistreddescription', + 'here' => 'accountdetailslinktext', + 'H5P Hub Registration' => 'registrationtitle', + 'An error occurred' => 'registrationfailed', + 'We were not able to create an account at this point. Something went wrong. Try again later.' => 'registrationfaileddescription', + ':length is the maximum number of characters' => 'maxlength', + 'Keyword already exists!' => 'keywordexists', + 'License details' => 'licensedetails', + 'Remove' => 'remove', + 'Remove image' => 'removeimage', + 'Cancel sharing' => 'cancelpublishconfirmationdialogtitle', + 'Are you sure you want to cancel the sharing process?' => 'cancelpublishconfirmationdialogdescription', + 'No' => 'cancelpublishconfirmationdialogcancelbuttontext', + 'Yes' => 'cancelpublishconfirmationdialogconfirmbuttontext', + 'Add' => 'add', + 'Save account settings' => 'updateregistrationonhub', + 'Your H5P Hub account settings have successfully been changed' => 'successfullyupdated', + 'One of the files inside the package exceeds the maximum file size allowed. (%file %used > %max)' => 'fileexceedsmaxsize', + 'The total size of the unpacked files exceeds the maximum size allowed. (%used > %max)' => 'unpackedfilesexceedsmaxsize', + 'Unable to read file from the package: %fileName' => 'couldnotreadfilefromzip', + 'Unable to parse JSON from the package: %fileName' => 'couldnotparsejsonfromzip', + 'Could not parse post data.' => 'couldnotparsepostdata', + 'The mbstring PHP extension is not loaded. H5P needs this to function properly' => 'nombstringexteension', + 'Assistive Technologies label' => 'assistivetechnologieslabel', + 'Typical age' => 'age', + 'The target audience of this content. Possible input formats separated by commas: "1,34-45,-50,59-".' => 'agedescription', + 'Invalid input format for Typical age. Possible input formats separated by commas: "1, 34-45, -50, -59-".' => 'invalidage', + 'H5P will reach out to the contact person in case there are any issues with the content shared by the publisher. The contact person\'s name or other information will not be published or shared with third parties' => 'contactpersondescription', + 'The email address will be used by H5P to reach out to the publisher in case of any issues with the content or in case the publisher needs to recover their account. It will not be published or shared with any third parties' => 'emailaddressdescription', + 'Copyrighted material cannot be shared in the H5P Content Hub. If the content is licensed with a OER friendly license like Creative Commons, please choose the appropriate license. If not this content cannot be shared.' => 'copyrightwarning', + 'Keywords already exists!' => 'keywordsexists', + 'Some of these keywords already exist' => 'somekeywordsexists', + ]; + // @codingStandardsIgnoreEnd + } + + // Some strings such as error messages are not translatable, in this case use message + // directly instead of crashing + // @see https://github.com/h5p/h5p-php-library/commit/2bd972168e7b22aaeea2dd13682ced9cf8233452#diff-5ca86cd0514d58be6708beff914aba66R1296. + if (!isset($translationsmap[$message])) { + return $message; + } + + return get_string($translationsmap[$message], 'hvp', $replacements); + } + + /** + * Implements getH5PPath + */ + // @codingStandardsIgnoreLine + public function getH5pPath() { + global $CFG; + + return $CFG->dirroot . '/mod/hvp/files'; + } + + /** + * Implements getLibraryFileUrl + */ + // @codingStandardsIgnoreLine + public function getLibraryFileUrl($libraryfoldername, $fileName) { + $context = \context_system::instance(); + $basepath = view_assets::getsiteroot() . '/'; + return "{$basepath}pluginfile.php/{$context->id}/mod_hvp/libraries/{$libraryfoldername}/{$fileName}"; + } + + /** + * Implements getUploadedH5PFolderPath + */ + // @codingStandardsIgnoreLine + public function getUploadedH5pFolderPath($setpath = null) { + static $path; + + if ($setpath !== null) { + $path = $setpath; + } + + if (!isset($path)) { + throw new \coding_exception('Using getUploadedH5pFolderPath() before path is set'); + } + + return $path; + } + + /** + * Implements getUploadedH5PPath + */ + // @codingStandardsIgnoreLine + public function getUploadedH5pPath($setpath = null) { + static $path; + + if ($setpath !== null) { + $path = $setpath; + } + + return $path; + } + + /** + * Implements loadLibraries + */ + // @codingStandardsIgnoreLine + public function loadLibraries() { + global $DB; + + $results = $DB->get_records_sql( + "SELECT id, machine_name, title, major_version, minor_version, + patch_version, runnable, restricted + FROM {hvp_libraries} + ORDER BY title ASC, major_version ASC, minor_version ASC"); + + $libraries = array(); + foreach ($results as $library) { + $libraries[$library->machine_name][] = $library; + } + + return $libraries; + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function setUnsupportedLibraries($libraries) { + // Not supported. + } + + /** + * Implements getUnsupportedLibraries. + */ + // @codingStandardsIgnoreLine + public function getUnsupportedLibraries() { + // Not supported. + } + + /** + * Implements getAdminUrl. + */ + // @codingStandardsIgnoreLine + public function getAdminUrl() { + // Not supported. + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function getLibraryId($machinename, $majorversion = null, $minorversion = null) { + global $DB; + + // Look for specific library. + $sqlwhere = 'WHERE machine_name = ?'; + $sqlargs = array($machinename); + + if ($majorversion !== null) { + // Look for major version. + $sqlwhere .= ' AND major_version = ?'; + $sqlargs[] = $majorversion; + if ($minorversion !== null) { + // Look for minor version. + $sqlwhere .= ' AND minor_version = ?'; + $sqlargs[] = $minorversion; + } + } + + // Get the lastest version which matches the input parameters. + $libraries = $DB->get_records_sql(" + SELECT id + FROM {hvp_libraries} + {$sqlwhere} + ORDER BY major_version DESC, + minor_version DESC, + patch_version DESC + ", $sqlargs, 0, 1); + if ($libraries) { + $library = reset($libraries); + return $library ? $library->id : false; + } else { + return false; + } + } + + /** + * Implements isPatchedLibrary + */ + // @codingStandardsIgnoreLine + public function isPatchedLibrary($library) { + global $DB, $CFG; + + if (isset($CFG->mod_hvp_dev) && $CFG->mod_hvp_dev) { + // Makes sure libraries are updated, patch version does not matter. + return true; + } + + $operator = $this->isInDevMode() ? '<=' : '<'; + $library = $DB->get_record_sql( + 'SELECT id + FROM {hvp_libraries} + WHERE machine_name = ? + AND major_version = ? + AND minor_version = ? + AND patch_version ' . $operator . ' ?', + array($library['machineName'], + $library['majorVersion'], + $library['minorVersion'], + $library['patchVersion']) + ); + + return $library ? true : false; + } + + /** + * Implements isInDevMode + */ + // @codingStandardsIgnoreLine + public function isInDevMode() { + return false; // Not supported (Files in moodle not editable). + } + + /** + * Implements mayUpdateLibraries + */ + // @codingStandardsIgnoreLine + public function mayUpdateLibraries($allow = false) { + static $override; + + // Allow overriding the permission check. Needed when installing. + // since caps hasn't been set. + if ($allow) { + $override = true; + } + if ($override) { + return true; + } + + // Check permissions. + $context = \context_system::instance(); + if (!has_capability('mod/hvp:updatelibraries', $context)) { + return false; + } + + return true; + } + + /** + * Implements getLibraryUsage + * + * Get number of content/nodes using a library, and the number of + * dependencies to other libraries + * + * @param int $id + * @param boolean $skipcontent Optional. Set as true to get number of content instances for library. + * @return array The array contains two elements, keyed by 'content' and 'libraries'. + * Each element contains a number + */ + // @codingStandardsIgnoreLine + public function getLibraryUsage($id, $skipcontent = false) { + global $DB; + + if ($skipcontent) { + $content = -1; + } else { + $content = intval($DB->get_field_sql( + "SELECT COUNT(distinct c.id) + FROM {hvp_libraries} l + JOIN {hvp_contents_libraries} cl ON l.id = cl.library_id + JOIN {hvp} c ON cl.hvp_id = c.id + WHERE l.id = ?", array($id) + )); + } + + $libraries = intval($DB->get_field_sql( + "SELECT COUNT(*) + FROM {hvp_libraries_libraries} + WHERE required_library_id = ?", array($id) + )); + + return array( + 'content' => $content, + 'libraries' => $libraries, + ); + } + + /** + * Implements getLibraryContentCount + */ + // @codingStandardsIgnoreLine + public function getLibraryContentCount() { + global $DB; + $contentcount = array(); + + // Count content using the same content type. + $res = $DB->get_records_sql( + "SELECT c.main_library_id, + l.machine_name, + l.major_version, + l.minor_version, + c.count + FROM (SELECT main_library_id, + count(id) as count + FROM {hvp} + GROUP BY main_library_id) c, + {hvp_libraries} l + WHERE c.main_library_id = l.id" + ); + + // Extract results. + foreach ($res as $lib) { + $contentcount["{$lib->machine_name} {$lib->major_version}.{$lib->minor_version}"] = $lib->count; + } + + return $contentcount; + } + + /** + * Implements saveLibraryData + */ + // @codingStandardsIgnoreLine + public function saveLibraryData(&$librarydata, $new = true) { + global $DB; + + // Some special properties needs some checking and converting before they can be saved. + $preloadedjs = $this->pathsToCsv($librarydata, 'preloadedJs'); + $preloadedcss = $this->pathsToCsv($librarydata, 'preloadedCss'); + $droplibrarycss = ''; + + if (isset($librarydata['dropLibraryCss'])) { + $libs = array(); + foreach ($librarydata['dropLibraryCss'] as $lib) { + $libs[] = $lib['machineName']; + } + $droplibrarycss = implode(', ', $libs); + } + + $embedtypes = ''; + if (isset($librarydata['embedTypes'])) { + $embedtypes = implode(', ', $librarydata['embedTypes']); + } + if (!isset($librarydata['semantics'])) { + $librarydata['semantics'] = ''; + } + if (!isset($librarydata['fullscreen'])) { + $librarydata['fullscreen'] = 0; + } + if (!isset($librarydata['hasIcon'])) { + $librarydata['hasIcon'] = 0; + } + // TODO: Can we move the above code to H5PCore? It's the same for multiple + // implementations. Perhaps core can update the data objects before calling + // this function? + // I think maybe it's best to do this when classes are created for + // library, content, etc. + + $library = (object) array( + 'title' => $librarydata['title'], + 'machine_name' => $librarydata['machineName'], + 'major_version' => $librarydata['majorVersion'], + 'minor_version' => $librarydata['minorVersion'], + 'patch_version' => $librarydata['patchVersion'], + 'runnable' => $librarydata['runnable'], + 'fullscreen' => $librarydata['fullscreen'], + 'embed_types' => $embedtypes, + 'preloaded_js' => $preloadedjs, + 'preloaded_css' => $preloadedcss, + 'drop_library_css' => $droplibrarycss, + 'semantics' => $librarydata['semantics'], + 'has_icon' => $librarydata['hasIcon'], + 'metadata_settings' => $librarydata['metadataSettings'], + 'add_to' => isset($librarydata['addTo']) ? json_encode($librarydata['addTo']) : null, + ); + + if ($new) { + // Create new library and keep track of id. + $library->id = $DB->insert_record('hvp_libraries', $library); + $librarydata['libraryId'] = $library->id; + } else { + // Update library data. + $library->id = $librarydata['libraryId']; + + // Save library data. + $DB->update_record('hvp_libraries', (object) $library); + + // Remove old dependencies. + $this->deleteLibraryDependencies($librarydata['libraryId']); + } + + // Log library successfully installed/upgraded. + new \mod_hvp\event( + 'library', ($new ? 'create' : 'update'), + null, null, + $library->machine_name, $library->major_version . '.' . $library->minor_version + ); + + // Update library translations. + $DB->delete_records('hvp_libraries_languages', array('library_id' => $librarydata['libraryId'])); + if (isset($librarydata['language'])) { + foreach ($librarydata['language'] as $languagecode => $languagejson) { + $DB->insert_record('hvp_libraries_languages', array( + 'library_id' => $librarydata['libraryId'], + 'language_code' => $languagecode, + 'language_json' => $languagejson, + )); + } + } + } + + /** + * Convert list of file paths to csv + * + * @param array $librarydata + * Library data as found in library.json files + * @param string $key + * Key that should be found in $librarydata + * @return string + * file paths separated by ', ' + */ + // @codingStandardsIgnoreLine + private function pathsToCsv($librarydata, $key) { + if (isset($librarydata[$key])) { + $paths = array(); + foreach ($librarydata[$key] as $file) { + $paths[] = $file['path']; + } + return implode(', ', $paths); + } + return ''; + } + + /** + * Implements lockDependencyStorage + */ + // @codingStandardsIgnoreLine + public function lockDependencyStorage() { + // Library development mode not supported. + } + + /** + * Implements unlockDependencyStorage + */ + // @codingStandardsIgnoreLine + public function unlockDependencyStorage() { + // Library development mode not supported. + } + + /** + * Implements deleteLibrary + */ + // @codingStandardsIgnoreLine + public function deleteLibrary($library) { + global $DB; + + // Delete library files. + $librarybase = $this->getH5pPath() . '/libraries/'; + $libname = "{$library->name}-{$library->major_version}.{$library->minor_version}"; + \H5PCore::deleteFileTree("{$librarybase}{$libname}"); + + // Remove library data from database. + $DB->delete('hvp_libraries_libraries', array('library_id' => $library->id)); + $DB->delete('hvp_libraries_languages', array('library_id' => $library->id)); + $DB->delete('hvp_libraries', array('id' => $library->id)); + } + + /** + * Implements saveLibraryDependencies + * + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function saveLibraryDependencies($libraryid, $dependencies, $dependencytype) { + global $DB; + + foreach ($dependencies as $dependency) { + // Find dependency library. + $dependencylibrary = $DB->get_record('hvp_libraries', array( + 'machine_name' => $dependency['machineName'], + 'major_version' => $dependency['majorVersion'], + 'minor_version' => $dependency['minorVersion'] + )); + + // Create relation. + $DB->insert_record('hvp_libraries_libraries', array( + 'library_id' => $libraryid, + 'required_library_id' => $dependencylibrary->id, + 'dependency_type' => $dependencytype + )); + } + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function updateContent($content, $contentmainid = null) { + global $DB; + + if (!isset($content['disable'])) { + $content['disable'] = \H5PCore::DISABLE_NONE; + } + + $data = array_merge(\H5PMetadata::toDBArray($content['metadata'], false), array( + 'name' => isset($content['metadata']->title) ? $content['metadata']->title : $content['name'], + 'course' => $content['course'], + 'intro' => $content['intro'], + 'introformat' => $content['introformat'], + 'json_content' => $content['params'], + 'embed_type' => 'div', + 'main_library_id' => $content['library']['libraryId'], + 'filtered' => '', + 'disable' => $content['disable'], + 'timemodified' => time(), + )); + + if (isset($content[ 'completionpass'])) { + $data[ 'completionpass' ] = $content[ 'completionpass' ]; + } + + if (!isset($content['id'])) { + $data['slug'] = ''; + $data['timecreated'] = $data['timemodified']; + $eventtype = 'create'; + $id = $DB->insert_record('hvp', $data); + } else { + $data['id'] = $content['id']; + $data['synced'] = \H5PContentHubSyncStatus::NOT_SYNCED; + $DB->update_record('hvp', $data); + $eventtype = 'update'; + $id = $data['id']; + } + + // Log content create/update/upload. + if (!empty($content['uploaded'])) { + $eventtype .= ' upload'; + } + new \mod_hvp\event( + 'content', $eventtype, + $id, $content['name'], + $content['library']['machineName'], + $content['library']['majorVersion'] . '.' . $content['library']['minorVersion'] + ); + + return $id; + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function insertContent($content, $contentmainid = null) { + return $this->updateContent($content); + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function resetContentUserData($contentid) { + global $DB; + + // Reset user data for this content. + $DB->execute("UPDATE {hvp_content_user_data} + SET data = 'RESET' + WHERE hvp_id = ? + AND delete_on_content_change = 1", + array($contentid)); + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function getWhitelist($islibrary, $defaultcontentwhitelist, $defaultlibrarywhitelist) { + return $defaultcontentwhitelist . ($islibrary ? ' ' . $defaultlibrarywhitelist : ''); + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function copyLibraryUsage($contentid, $copyfromid, $contentmainid = null) { + global $DB; + + $libraryusage = $DB->get_record('hvp_contents_libraries', array( + 'id' => $copyfromid + )); + + $libraryusage->id = $contentid; + $DB->insert_record_raw('hvp_contents_libraries', (array)$libraryusage, false, false, true); + + // TODO: This must be verified at a later time. + // Currently in Moodle copyLibraryUsage() will never be called. + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function loadLibrarySemantics($name, $majorversion, $minorversion) { + global $DB; + + $semantics = $DB->get_field_sql( + "SELECT semantics + FROM {hvp_libraries} + WHERE machine_name = ? + AND major_version = ? + AND minor_version = ?", + array($name, $majorversion, $minorversion)); + + return ($semantics === false ? null : $semantics); + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function alterLibrarySemantics(&$semantics, $name, $majorversion, $minorversion) { + global $PAGE; + + $PAGE->set_context(null); + + $renderer = $PAGE->get_renderer('mod_hvp'); + $renderer->hvp_alter_semantics($semantics, $name, $majorversion, $minorversion); + } + + /** + * Implements loadContent + */ + // @codingStandardsIgnoreLine + public function loadContent($id) { + global $DB; + + $data = $DB->get_record_sql(" + SELECT + hc.id, + hc.name, + hc.intro, + hc.introformat, + hc.json_content, + hc.filtered, + hc.slug, + hc.embed_type, + hc.disable, + hl.id AS library_id, + hl.machine_name, + hl.major_version, + hl.minor_version, + hl.embed_types, + hl.fullscreen, + hc.name as title, + hc.authors, + hc.source, + hc.license, + hc.license_version, + hc.license_extras, + hc.year_from, + hc.year_to, + hc.changes, + hc.author_comments, + hc.default_language, + hc.shared, + hc.synced, + hc.hub_id, + hc.a11y_title + FROM {hvp} hc + JOIN {hvp_libraries} hl ON hl.id = hc.main_library_id + WHERE hc.id = ?", array($id) + ); + + // Return null if not found. + if ($data === false) { + return null; + } + + // Some databases do not support camelCase, so we need to manually + // map the values to the camelCase names used by the H5P core. + $content = array( + 'id' => $data->id, + 'title' => $data->name, + 'intro' => $data->intro, + 'introformat' => $data->introformat, + 'params' => $data->json_content, + 'filtered' => $data->filtered, + 'slug' => $data->slug, + 'embedType' => $data->embed_type, + 'disable' => $data->disable, + 'shared' => $data->shared, + 'synced' => $data->synced, + 'contentHubId' => $data->hub_id, + 'libraryId' => $data->library_id, + 'libraryName' => $data->machine_name, + 'libraryMajorVersion' => $data->major_version, + 'libraryMinorVersion' => $data->minor_version, + 'libraryEmbedTypes' => $data->embed_types, + 'libraryFullscreen' => $data->fullscreen, + ); + + $metadatafields = [ + 'title', + 'authors', + 'source', + 'license', + 'license_version', + 'license_extras', + 'year_from', + 'year_to', + 'changes', + 'author_comments', + 'default_language', + 'a11y_title' + ]; + + $content['metadata'] = \H5PCore::snakeToCamel( + array_reduce($metadatafields, function ($array, $field) use ($data) { + if (isset($data->$field)) { + $value = $data->$field; + // Decode json fields. + if (in_array($field, ['authors', 'changes'])) { + $value = json_decode($data->$field); + } + + $array[$field] = $value; + } + return $array; + }, []) + ); + + return $content; + } + + /** + * Implements loadContentDependencies + */ + // @codingStandardsIgnoreLine + public function loadContentDependencies($id, $type = null) { + global $DB; + + $query = "SELECT hcl.id AS unidepid + , hl.id + , hl.machine_name + , hl.major_version + , hl.minor_version + , hl.patch_version + , hl.preloaded_css + , hl.preloaded_js + , hcl.drop_css + , hcl.dependency_type + FROM {hvp_contents_libraries} hcl + JOIN {hvp_libraries} hl ON hcl.library_id = hl.id + WHERE hcl.hvp_id = ?"; + $queryargs = array($id); + + if ($type !== null) { + $query .= " AND hcl.dependency_type = ?"; + $queryargs[] = $type; + } + + $query .= " ORDER BY hcl.weight"; + $data = $DB->get_records_sql($query, $queryargs); + + $dependencies = array(); + foreach ($data as $dependency) { + unset($dependency->unidepid); + $dependencies[$dependency->machine_name] = \H5PCore::snakeToCamel($dependency); + } + + return $dependencies; + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function getOption($name, $default = false) { + $value = get_config('mod_hvp', $name); + if ($value === false) { + return $default; + } + return $value; + } + + /** + * Implements setOption(). + */ + // @codingStandardsIgnoreLine + public function setOption($name, $value) { + set_config($name, $value, 'mod_hvp'); + } + + /** + * Implements updateContentFields(). + */ + // @codingStandardsIgnoreLine + public function updateContentFields($id, $fields) { + global $DB; + + $content = new \stdClass(); + $content->id = $id; + + foreach ($fields as $name => $value) { + $content->$name = $value; + } + + $DB->update_record('hvp', $content); + } + + /** + * Implements deleteLibraryDependencies + */ + // @codingStandardsIgnoreLine + public function deleteLibraryDependencies($libraryid) { + global $DB; + + $DB->delete_records('hvp_libraries_libraries', array('library_id' => $libraryid)); + } + + /** + * Implements deleteContentData + */ + // @codingStandardsIgnoreLine + public function deleteContentData($contentid) { + global $DB; + + // Remove content. + $DB->delete_records('hvp', array('id' => $contentid)); + + // Remove content library dependencies. + $this->deleteLibraryUsage($contentid); + + // Remove user data for content. + $DB->delete_records('hvp_content_user_data', array('hvp_id' => $contentid)); + } + + /** + * Implements deleteLibraryUsage + */ + // @codingStandardsIgnoreLine + public function deleteLibraryUsage($contentid) { + global $DB; + + $DB->delete_records('hvp_contents_libraries', array('hvp_id' => $contentid)); + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function saveLibraryUsage($contentid, $librariesinuse) { + global $DB; + + $droplibrarycsslist = array(); + foreach ($librariesinuse as $dependency) { + if (!empty($dependency['library']['dropLibraryCss'])) { + $droplibrarycsslist = array_merge($droplibrarycsslist, explode(', ', $dependency['library']['dropLibraryCss'])); + } + } + // TODO: Consider moving the above code to core. Same for all impl. + + foreach ($librariesinuse as $dependency) { + $dropcss = in_array($dependency['library']['machineName'], $droplibrarycsslist) ? 1 : 0; + $DB->insert_record('hvp_contents_libraries', array( + 'hvp_id' => $contentid, + 'library_id' => $dependency['library']['libraryId'], + 'dependency_type' => $dependency['type'], + 'drop_css' => $dropcss, + 'weight' => $dependency['weight'] + )); + } + } + + /** + * Implements loadLibrary + */ + // @codingStandardsIgnoreLine + public function loadLibrary($machinename, $majorversion, $minorversion) { + global $DB; + + $library = $DB->get_record('hvp_libraries', array( + 'machine_name' => $machinename, + 'major_version' => $majorversion, + 'minor_version' => $minorversion + )); + + $librarydata = array( + 'libraryId' => $library->id, + 'machineName' => $library->machine_name, + 'title' => $library->title, + 'majorVersion' => $library->major_version, + 'minorVersion' => $library->minor_version, + 'patchVersion' => $library->patch_version, + 'embedTypes' => $library->embed_types, + 'preloadedJs' => $library->preloaded_js, + 'preloadedCss' => $library->preloaded_css, + 'dropLibraryCss' => $library->drop_library_css, + 'fullscreen' => $library->fullscreen, + 'runnable' => $library->runnable, + 'semantics' => $library->semantics, + 'restricted' => $library->restricted, + 'hasIcon' => $library->has_icon + ); + + $dependencies = $DB->get_records_sql( + 'SELECT hl.id, hl.machine_name, hl.major_version, hl.minor_version, hll.dependency_type + FROM {hvp_libraries_libraries} hll + JOIN {hvp_libraries} hl ON hll.required_library_id = hl.id + WHERE hll.library_id = ?', array($library->id)); + foreach ($dependencies as $dependency) { + $librarydata[$dependency->dependency_type . 'Dependencies'][] = array( + 'machineName' => $dependency->machine_name, + 'majorVersion' => $dependency->major_version, + 'minorVersion' => $dependency->minor_version + ); + } + + return $librarydata; + } + + /** + * Implements clearFilteredParameters(). + * + * @param array $libraryids array of library ids + * + * @throws \dml_exception + * @throws \coding_exception + */ + // @codingStandardsIgnoreLine + public function clearFilteredParameters($libraryids) { + global $DB; + if (empty($libraryids)) { + return; + } + + list($insql, $inparams) = $DB->get_in_or_equal($libraryids); + $DB->execute(" + UPDATE {hvp} + SET filtered = null + WHERE main_library_id $insql", + $inparams + ); + } + + /** + * Implements getNumNotFiltered(). + */ + // @codingStandardsIgnoreLine + public function getNumNotFiltered() { + global $DB; + + return (int) $DB->get_field_sql( + "SELECT COUNT(id) + FROM {hvp} + WHERE " . $DB->sql_compare_text('filtered') . " = ''"); + } + + /** + * Implements getNumContent(). + */ + // @codingStandardsIgnoreLine + public function getNumContent($libraryid, $skip = NULL) { + global $DB; + $skipquery = empty($skip) ? '' : " AND id NOT IN ($skip)"; + + return (int) $DB->get_field_sql( + "SELECT COUNT(id) FROM {hvp} WHERE main_library_id = ?{$skipquery}", + array($libraryid)); + } + + /** + * Implements isContentSlugAvailable + */ + // @codingStandardsIgnoreLine + public function isContentSlugAvailable($slug) { + global $DB; + + return !$DB->get_records_sql("SELECT id, slug FROM {hvp} WHERE slug = ?", array($slug)); + } + + /** + * Implements saveCachedAssets + */ + // @codingStandardsIgnoreLine + public function saveCachedAssets($key, $libraries) { + global $DB; + + foreach ($libraries as $library) { + $cachedasset = (object) array( + 'library_id' => $library['id'], + 'hash' => $key + ); + $DB->insert_record('hvp_libraries_cachedassets', $cachedasset); + } + } + + /** + * Implements deleteCachedAssets + */ + // @codingStandardsIgnoreLine + public function deleteCachedAssets($libraryid) { + global $DB; + + // Get all the keys so we can remove the files. + $results = $DB->get_records_sql( + 'SELECT hash + FROM {hvp_libraries_cachedassets} + WHERE library_id = ?', + array($libraryid)); + + // Remove all invalid keys. + $hashes = array(); + foreach ($results as $key) { + $hashes[] = $key->hash; + $DB->delete_records('hvp_libraries_cachedassets', array('hash' => $key->hash)); + } + + return $hashes; + } + + /** + * Implements getLibraryStats + */ + // @codingStandardsIgnoreLine + public function getLibraryStats($type) { + global $DB; + $count = array(); + + // Get the counts for the given type of event. + $records = $DB->get_records_sql( + "SELECT id, + library_name AS name, + library_version AS version, + num + FROM {hvp_counters} + WHERE type = ?", + array($type)); + + // Extract num from records. + foreach ($records as $library) { + $count[$library->name . ' ' . $library->version] = $library->num; + } + + return $count; + } + + /** + * Implements getNumAuthors + */ + // @codingStandardsIgnoreLine + public function getNumAuthors() { + global $DB; + + // Get number of unique courses using H5P. + return intval($DB->get_field_sql( + "SELECT COUNT(DISTINCT course) + FROM {hvp}" + )); + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function afterExportCreated($content, $filename) { + } + + /** + * Implements hasPermission + * @method hasPermission + * @param \H5PPermission $permission + * @param int $cmid context module id + * @return boolean + */ + // @codingStandardsIgnoreLine + public function hasPermission($permission, $cmid = null) { + switch ($permission) { + case \H5PPermission::DOWNLOAD_H5P: + case \H5PPermission::COPY_H5P: + $cmcontext = \context_module::instance($cmid); + return has_capability('mod/hvp:getexport', $cmcontext); + case \H5PPermission::CREATE_RESTRICTED: + return has_capability('mod/hvp:userestrictedlibraries', $this->getajaxcoursecontext()); + case \H5PPermission::UPDATE_LIBRARIES: + $context = \context_system::instance(); + return has_capability('mod/hvp:updatelibraries', $context); + case \H5PPermission::INSTALL_RECOMMENDED: + return has_capability('mod/hvp:installrecommendedh5plibraries', $this->getajaxcoursecontext()); + case \H5PPermission::EMBED_H5P: + $cmcontext = \context_module::instance($cmid); + return has_capability('mod/hvp:getembedcode', $cmcontext); + } + return false; + } + + /** + * Gets course context in AJAX + * + * @return bool|\context|\context_course + */ + private function getajaxcoursecontext() { + $context = \context::instance_by_id(required_param('contextId', PARAM_RAW)); + if ($context->contextlevel === CONTEXT_COURSE) { + return $context; + } + + return $context->get_course_context(); + } + + /** + * Replaces existing content type cache with the one passed in + * + * @param object $contenttypecache Json with an array called 'libraries' + * containing the new content type cache that should replace the old one. + */ + // @codingStandardsIgnoreLine + public function replaceContentTypeCache($contenttypecache) { + global $DB; + + // Replace existing cache. + $DB->delete_records('hvp_libraries_hub_cache'); + foreach ($contenttypecache->contentTypes as $ct) { + $DB->insert_record('hvp_libraries_hub_cache', (object) array( + 'machine_name' => $ct->id, + 'major_version' => $ct->version->major, + 'minor_version' => $ct->version->minor, + 'patch_version' => $ct->version->patch, + 'h5p_major_version' => $ct->coreApiVersionNeeded->major, + 'h5p_minor_version' => $ct->coreApiVersionNeeded->minor, + 'title' => $ct->title, + 'summary' => $ct->summary, + 'description' => $ct->description, + 'icon' => $ct->icon, + 'created_at' => (new \DateTime($ct->createdAt))->getTimestamp(), + 'updated_at' => (new \DateTime($ct->updatedAt))->getTimestamp(), + 'is_recommended' => $ct->isRecommended === true ? 1 : 0, + 'popularity' => $ct->popularity, + 'screenshots' => json_encode($ct->screenshots), + 'license' => json_encode(isset($ct->license) ? $ct->license : array()), + 'example' => $ct->example, + 'tutorial' => isset($ct->tutorial) ? $ct->tutorial : '', + 'keywords' => json_encode(isset($ct->keywords) ? $ct->keywords : array()), + 'categories' => json_encode(isset($ct->categories) ? $ct->categories : array()), + 'owner' => $ct->owner + ), false, true); + } + } + + /** + * Implements loadAddons + */ + // @codingStandardsIgnoreLine + public function loadAddons() { + global $DB; + $addons = array(); + + $records = $DB->get_records_sql( + "SELECT l1.id AS library_id, + l1.machine_name, + l1.major_version, + l1.minor_version, + l1.patch_version, + l1.add_to, + l1.preloaded_js, + l1.preloaded_css + FROM {hvp_libraries} l1 + LEFT JOIN {hvp_libraries} l2 + ON l1.machine_name = l2.machine_name + AND (l1.major_version < l2.major_version + OR (l1.major_version = l2.major_version + AND l1.minor_version < l2.minor_version)) + WHERE l1.add_to IS NOT NULL + AND l2.machine_name IS NULL"); + + // NOTE: These are treated as library objects but are missing the following properties: + // title, embed_types, drop_library_css, fullscreen, runnable, semantics, has_icon. + + // Extract num from records. + foreach ($records as $addon) { + $addons[] = \H5PCore::snakeToCamel($addon); + } + + return $addons; + } + + /** + * Implements getLibraryConfig + */ + // @codingStandardsIgnoreLine + public function getLibraryConfig($libraries = null) { + global $CFG; + return (isset($CFG->mod_hvp_library_config) ? $CFG->mod_hvp_library_config : null); + } + + /** + * Implements libraryHasUpgrade + */ + // @codingStandardsIgnoreLine + public function libraryHasUpgrade($library) { + global $DB; + + $results = $DB->get_records_sql( + "SELECT id + FROM {hvp_libraries} + WHERE machine_name = ? + AND (major_version > ? + OR (major_version = ? AND minor_version > ?))", + array( + $library['machineName'], + $library['majorVersion'], + $library['majorVersion'], + $library['minorVersion'] + ), + 0, + 1 + ); + + return !empty($results); + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function replaceContentHubMetadataCache($metadata, $lang = 'en') { + global $DB; + + // Check if exist in database. + $cache = $DB->get_record_sql( + 'SELECT id + FROM {hvp_content_hub_cache} + WHERE language = ?', + array($lang) + ); + if ($cache) { + // Update. + $DB->execute("UPDATE {hvp_content_hub_cache} SET json = ? WHERE id = ?", array($metadata, $cache->id)); + } else { + // Insert. + $DB->insert_record('hvp_content_hub_cache', (object) array( + 'json' => $metadata, + 'language' => $lang, + 'last_checked' => time(), + )); + } + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function getContentHubMetadataCache($lang = 'en') { + global $DB; + $cache = $DB->get_record_sql( + 'SELECT json + FROM {hvp_content_hub_cache} + WHERE language = ?', + array($lang) + ); + return $cache ? $cache->json : null; + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function getContentHubMetadataChecked($lang = 'en') { + global $DB; + $cache = $DB->get_record_sql( + 'SELECT last_checked + FROM {hvp_content_hub_cache} + WHERE language = ?', + array($lang) + ); + if ($cache) { + $time = new \DateTime(); + $time->setTimestamp($cache->last_checked); + $cache = $time->format("D, d M Y H:i:s \G\M\T"); + } + return $cache; + } + + /** + * @inheritdoc + */ + // @codingStandardsIgnoreLine + public function setContentHubMetadataChecked($time, $lang = 'en') { + global $DB; + $DB->execute("UPDATE {hvp_content_hub_cache} SET last_checked = ? WHERE language = ?", array($time, $lang)); + } +} diff --git a/classes/mobile_auth.php b/classes/mobile_auth.php new file mode 100644 index 0000000..e80691c --- /dev/null +++ b/classes/mobile_auth.php @@ -0,0 +1,123 @@ +. + +/** + * Helpers for authenticating mobile users through tokens + * + * @package mod_hvp + * @copyright 2019 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; + +defined('MOODLE_INTERNAL') || die(); + +class mobile_auth { + + const VALID_TIME = 60; + + /** + * Generate embed auth token + * + * @param string $secret Secret phrase added to the hash + * @param int $validfor Time factor that determines how long the token is valid + * + * @return array Login token and secret + * @throws \Exception + */ + public static function create_embed_auth_token($secret = null, $validfor = null) { + if (!$validfor) { + $validfor = self::get_time_factor(); + } + + if (empty($secret)) { + if (function_exists('random_bytes')) { + $secret = base64_encode(random_bytes(15)); + } else if (function_exists('openssl_random_pseudo_bytes')) { + $secret = base64_encode(openssl_random_pseudo_bytes(15)); + } else { + $secret = uniqid('', true); + } + } + + return [ + hash('md5', 'embed_auth' . $validfor . $secret), + $secret + ]; + } + + /** + * Validate embed auth token + * + * @param string $token + * @param string $secret + * + * @return bool True if valid token was supplied + * @throws \Exception + */ + public static function validate_embed_auth_token($token, $secret) { + $timefactor = self::get_time_factor(); + // Splitting into two halves and allowing both allows for fractions roundup in the time factor. + list($generatedtoken) = self::create_embed_auth_token($secret, $timefactor); + list($generatedtoken2) = self::create_embed_auth_token($secret, $timefactor - 1); + return $token === $generatedtoken || $token === $generatedtoken2; + } + + /** + * Check if provided user_id and token are valid for authenticating the user + * + * @param string $userid + * @param string $token + * + * @return bool True if token and user_id is valid + * @throws \dml_exception + */ + public static function has_valid_token($userid, $secret) { + global $DB; + + if (!$userid || !$secret) { + return false; + } + + $auth = $DB->get_record('hvp_auth', array( + 'user_id' => $userid, + )); + if (!$auth) { + return false; + } + + $isvalid = self::validate_embed_auth_token($auth->secret, $secret); + + // Cleanup user's token when used. + if ($isvalid) { + $DB->delete_records('hvp_auth', array( + 'user_id' => $userid + )); + } + + return $isvalid; + } + + /** + * Get time factor for how long the token is valid + * + * @return float + */ + public static function get_time_factor() { + return ceil(time() / self::VALID_TIME); + } +} diff --git a/classes/output/mobile.php b/classes/output/mobile.php new file mode 100644 index 0000000..3a8f91f --- /dev/null +++ b/classes/output/mobile.php @@ -0,0 +1,98 @@ +. + +namespace mod_hvp\output; + +defined('MOODLE_INTERNAL') || die(); + +use context_module; +use mod_hvp; + +class mobile { + + public static function mobile_course_view($args) { + global $DB, $CFG, $OUTPUT, $USER; + + $cmid = $args['cmid']; + if (!$CFG->allowframembedding) { + $context = \context_system::instance(); + if (has_capability('moodle/site:config', $context)) { + $template = 'mod_hvp/iframe_embedding_disabled'; + } else { + $template = 'mod_hvp/contact_site_administrator'; + } + return array( + 'templates' => array( + array( + 'id' => 'noiframeembedding', + 'html' => $OUTPUT->render_from_template($template, []) + ) + ) + ); + } + + // Verify course context. + $cm = get_coursemodule_from_id('hvp', $cmid); + if (!$cm) { + print_error('invalidcoursemodule'); + } + $course = $DB->get_record('course', array('id' => $cm->course)); + if (!$course) { + print_error('coursemisconf'); + } + require_course_login($course, false, $cm, true, true); + $context = context_module::instance($cm->id); + require_capability('mod/hvp:view', $context); + + list($token, $secret) = mod_hvp\mobile_auth::create_embed_auth_token(); + + // Store secret in database. + $auth = $DB->get_record('hvp_auth', array( + 'user_id' => $USER->id, + )); + $currenttimestamp = time(); + if ($auth) { + $DB->update_record('hvp_auth', array( + 'id' => $auth->id, + 'secret' => $token, + 'created_at' => $currenttimestamp, + )); + } else { + $DB->insert_record('hvp_auth', array( + 'user_id' => $USER->id, + 'secret' => $token, + 'created_at' => $currenttimestamp + )); + } + + $data = [ + 'cmid' => $cmid, + 'wwwroot' => $CFG->wwwroot, + 'user_id' => $USER->id, + 'secret' => urlencode($secret) + ]; + + return array( + 'templates' => array( + array( + 'id' => 'main', + 'html' => $OUTPUT->render_from_template('mod_hvp/mobile_view_page', $data), + ), + ), + 'javascript' => file_get_contents($CFG->dirroot . '/mod/hvp/library/js/h5p-resizer.js'), + ); + } +} diff --git a/classes/privacy/provider.php b/classes/privacy/provider.php new file mode 100644 index 0000000..08f18a2 --- /dev/null +++ b/classes/privacy/provider.php @@ -0,0 +1,519 @@ +. + +/** + * Privacy Subsystem implementation for H5P. + */ + +namespace mod_hvp\privacy; + +use \core_privacy\local\request\writer; +use \core_privacy\local\request\contextlist; +use \core_privacy\local\request\approved_contextlist; +use \core_privacy\local\request\deletion_criteria; +use \core_privacy\local\request\approved_userlist; +use \core_privacy\local\request\userlist; +use \core_privacy\local\metadata\collection; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Privacy Subsystem implementation for H5P. + */ +class provider implements + // This plugin has data. + \core_privacy\local\metadata\provider, + \core_privacy\local\request\core_userlist_provider, + // This plugin currently implements the original plugin_provider interface. + \core_privacy\local\request\plugin\provider { + + use \core_privacy\local\legacy_polyfill; + + /** + * Get the list of contexts that contain user information for the specified user. + * + * @param collection $items The collection to add metadata to. + * + * @return collection The array of metadata + */ + public static function _get_metadata(collection $items) { + // Stores files using the Moodle file api. + $items->add_subsystem_link( + 'core_files', + [], + 'privacy:metadata:core_files' + ); + + // Stores grades using the Moodle gradebook api. + $items->add_subsystem_link( + 'core_grades', + [], + 'privacy:metadata:core_grades' + ); + + // Content user data table. + $items->add_database_table('hvp_content_user_data', [ + 'id' => 'privacy:metadata:hvp_content_user_data:id', + 'user_id' => 'privacy:metadata:hvp_content_user_data:user_id', + 'hvp_id' => 'privacy:metadata:hvp_content_user_data:hvp_id', + 'sub_content_id' => 'privacy:metadata:hvp_content_user_data:sub_content_id', + 'data_id' => 'privacy:metadata:hvp_content_user_data:data_id', + 'data' => 'privacy:metadata:hvp_content_user_data:data', + 'preloaded' => 'privacy:metadata:hvp_content_user_data:preloaded', + 'delete_on_content_change' => 'privacy:metadata:hvp_content_user_data:delete_on_content_change', + ], + 'privacy:metadata:hvp_content_user_data' + ); + + // Events table. + $items->add_database_table('hvp_events', [ + 'id' => 'privacy:metadata:hvp_events:id', + 'user_id' => 'privacy:metadata:hvp_events:user_id', + 'created_at' => 'privacy:metadata:hvp_events:created_at', + 'type' => 'privacy:metadata:hvp_events:type', + 'sub_type' => 'privacy:metadata:hvp_events:sub_type', + 'content_id' => 'privacy:metadata:hvp_events:content_id', + 'content_title' => 'privacy:metadata:hvp_events:content_title', + 'library_name' => 'privacy:metadata:hvp_events:library_name', + 'library_version' => 'privacy:metadata:hvp_events:library_version', + ], 'privacy:metadata:hvp_events'); + + // Xapi results table. + $items->add_database_table('hvp_xapi_results', [ + 'id' => 'privacy:metadata:hvp_xapi_results:id', + 'content_id' => 'privacy:metadata:hvp_xapi_results:content_id', + 'user_id' => 'privacy:metadata:hvp_xapi_results:user_id', + 'parent_id' => 'privacy:metadata:hvp_xapi_results:parent_id', + 'interaction_type' => 'privacy:metadata:hvp_xapi_results:interaction_type', + 'description' => 'privacy:metadata:hvp_xapi_results:description', + 'correct_responses_pattern' => 'privacy:metadata:hvp_xapi_results:correct_responses_pattern', + 'response' => 'privacy:metadata:hvp_xapi_results:response', + 'additionals' => 'privacy:metadata:hvp_xapi_results:additionals', + 'raw_score' => 'privacy:metadata:hvp_xapi_results:raw_score', + 'max_score' => 'privacy:metadata:hvp_xapi_results:max_score', + ], 'privacy:metadata:hvp_xapi_results'); + + return $items; + } + + /** + * Get the list of contexts where the specified user has attempted a quiz, or been involved with manual marking + * and/or grading of a quiz. + * + * @param int $userid The user to search. + * + * @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin. + */ + public static function _get_contexts_for_userid($userid) { + $contextlist = new contextlist(); + + // Context for content_user_data. + $cudsql = " + SELECT + c.id + FROM {course_modules} cm + INNER JOIN {modules} m ON m.id = cm.module + INNER JOIN {context} c ON c.instanceid = cm.id + INNER JOIN {hvp} h ON h.id = cm.instance + INNER JOIN {hvp_content_user_data} d ON h.id = d.hvp_id + WHERE m.name = 'hvp' + AND c.contextlevel = :contextlevel + AND d.user_id = :userid + "; + + $cudparams = array( + 'contextlevel' => CONTEXT_MODULE, + 'userid' => $userid, + ); + + $contextlist->add_from_sql($cudsql, $cudparams); + + // Context for xapi results. + $xapisql = " + SELECT + c.id + FROM {course_modules} cm + INNER JOIN {modules} m ON m.id = cm.module + INNER JOIN {context} c ON c.instanceid = cm.id + INNER JOIN {hvp} h ON h.id = cm.instance + INNER JOIN {hvp_xapi_results} x ON x.content_id = h.id + WHERE m.name = 'hvp' + AND c.contextlevel = :contextlevel + AND x.user_id = :userid + "; + + $xapiparams = array( + 'contextlevel' => CONTEXT_MODULE, + 'userid' => $userid, + ); + + $contextlist->add_from_sql($xapisql, $xapiparams); + + // Table hvp_events note: + // H5P events are not tied to instance ids, thus we cannot determine + // their context ids, they are considered to be user level context + // actions. + + return $contextlist; + } + + /** + * Export all user data for the specified user, in the specified contexts, using the supplied + * exporter instance. + * + * @param approved_contextlist $contextlist The approved contexts to export information for. + */ + public static function _export_user_data(approved_contextlist $contextlist) { + global $DB; + + if (!count($contextlist)) { + return; + } + + $user = $contextlist->get_user(); + $userid = $user->id; + list($contextsql, $contextparams) = $DB->get_in_or_equal($contextlist->get_contextids(), SQL_PARAMS_NAMED); + + $cud = self::get_exportable_content_user_data($contextsql, $contextparams, $userid); + $xapi = self::get_exportable_xapi_results($contextsql, $contextparams, $userid); + + // Export data with context. + foreach ($contextlist->get_contexts() as $context) { + $h5pdata = \core_privacy\local\request\helper::get_context_data($context, $contextlist->get_user()); + \core_privacy\local\request\helper::export_context_files($context, $contextlist->get_user()); + + // Add content user data. + if (!empty($cud[$context->id]) && !empty($cud[$context->id]->data)) { + $h5pdata->contentuserdata = $cud[$context->id]->data; + } + + // Add xAPI data. + if (!empty($xapi[$context->id])) { + $h5pdata->xapiresults = $xapi[$context->id]; + } + + writer::with_context($context)->export_data([], $h5pdata); + } + + // Write H5PEvents to subcontext of the user context. + $usercontext = \context_user::instance($userid); + $h5pevents = self::get_exportable_events($userid); + writer::with_context($usercontext)->export_data(['H5PEvents'], $h5pevents); + } + + /** + * Get exportable content user data for a given context and user + * + * @param $contextsql + * @param $contextparams + * @param $userid + * + * @return array Exportable and writable content user data + * @throws \dml_exception + */ + protected static function get_exportable_content_user_data($contextsql, $contextparams, $userid) { + global $DB; + + $cudsql = " + SELECT + c.id as contextid, + cm.id as cmid, + h.id, + h.name, + cud.data + FROM {context} c + INNER JOIN {course_modules} cm ON cm.id = c.instanceid AND c.contextlevel = :contextlevel + INNER JOIN {modules} m ON m.id = cm.module AND m.name = :modname + INNER JOIN {hvp} h ON h.id = cm.instance + INNER JOIN {hvp_content_user_data} cud ON cud.hvp_id = h.id + WHERE cud.user_id = :userid + AND c.id {$contextsql} + "; + + $cudparams = [ + 'contextlevel' => CONTEXT_MODULE, + 'modname' => 'hvp', + 'userid' => $userid, + ]; + $cudparams += $contextparams; + + $cudresult = $DB->get_recordset_sql($cudsql, $cudparams); + $cud = []; + foreach ($cudresult as $record) { + $cud[$record->contextid] = $record; + } + $cudresult->close(); + + return $cud; + } + + /** + * Get exportable xapi results from context and user id + * + * @param $contextsql + * @param $contextparams + * @param $userid + * + * @return array Exportable and writable xapi results + * @throws \dml_exception + */ + protected static function get_exportable_xapi_results($contextsql, $contextparams, $userid) { + global $DB; + + $xapisql = " + SELECT + c.id as contextid, + cm.id as cmid, + h.id, + h.name, + x.content_id, + x.parent_id, + x.description, + x.response, + x.additionals, + x.raw_score, + x.max_score + FROM {context} c + INNER JOIN {course_modules} cm ON cm.id = c.instanceid AND c.contextlevel = :contextlevel + INNER JOIN {modules} m ON m.id = cm.module AND m.name = :modname + INNER JOIN {hvp} h ON h.id = cm.instance + INNER JOIN {hvp_xapi_results} x ON x.content_id = h.id + WHERE x.user_id = :userid + AND c.id {$contextsql} + "; + + $xapiparams = [ + 'contextlevel' => CONTEXT_MODULE, + 'modname' => 'hvp', + 'userid' => $userid, + ]; + $xapiparams += $contextparams; + + $xapiresult = $DB->get_recordset_sql($xapisql, $xapiparams); + $xapi = []; + foreach ($xapiresult as $record) { + $h5pxapi = (object) array(); + if (!empty($record->content_id)) { + $h5pxapi->content_id = $record->content_id; + } + + if (!empty($record->parent_id)) { + $h5pxapi->parent_id = $record->parent_id; + } + + if (!empty($record->description)) { + $h5pxapi->description = $record->description; + } + + if (!empty($record->response)) { + $h5pxapi->response = $record->response; + } + + if (!empty($record->additionals)) { + $h5pxapi->additionals = $record->additionals; + } + + if (!empty($record->raw_score)) { + $h5pxapi->raw_score = $record->raw_score; + } + + if (!empty($record->max_score)) { + $h5pxapi->max_score = $record->max_score; + } + + $xapi[$record->contextid][] = $h5pxapi; + } + $xapiresult->close(); + + return $xapi; + } + + /** + * Get exportable H5P events from user id + * + * @param $userid + * + * @return object Exportable and writable H5P events + * @throws \dml_exception + */ + protected static function get_exportable_events($userid) { + global $DB; + + $eventssql = " + SELECT * + FROM {hvp_events} + WHERE user_id = :userid + "; + + $eventsparams = [ + 'userid' => $userid, + ]; + + $h5peventsresults = $DB->get_recordset_sql($eventssql, $eventsparams); + $h5pevents = (object) [ + 'events' => [], + ]; + foreach ($h5peventsresults as $event) { + $h5pevents->events[] = $event; + } + $h5peventsresults->close(); + + return $h5pevents; + } + + /** + * Delete all data for all users in the specified context. + * + * @param \context $context The specific context to delete data for. + */ + public static function _delete_data_for_all_users_in_context(\context $context) { + global $DB; + + if ($context->contextlevel == CONTEXT_USER) { + // Delete all H5P events. + $DB->delete_records('hvp_events'); + return; + } else if ($context->contextlevel != CONTEXT_MODULE) { + return; + } + + $cm = get_coursemodule_from_id('hvp', $context->instanceid); + if (!$cm) { + return; + } + + // Delete content user data. + $DB->delete_records('hvp_content_user_data', [ + 'hvp_id' => $cm->instance, + ]); + + // Delete xAPI results. + $DB->delete_records('hvp_xapi_results', [ + 'content_id' => $cm->instance, + ]); + } + + /** + * Delete all user data for the specified user, in the specified contexts. + * + * @param approved_contextlist $contextlist The approved contexts and user information to delete information for. + */ + public static function _delete_data_for_user(approved_contextlist $contextlist) { + global $DB; + + $count = $contextlist->count(); + if (empty($count)) { + return; + } + + $userid = $contextlist->get_user()->id; + foreach ($contextlist->get_contexts() as $context) { + $cm = get_coursemodule_from_id('hvp', $context->instanceid); + + if (!$cm) { + continue; + } + + // Delete content user data. + $DB->delete_records('hvp_content_user_data', [ + 'hvp_id' => $cm->instance, + 'user_id' => $userid, + ]); + + // Delete xAPI results. + $DB->delete_records('hvp_xapi_results', [ + 'content_id' => $cm->instance, + 'user_id' => $userid, + ]); + } + + // Delete H5P events. + $DB->delete_records('hvp_events', [ + 'user_id' => $userid, + ]); + } + + /** + * Get the list of users who have data within a context. + * + * @param userlist $userlist The userlist containing the list of users who have data in this context/plugin combination. + */ + public static function get_users_in_context(userlist $userlist) { + $context = $userlist->get_context(); + if (!is_a($context, \context_module::class)) { + return; + } + + $sql = " + SELECT d.user_id + FROM {course_modules} cm + INNER JOIN {modules} m ON m.id = cm.module AND m.name = 'hvp' + INNER JOIN {context} c ON c.instanceid = cm.id + INNER JOIN {hvp} h ON h.id = cm.instance + INNER JOIN {hvp_content_user_data} d ON h.id = d.hvp_id + WHERE c.contextlevel = :contextlevel AND c.id = :contextid"; + + $params = [ + 'contextlevel' => CONTEXT_MODULE, + 'contextid' => $context->id, + ]; + $userlist->add_from_sql('user_id', $sql, $params); + + $sql = " + SELECT + x.user_id + FROM {course_modules} cm + INNER JOIN {modules} m ON m.id = cm.module AND m.name = 'hvp' + INNER JOIN {context} c ON c.instanceid = cm.id + INNER JOIN {hvp} h ON h.id = cm.instance + INNER JOIN {hvp_xapi_results} x ON x.content_id = h.id + WHERE c.contextlevel = :contextlevel AND c.id = :contextid"; + $userlist->add_from_sql('user_id', $sql, $params); + } + + /** + * Delete multiple users within a single context. + * + * @param approved_userlist $userlist The approved context and user information to delete information for. + */ + public static function delete_data_for_users(approved_userlist $userlist) { + global $DB; + $context = $userlist->get_context(); + if (!is_a($context, \context_module::class)) { + return; + } + $cm = get_coursemodule_from_id('hvp', $context->instanceid); + + // Prepare SQL to gather all completed IDs. + $userids = $userlist->get_userids(); + list($insql, $inparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED); + + $inparams['hvpid'] = $cm->instance; + + $DB->delete_records_select( + 'hvp_content_user_data', + "hvp_id = :hvpid AND user_id $insql", + $inparams + ); + + $DB->delete_records_select( + 'hvp_xapi_results', + "hvp_id = :hvpid AND user_id $insql", + $inparams + ); + + } +} diff --git a/classes/results.php b/classes/results.php new file mode 100644 index 0000000..c958a4d --- /dev/null +++ b/classes/results.php @@ -0,0 +1,379 @@ +. + +/** + * The mod_hvp file storage + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; +defined('MOODLE_INTERNAL') || die(); + +/** + * The mod_hvp file storage class. + * + * @package mod_hvp + * @since Moodle 2.7 + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class results { + + // Type specific inputs. + protected $contentid; + + // Generic result inputs. + protected $offset, $limit, $orderby, $orderdir, $filters; + + /** + * Start handling results by filtering input parameters. + */ + public function __construct() { + $this->filter_input(); + } + + /** + * Filter and load input parameters + * + * @throws \coding_exception + */ + protected function filter_input() { + // Type specifc. + $this->contentid = optional_param('content_id', 0, PARAM_INT); + + // Used to handle pagination. + $this->offset = optional_param('offset', 0, PARAM_INT); + + // Max number of items to display on one page. + $this->limit = optional_param('limit', 20, PARAM_INT); + if ($this->limit > 100) { + // Avoid wrong usage. + throw new \coding_exception('limit to high'); + } + + // Field to order by. + $this->orderby = optional_param('sortBy', 0, PARAM_INT); + + // Direction to order in. + $this->orderdir = optional_param('sortDir', 0, PARAM_INT); + + // List of fields to filter results on. + $this->filters = optional_param_array('filters', array(), PARAM_RAW_TRIMMED); + } + + /** + * Print results data + */ + public function print_results() { + global $USER; + + $cm = get_coursemodule_from_instance('hvp', $this->contentid); + if (!$cm) { + \H5PCore::ajaxError('No such content'); + http_response_code(404); + return; + } + + // Check permission. + $context = \context_module::instance($cm->id); + $viewownresults = has_capability('mod/hvp:viewresults', $context); + $viewallresults = has_capability('mod/hvp:viewallresults', $context); + if (!$viewownresults && !$viewallresults) { + \H5PCore::ajaxError(get_string('nopermissiontoviewresult', 'hvp')); + http_response_code(403); + return; + } + + // Only get own results if can't view all. + $uid = $viewallresults ? null : (int)$USER->id; + $results = $this->get_results($uid); + $rows = $this->get_human_readable_results($results, $cm->course); + + header('Cache-Control: no-cache'); + header('Content-type: application/json'); + print json_encode(array( + 'num' => $this->get_results_num(), + 'rows' => $rows + )); + } + + /** + * Constructs human readable results + * + * @param $results + * @param $course + * + * @return array + */ + private function get_human_readable_results($results, $course) { + // Make data readable for humans. + $rows = array(); + foreach ($results as $result) { + $userlink = \html_writer::link( + new \moodle_url('/user/view.php', array( + 'id' => $result->id, + 'course' => $course + )), + \fullname($result) + ); + + $reviewlink = '—'; + + // Check if result has xAPI data. + if ($result->xapiid) { + $reviewlink = \html_writer::link( + new \moodle_url('/mod/hvp/review.php', + array( + 'id' => $this->contentid, + 'course' => $course, + 'user' => $result->id + ) + ), + get_string('viewreportlabel', 'hvp') + ); + } else if ($result->rawgrade !== null) { + $reviewlink = get_string('reportnotsupported', 'hvp'); + } + + $rows[] = array( + $userlink, + $result->rawgrade === null ? '—' : (int) $result->rawgrade, + $result->rawgrade === null ? '—' : (int) $result->rawgrademax, + empty($result->timemodified) ? '—' : date('Y/m/d – H:i', $result->timemodified), + $reviewlink + ); + } + + return $rows; + } + + /** + * Builds the SQL query required to retrieve results for the given + * interactive content. + * + * @param int $uid Only get results for uid + * + * @throws \coding_exception + * @return array + */ + protected function get_results($uid=null) { + // Add extra fields, joins and where for the different result lists. + if ($this->contentid !== 0) { + list($fields, $join, $where, $order, $args) = $this->get_content_sql($uid); + } else { + throw new \coding_exception('missing content_id'); + } + + // Xapi join. + $where[] = "x.content_id = ?"; + $args[] = $this->contentid; + + // Build where statement. + $where[] = "i.itemtype = 'mod'"; + $where[] = "i.itemmodule = 'hvp'"; + $where[] = "x.parent_id IS NULL"; + $where = 'WHERE ' . implode(' AND ', $where); + + // Order results by the select column and direction. + $order[] = 'g.rawgrade'; + $order[] = 'g.rawgrademax'; + $order[] = 'g.timemodified'; + $orderby = $this->get_order_sql($order); + + // Join on xAPI results. + $join .= ' LEFT JOIN {hvp_xapi_results} x ON g.userid = x.user_id'; + $groupby = ' GROUP BY i.id, g.id, u.id, i.iteminstance, x.id'; + + // Get from statement. + $from = $this->get_from_sql(); + + // Execute query and get results. + return $this->get_sql_results(" + SELECT u.id, + i.id AS gradeitemid, + g.id AS gradeid, + {$fields} + g.rawgrade, + g.rawgrademax, + g.timemodified, + x.id as xapiid + {$from} + {$join} + {$where} + {$groupby} + {$orderby} + ", $args, + $this->offset, + $this->limit); + } + + /** + * Build and execute the query needed to tell the number of total results. + * This is used to create pagination. + * + * @return int + */ + protected function get_results_num() { + global $DB; + + list(, $join, $where, , $args) = $this->get_content_sql(); + $where[] = "i.itemtype = 'mod'"; + $where[] = "i.itemmodule = 'hvp'"; + $where = 'WHERE ' . implode(' AND ', $where); + $from = $this->get_from_sql(); + + return (int) $DB->get_field_sql("SELECT COUNT(i.id) {$from} {$join} {$where}", $args); + } + + /** + * Builds the order part of the SQL query. + * + * @param array $fields Fields allowed to order by + * @throws \coding_exception + * @return string + */ + protected function get_order_sql($fields) { + // Make sure selected order field is valid. + if (!isset($fields[$this->orderby])) { + throw new \coding_exception('invalid order field'); + } + + // Find selected sortable field. + $field = $fields[$this->orderby]; + + if (is_object($field)) { + // Some fields are reverse sorted by default, e.g. text fields. + // This feels more natural for the humans. + if (!empty($field->reverse)) { + $this->orderdir = !$this->orderdir; + } + + $field = $field->name; + } + + $dir = ($this->orderdir ? 'ASC' : 'DESC'); + if ($field === 'u.firstname') { + // Order by all user name fields. + $field = implode(" {$dir}, ", self::get_ordered_user_name_fields()); + } + + return "ORDER BY {$field} {$dir}"; + } + + /** + * Get from part of the SQL query. + * + * @return string + */ + protected function get_from_sql() { + return " FROM {grade_items} i LEFT JOIN {grade_grades} g ON i.id = g.itemid LEFT JOIN {user} u ON u.id = g.userid"; + } + + /** + * Get all user name fields in display order. + * + * @param string $prefix Optional table prefix to prepend to all fields + * @return array + */ + public static function get_ordered_user_name_fields($prefix = 'u.') { + static $ordered; + + if (empty($ordered)) { + $available = \get_all_user_name_fields(); + $displayname = \fullname((object)$available); + if (empty($displayname)) { + $ordered = array("{$prefix}firstname", "{$prefix}lastname"); + } else { + // Find fields in order. + foreach ($available as $key => $value) { + $ordered[] = $prefix . $available[$key]; + } + } + } + + return $ordered; + } + + /** + * Get the different parts needed to create the SQL for getting results + * belonging to a specifc content. + * (An alternative to this could be getting all the results for a + * specified user.) + * + * @param int $uid Only get users with this id + * @return array $fields, $join, $where, $order, $args + */ + protected function get_content_sql($uid=null) { + global $DB; + + $usernamefields = implode(', ', self::get_ordered_user_name_fields()); + $fields = " {$usernamefields}, "; + $join = ""; + $where = array("i.iteminstance = ?"); + $args = array($this->contentid); + + // Only get entries with own user id. + if (isset($uid)) { + array_push($where, "u.id = ?"); + array_push($args, $uid); + } + + if (isset($this->filters[0])) { + $keywordswhere = array(); + + // Split up keywords using whitespace and comma. + foreach (preg_split("/[\s,]+/", $this->filters[0]) as $keyword) { + // Search all user name fields. + $usernamewhere = array(); + foreach (self::get_ordered_user_name_fields() as $usernamefield) { + $usernamewhere[] = $DB->sql_like($usernamefield, '?', false); + $args[] = '%' . $keyword . '%'; + } + + // Add user name fields where to keywords where. + if (!empty($usernamewhere)) { + $keywordswhere[] = '(' . implode(' OR ', $usernamewhere) . ')'; + } + } + + // Add keywords where to SQL where. + if (!empty($keywordswhere)) { + $where[] = '(' . implode(' AND ', $keywordswhere) . ')'; + } + } + $order = array((object) array( + 'name' => 'u.firstname', + 'reverse' => true + )); + + return array($fields, $join, $where, $order, $args); + } + + /** + * Execute given query and return any results + * + * @param string $query + * @param array $args Used for placeholders + * @return array + */ + protected function get_sql_results($query, $args, $limitfrom = 0, $limitnum = 0) { + global $DB; + return $DB->get_records_sql($query, $args, $limitfrom, $limitnum); + } +} diff --git a/classes/task/look_for_updates.php b/classes/task/look_for_updates.php new file mode 100644 index 0000000..9f2aa09 --- /dev/null +++ b/classes/task/look_for_updates.php @@ -0,0 +1,47 @@ +. +/** + * Defines the task which looks for H5P updates. + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp\task; + +defined('MOODLE_INTERNAL') || die(); + +/** + * The mod_hvp look for updates task class + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class look_for_updates extends \core\task\scheduled_task { + public function get_name() { + return get_string('lookforupdates', 'mod_hvp'); + } + + public function execute() { + // Check to make sure external communications hasn't been disabled. + if (get_config('mod_hvp', 'hub_is_enabled') || get_config('mod_hvp', 'send_usage_statistics')) { + $core = \mod_hvp\framework::instance(); + $core->fetchLibrariesMetadata(); + } + } +} diff --git a/classes/task/remove_old_auth_tokens.php b/classes/task/remove_old_auth_tokens.php new file mode 100644 index 0000000..4e102cf --- /dev/null +++ b/classes/task/remove_old_auth_tokens.php @@ -0,0 +1,52 @@ +. + +/** + * Defines the task which removes old mobile auth tokens from the hvp_auth table. + * + * @package mod_hvp + * @copyright 2019 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp\task; + +use mod_hvp\mobile_auth; + +defined('MOODLE_INTERNAL') || die(); + +/** + * The mod_hvp remove old auth tokens class + * + * @package mod_hvp + * @copyright 2019 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class remove_old_auth_tokens extends \core\task\scheduled_task { + public function get_name() { + return get_string('removeoldmobileauthentries', 'mod_hvp'); + } + + public function execute() { + global $DB; + + require_once(__DIR__ . '/../../autoloader.php'); + $deletethreshold = time() - mobile_auth::VALID_TIME; + $DB->delete_records_select('hvp_auth', 'created_at < :threshold', array( + 'threshold' => $deletethreshold, + )); + } +} diff --git a/classes/task/remove_old_log_entries.php b/classes/task/remove_old_log_entries.php new file mode 100644 index 0000000..6d8ae83 --- /dev/null +++ b/classes/task/remove_old_log_entries.php @@ -0,0 +1,48 @@ +. +/** + * Defines the task which looks for H5P updates. + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp\task; + +defined('MOODLE_INTERNAL') || die(); + +/** + * The mod_hvp look for updates task class + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class remove_old_log_entries extends \core\task\scheduled_task { + public function get_name() { + return get_string('removeoldlogentries', 'mod_hvp'); + } + + public function execute() { + global $DB; + + require_once(__DIR__ . '/../../autoloader.php'); + // @codingStandardsIgnoreLine + $olderthan = (time() - \H5PEventBase::$log_time); + $DB->execute("DELETE FROM {hvp_events} WHERE created_at < {$olderthan}"); + } +} diff --git a/classes/task/remove_tmpfiles.php b/classes/task/remove_tmpfiles.php new file mode 100644 index 0000000..7a5e7a5 --- /dev/null +++ b/classes/task/remove_tmpfiles.php @@ -0,0 +1,63 @@ +. +/** + * Defines the task which removes old tmp files + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp\task; + +defined('MOODLE_INTERNAL') || die(); + +/** + * The mod_hvp look for updates task class + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class remove_tmpfiles extends \core\task\scheduled_task { + public function get_name() { + return get_string('removetmpfiles', 'mod_hvp'); + } + + public function execute() { + global $DB; + $tmpfiles = $DB->get_records_sql( + "SELECT f.id + FROM {hvp_tmpfiles} tf + JOIN {files} f ON f.id = tf.id + WHERE f.timecreated < ?", + array(time() - 86400) + ); + if (empty($tmpfiles)) { + return; // Nothing to clean up. + } + + $fs = get_file_storage(); + foreach ($tmpfiles as $tmpfile) { + // Delete file. + $file = $fs->get_file_by_id($tmpfile->id); + $file->delete(); + + // Remove tmpfile entry. + $DB->delete_records('hvp_tmpfiles', array('id' => $tmpfile->id)); + } + } +} diff --git a/classes/upload_libraries_form.php b/classes/upload_libraries_form.php new file mode 100644 index 0000000..3142676 --- /dev/null +++ b/classes/upload_libraries_form.php @@ -0,0 +1,142 @@ +. + +/** + * \mod_hvp\upload_libraries_form class + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; + +defined('MOODLE_INTERNAL') || die(); + +// Load moodleform class. +require_once("$CFG->libdir/formslib.php"); + +/** + * Form to upload new H5P libraries and upgrade existing once + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class upload_libraries_form extends \moodleform { + + /** + * Define form elements + */ + public function definition() { + global $CFG, $OUTPUT; + + // Get form. + $mform = $this->_form; + + // Add File Picker. + $mform->addElement('filepicker', 'h5pfile', get_string('h5pfile', 'hvp'), null, + array('maxbytes' => $CFG->maxbytes, 'accepted_types' => '*.h5p')); + + // Add options. + $mform->addElement('checkbox', + 'onlyupdate', + get_string('options', 'hvp'), + get_string('onlyupdate', 'hvp'), + array('group' => 1) + ); + $mform->setType('onlyupdate', PARAM_BOOL); + $mform->setDefault('onlyupdate', false); + + $mform->addElement('checkbox', + 'disablefileextensioncheck', + '', + get_string('disablefileextensioncheck', 'hvp'), + array('group' => 1) + ); + $mform->setType('disablefileextensioncheck', PARAM_BOOL); + $mform->setDefault('disablefileextensioncheck', false); + + $notification = $OUTPUT->notification( + get_string('disablefileextensioncheckwarning', 'hvp'), + 'notifymessage' + ); + $mform->addElement('static', '', '', $notification); + + // Upload button. + $this->add_action_buttons(false, get_string('upload', 'hvp')); + } + + /** + * Preprocess incoming data + * + * @param array $defaultvalues default values for form + */ + public function data_preprocessing(&$defaultvalues) { + // Aaah.. we meet again h5pfile!. + $draftitemid = file_get_submitted_draft_itemid('h5pfile'); + file_prepare_draft_area($draftitemid, $this->context->id, 'mod_hvp', 'package', 0); + $defaultvalues['h5pfile'] = $draftitemid; + } + + /** + * Validate incoming data + * + * @param array $data array of ("fieldname"=>value) of submitted data + * @param array $files array of uploaded files "element_name"=>tmp_file_path + * @return array of "element_name"=>"error_description" if there are errors, + * or an empty array if everything is OK (true allowed for backwards compatibility too). + */ + public function validation($data, $files) { + global $CFG; + $errors = array(); + + // Check for file. + if (empty($data['h5pfile'])) { + $errors['h5pfile'] = get_string('required'); + return $errors; + } + + $files = $this->get_draft_files('h5pfile'); + if (count($files) < 1) { + $errors['h5pfile'] = get_string('required'); + return $errors; + } + + // Add file so that core framework can find it. + $file = reset($files); + $interface = \mod_hvp\framework::instance('interface'); + + $path = $CFG->tempdir . uniqid('/hvp-'); + $interface->getUploadedH5pFolderPath($path); + $path .= '.h5p'; + $interface->getUploadedH5pPath($path); + $file->copy_content_to($path); + + // Validate package. + $h5pvalidator = \mod_hvp\framework::instance('validator'); + if (!$h5pvalidator->isValidPackage(true, isset($data['onlyupdate']))) { + // Errors while validating the package. + $errors = array_map(function ($message) { + return $message->message; + }, framework::messages('error')); + + $messages = array_merge(framework::messages('info'), $errors); + $errors['h5pfile'] = implode('
', $messages); + } + return $errors; + } +} diff --git a/classes/user_grades.php b/classes/user_grades.php new file mode 100644 index 0000000..3981875 --- /dev/null +++ b/classes/user_grades.php @@ -0,0 +1,226 @@ +. + +/** + * The mod_hvp user grades + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +namespace mod_hvp; + +defined('MOODLE_INTERNAL') || die(); + +require(__DIR__ . '/../lib.php'); + +/** + * Handles grade storage for users + * @package mod_hvp + */ +class user_grades { + + public static function handle_ajax() { + global $DB, $USER, $CFG; + + if (!\H5PCore::validToken('result', required_param('token', PARAM_RAW))) { + \H5PCore::ajaxError(get_string('invalidtoken', 'hvp')); + return; + } + + $cm = get_coursemodule_from_id('hvp', required_param('contextId', PARAM_INT)); + if (!$cm) { + \H5PCore::ajaxError('No such content'); + http_response_code(404); + return; + } + + // Content parameters. + $score = required_param('score', PARAM_INT); + $maxscore = required_param('maxScore', PARAM_INT); + + // Check permission. + $context = \context_module::instance($cm->id); + if (!has_capability('mod/hvp:saveresults', $context)) { + \H5PCore::ajaxError(get_string('nopermissiontosaveresult', 'hvp')); + http_response_code(403); + return; + } + + // Get hvp data from content. + $hvp = $DB->get_record('hvp', array('id' => $cm->instance)); + if (!$hvp) { + \H5PCore::ajaxError('No such content'); + http_response_code(404); + return; + } + + // Create grade object and set grades. + $grade = (object) array( + 'userid' => $USER->id + ); + + // Set grade using Gradebook API. + $hvp->cmidnumber = $cm->idnumber; + $hvp->name = $cm->name; + $hvp->rawgrade = $score; + $hvp->rawgrademax = $maxscore; + hvp_grade_item_update($hvp, $grade); + + // Get content info for log. + $content = $DB->get_record_sql( + "SELECT c.name AS title, l.machine_name AS name, l.major_version, l.minor_version + FROM {hvp} c + JOIN {hvp_libraries} l ON l.id = c.main_library_id + WHERE c.id = ?", + array($hvp->id) + ); + + require_once($CFG->libdir.'/completionlib.php'); + + // Load Course. + $course = $DB->get_record('course', array('id' => $cm->course)); + $completion = new \completion_info( $course ); + + if ( $completion->is_enabled( $cm) ) { + $completion->update_state($cm, COMPLETION_COMPLETE); + } + + // Log results set event. + new \mod_hvp\event( + 'results', 'set', + $hvp->id, $content->title, + $content->name, $content->major_version . '.' . $content->minor_version + ); + + // Trigger Moodle event for async notification messages. + $event = \mod_hvp\event\attempt_submitted::create([ + 'context' => $context, + ]); + $event->trigger(); + + \H5PCore::ajaxSuccess(); + } + + /** + * Since the subcontent types do not have their own row in the table, + * we use the hvp_results_table as a 'staging area' to set and get + * dynamically graded scores. + */ + public static function handle_dynamic_grading() { + global $DB; + + if (!\H5PCore::validToken('result', required_param('token', PARAM_RAW))) { + \H5PCore::ajaxError(get_string('invalidtoken', 'hvp')); + return; + } + + $cm = get_coursemodule_from_id('hvp', required_param('contextId', PARAM_INT)); + if (!$cm) { + \H5PCore::ajaxError('No such content'); + http_response_code(404); + return; + } + + // Content parameters. + $subcontentid = required_param('subcontent_id', PARAM_INT); + $score = required_param('score', PARAM_INT); + + // Update the answer's score. + $data = (object) [ + 'id' => $subcontentid, + 'raw_score' => $score + ]; + $DB->update_record('hvp_xapi_results', $data, false); + + // Load freshly updated record. + $answer = $DB->get_record('hvp_xapi_results', array('id' => $subcontentid)); + + // Get the sum of all the OEQ scores with the same parent. + $totalgradablesscore = intval($DB->get_field_sql( + "SELECT SUM(raw_score) + FROM {hvp_xapi_results} + WHERE parent_id = ? + AND additionals = ?", array($answer->parent_id, + '{"extensions":{"https:\/\/h5p.org\/x-api\/h5p-machine-name":"H5P.FreeTextQuestion"}}') + )); + + // Get the original raw score from the main content type. + $baseanswer = $DB->get_record('hvp_xapi_results', array( + 'id' => $answer->parent_id + )); + + // Get hvp data from content. + $hvp = $DB->get_record('hvp', array('id' => $cm->instance)); + if (!$hvp) { + \H5PCore::ajaxError('No such content'); + http_response_code(404); + return; + } + + // Set grade using Gradebook API. + $hvp->rawgrade = $baseanswer->raw_score + $totalgradablesscore; + $hvp->rawgrademax = $baseanswer->max_score; + hvp_grade_item_update($hvp, (object) array( + 'userid' => $answer->user_id + )); + + // Get the num of ungraded OEQ answers. + $numungraded = intval($DB->get_field_sql( + "SELECT COUNT(*) + FROM {hvp_xapi_results} + WHERE parent_id = ? + AND raw_score IS NULL + AND additionals = ?", array($answer->parent_id, + '{"extensions":{"https:\/\/h5p.org\/x-api\/h5p-machine-name":"H5P.FreeTextQuestion"}}') + )); + + $response = [ + 'score' => $answer->raw_score, + 'maxScore' => $answer->max_score, + 'totalUngraded' => $numungraded, + ]; + \H5PCore::ajaxSuccess($response); + } + + /** + * Fetch score/maxScore for ungraded item + number of ungraded items. + */ + public static function return_subcontent_grade() { + global $DB; + + // Content parameters. + $subcontentid = required_param('subcontent_id', PARAM_INT); + $answer = $DB->get_record('hvp_xapi_results', array('id' => $subcontentid)); + + // Get the num of ungraded OEQ answers. + $numungraded = intval($DB->get_field_sql( + "SELECT COUNT(*) + FROM {hvp_xapi_results} + WHERE parent_id = ? + AND raw_score IS NULL + AND additionals = ?", array($answer->parent_id, + '{"extensions":{"https:\/\/h5p.org\/x-api\/h5p-machine-name":"H5P.FreeTextQuestion"}}') + )); + + $response = [ + 'score' => $answer->raw_score, + 'maxScore' => $answer->max_score, + 'totalUngraded' => $numungraded, + ]; + \H5PCore::ajaxSuccess($response); + } +} diff --git a/classes/view_assets.php b/classes/view_assets.php new file mode 100644 index 0000000..8ce3442 --- /dev/null +++ b/classes/view_assets.php @@ -0,0 +1,363 @@ +. + +/** + * The mod_hvp view assets convenience class for viewing and embedding H5Ps + * + * @package mod_hvp + * @copyright 2017 Joubel + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; + +use moodle_url; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Handles finding and attaching assets for view + * @package mod_hvp + */ +class view_assets { + + private $cm; + private $course; + private $core; + private $content; + private $jsrequires; + private $cssrequires; + + protected $settings; + protected $embedtype; + protected $files; + + public function __construct($cm, $course, $options = []) { + $this->cm = $cm; + $this->course = $course; + $this->core = framework::instance(); + $this->content = $this->core->loadContent($cm->instance); + $this->settings = hvp_get_core_assets(\context_module::instance($cm->id)); + $this->jsrequires = []; + $this->cssrequires = []; + + $context = \context_module::instance($this->cm->id); + $displayoptions = $this->core->getDisplayOptionsForView($this->content['disable'], $context->instanceid); + if (isset($options['disabledownload']) && $options['disabledownload']) { + $displayoptions[\H5PCore::DISPLAY_OPTION_DOWNLOAD] = false; + } + if (isset($options['disablefullscreen']) && $options['disablefullscreen']) { + $this->settings['fullscreenDisabled'] = true; + } + + // Add JavaScript settings for this content. + $cid = 'cid-' . $this->content['id']; + $root = self::getsiteroot(); + $this->settings['contents'][ $cid ] = array( + 'library' => \H5PCore::libraryToString($this->content['library']), + 'jsonContent' => $this->getfilteredparameters(), + 'fullScreen' => $this->content['library']['fullscreen'], + 'exportUrl' => $this->getexportsettings($displayoptions[ \H5PCore::DISPLAY_OPTION_DOWNLOAD ]), + 'embedCode' => $this->getembedcode($displayoptions[ \H5PCore::DISPLAY_OPTION_EMBED ]), + 'resizeCode' => $this->getresizecode($displayoptions[ \H5PCore::DISPLAY_OPTION_EMBED ]), + 'title' => $this->content['title'], + 'displayOptions' => $displayoptions, + 'url' => "{$root}/mod/hvp/view.php?id={$this->cm->id}", + 'contentUrl' => "{$root}/pluginfile.php/{$context->id}/mod_hvp/content/{$this->content['id']}", + 'metadata' => $this->content['metadata'], + 'contentUserData' => array( + 0 => content_user_data::load_pre_loaded_user_data($this->content['id']) + ) + ); + + $this->embedtype = isset($options->forceembedtype) ? $options->forceembedtype : \H5PCore::determineEmbedType( + $this->content['embedType'], $this->content['library']['embedTypes'] + ); + + $this->files = $this->getdependencyfiles(); + $this->generateassets(); + } + + /** + * Filtered and potentially altered parameters + * + * @return Object|string + */ + private function getfilteredparameters() { + global $PAGE; + + $safeparameters = $this->core->filterParameters($this->content); + $decodedparams = json_decode($safeparameters); + $hvpoutput = $PAGE->get_renderer('mod_hvp'); + $hvpoutput->hvp_alter_filtered_parameters( + $decodedparams, + $this->content['library']['name'], + $this->content['library']['majorVersion'], + $this->content['library']['minorVersion'] + ); + $safeparameters = json_encode($decodedparams); + + return $safeparameters; + } + + /** + * Export path for settings + * + * @param $downloadenabled + * + * @return string + */ + private function getexportsettings($downloadenabled) { + global $CFG; + + if ( ! $downloadenabled || (isset($CFG->mod_hvp_export) && $CFG->mod_hvp_export === false)) { + return ''; + } + + $modulecontext = \context_module::instance($this->cm->id); + $slug = $this->content['slug'] ? $this->content['slug'] . '-' : ''; + $url = \moodle_url::make_pluginfile_url($modulecontext->id, + 'mod_hvp', + 'exports', + '', + '', + "{$slug}{$this->content['id']}.h5p" + ); + + return $url->out(); + } + + /** + * Embed code for settings + * + * @param $embedenabled + * + * @return string + */ + private function getembedcode($embedenabled) { + if ( ! $embedenabled) { + return ''; + } + + $root = self::getsiteroot(); + $embedurl = new \moodle_url("{$root}/mod/hvp/embed.php?id={$this->cm->id}"); + $title = isset($this->content['metadata']['a11yTitle']) + ? $this->content['metadata']['a11yTitle'] + : (isset($this->content['metadata']['title']) + ? $this->content['metadata']['title'] + : '' + ); + + return ""; + } + + /** + * Resizing script for settings + * + * @param $embedenabled + * + * @return string + */ + private function getresizecode($embedenabled) { + if ( ! $embedenabled) { + return ''; + } + + $resizeurl = new \moodle_url(self::getsiteroot() . '/mod/hvp/library/js/h5p-resizer.js'); + + return ""; + } + + /** + * Finds library dependencies of view + * + * @return array Files that the view has dependencies to + */ + private function getdependencyfiles() { + global $PAGE; + + $preloadeddeps = $this->core->loadContentDependencies($this->content['id'], 'preloaded'); + $files = $this->core->getDependenciesFiles($preloadeddeps); + + // Add additional asset files if required. + $hvpoutput = $PAGE->get_renderer('mod_hvp'); + $hvpoutput->hvp_alter_scripts($files['scripts'], $preloadeddeps, $this->embedtype); + $hvpoutput->hvp_alter_styles($files['styles'], $preloadeddeps, $this->embedtype); + + return $files; + } + + /** + * Generates assets depending on embed type + */ + private function generateassets() { + if ($this->embedtype === 'div') { + $context = \context_system::instance(); + $hvppath = "/pluginfile.php/{$context->id}/mod_hvp"; + + // Schedule JavaScripts for loading through Moodle. + foreach ($this->files['scripts'] as $script) { + $url = $script->path . $script->version; + + // Add URL prefix if not external. + $isexternal = strpos($script->path, '://'); + if ($isexternal === false) { + $url = $hvppath . $url; + } + $this->settings['loadedJs'][] = $url; + $this->jsrequires[] = new \moodle_url($isexternal ? $url : self::getsiteroot() . $url); + } + + // Schedule stylesheets for loading through Moodle. + foreach ($this->files['styles'] as $style) { + $url = $style->path . $style->version; + + // Add URL prefix if not external. + $isexternal = strpos($style->path, '://'); + if ($isexternal === false) { + $url = $hvppath . $url; + } + $this->settings['loadedCss'][] = $url; + $this->cssrequires[] = new \moodle_url($isexternal ? $url : self::getsiteroot() . $url); + } + } else { + // JavaScripts and stylesheets will be loaded through h5p.js. + $cid = 'cid-' . $this->content['id']; + $this->settings['contents'][ $cid ]['scripts'] = $this->core->getAssetsUrls($this->files['scripts']); + $this->settings['contents'][ $cid ]['styles'] = $this->core->getAssetsUrls($this->files['styles']); + } + } + + public function getcontent() { + return $this->content; + } + + /** + * Logs viewed to all handlers + */ + public function logviewed() { + $this->logh5pviewedevent(); + $this->logcompletioncriteriaviewed(); + $this->triggermoduleviewedevent(); + } + + /** + * Logs content viewed to H5P core + */ + public function logh5pviewedevent() { + new event( + 'content', null, + $this->content['id'], $this->content['title'], + $this->content['library']['name'], + $this->content['library']['majorVersion'] . '.' . $this->content['library']['minorVersion'] + ); + } + + /** + * Logs activity viewed to completion criterias + */ + public function logcompletioncriteriaviewed() { + $completion = new \completion_info($this->course); + $completion->set_module_viewed($this->cm); + } + + /** + * Allows observers to act on viewed event + */ + public function triggermoduleviewedevent() { + $event = event\course_module_viewed::create(array( + 'objectid' => $this->cm->instance, + 'context' => \context_module::instance($this->cm->id) + )); + $event->add_record_snapshot('course_modules', $this->cm); + $event->trigger(); + } + + + /** + * Adds js assets to current page + */ + public function addassetstopage() { + global $PAGE; + + foreach ($this->jsrequires as $script) { + $PAGE->requires->js($script, true); + } + + foreach ($this->cssrequires as $css) { + $PAGE->requires->css($css); + } + + // Print JavaScript settings to page. + $PAGE->requires->data_for_js('H5PIntegration', $this->settings, true); + + // Add xAPI collector script. + $PAGE->requires->js(new \moodle_url(self::getsiteroot() . '/mod/hvp/xapi-collector.js'), true); + } + + /** + * Outputs h5p view + */ + public function outputview() { + if ($this->embedtype === 'div') { + echo "
content['id']}\">
"; + } else { + $title = isset($this->content['metadata']['a11yTitle']) + ? $this->content['metadata']['a11yTitle'] + : (isset($this->content['metadata']['title']) + ? $this->content['metadata']['title'] + : '' + ); + + echo "
" . + "" . + "
"; + } + } + + /** + * Checks if content is valid, prints an error if not + */ + public function validatecontent() { + if ($this->content === null) { + print_error('invalidhvp', 'mod_hvp'); + } + } + + /** + * Gets the site root absolute address + * + * @return string Root address for the site + */ + public static function getsiteroot() { + global $CFG; + // In Moodle 3.4 version wwwroot is always the same as httpswwwroot. + if ($CFG->version < 2017111300) { + return $CFG->httpswwwroot; + } + + return $CFG->wwwroot; + } +} diff --git a/classes/xapi_result.php b/classes/xapi_result.php new file mode 100644 index 0000000..54f8d2a --- /dev/null +++ b/classes/xapi_result.php @@ -0,0 +1,154 @@ +. + +/** + * The mod_hvp content user data. + * + * @package mod_hvp + * @since Moodle 2.7 + * @copyright 2017 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mod_hvp; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Class xapi_result handles xapi results and corresponding db operations. + * + * @package mod_hvp + */ +class xapi_result { + + /** + * Handle xapi results endpoint + */ + public static function handle_ajax() { + // Validate token. + if (!self::validate_token()) { + $core = framework::instance(); + \H5PCore::ajaxError($core->h5pF->t('Invalid security token.'), + 'INVALID_TOKEN'); + return; + } + + $cm = get_coursemodule_from_id('hvp', required_param('contextId', PARAM_INT)); + if (!$cm) { + \H5PCore::ajaxError('No such content'); + http_response_code(404); + return; + } + + $xapiresult = required_param('xAPIResult', PARAM_RAW); + + // Validate. + $context = \context_module::instance($cm->id); + if (!has_capability('mod/hvp:saveresults', $context)) { + \H5PCore::ajaxError(get_string('nopermissiontosaveresult', 'hvp')); + return; + } + + $xapijson = json_decode($xapiresult); + if (!$xapijson) { + \H5PCore::ajaxError('Invalid json in xAPI data.'); + return; + } + + if (!self::validate_xapi_data($xapijson)) { + \H5PCore::ajaxError('Invalid xAPI data.'); + return; + } + + // Delete any old results. + self::remove_xapi_data($cm->instance); + + // Store results. + self::store_xapi_data($cm->instance, $xapijson); + + // Successfully inserted xAPI result. + \H5PCore::ajaxSuccess(); + } + + /** + * Validate xAPI results token + * + * @return bool True if token was valid + */ + private static function validate_token() { + $token = required_param('token', PARAM_ALPHANUM); + return \H5PCore::validToken('xapiresult', $token); + + } + + /** + * Validate xAPI data + * + * @param object $xapidata xAPI data + * + * @return bool True if valid data + */ + private static function validate_xapi_data($xapidata) { + $xapidata = new \H5PReportXAPIData($xapidata); + return $xapidata->validateData(); + } + + /** + * Store xAPI result(s) + * + * @param int $contentid Content id + * @param object $xapidata xAPI data + * @param int $parentid Parent id + */ + private static function store_xapi_data($contentid, $xapidata, $parentid = null) { + global $DB, $USER; + + $xapidata = new \H5PReportXAPIData($xapidata, $parentid); + $insertedid = $DB->insert_record('hvp_xapi_results', (object) array( + 'content_id' => $contentid, + 'user_id' => $USER->id, + 'parent_id' => $xapidata->getParentID(), + 'interaction_type' => $xapidata->getInteractionType(), + 'description' => $xapidata->getDescription(), + 'correct_responses_pattern' => $xapidata->getCorrectResponsesPattern(), + 'response' => $xapidata->getResponse(), + 'additionals' => $xapidata->getAdditionals(), + 'raw_score' => $xapidata->getScoreRaw(), + 'max_score' => $xapidata->getScoreMax(), + )); + + // Save sub content statements data. + if ($xapidata->isCompound()) { + foreach ($xapidata->getChildren($contentid) as $child) { + self::store_xapi_data($contentid, $child, $insertedid); + } + } + } + + /** + * Remove xAPI result(s) + * + * @param int $contentid Content id + */ + private static function remove_xapi_data($contentid) { + global $DB, $USER; + + $DB->delete_records('hvp_xapi_results', array( + 'content_id' => $contentid, + 'user_id' => $USER->id + )); + } +} diff --git a/content_hub_registration.php b/content_hub_registration.php new file mode 100644 index 0000000..d88f88e --- /dev/null +++ b/content_hub_registration.php @@ -0,0 +1,54 @@ +. +/** + * Responsible for displaying the content upgrade page + * + * @package mod_hvp + * @copyright 2020 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +use mod_hvp\content_hub_service; + +require_once("../../config.php"); +require_once($CFG->libdir.'/adminlib.php'); +require_once("locallib.php"); + +global $PAGE, $SITE, $OUTPUT, $CFG; + +// No guest autologin. +require_login(0, false); + +$context = \context_system::instance(); +require_capability('mod/hvp:contenthubregistration', $context); + +$pageurl = new moodle_url('/mod/hvp/content_hub_registration.php'); +$PAGE->set_context(context_system::instance()); +$PAGE->set_url($pageurl); +$PAGE->set_title("{$SITE->shortname}: " . get_string('upgrade', 'hvp')); +$PAGE->set_heading(get_string('contenthub:settings:heading', 'mod_hvp')); + +$settings = content_hub_service::get_registration_ui_settings(); +$PAGE->requires->data_for_js('H5PSettings', $settings, true); +$PAGE->requires->js(new moodle_url('library/js/h5p-hub-registration.js'), true); +$PAGE->requires->css(new moodle_url('library/styles/h5p.css')); +$PAGE->requires->css(new moodle_url('library/styles/h5p-hub-registration.css')); + +echo $OUTPUT->header(); + +echo $OUTPUT->render_from_template('mod_hvp/content_hub_registration', []); +$PAGE->requires->js_call_amd('mod_hvp/contenthubregistration', 'init'); + +echo $OUTPUT->footer(); \ No newline at end of file diff --git a/dataviews.js b/dataviews.js new file mode 100644 index 0000000..2934c08 --- /dev/null +++ b/dataviews.js @@ -0,0 +1,43 @@ +/* global H5PDataView */ +(function($) { + + /** + * Creates a new dataview. + * + * @private + * @param {object} dataView Structure + * @param {string} dataView.source AJAX URL for data view + * @param {object[]} dataView.headers Header text and props + * @param {boolean[]} dataView.filters Which fields to allow filtering for + * @param {object} dataView.order Default order by and direction + * @param {object} dataView.l10n Translations + * @param {Element} wrapper Where in the DOM should the dataview be appended + * @param {function} loaded Callback for when the dataview is ready + */ + var createDataView = function(dataView, wrapper, loaded) { + new H5PDataView( + wrapper, + dataView.source, + dataView.headers, + dataView.l10n, + undefined, + dataView.filters, + loaded, + dataView.order + ); + }; + + // Create data views when page is done loading. + $(document).ready(function() { + for (var id in H5PIntegration.dataViews) { + if (!H5PIntegration.dataViews.hasOwnProperty(id)) { + continue; + } + + var wrapper = $('#' + id).get(0); + if (wrapper !== undefined) { + createDataView(H5PIntegration.dataViews[id], wrapper); + } + } + }); +})(H5P.jQuery); diff --git a/db/access.php b/db/access.php new file mode 100644 index 0000000..397bd92 --- /dev/null +++ b/db/access.php @@ -0,0 +1,207 @@ +. + +/** + * Capability definitions for the hvp module. + * + * Available archetypes: + * manager + * coursecreator + * editingteacher + * teacher + * student + * guest + * user + * frontpage + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$capabilities = array( + + 'mod/hvp:view' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array( + 'manager' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'student' => CAP_ALLOW, + 'guest' => CAP_ALLOW + ) + ), + + 'mod/hvp:addinstance' => array( + 'riskbitmask' => RISK_SPAM | RISK_XSS, + 'captype' => 'write', + 'contextlevel' => CONTEXT_COURSE, + 'archetypes' => array( + 'editingteacher' => CAP_ALLOW, + 'manager' => CAP_ALLOW + ), + 'clonepermissionsfrom' => 'moodle/course:manageactivities' + ), + + 'mod/hvp:manage' => array( + 'riskbitmask' => RISK_SPAM | RISK_XSS, + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array( + 'editingteacher' => CAP_ALLOW, + 'manager' => CAP_ALLOW + ), + 'clonepermissionsfrom' => 'mod/hvp:addinstance' + ), + + 'mod/hvp:share' => array( + 'riskbitmask' => RISK_SPAM, + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array( + 'editingteacher' => CAP_ALLOW, + 'manager' => CAP_ALLOW + ), + 'clonepermissionsfrom' => 'mod/hvp:addinstance' + ), + + 'mod/hvp:getexport' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array( + 'manager' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'teacher' => CAP_ALLOW + ) + ), + + 'mod/hvp:getembedcode' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array( + 'manager' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'teacher' => CAP_ALLOW + ) + ), + + 'mod/hvp:saveresults' => array( + 'riskbitmask' => RISK_SPAM, + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array( + 'student' => CAP_ALLOW + ) + ), + + 'mod/hvp:savecontentuserdata' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array( + 'manager' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'student' => CAP_ALLOW + ) + ), + + 'mod/hvp:viewresults' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array( + 'student' => CAP_ALLOW + ) + ), + + 'mod/hvp:viewallresults' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array( + 'manager' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'teacher' => CAP_ALLOW + ) + ), + + 'mod/hvp:restrictlibraries' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_SYSTEM, + 'archetypes' => array( + 'manager' => CAP_ALLOW + ) + ), + + 'mod/hvp:userestrictedlibraries' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_COURSE, + 'archetypes' => array( + 'manager' => CAP_ALLOW + ) + ), + + 'mod/hvp:updatelibraries' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_SYSTEM, + 'archetypes' => array( + 'manager' => CAP_ALLOW + ) + ), + + 'mod/hvp:getcachedassets' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_SYSTEM, + 'archetypes' => array( + 'manager' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'teacher' => CAP_ALLOW, + 'student' => CAP_ALLOW, + 'user' => CAP_ALLOW, + 'guest' => CAP_ALLOW + ) + ), + + 'mod/hvp:installrecommendedh5plibraries' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_COURSE, + 'archetypes' => array( + 'manager' => CAP_ALLOW + ) + ), + + // Receive a confirmation message of own h5p submission. + 'mod/hvp:emailconfirmsubmission' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array() + ), + + // Receive a notification message of other peoples' h5p submissions. + 'mod/hvp:emailnotifysubmission' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array() + ), + + 'mod/hvp:contenthubregistration' => [ + 'captype' => 'write', + 'contextlevel' => CONTEXT_SYSTEM, + 'archetypes' => [], // Only admins by default. + ], + +); diff --git a/db/events.php b/db/events.php new file mode 100644 index 0000000..c6f7983 --- /dev/null +++ b/db/events.php @@ -0,0 +1,38 @@ +. + +/** + * Add event handlers for H5P + * + * @package mod_hvp + * @category event + * @copyright 2020 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + + +defined('MOODLE_INTERNAL') || die(); + +$observers = array( + + // Handle attempt submitted event, as a way to send confirmation messages asynchronously. + array( + 'eventname' => '\mod_hvp\event\attempt_submitted', + 'includefile' => '/mod/hvp/locallib.php', + 'callback' => 'hvp_attempt_submitted_handler', + 'internal' => false + ), +); diff --git a/db/install.php b/db/install.php new file mode 100644 index 0000000..89c56ed --- /dev/null +++ b/db/install.php @@ -0,0 +1,54 @@ +. + +defined('MOODLE_INTERNAL') || die(); + +function xmldb_hvp_install() { + + // Try to install all the default content types. + require_once(__DIR__ . '/../autoloader.php'); + + // Fetch info about library updates. + $core = \mod_hvp\framework::instance('core'); + $core->fetchLibrariesMetadata(); + + // Check that plugin is set up correctly. + $core->checkSetupForRequirements(); + + // Print any messages. + echo '

' . get_string('welcomeheader', 'hvp') . '

' . + '

' . + get_string('welcomegettingstarted', 'hvp', array( + 'moodle_tutorial' => 'href="https://h5p.org/moodle" target="_blank"', + 'example_content' => 'href="https://h5p.org/content-types-and-applications" target="_blank"' + )) . + '

' . + '

' . + get_string('welcomecommunity', 'hvp', array( + 'forums' => 'href="https://h5p.org/forum" target="_blank"' + )) . + '

' . + '

' . get_string('welcomecontactus', 'hvp', + 'href="https://h5p.org/contact" target="_blank"') . + '

'; + + // Notify of communication with H5P Hub. + // @codingStandardsIgnoreLine + echo "

H5P fetches content types directly from the H5P Hub. In order to do this the H5P plugin will communicate with the Hub once a day to fetch information about new and updated content types. It will send in anonymous data to the Hub about H5P usage. Read more at the plugin communication page at H5P.org.

"; + + \mod_hvp\framework::printMessages('info', \mod_hvp\framework::messages('info')); + \mod_hvp\framework::printMessages('error', \mod_hvp\framework::messages('error')); +} diff --git a/db/install.xml b/db/install.xml new file mode 100644 index 0000000..46e7498 --- /dev/null +++ b/db/install.xml @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + +
+ + + + + + + + + + +
+ + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + +
+ + + + + + + +
+ + + + + + + + + + + + + + +
+ + + + + + + + + + + + + +
+
+
diff --git a/db/messages.php b/db/messages.php new file mode 100644 index 0000000..a08d8f0 --- /dev/null +++ b/db/messages.php @@ -0,0 +1,40 @@ +. + +/** + * Defines message providers (types of message sent) for the hvp module. + * + * @package mod_hvp + * @copyright 2020 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$messageproviders = array( + // Notify teacher that a student has submitted an attempt. + 'submission' => array( + 'capability' => 'mod/hvp:emailnotifysubmission' + ), + + // Confirm a student's quiz attempt. + 'confirmation' => array( + 'capability' => 'mod/hvp:emailconfirmsubmission', + 'defaults' => array( + 'airnotifier' => MESSAGE_PERMITTED + MESSAGE_DEFAULT_LOGGEDIN + MESSAGE_DEFAULT_LOGGEDOFF, + ), + ), +); diff --git a/db/mobile.php b/db/mobile.php new file mode 100644 index 0000000..364aba1 --- /dev/null +++ b/db/mobile.php @@ -0,0 +1,32 @@ +. + +defined('MOODLE_INTERNAL') || die(); + +$addons = array( + "mod_hvp" => array( // Plugin identifier. + 'handlers' => array( // Different places where the plugin will display content. + 'coursehvp' => array( // Handler unique name (alphanumeric). + 'delegate' => 'CoreCourseModuleDelegate', // Delegate (where to display the link to the plugin). + 'method' => 'mobile_course_view', // Main function in \mod_certificate\output\mobile. + 'displaydata' => array( + 'icon' => $CFG->wwwroot . '/mod/hvp/pix/icon.svg', + 'class' => '', + ), + ) + ) + ) +); diff --git a/db/tasks.php b/db/tasks.php new file mode 100644 index 0000000..276e295 --- /dev/null +++ b/db/tasks.php @@ -0,0 +1,63 @@ +. +/** + * Defines the task which looks for H5P updates. + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$tasks = array( + array( + 'classname' => 'mod_hvp\task\look_for_updates', + 'blocking' => 0, + 'minute' => 'R', + 'hour' => 'R', + 'day' => '*', + 'dayofweek' => '*', + 'month' => '*' + ), + array( + 'classname' => 'mod_hvp\task\remove_tmpfiles', + 'blocking' => 0, + 'minute' => 'R', + 'hour' => 'R', + 'day' => '*', + 'dayofweek' => '*', + 'month' => '*' + ), + array( + 'classname' => 'mod_hvp\task\remove_old_log_entries', + 'blocking' => 0, + 'minute' => 'R', + 'hour' => 'R', + 'day' => '*', + 'dayofweek' => '*', + 'month' => '*' + ), + array( + 'classname' => 'mod_hvp\task\remove_old_auth_tokens', + 'blocking' => 0, + 'minute' => 'R', + 'hour' => '*', + 'day' => '*', + 'dayofweek' => '*', + 'month' => '*' + ) +); diff --git a/db/upgrade.php b/db/upgrade.php new file mode 100644 index 0000000..dcad1a6 --- /dev/null +++ b/db/upgrade.php @@ -0,0 +1,606 @@ +. + +/** + * Upgrade definitions for the hvp module. + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +/** + * Adds data for tracking when content was created and last modified. + */ +function hvp_upgrade_2016011300() { + global $DB; + $dbman = $DB->get_manager(); + + $table = new xmldb_table('hvp'); + + // Define field timecreated to be added to hvp. + $timecreated = new xmldb_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'slug'); + + // Conditionally launch add field timecreated. + if (!$dbman->field_exists($table, $timecreated)) { + $dbman->add_field($table, $timecreated); + } + + // Define field timemodified to be added to hvp. + $timemodified = new xmldb_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'timecreated'); + + // Conditionally launch add field timemodified. + if (!$dbman->field_exists($table, $timemodified)) { + $dbman->add_field($table, $timemodified); + } +} + +/** + * Adds table for keeping track of, and cleaning up temporary files + */ +function hvp_upgrade_2016042500() { + global $DB; + $dbman = $DB->get_manager(); + + // Define table hvp_tmpfiles to be created. + $table = new xmldb_table('hvp_tmpfiles'); + + // Adding fields to table hvp_tmpfiles. + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); + + // Adding keys to table hvp_tmpfiles. + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); + + // Conditionally launch create table for hvp_tmpfiles. + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } +} + +/** + * Adds events table + */ +function hvp_upgrade_2016050600() { + global $DB; + $dbman = $DB->get_manager(); + + // Define table hvp_events to be created. + $table = new xmldb_table('hvp_events'); + + // Adding fields to table hvp_events. + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('user_id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); + $table->add_field('created_at', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); + $table->add_field('type', XMLDB_TYPE_CHAR, '63', null, XMLDB_NOTNULL, null, null); + $table->add_field('sub_type', XMLDB_TYPE_CHAR, '63', null, XMLDB_NOTNULL, null, null); + $table->add_field('content_id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); + $table->add_field('content_title', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); + $table->add_field('library_name', XMLDB_TYPE_CHAR, '127', null, XMLDB_NOTNULL, null, null); + $table->add_field('library_version', XMLDB_TYPE_CHAR, '31', null, XMLDB_NOTNULL, null, null); + + // Adding keys to table hvp_events. + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); + + // Conditionally launch create table for hvp_events. + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } + + // Define table hvp_counters to be created. + $table = new xmldb_table('hvp_counters'); + + // Adding fields to table hvp_counters. + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('type', XMLDB_TYPE_CHAR, '63', null, XMLDB_NOTNULL, null, null); + $table->add_field('library_name', XMLDB_TYPE_CHAR, '127', null, XMLDB_NOTNULL, null, null); + $table->add_field('library_version', XMLDB_TYPE_CHAR, '31', null, XMLDB_NOTNULL, null, null); + $table->add_field('num', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); + + // Adding keys to table hvp_counters. + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); + + // Adding indexes to table hvp_counters. + $table->add_index('realkey', XMLDB_INDEX_NOTUNIQUE, [ + 'type', + 'library_name', + 'library_version', + ]); + + // Conditionally launch create table for hvp_counters. + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } +} + +/** + * Adds intro and introformat to hvp table + */ +function hvp_upgrade_2016051000() { + global $DB; + $dbman = $DB->get_manager(); + + $table = new xmldb_table('hvp'); + + // Define field intro to be added to hvp. + $intro = new xmldb_field('intro', XMLDB_TYPE_TEXT, null, null, null, null, null, 'name'); + + // Add field intro if not defined already. + if (!$dbman->field_exists($table, $intro)) { + $dbman->add_field($table, $intro); + } + + // Define field introformat to be added to hvp. + $introformat = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, '0', 'intro'); + + // Add field introformat if not defined already. + if (!$dbman->field_exists($table, $introformat)) { + $dbman->add_field($table, $introformat); + } +} + +/** + * Changes context of activity files to enable backup an restore. + */ +function hvp_upgrade_2016110100() { + global $DB; + + // Change context of activity files from COURSE to MODULE. + $filearea = 'content'; + $component = 'mod_hvp'; + + // Find activity ID and correct context ID. + $hvpsresult = $DB->get_records_sql( + "SELECT f.id AS fileid, f.itemid, c.id, f.filepath, f.filename, f.pathnamehash + FROM {files} f + JOIN {course_modules} cm ON f.itemid = cm.instance + JOIN {modules} md ON md.id = cm.module + JOIN {context} c ON c.instanceid = cm.id + WHERE md.name = 'hvp' + AND f.filearea = 'content' + AND c.contextlevel = " . CONTEXT_MODULE + ); + + foreach ($hvpsresult as $hvp) { + // Need to re-hash pathname after changing context. + $pathnamehash = file_storage::get_pathname_hash($hvp->id, + $component, + $filearea, + $hvp->itemid, + $hvp->filepath, + $hvp->filename + ); + + // Double check that hash doesn't exist (avoid duplicate entries). + if (!$DB->get_field_sql("SELECT contextid FROM {files} WHERE pathnamehash = '{$pathnamehash}'")) { + // Update context ID and pathname hash for files. + $DB->execute(" + UPDATE {files} + SET contextid = {$hvp->id}, + pathnamehash = '{$pathnamehash}' + WHERE pathnamehash = '{$hvp->pathnamehash}'" + ); + } + } +} + +/** + * Notifies about breaking changes to H5P content type styling + */ +function hvp_upgrade_2016122800() { + // @codingStandardsIgnoreLine + \mod_hvp\framework::messages('info', 'Upgrade your H5P content types! Old content types will still work, but the authoring tool will look and feel much better if you upgrade the content types.'); + \mod_hvp\framework::printMessages('info', \mod_hvp\framework::messages('info')); +} + +/** + * Adds content type cache to enable the content type hub + */ +function hvp_upgrade_2017040500() { + global $DB; + $dbman = $DB->get_manager(); + + // Add content type cache database. + $table = new xmldb_table('hvp_libraries_hub_cache'); + + // Adding fields to table hvp_libraries_hub_cache. + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('machine_name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); + $table->add_field('major_version', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null); + $table->add_field('minor_version', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null); + $table->add_field('patch_version', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null); + $table->add_field('h5p_major_version', XMLDB_TYPE_INTEGER, '4', null, null, null, null); + $table->add_field('h5p_minor_version', XMLDB_TYPE_INTEGER, '4', null, null, null, null); + $table->add_field('title', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); + $table->add_field('summary', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null); + $table->add_field('description', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null); + $table->add_field('icon', XMLDB_TYPE_CHAR, '511', null, XMLDB_NOTNULL, null, null); + $table->add_field('created_at', XMLDB_TYPE_INTEGER, '11', null, XMLDB_NOTNULL, null, null); + $table->add_field('updated_at', XMLDB_TYPE_INTEGER, '11', null, XMLDB_NOTNULL, null, null); + $table->add_field('is_recommended', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); + $table->add_field('popularity', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); + $table->add_field('screenshots', XMLDB_TYPE_TEXT, null, null, null, null, null); + $table->add_field('license', XMLDB_TYPE_TEXT, null, null, null, null, null); + $table->add_field('example', XMLDB_TYPE_CHAR, '511', null, XMLDB_NOTNULL, null, null); + $table->add_field('tutorial', XMLDB_TYPE_CHAR, '511', null, null, null, null); + $table->add_field('keywords', XMLDB_TYPE_TEXT, null, null, null, null, null); + $table->add_field('categories', XMLDB_TYPE_TEXT, null, null, null, null, null); + $table->add_field('owner', XMLDB_TYPE_CHAR, '511', null, null, null, null); + + // Adding keys to table hvp_libraries_hub_cache. + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); + + // Conditionally create table for hvp_libraries_hub_cache. + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } + + // Update the content type cache. + $core = \mod_hvp\framework::instance(); + $core->updateContentTypeCache(); + + // Print messages. + \mod_hvp\framework::printMessages('info', \mod_hvp\framework::messages('info')); + \mod_hvp\framework::printMessages('error', \mod_hvp\framework::messages('error')); + + // Add has_icon to libraries folder. + $table = new xmldb_table('hvp_libraries'); + + // Define field has_icon to be added to hvp_libraries. + $hasicon = new xmldb_field('has_icon', XMLDB_TYPE_INTEGER, '1', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + + // Add field has_icon if it does not exist. + if (!$dbman->field_exists($table, $hasicon)) { + $dbman->add_field($table, $hasicon); + } + + // Display hub communication info. + if (!get_config('mod_hvp', 'external_communication')) { + // @codingStandardsIgnoreLine + \mod_hvp\framework::messages('info', 'H5P now fetches content types directly from the H5P Hub. In order to do this, the H5P plugin will communicate with H5P.org once per day to fetch information about new and updated content types. It will send in anonymous data to the hub about H5P usage. You may disable the data contribution and/or the H5P Hub in the H5P settings.'); + \mod_hvp\framework::printMessages('info', \mod_hvp\framework::messages('info')); + } + + // Enable hub and delete old communication variable. + set_config('hub_is_enabled', true, 'mod_hvp'); + unset_config('hub_is_enabled', 'mod_hvp'); +} + +/** + * Adds xAPI results table to enable reporting + */ +function hvp_upgrade_2017050900() { + global $DB; + $dbman = $DB->get_manager(); + + // Add report rendering. + $table = new xmldb_table('hvp_xapi_results'); + + // Add fields. + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('content_id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); + $table->add_field('user_id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); + $table->add_field('parent_id', XMLDB_TYPE_INTEGER, '10', null, null, null, null); + $table->add_field('interaction_type', XMLDB_TYPE_CHAR, '127', null, XMLDB_NOTNULL, null, null); + $table->add_field('description', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null); + $table->add_field('correct_responses_pattern', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null); + $table->add_field('response', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null); + $table->add_field('additionals', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null); + + // Add keys and index. + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); + $table->add_index('result', XMLDB_INDEX_UNIQUE, [ + 'id', + 'content_id', + 'user_id', + ]); + + // Create table if it does not exist. + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } +} + +/** + * Adds raw score and max score to xapi results table + */ +function hvp_upgrade_2017060900() { + global $DB; + $dbman = $DB->get_manager(); + + // Add score to report rendering. + $table = new xmldb_table('hvp_xapi_results'); + + if ($dbman->table_exists($table)) { + // Raw score field. + $scorefield = new xmldb_field('raw_score', XMLDB_TYPE_INTEGER, '6'); + if (!$dbman->field_exists($table, $scorefield)) { + $dbman->add_field($table, $scorefield); + } + + // Max score field. + $maxscorefield = new xmldb_field('max_score', XMLDB_TYPE_INTEGER, '6'); + if (!$dbman->field_exists($table, $maxscorefield)) { + $dbman->add_field($table, $maxscorefield); + } + } +} + +function hvp_upgrade_2018090300() { + global $DB; + $dbman = $DB->get_manager(); + + $table = new xmldb_table('hvp'); + + // Remove old, unused metadata fields. + if ($dbman->field_exists($table, 'author')) { + $dbman->drop_field($table, new xmldb_field('author')); + } + + if ($dbman->field_exists($table, 'license')) { + $dbman->drop_field($table, new xmldb_field('license')); + } + + if ($dbman->field_exists($table, 'meta_keywords')) { + $dbman->drop_field($table, new xmldb_field('meta_keywords')); + } + + if ($dbman->field_exists($table, 'meta_description')) { + $dbman->drop_field($table, new xmldb_field('meta_description')); + } + + // Create new metadata fields. + if (!$dbman->field_exists($table, 'authors')) { + $dbman->add_field($table, + new xmldb_field('authors', XMLDB_TYPE_TEXT, null, null, null, null, null) + ); + } + + if (!$dbman->field_exists($table, 'source')) { + $dbman->add_field($table, + new xmldb_field('source', XMLDB_TYPE_CHAR, '255', null, null, null, null) + ); + } + + if (!$dbman->field_exists($table, 'year_from')) { + $dbman->add_field($table, + new xmldb_field('year_from', XMLDB_TYPE_INTEGER, '4', null, null, null, null) + ); + } + + if (!$dbman->field_exists($table, 'year_to')) { + $dbman->add_field($table, + new xmldb_field('year_to', XMLDB_TYPE_INTEGER, '4', null, null, null, null) + ); + } + + if (!$dbman->field_exists($table, 'license')) { + $dbman->add_field($table, + new xmldb_field('license', XMLDB_TYPE_CHAR, '63', null, null, null, null) + ); + } + + if (!$dbman->field_exists($table, 'license_version')) { + $dbman->add_field($table, + new xmldb_field('license_version', XMLDB_TYPE_CHAR, '15', null, null, null, null) + ); + } + + if (!$dbman->field_exists($table, 'changes')) { + $dbman->add_field($table, + new xmldb_field('changes', XMLDB_TYPE_TEXT, null, null, null, null, null) + ); + } + + if (!$dbman->field_exists($table, 'license_extras')) { + $dbman->add_field($table, + new xmldb_field('license_extras', XMLDB_TYPE_TEXT, null, null, null, null, null) + ); + } + + if (!$dbman->field_exists($table, 'author_comments')) { + $dbman->add_field($table, + new xmldb_field('author_comments', XMLDB_TYPE_TEXT, null, null, null, null, null) + ); + } + + // Add new libraries fields. + $table = new xmldb_table('hvp_libraries'); + if (!$dbman->field_exists($table, 'add_to')) { + $dbman->add_field($table, + new xmldb_field('add_to', XMLDB_TYPE_TEXT, null, null, null, null, null) + ); + } + + if (!$dbman->field_exists($table, 'metadata_settings')) { + $dbman->add_field($table, + new xmldb_field('metadata_settings', XMLDB_TYPE_TEXT, null, null, null, null, null) + ); + } +} + + +/** + * Adds authentication table + * + * @throws ddl_exception + */ +function hvp_upgrade_2019022600() { + global $DB; + $dbman = $DB->get_manager(); + + // Add auth table. + $table = new xmldb_table('hvp_auth'); + + // Add fields. + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('user_id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); + $table->add_field('created_at', XMLDB_TYPE_INTEGER, '11', null, XMLDB_NOTNULL, null, null); + $table->add_field('secret', XMLDB_TYPE_CHAR, '64', null, XMLDB_NOTNULL, null, null); + + // Add keys and index. + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); + $table->add_index('user_id', XMLDB_INDEX_UNIQUE, ['user_id']); + + // Create table if it does not exist. + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } +} + +/** + * Add default language to content + * + * @throws ddl_exception + * @throws ddl_table_missing_exception + */ +function hvp_upgrade_2019030700() { + global $DB; + $dbman = $DB->get_manager(); + + $table = new xmldb_table('hvp'); + + if (!$dbman->field_exists($table, 'default_language')) { + $dbman->add_field($table, + new xmldb_field('default_language', XMLDB_TYPE_CHAR, '32', null, null, null, null) + ); + } +} + +function hvp_upgrade_2020080400() { + global $DB; + $dbman = $DB->get_manager(); + // Define field completionscorerequired to be added to hvp. + $table = new xmldb_table('hvp'); + // Conditionally launch add field completionscorerequired. + if (!$dbman->field_exists($table, 'completionpass')) { + $dbman->add_field( + $table, + new xmldb_field('completionpass', XMLDB_TYPE_INTEGER, '1', null, null, null, 0, 'timemodified') + ); + } +} + +function hvp_upgrade_2020080401() { + global $DB; + $dbman = $DB->get_manager(); + + // Changing nullability of field completionpass on table hvp to not null. + $table = new xmldb_table('hvp'); + $field = new xmldb_field('completionpass', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'timemodified'); + + // Launch change of nullability for field completionpass. + $dbman->change_field_notnull($table, $field); +} + +function hvp_upgrade_2020082800() { + global $DB; + $dbman = $DB->get_manager(); + + $table = new xmldb_table('hvp'); + + if (!$dbman->field_exists($table, 'a11y_title')) { + $dbman->add_field($table, + new xmldb_field('a11y_title', XMLDB_TYPE_CHAR, '255', null, null, null, null) + ); + } +} + +/** + * Drop old unused unique index, add nonunique index. + */ +function hvp_upgrade_2020091500() { + global $DB; + $dbman = $DB->get_manager(); + $table = new xmldb_table('hvp_xapi_results'); + $index = new xmldb_index('results', XMLDB_INDEX_NOTUNIQUE, ['content_id', 'user_id']); + if (!$dbman->index_exists($table, $index)) { + $dbman->add_index($table, $index); + } + + $oldindex = new xmldb_index('result', XMLDB_INDEX_UNIQUE, ['id', 'content_id', 'user_id']); + $dbman->drop_index($table, $oldindex); +} + +function hvp_upgrade_2020112600() { + global $DB; + $dbman = $DB->get_manager(); + + // Add Content Hub fields to main content table. + $table = new xmldb_table('hvp'); + if (!$dbman->field_exists($table, 'shared')) { + $dbman->add_field($table, new xmldb_field('shared', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, 0, 'completionpass')); + } + if (!$dbman->field_exists($table, 'synced')) { + $dbman->add_field($table, new xmldb_field('synced', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'shared')); + } + if (!$dbman->field_exists($table, 'hub_id')) { + $dbman->add_field($table, new xmldb_field('hub_id', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'synced')); + } + + // Create table for caching content hub metadata. + $table = new xmldb_table('hvp_content_hub_cache'); + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('language', XMLDB_TYPE_CHAR, '31', null, XMLDB_NOTNULL, null, null); + $table->add_field('json', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null); + $table->add_field('last_checked', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); + + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); + $table->add_index('language', XMLDB_INDEX_UNIQUE, ['language']); + + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } +} + +/** + * Hvp module upgrade function. + * + * @param string $oldversion The version we are upgrading from + * + * @return bool Success + */ +function xmldb_hvp_upgrade($oldversion) { + $upgrades = [ + 2016011300, + 2016042500, + 2016050600, + 2016051000, + 2016110100, + 2016122800, + 2017040500, + 2017050900, + 2017060900, + 2018090300, + 2019022600, + 2019030700, + 2020080400, + 2020080401, + 2020082800, + 2020091500, + 2020112600, + ]; + + foreach ($upgrades as $version) { + if ($oldversion < $version) { + call_user_func("hvp_upgrade_{$version}"); + upgrade_mod_savepoint(true, $version, 'hvp'); + } + } + + return true; +} diff --git a/editor.js b/editor.js new file mode 100644 index 0000000..c3c9a6c --- /dev/null +++ b/editor.js @@ -0,0 +1,50 @@ +(function($) { + + /** + * Get closest row of element + * + * @param {jQuery} $el + * @returns {jQuery} + */ + function getRow($el) { + return $el.closest('.fitem'); + } + + /** + * Initializes editor + */ + function init() { + var $editor = $('.h5p-editor'); + var $fileField = $('input[name="h5pfile"]'); + + if (H5PIntegration.hubIsEnabled) { + // TODO: This can easily break in new themes. Improve robustness of this + // by not including h5paction in form, when it should not be used. + $('input[name="h5paction"]').parents('.fitem').last().hide(); + } + + const mformId = H5PIntegration.editor && H5PIntegration.editor.formId !== null + ? H5PIntegration.editor.formId + : 'mform1'; + + // Cancel validation and submission of form if clicking cancel button + const cancelSubmitCallback = function ($button) { + return $button.is('[name="cancel"]'); + }; + + H5PEditor.init( + $('#' + mformId), + $('input[name="h5paction"]'), + getRow($fileField), + getRow($editor), + $editor, + $('input[name="h5plibrary"]'), + $('input[name="h5pparams"]'), + $('input[name="h5pmaxscore"]'), + $('input[name="name"]'), + cancelSubmitCallback + ); + } + + $(document).ready(init); +})(H5P.jQuery); diff --git a/editor/README.md b/editor/README.md new file mode 100644 index 0000000..18dc522 --- /dev/null +++ b/editor/README.md @@ -0,0 +1,10 @@ +H5P Editor PHP Library +========== + +A general library that is supposed to be used in most PHP implementations of H5P. + +## License + +All code is licensed under MIT License + +Open Sans font is licensed under Apache license, Version 2.0 \ No newline at end of file diff --git a/editor/ckeditor/CHANGES.md b/editor/ckeditor/CHANGES.md new file mode 100644 index 0000000..1e7b8e8 --- /dev/null +++ b/editor/ckeditor/CHANGES.md @@ -0,0 +1,2117 @@ +CKEditor 4 Changelog +==================== + +## CKEditor 4.17.1 + +Fixed issues: + +* [#4979](https://github.com/ckeditor/ckeditor4/issues/3757): Added cache key in [#4761](https://github.com/ckeditor/ckeditor4/issues/4761) started to breaking relative links for external CSS resources. The fix had been reverted and will be corrected in the upcoming release. + +## CKEditor 4.17 + +**Security Updates:** + +* Fixed XSS vulnerability in the core module reported by [William Bowling](https://github.com/wbowling). + + Issue summary: The vulnerability allowed to inject malformed comments HTML bypassing content sanitization, which could result in executing JavaScript code. See [security advisory](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-7h26-63m7-qhf2) for more details. + +* Fixed XSS vulnerability in the core module reported by [Maurice Dauer](https://twitter.com/laytonctf). + + Issue summary: The vulnerability allowed to inject malformed HTML bypassing content sanitization, which could result in executing JavaScript code. See [security advisory](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-pvmx-g8h5-cprj) for more details. + +You can read more details in the relevant security advisory and [contact us](security@cksource.com) if you have more questions. + +**An upgrade is highly recommended!** + +**Highlights:** + +Adobe [ended support of Flash Player](https://www.adobe.com/products/flashplayer/end-of-life.html) on December 31, 2020 and blocked Flash content from running in Flash Player beginning January 12, 2021. +We have decided to deprecate and remove the [Flash](https://ckeditor.com/cke4/addon/flash) plugin from CKEditor 4 to help protect users' systems and discourage using insecure software. + +New Features: + +* [#3433](https://github.com/ckeditor/ckeditor4/issues/3433): Marked required fields in dialogs with asterisk (`*`) symbol. +* [#4374](https://github.com/ckeditor/ckeditor4/issues/4374): Integrated the [Maximize](https://ckeditor.com/cke4/addon/maximize) plugin with browser's History API. +* [#4461](https://github.com/ckeditor/ckeditor4/issues/4461): Introduced the possibility to delay editor initialization while it is in a detached DOM element. +* [#4462](https://github.com/ckeditor/ckeditor4/issues/4462): Introduced support for reattaching editor container element to DOM. +* [#4612](https://github.com/ckeditor/ckeditor4/issues/4612): Allow pasting images as Base64 from [clipboard](https://ckeditor.com/cke4/addon/clipboard) in all browsers except IE. +* [#4681](https://github.com/ckeditor/ckeditor4/issues/4681): Allow drag and drop images as Base64. +* [#4750](https://github.com/ckeditor/ckeditor4/issues/4750): Added notification for pasting and dropping unsupported file types into the editor. +* [#4807](https://github.com/ckeditor/ckeditor4/issues/4807): [Chrome] Improved the performance of pasting large images. Thanks to [FlowIT-JIT](https://github.com/FlowIT-JIT)! +* [#4850](https://github.com/ckeditor/ckeditor4/issues/4850): Added support for loading [content templates](https://ckeditor.com/cke4/addon/templates) from HTML files. Thanks to [Fynn96](https://github.com/Fynn96)! +* [#4874](https://github.com/ckeditor/ckeditor4/issues/4874): Added the [`config.clipboard_handleImages`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-clipboard_handleImages) configuration option for enabling and disabling built-in support for pasting and dropping images in the [Clipboard](https://ckeditor.com/cke4/addon/clipboard) plugin. Thanks to [FlowIT-JIT](https://github.com/FlowIT-JIT)! +* [#4026](https://github.com/ckeditor/ckeditor4/issues/4026): [Preview](https://ckeditor.com/cke4/addon/preview) plugin now uses the [`editor#title`](http://localhost/ckeditor4-docs/build/docs/ckeditor4/latest/api/CKEDITOR_editor.html#property-title) property for the title of the preview window. Thanks to [Ely](https://github.com/Elyasin)! +* [#4467](https://github.com/ckeditor/ckeditor4/issues/4467): Added support for inserting content next to a block [widgets](https://ckeditor.com/cke4/addon/widget) using keyboard navigation. Thanks to [bunglegrind](https://github.com/bunglegrind)! + +Fixed Issues: + +* [#3757](https://github.com/ckeditor/ckeditor4/issues/3757): [Firefox] Fixed: images pasted from [clipboard](https://ckeditor.com/cke4/addon/clipboard) are not inserted as Base64-encoded images. +* [#3876](https://github.com/ckeditor/ckeditor4/issues/3876): Fixed: The [Print](https://ckeditor.com/cke4/addon/print) plugin incorrectly prints links and images. +* [#4444](https://github.com/ckeditor/ckeditor4/issues/4444): [Firefox] Fixed: Print preview is incorrectly loaded from CDN. +* [#4596](https://github.com/ckeditor/ckeditor4/issues/4596): Fixed: Incorrect handling of HSL/HSLA values in [`CKEDITOR.tools.color`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools_color.html). +* [#4597](https://github.com/ckeditor/ckeditor4/issues/4597): Fixed: Incorrect color conversion for HSL/HSLA values in [`CKEDITOR.tools.color`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools_color.html). +* [#4604](https://github.com/ckeditor/ckeditor4/issues/4604): Fixed: [`CKEDITOR.plugins.clipboard.dataTransfer#getTypes()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_clipboard_dataTransfer.html#method-getTypes) returns no types. +* [#4761](https://github.com/ckeditor/ckeditor4/issues/4761): Fixed: Not all resources loaded by the editor respect the cache key. +* [#4783](https://github.com/ckeditor/ckeditor4/issues/4783): Fixed: The [Accessibility Help](https://ckeditor.com/cke4/addon/a11yhelp) dialog does not contain info about focus being moved back to the editing area upon activating a toolbar button. +* [#4790](https://github.com/ckeditor/ckeditor4/issues/4790): Fixed: Printing page is invoked before the printed page is fully loaded. +* [#4874](https://github.com/ckeditor/ckeditor4/issues/4874): Fixed: Built-in support for pasting and dropping images in the [Clipboard](https://ckeditor.com/cke4/addon/clipboard) plugin restricts third party plugins from handling image pasting. Thanks to [FlowIT-JIT](https://github.com/FlowIT-JIT)! +* [#4888](https://github.com/ckeditor/ckeditor4/issues/4888): Fixed: The [`CKEDITOR.dialog#setState()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dialog.html#method-setState) method throws error when there is no "OK" button in the dialog. +* [#4858](https://github.com/ckeditor/ckeditor4/issues/4858): Fixed: The [Autolink](https://ckeditor.com/cke4/addon/autolink) plugin incorrectly escapes the `&` characters when pasting links into the editor. +* [#4892](https://github.com/ckeditor/ckeditor4/issues/4892): Fixed: Focus of buttons in dialogs is not visible enough in High Contrast mode. +* [#3858](https://github.com/ckeditor/ckeditor4/issues/3858): Fixed: Pasting content in `ENTER_BR` [enter mode](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-enterMode) crashes the editor. +* [#4891](https://github.com/ckeditor/ckeditor4/issues/4891): Fixed: The [Autogrow](https://ckeditor.com/cke4/addon/autogrow) plugin applies fixed width to the editor. + +API Changes: + +* [#4462](https://github.com/ckeditor/ckeditor4/issues/4462): [`CKEDITOR.editor#getSelection()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#method-getSelection) now returns `null` if the editor is in recreating state. +* [#4583](https://github.com/ckeditor/ckeditor4/issues/4583): Added support for new, comma-less color syntax to [`CKEDITOR.tools.color`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools_color.html). +* [#4604](https://github.com/ckeditor/ckeditor4/issues/4604): Added the [`CKEDITOR.plugins.clipboard.dataTransfer#isFileTransfer()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_clipboard_dataTransfer.html#method-isFileTransfer) method. +* [#4790](https://github.com/ckeditor/ckeditor4/issues/4790): Added `callback` parameter to [`CKEDITOR.plugins.preview#createPreview()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_preview.html#method-createPreview) method. + +Other Changes: + +* [#4866](https://github.com/ckeditor/ckeditor4/issues/#4866): The [Flash](https://ckeditor.com/cke4/addon/flash) plugin is now deprecated and has been removed from CKEditor 4. +* [#4901](https://github.com/ckeditor/ckeditor4/issues/4901): Redesigned buttons placement in the [Content templates](https://ckeditor.com/cke4/addon/templates) dialog to make it more UX friendly. Thanks to [Fynn96](https://github.com/Fynn96)! + +## CKEditor 4.16.2 + +**Security Updates:** + +* Fixed XSS vulnerability in the [Clipboard](https://ckeditor.com/cke4/addon/clipboard) plugin reported by [Anton Subbotin](https://github.com/skavans). + + Issue summary: The vulnerability allowed to abuse paste functionality using malformed HTML, which could result in injecting arbitrary HTML into the editor. See [security advisory](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-7889-rm5j-hpgg) for more details. + +* Fixed XSS vulnerability in the [Widget](https://ckeditor.com/cke4/addon/widget) plugin reported by [Anton Subbotin](https://github.com/skavans). + + Issue summary: The vulnerability allowed to abuse undo functionality using malformed [Widget](https://ckeditor.com/cke4/addon/widget) HTML, which could result in executing JavaScript code. See [security advisory](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-6226-h7ff-ch6c) for more details. + +* Fixed XSS vulnerability in the [Fake Objects](https://ckeditor.com/cke4/addon/fakeobjects) plugin reported by [Mika Kulmala](https://github.com/kulmik). + + Issue summary: The vulnerability allowed to inject malformed [Fake Objects](https://ckeditor.com/cke4/addon/fakeobjects) HTML, which could result in executing JavaScript code. See [security advisory](https://github.com/ckeditor/ckeditor4/security/advisories/GHSA-m94c-37g6-cjhc) for more details. + +You can read more details in the relevant security advisory and [contact us](security@cksource.com) if you have more questions. + +**An upgrade is highly recommended!** + +Fixed Issues: +* [#4777](https://github.com/ckeditor/ckeditor4/issues/4777): Fixed: HTML comments in widgets not processed correctly. +* [#4733](https://github.com/ckeditor/ckeditor4/pull/4733): Fixed: [Link](https://ckeditor.com/cke4/addon/link) prevent duplicate anchors in text with styles. + * [#4728](https://github.com/ckeditor/ckeditor4/issues/4728): Fixed: Multiple anchors in one line and multi-line with text style. + * [#3863](https://github.com/ckeditor/ckeditor4/issues/3863): Fixed: Multiple anchors in single word with text style. +* [#3819](https://github.com/ckeditor/ckeditor4/issues/3819): [Chrome] Fixed: After removing one of the two consecutive spaces, the ` ` character appears in the editor instead of a space. +* [#4666](https://github.com/ckeditor/ckeditor4/pull/4666): [IE] Introduce CSS.escape polyfill. Thanks to [limingli0707](https://github.com/limingli0707)! + * [#681](https://github.com/ckeditor/ckeditor4/issues/681): Fixed: Table elements (td, tr, th, ..) with an id that starts with dot (.) causes javascript runtime err. + * [#641](https://github.com/ckeditor/ckeditor4/issues/641): Fixed: UploadImage Plugin Widgets not working in IE, Opera, Safari, PhantomJS. +* [#3638](https://github.com/ckeditor/ckeditor4/issues/3638): Fixed: Opening the same dialog twice causes it to become hidden under the dialog's page cover. +* [#4247](https://github.com/ckeditor/ckeditor4/issues/4247): Fixed: [Color Button](https://ckeditor.com/cke4/addon/colorbutton)'s incorrect rendering on the first opening. +* [#4555](https://github.com/ckeditor/ckeditor4/issues/4555): Fixed: [Font](https://ckeditor.com/cke4/addon/font) styles with attributes are not applied correctly when used multiple times over the same selection. +* [#4782](https://github.com/ckeditor/ckeditor4/issues/4782): [Firefox] Fixed: `TypeError` is thrown when switching to Source View and back while [Autocomplete](https://ckeditor.com/cke4/addon/autocomplete) plugin is enabled. + +## CKEditor 4.16.1 + +Fixed Issues: +* [#4617](https://github.com/ckeditor/ckeditor4/issues/4617): Fixed: [Autocomplete](https://ckeditor.com/cke4/addon/autocomplete) is not accessible in inline editors. +* [#4493](https://github.com/ckeditor/ckeditor4/issues/4493): Fixed: The [drop-down](https://ckeditor.com/cke4/addon/richcombo) label does not reflect the current value of the drop-down. +* [#1572](https://github.com/ckeditor/ckeditor4/issues/1572): Fixed: A paragraph before or after a [widget](https://ckeditor.com/cke4/addon/widget) cannot be removed. Thanks to [bunglegrind](https://github.com/bunglegrind)! +* [#4301](https://github.com/ckeditor/ckeditor4/issues/4301): Fixed: Pasted content is overwritten when pasted in an initially empty editor with the [`div` Enter mode](https://ckeditor.com/docs/ckeditor4/latest/features/enterkey.html). +* [#4351](https://github.com/ckeditor/ckeditor4/issues/4351): Fixed: Incorrect values for RGBA/HSLA colors in [Color Dialog](https://ckeditor.com/cke4/addon/colordialog). +* [#4509](https://github.com/ckeditor/ckeditor4/issues/4509): Fixed: Incorrect handling of drag & drop inside [widgets](https://ckeditor.com/cke4/addon/widget) and nested editables. +* [#4611](https://github.com/ckeditor/ckeditor4/issues/4611): [Android, iOS] Fixed: Incorrect hover styles for buttons in the toolbar on mobile devices. +* [#4652](https://github.com/ckeditor/ckeditor4/issues/4652): Fixed: [Event data](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_eventInfo.html) set to `false` is treated as an event cancelation. +* [#4659](https://github.com/ckeditor/ckeditor4/issues/4659): Fixed: [`CKEDITOR.htmlParser`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_htmlParser.html) does not treat `--!>` as a comment end tag correctly. + +## CKEditor 4.16 + +**Security Updates:** + +* Fixed ReDoS vulnerability in the [Autolink](https://ckeditor.com/cke4/addon/autolink) plugin. + + Issue summary: It was possible to execute a ReDoS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted URL-like text into the editor and press Enter or Space. + +* Fixed ReDoS vulnerability in the [Advanced Tab for Dialogs](https://ckeditor.com/cke4/addon/dialogadvtab) plugin. + + Issue summary: It was possible to execute a ReDoS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted text into the Styles dialog. + +**An upgrade is highly recommended!** + +New Features: + +* [#2800](https://github.com/ckeditor/ckeditor4/issues/2800): Unsupported image formats are now gracefully handled by the [Paste from Word](https://ckeditor.com/cke4/addon/pastefromword) plugin on paste, additionally showing descriptive error messages. +* [#2800](https://github.com/ckeditor/ckeditor4/issues/2800): Unsupported image formats are now gracefully handled by the [Paste from LibreOffice](https://ckeditor.com/cke4/addon/pastefromlibreoffice) plugin on paste, additionally showing descriptive error messages. +* [#3582](https://github.com/ckeditor/ckeditor4/issues/3582): Introduced smart positioning of the [Autocomplete](https://ckeditor.com/cke4/addon/autocomplete) panel used by the [Mentions](https://ckeditor.com/cke4/addon/mentions) and [Emoji](https://ckeditor.com/cke4/addon/emoji) plugins. The panel will now be additionally positioned related to the browser viewport to be always fully visible. +* [#4388](https://github.com/ckeditor/ckeditor4/issues/4388): Added the option to remove an iframe created with the [IFrame Dialog](https://ckeditor.com/cke4/addon/iframe) plugin from the sequential keyboard navigation using the `tabindex` attribute. Thanks to [Timo Kirkkala](https://github.com/kirkkala)! + +Fixed Issues: + +* [#1134](https://github.com/ckeditor/ckeditor4/issues/1134): [Safari] Fixed: [Paste from Word](https://ckeditor.com/cke4/addon/pastefromword) does not embed images. +* [#2800](https://github.com/ckeditor/ckeditor4/issues/2800): Fixed: No images are imported from Microsoft Word when the content is pasted via the [Paste from Word](https://ckeditor.com/cke4/addon/pastefromword) plugin if there is at least one image of unsupported format. +* [#4379](https://github.com/ckeditor/ckeditor4/issues/4379): [Edge] Fixed: Incorrect detection of the [high contrast mode](https://ckeditor.com/docs/ckeditor4/latest/guide/dev_a11y.html#high-contrast-mode). +* [#4422](https://github.com/ckeditor/ckeditor4/issues/4422): Fixed: Missing space between the button name and the keyboard shortcut inside the button label in the [high contrast mode](https://ckeditor.com/docs/ckeditor4/latest/guide/dev_a11y.html#high-contrast-mode). +* [#2208](https://github.com/ckeditor/ckeditor4/issues/2208): [IE] Fixed: The [Autolink](https://ckeditor.com/cke4/addon/autolink) plugin duplicates the native browser implementation. +* [#1824](https://github.com/ckeditor/ckeditor4/issues/1824): Fixed: The [Autolink](https://ckeditor.com/cke4/addon/autolink) plugin should require the [Link](https://ckeditor.com/cke4/addon/link) plugin. +* [#4253](https://github.com/ckeditor/ckeditor4/issues/4253): Fixed: The [Editor Placeholder](https://ckeditor.com/cke4/addon/editorplaceholder) plugin throws an error during the editor initialization with [`config.fullPage`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-fullPage) enabled when there is no `` tag in the editor content. +* [#4372](https://github.com/ckeditor/ckeditor4/issues/4372): Fixed: The [Autogrow](https://ckeditor.com/cke4/addon/autogrow) plugin changes the editor's width when used with an absolute [`config.width`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-width) value. + +API Changes: + +* [#4358](https://github.com/ckeditor/ckeditor4/issues/4358): Introduced the [`CKEDITOR.tools.color`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_tools_color.html) class which adds colors validation and methods for converting colors between various formats: named colors, HEX, RGB, RGBA, HSL and HSLA. +* [#3782](https://github.com/ckeditor/ckeditor4/issues/3782): Moved the [`CKEDITOR.plugins.pastetools.filters.word.images`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_pastetools_filters_word_images.html) filters to the [`CKEDITOR.plugins.pastetools.filters.image`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_pastetools_filters_image.html) namespace. +* [#4297](https://github.com/ckeditor/ckeditor4/issues/4297): All [`CKEDITOR.plugins.pastetools.filters`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_plugins_pastetools_filters.html) are now available under the [`CKEDITOR.pasteTools`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#property-pasteTools) alias. +* [#4394](https://github.com/ckeditor/ckeditor4/issues/4394): Introduced [`CKEDITOR.ajax`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_ajax.html) specialized loading methods for loading binary ([`CKEDITOR.ajax.loadBinary()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_ajax.html#method-loadBinary)) and text ([`CKEDITOR.ajax.loadText()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_ajax.html#method-loadText)) data. + +Other Changes: + +* The [WebSpellChecker](https://ckeditor.com/cke4/addon/wsc) (WSC) plugin is now disabled by default in [Standard and Full presets](https://ckeditor.com/cke4/presets). It can be enabled via [`extraPlugins`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-extraPlugins) configuration option. + +## CKEditor 4.15.1 + +**Security Updates:** + +* Fixed XSS vulnerability in the [Color History feature](https://ckeditor.com/docs/ckeditor4/latest/features/colorbutton.html#color-history) reported by [Mark Wade](https://github.com/mark-wade). + + Issue summary: It was possible to execute an XSS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted HTML code into the [Color Button](https://ckeditor.com/cke4/addon/colorbutton) dialog. + +**An upgrade is highly recommended!** + +Fixed Issues: + +* [#4293](https://github.com/ckeditor/ckeditor4/issues/4293): Fixed: The [`CKEDITOR.inlineAll()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-inlineAll) method tries to initialize inline editor also on elements with an editor already attached to them. +* [#3961](https://github.com/ckeditor/ckeditor4/issues/3961): Fixed: The [Table Resize](https://ckeditor.com/cke4/addon/tableresize) plugin prevents editing of merged cells. +* [#3649](https://github.com/ckeditor/ckeditor4/issues/3649): Fixed: Applying a [block format](https://ckeditor.com/docs/ckeditor4/latest/features/format.html) should remove existing block styles. +* [#4282](https://github.com/ckeditor/ckeditor4/issues/4282): Fixed: The [script loader](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_scriptLoader.html) does not execute callback for scripts already loaded when called for the second time. Thanks to [Alexander Korotkevich](https://github.com/aldoom)! +* [#4273](https://github.com/ckeditor/ckeditor4/issues/4273): Fixed: A memory leak in the [`CKEDITOR.domReady()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-domReady) method connected with not removing `load` event listeners. Thanks to [rohit1](https://github.com/rohit1)! +* [#1330](https://github.com/ckeditor/ckeditor4/issues/1330): Fixed: Incomplete CSS margin parsing if an `auto` or `0` value is used. +* [#4286](https://github.com/ckeditor/ckeditor4/issues/4286): Fixed: The [Auto Grow](https://ckeditor.com/cke4/addon/autogrow) plugin causes the editor width to be set to `0` on editor resize. +* [#848](https://github.com/ckeditor/ckeditor4/issues/848): Fixed: Arabic text not being "bound" correctly when pasting. Thanks to [Thomas Hunkapiller](https://github.com/devoidfury) and [J. Ivan Duarte Rodríguez](https://github.com/jidrone-mbm)! + +API Changes: + +* [#3649](https://github.com/ckeditor/ckeditor4/issues/3649): Added a new [`stylesRemove`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#event-stylesRemove) editor event. + +Other Changes: + +* [#4262](https://github.com/ckeditor/ckeditor4/issues/4262): Removed the global reference to the `stylesLoaded` variable. Thanks to [Levi Carter](https://github.com/swiftMessenger)! +* Updated the [Export to PDF](https://ckeditor.com/cke4/addon/exportpdf) plugin to `1.0.1` version: + * Improved external CSS support for [classic editor](https://ckeditor.com/docs/ckeditor4/latest/examples/classic.html) by handling exceptions and displaying convenient [error messages](https://ckeditor.com/docs/ckeditor4/latest/guide/dev_errors.html#exportpdf-stylesheets-incaccessible). + +## CKEditor 4.15 + +New features: + +* [#3940](https://github.com/ckeditor/ckeditor4/issues/3940): Introduced the `colorName` property for customizing foreground and background styles in the [Color Button](https://ckeditor.com/cke4/addon/colorbutton) plugin via the [`config.colorButton_foreStyle`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-colorButton_foreStyle) and [`config.colorButton_backStyle`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-colorButton_backStyle) configuration options. +* [#3793](https://github.com/ckeditor/ckeditor4/issues/3793): Introduced the [Editor Placeholder](https://ckeditor.com/cke4/addon/editorplaceholder) plugin. +* [#1795](https://github.com/ckeditor/ckeditor4/issues/1795): The colors picked from the [Color Dialog](https://ckeditor.com/cke4/addon/colordialog) are now stored in the [Color Button](https://ckeditor.com/cke4/addon/colorbutton) palette and can be reused easily. +* [#3783](https://github.com/ckeditor/ckeditor4/issues/3783): The colors used in the document are now displayed as a part of the [Color Button](https://ckeditor.com/cke4/addon/colorbutton) palette. + +Fixed Issues: + +* [#4060](https://github.com/ckeditor/ckeditor4/issues/4060): Fixed: The content inside a [widget](https://ckeditor.com/cke4/addon/widget) nested editable is escaped twice. +* [#4183](https://github.com/ckeditor/ckeditor4/issues/4183): [Safari] Fixed: Incorrect image dimensions when using the [Easy Image](https://ckeditor.com/cke4/addon/easyimage) plugin alongside the [IFrame Editing Area](https://ckeditor.com/cke4/addon/wysiwygarea) plugin. +* [#3693](https://github.com/ckeditor/ckeditor4/issues/3693): Fixed: Incorrect default values for several [Color Button](https://ckeditor.com/cke4/addon/colorbutton) configuration variables in the API documentation. +* [#3795](https://github.com/ckeditor/ckeditor4/issues/3795): Fixed: Setting the [`config.dataIndentationChars`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-dataIndentationChars) configuration option to an empty string is ignored and replaced by a tab (`\t`) character. Thanks to [Thomas Grinderslev](https://github.com/Znegl)! +* [#4107](https://github.com/ckeditor/ckeditor4/issues/4107): Fixed: Multiple [Autocomplete](https://ckeditor.com/cke4/addon/autocomplete) instances cause keyboard navigation issues. +* [#4041](https://github.com/ckeditor/ckeditor4/issues/4041): Fixed: The[`selection.scrollIntoView`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_dom_selection.html#method-scrollIntoView) method throws an error when the editor selection is not set. +* [#3361](https://github.com/ckeditor/ckeditor4/issues/3361): Fixed: Loading multiple [custom editor configurations](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-customConfig) is prone to a race condition between these. +* [#4007](https://github.com/ckeditor/ckeditor4/issues/4007): Fixed: Screen readers do not announce the [Rich Combo](https://ckeditor.com/cke4/addon/richcombo) plugin is collapsed or expanded. +* [#4141](https://github.com/ckeditor/ckeditor4/issues/4141): Fixed: The styles are incorrectly applied when there is a `` DOM element. + +Other Changes: + +* [#13859](https://dev.ckeditor.com/ticket/13859): Test cases created with `bender.tools.createTestsForEditors` will also receive editor bot as a second parameter. + +## CKEditor 4.5.4 + +New Features: + +* [#13632](https://dev.ckeditor.com/ticket/13632): Introduce error logging mechanism. +* [#13730](https://dev.ckeditor.com/ticket/13730): Switch to the new error logging mechanism. + +Fixed Issues: + +* [#9856](https://dev.ckeditor.com/ticket/9856): Fixed: Cannot use the native context menu together with the [Div Editing Area](https://ckeditor.com/cke4/addon/divarea) plugin. Thanks to [Mark Wade](https://github.com/mark-wade)! +* [#12733](https://dev.ckeditor.com/ticket/12733): [IE9+] Fixed: Radio button `onChange` does not work. Thanks to [Iliya Kostadinov](https://github.com/iliyakostadinov)! +* [#13142](https://dev.ckeditor.com/ticket/13142): [Edge] Fixed: *Ctrl+A* and then *Backspace* result in an empty `
` element. +* [#13599](https://dev.ckeditor.com/ticket/13599): Fixed: Cross-editor drag and drop of an inline widget results in error/artifacts. +* [#13640](https://dev.ckeditor.com/ticket/13640): [IE] Fixed: Dropping a widget outside the `` element is not handled correctly. +* [#13533](https://dev.ckeditor.com/ticket/13533): Fixed: No progress during upload. +* [#13680](https://dev.ckeditor.com/ticket/13680): Fixed: The parser should allow the `` element to be a child of the `` element. +* [#11724](https://dev.ckeditor.com/ticket/11724): [Touch devices] Fixed: Drop-downs often hide right after opening them. +* [#13690](https://dev.ckeditor.com/ticket/13690): Fixed: Copying content from IE to Chrome adds an extra paragraph. +* [#13284](https://dev.ckeditor.com/ticket/13284): Fixed: Cannot drag and drop a widget if the text caret is placed just after the widget instance. +* [#13516](https://dev.ckeditor.com/ticket/13516): Fixed: CKEditor removes empty HTML5 anchors without the `name` attribute. +* [#13765](https://dev.ckeditor.com/ticket/13765): [Safari 9] Fixed: Problems with rendering samples. + +Other Changes: + +* [#11725](https://dev.ckeditor.com/ticket/11725): Marked [`CKEDITOR.env.mobile`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_env.html#property-mobile) as deprecated. The reason is that it is no longer clear what "mobile" means. +* [#13737](https://dev.ckeditor.com/ticket/13737): Upgraded [Bender.js](https://github.com/benderjs/benderjs) to 0.4.1. + +## CKEditor 4.5.3 + +New Features: + +* [#13501](https://dev.ckeditor.com/ticket/13501): Added the [`config.fileTools_defaultFileName`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-fileTools_defaultFileName) option to allow setting a default file name for paste uploads. +* [#13603](https://dev.ckeditor.com/ticket/13603): Added support for uploading dropped BMP images. + +Fixed Issues: + +* [#13590](https://dev.ckeditor.com/ticket/13590): Fixed: Various issues related to the [Paste from Word](https://ckeditor.com/cke4/addon/pastefromword) feature. Fixes also: + * [#11215](https://dev.ckeditor.com/ticket/11215), + * [#8780](https://dev.ckeditor.com/ticket/8780), + * [#12762](https://dev.ckeditor.com/ticket/12762). +* [#13386](https://dev.ckeditor.com/ticket/13386): [Edge] Fixed: Issues with selecting and editing images. +* [#13568](https://dev.ckeditor.com/ticket/13568): Fixed: The [`editor.getSelectedHtml()`](https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#method-getSelectedHtml) method returns invalid results for entire content selection. +* [#13453](https://dev.ckeditor.com/ticket/13453): Fixed: Drag&drop of entire editor content throws an error. +* [#13465](https://dev.ckeditor.com/ticket/13465): Fixed: Error is thrown and the widget is lost on drag&drop if it is the only content of the editor. +* [#13414](https://dev.ckeditor.com/ticket/13414): Fixed: Content auto paragraphing in a nested editable despite editor configuration. +* [#13429](https://dev.ckeditor.com/ticket/13429): Fixed: Incorrect selection after content insertion by the [Auto Embed](https://ckeditor.com/cke4/addon/autoembed) plugin. +* [#13388](https://dev.ckeditor.com/ticket/13388): Fixed: [Table Resize](https://ckeditor.com/cke4/addon/tableresize) integration with [Undo](https://ckeditor.com/cke4/addon/undo) is broken. + +Other Changes: + +* [#13637](https://dev.ckeditor.com/ticket/13637): Several icons were refactored. +* Updated [Bender.js](https://github.com/benderjs/benderjs) to 0.3.0 and introduced the ability to run tests via HTTPs ([#13265](https://dev.ckeditor.com/ticket/13265)). + +## CKEditor 4.5.2 + +Fixed Issues: + +* [#13609](https://dev.ckeditor.com/ticket/13609): [Edge] Fixed: The browser crashes when switching to the source mode. Thanks to [Andrew Williams and Mark Smeed](http://webxsolution.com/)! +* [PR#201](https://github.com/ckeditor/ckeditor4/pull/201): Fixed: Buttons in the toolbar configurator cause form submission. Thanks to [colemanw](https://github.com/colemanw)! +* [#13422](https://dev.ckeditor.com/ticket/13422): Fixed: A monospaced font should be used in the ` +

+ + + + + +

About

+

The BootstrapCK4-Skin is a skin for CKEditor4 based on Twitter Bootstrap3 styles.

+

Sass is used to rewrite the editor's styles and Grunt to be able to watch, convert and minify the sass into css files. These files aren't really needed for the simple use of the skin, but handy if you want to make some adjustments to it.

+

For more information about skins, please check the CKEditor Skin SDK

+ + +

Installation

+

Just skin please

+ +

Add the whole bootstrapck folder to the skin folder.
+ In ckeditor.js and config.js change the skin name to "bootstrapck".
+ Done!

+ +

The whole skin - sass - grunt package

+ +

All the sass files are included in the bootstrapck folder, so first follow the 'just skin please'-steps
+ Now add the Gruntfile.js and the package.json to de ckeditor folder.

+
npm install 
grunt build
+

You can start tampering now.

+

Or if you'd like to adjust the icons, use the bootstrapck-dev folder instead.

+ + +

Authors

+

Indri Kenens (indri.kenens@kunstmaan.be)

+ +

Contact

+

Kunstmaan (support@kunstmaan.be)

+ + +

Download

+

+ You can download this project in either + zip or + tar formats. +

+

You can also clone the project with Git + by running:

$ git clone git://github.com/Kunstmaan/BootstrapCK4-Skin

+ + +

Previous version

+

If you would like to get the Bootstrap2 skin for CKeditor3, here's the previous version.

+ + + +
+ + + + + + + + + + + + + + + + + + diff --git a/editor/ckeditor/skins/bootstrapck/sample/css/bootstrapck-sample.css b/editor/ckeditor/skins/bootstrapck/sample/css/bootstrapck-sample.css new file mode 100644 index 0000000..c135ef0 --- /dev/null +++ b/editor/ckeditor/skins/bootstrapck/sample/css/bootstrapck-sample.css @@ -0,0 +1 @@ +body{margin-top:1.0em;background-color:#fff;font-family:Helvetica,Arial,sans-serif;color:#404040}.container{margin:0 auto;width:900px;padding:0 0 20px}h1{font-size:40px;margin:40px 0 28px;padding:110px 0 9px;border-bottom:1px solid #ccc}h1 a,h1 a:visited,h1 a:focus,h1 a:hover{color:#404040;text-decoration:none}h1 span{font-size:18px;font-weight:normal;color:#bfbfbf}h1 span a,h1 span a:visited,h1 span a:focus,h1 span a:hover{color:#bfbfbf}h1 a{text-decoration:none}h2{font-size:23px;margin:10px 0 8px}h3{font-size:16px;margin:10px 0 8px}p{margin:0 0 30px;font-size:13px;line-height:18px}a,a:visited,a:focus{color:#0069d6;text-decoration:none}a:hover{color:#00438a;text-decoration:underline}.download{float:right}pre{background:#f5f5f5;color:#404040;padding:16px;border:1px solid rgba(0,0,0,0.05);border-radius:4px;box-shadow:0 1px 1px rgba(0,0,0,0.05) inset;margin:-20px 0 10px;line-height:200%}.twitter{margin:-20px 0 40px;color:#666}.twitter iframe{vertical-align:bottom;margin:0 0 0 5px}.footer{text-align:center;padding-top:20px;margin-top:60px;font-size:14px;color:#808080;border-top:1px solid #ccc}.footer a,.footer a:visited,.footer a:focus{color:#333}.footer a:hover{color:#000} \ No newline at end of file diff --git a/editor/ckeditor/skins/bootstrapck/sample/js/analytics.js b/editor/ckeditor/skins/bootstrapck/sample/js/analytics.js new file mode 100644 index 0000000..fd6c93a --- /dev/null +++ b/editor/ckeditor/skins/bootstrapck/sample/js/analytics.js @@ -0,0 +1,4 @@ +var _ga=_ga||{},_gaq=_gaq||[];_ga.trackSocial=function(a,c){_ga.trackFacebook(a,c);_ga.trackTwitter(a,c)}; +_ga.trackFacebook=function(a,c){var d=_ga.buildTrackerName_(c);try{FB&&FB.Event&&FB.Event.subscribe&&(FB.Event.subscribe("edge.create",function(b){_gaq.push([d+"_trackSocial","facebook","like",b,a])}),FB.Event.subscribe("edge.remove",function(b){_gaq.push([d+"_trackSocial","facebook","unlike",b,a])}),FB.Event.subscribe("message.send",function(b){_gaq.push([d+"_trackSocial","facebook","send",b,a])}))}catch(e){}};_ga.buildTrackerName_=function(a){return a?a+".":""}; +_ga.trackTwitter=function(a,c){var d=_ga.buildTrackerName_(c);try{twttr&&twttr.events&&twttr.events.bind&&twttr.events.bind("tweet",function(b){if(b){var c;b.target&&"IFRAME"==b.target.nodeName&&(c=_ga.extractParamFromUri_(b.target.src,"url"));_gaq.push([d+"_trackSocial","twitter","tweet",c,a])}})}catch(e){}};_ga.extractParamFromUri_=function(a,c){if(a){var a=a.split("#")[0],d=a.split("?");if(1!=d.length)for(var d=decodeURI(d[1]),c=c+"=",d=d.split("&"),e=0,b;b=d[e];++e)if(0===b.indexOf(c))return unescape(b.split("=")[1])}}; +jQuery&&jQuery("a").click(function(){var a=jQuery(this).attr("href");null!=a&&(a.match(/^http/i)&&!a.match(document.domain)?_gaq.push(["_trackEvent","outgoing","click",a]):a.match(/\.(doc|pdf|xls|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)$/i)?_gaq.push(["_trackEvent","download","click",a]):a.match(/^mailto:/i)&&_gaq.push(["_trackEvent","mailto","click",a]))}); \ No newline at end of file diff --git a/editor/ckeditor/skins/bootstrapck/sample/js/jquery-1.11.0.min.js b/editor/ckeditor/skins/bootstrapck/sample/js/jquery-1.11.0.min.js new file mode 100644 index 0000000..662b227 --- /dev/null +++ b/editor/ckeditor/skins/bootstrapck/sample/js/jquery-1.11.0.min.js @@ -0,0 +1,189 @@ +!function(o,ea){"object"==typeof module&&"object"==typeof module.exports?module.exports=o.document?ea(o,!0):function(o){if(!o.document)throw Error("jQuery requires a window with a document");return ea(o)}:ea(o)}("undefined"!=typeof window?window:this,function(o,ea){function Ba(a){var b=a.length,d=c.type(a);return"function"===d||c.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===d||0===b||"number"==typeof b&&0e;e++)c.event.add(b,d,h[d][e])}g.data&&(g.data=c.extend({},g.data))}}function hb(a,b){var d=c(b.createElement(a)).appendTo(b.body),e=o.getDefaultComputedStyle?o.getDefaultComputedStyle(d[0]).display:c.css(d[0],"display");return d.detach(),e}function ib(a){var b=l,d=jb[a];return d||(d=hb(a,b),"none"!==d&&d||(fa=(fa||c(" + diff --git a/templates/review.mustache b/templates/review.mustache new file mode 100644 index 0000000..e0a53d9 --- /dev/null +++ b/templates/review.mustache @@ -0,0 +1,44 @@ +
+
+
+ + +
{{title}}
+ + + {{# maxScore }} +
+ + +
+ + {{# str }} reportingscorelabel, mod_hvp {{/ str }} + + + + {{rawScore}} + + {{# str }} reportingscoredelimiter, mod_hvp {{/ str }} {{maxScore}} + +
+ + +
+ + {{# str }} reportingscaledscorelabel, mod_hvp {{/ str }} + + + + {{scaledScore}} + + {{# str }} reportingscoredelimiter, mod_hvp {{/ str }} {{maxScaledScore}} + +
+
+ {{/ maxScore }} + +
+ + +
{{{report}}}
+
diff --git a/thirdpartylibs.xml b/thirdpartylibs.xml new file mode 100644 index 0000000..ef5c841 --- /dev/null +++ b/thirdpartylibs.xml @@ -0,0 +1,21 @@ + + + + library + H5P Core + 1.13 + MIT + + + editor + H5P Editor + (86b5450) + MIT + + + reporting + H5P Reporting + (8fe2c5d) + MIT + + diff --git a/upgrade_content_page.php b/upgrade_content_page.php new file mode 100644 index 0000000..5a549a1 --- /dev/null +++ b/upgrade_content_page.php @@ -0,0 +1,105 @@ +. +/** + * Responsible for displaying the content upgrade page + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once("../../config.php"); +require_once($CFG->libdir.'/adminlib.php'); +require_once("locallib.php"); + +// No guest autologin. +require_login(0, false); + +$libraryid = required_param('library_id', PARAM_INT); +$pageurl = new moodle_url('/mod/hvp/upgrade_content_page.php', array('library_id' => $libraryid)); +$PAGE->set_url($pageurl); +admin_externalpage_setup('h5plibraries'); +$PAGE->set_title("{$SITE->shortname}: " . get_string('upgrade', 'hvp')); + +// Inform moodle which menu entry currently is active! +$core = \mod_hvp\framework::instance(); +global $DB; +$results = $DB->get_records_sql('SELECT hl2.id as id, hl2.machine_name as name, hl2.title, hl2.major_version, + hl2.minor_version, hl2.patch_version + FROM {hvp_libraries} hl1 JOIN {hvp_libraries} hl2 ON hl1.machine_name = hl2.machine_name + WHERE hl1.id = ? + ORDER BY hl2.title ASC, hl2.major_version ASC, hl2.minor_version ASC', array($libraryid)); +$versions = array(); +foreach ($results as $result) { + $versions[$result->id] = $result; +} +$library = $versions[$libraryid]; +$upgrades = $core->getUpgrades($library, $versions); + +$PAGE->set_heading(get_string('upgradeheading', 'hvp', $library->title . ' (' . \H5PCore::libraryVersion($library) . ')')); + +// Get num of contents that can be upgraded. +$numcontents = $core->h5pF->getNumContent($libraryid); +if (count($versions) < 2) { + echo $OUTPUT->header(); + echo get_string('upgradenoavailableupgrades', 'hvp'); +} else if ($numcontents === 0) { + echo $OUTPUT->header(); + echo get_string('upgradenothingtodo', 'hvp'); +} else { + $settings = array( + 'libraryInfo' => array( + 'message' => get_string('upgrademessage', 'hvp', $numcontents), + 'inProgress' => get_string('upgradeinprogress', 'hvp'), + 'error' => get_string('upgradeerror', 'hvp'), + 'errorData' => get_string('upgradeerrordata', 'hvp'), + 'errorScript' => get_string('upgradeerrorscript', 'hvp'), + 'errorContent' => get_string('upgradeerrorcontent', 'hvp'), + 'errorParamsBroken' => get_string('upgradeerrorparamsbroken', 'hvp'), + 'errorLibrary' => get_string('upgradeerrormissinglibrary', 'hvp'), + 'errorTooHighVersion' => get_string('upgradeerrortoohighversion', 'hvp'), + 'errorNotSupported' => get_string('upgradeerrornotsupported', 'hvp'), + 'done' => get_string('upgradedone', 'hvp', $numcontents) . + ' ' . + get_string('upgradereturn', 'hvp') . '', + 'library' => array( + 'name' => $library->name, + 'version' => $library->major_version . '.' . $library->minor_version, + ), + 'libraryBaseUrl' => (new moodle_url('/mod/hvp/ajax.php', + array('action' => 'getlibrarydataforupgrade')))->out(false) . '&library=', + 'scriptBaseUrl' => (new moodle_url('/mod/hvp/library/js'))->out(false), + 'buster' => hvp_get_cache_buster(), + 'versions' => $upgrades, + 'contents' => $numcontents, + 'buttonLabel' => get_string('upgradebuttonlabel', 'hvp'), + 'infoUrl' => (new moodle_url('/mod/hvp/ajax.php', array('action' => 'libraryupgradeprogress', + 'library_id' => $libraryid)))->out(false), + 'total' => $numcontents, + 'token' => \H5PCore::createToken('contentupgrade') + ) + ); + + // Add JavaScripts. + $liburl = \mod_hvp\view_assets::getsiteroot() . '/mod/hvp/library/'; + hvp_admin_add_generic_css_and_js($PAGE, $liburl, $settings); + $PAGE->requires->js(new moodle_url($liburl . 'js/h5p-version.js' . hvp_get_cache_buster()), true); + $PAGE->requires->js(new moodle_url($liburl . 'js/h5p-content-upgrade.js' . hvp_get_cache_buster()), true); + echo $OUTPUT->header(); + echo '
' . get_string('enablejavascript', 'hvp') . '
'; +} + +echo $OUTPUT->footer(); diff --git a/version.php b/version.php new file mode 100644 index 0000000..295e63d --- /dev/null +++ b/version.php @@ -0,0 +1,31 @@ +. + +/** + * @package mod + * @subpackage hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$plugin->version = 2023052600; +$plugin->requires = 2013051403; +$plugin->cron = 0; +$plugin->component = 'mod_hvp'; +$plugin->maturity = MATURITY_STABLE; +$plugin->release = '1.23.1'; diff --git a/view.css b/view.css new file mode 100644 index 0000000..c287fd6 --- /dev/null +++ b/view.css @@ -0,0 +1,77 @@ +.content-hub-icon { + font-family: h5p!important; + speak: none; + font-style: normal; + font-weight: 400; + font-variant: normal; + text-transform: none; + line-height: 1; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} +.content-hub-icon:before { + content: "\e93b"; +} +.content-hub-options { + font-size: 14px; + margin: 0 auto; + display: flex; + flex-wrap: wrap; + align-items: baseline; + color: #333333; + box-shadow: 0 4px 4px -4px #e0e0e0; + z-index: 1; + position: relative; + padding: 1em 0; +} +.content-hub-options > div { + margin-left: 2em; + white-space: nowrap; +} +.content-hub-options > div:first-child { + margin-left: 0; + font-weight: bold; +} +.content-hub-options > div.content-hub-share { + font-weight: normal; +} +.content-hub-options > div:first-child > i { + margin-right: 0.5em; + font-size: 1.25em; + vertical-align: middle; + display: inline-block; +} +.content-hub-options a { + color: #186df7; +} +.content-hub-options a span { + text-decoration: underline; +} +.content-hub-options form { + margin: 0; +} +.content-hub-options .content-hub-sharing { + font-size: 0.917em; + color: #186df7; +} +.content-hub-options .content-hub-sync a:before, +.content-hub-options .content-hub-unshare a:before, +.content-hub-options .content-hub-sharing:before { + font-family: "h5p"; + margin-right: 0.5em; + font-size: 0.7em; + line-height: 1; + content: "\e917"; +} +.content-hub-options .content-hub-unshare a:before { + content: "\e916"; +} +.content-hub-options .content-hub-sharing:before { + content: "\e917"; + display: inline-block; + animation: spin 2s linear infinite; +} +@keyframes spin { + from {transform:rotate(0deg);} + to {transform:rotate(360deg);} +} diff --git a/view.php b/view.php new file mode 100644 index 0000000..8368ad7 --- /dev/null +++ b/view.php @@ -0,0 +1,101 @@ +. +/** + * View H5P Content + * + * @package mod_hvp + * @copyright 2016 Joubel AS + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +require_once("../../config.php"); +require_once("locallib.php"); + +global $PAGE, $DB, $CFG, $OUTPUT; + +$id = required_param('id', PARAM_INT); + +// Verify course context. +$cm = get_coursemodule_from_id('hvp', $id); +if (!$cm) { + print_error('invalidcoursemodule'); +} +$course = $DB->get_record('course', array('id' => $cm->course)); +if (!$course) { + print_error('coursemisconf'); +} +require_course_login($course, true, $cm); +$context = context_module::instance($cm->id); +require_capability('mod/hvp:view', $context); + +// Set up view assets. +$view = new \mod_hvp\view_assets($cm, $course); +$content = $view->getcontent(); +$view->validatecontent(); + +// Configure page. +$PAGE->set_url(new \moodle_url('/mod/hvp/view.php', array('id' => $id))); +$PAGE->set_title(format_string($content['title'])); +$PAGE->set_heading($course->fullname); + +// Add H5P assets to page. +$view->addassetstopage(); +$view->logviewed(); + +$PAGE->requires->css(new moodle_url(\mod_hvp\view_assets::getsiteroot() . '/mod/hvp/view.css')); + +// Print page HTML. +echo $OUTPUT->header(); +if ($CFG->branch < 400) { + echo $OUTPUT->heading(format_string($content['title'])); + echo '
'; + + // Output introduction. + if (trim(strip_tags($content['intro'], ''))) { + echo $OUTPUT->box_start('mod_introbox', 'hvpintro'); + echo format_module_intro('hvp', (object) array( + 'intro' => $content['intro'], + 'introformat' => $content['introformat'], + ), $cm->id); + echo $OUTPUT->box_end(); + } +} + +$hashub = (has_capability('mod/hvp:share', $context) && !empty(get_config('mod_hvp', 'site_uuid')) && !empty(get_config('mod_hvp', 'hub_secret'))); +$isshared = $content['shared'] === '1'; +$huboptionsdata = array( + 'id' => $id, + 'isshared' => $isshared +); + +// Update Hub status for content before printing out messages. +if ($hashub && $isshared) { + $newstate = hvp_update_hub_status($content); + $synced = $newstate !== false ? $newstate : intval($content['synced']); + $huboptionsdata['canbesynced'] = $synced !== \H5PContentHubSyncStatus::SYNCED && $synced !== \H5PContentHubSyncStatus::WAITING; + $huboptionsdata['waitingclass'] = $synced === \H5PContentHubSyncStatus::WAITING ? '' : ' hidden'; + $huboptionsdata['token'] = \H5PCore::createToken('share_' . $id); +} + +// Print any messages. +\mod_hvp\framework::printMessages('info', \mod_hvp\framework::messages('info')); +\mod_hvp\framework::printMessages('error', \mod_hvp\framework::messages('error')); + +if ($hashub) { + echo $OUTPUT->render_from_template('mod_hvp/hub_options', $huboptionsdata); +} + +$view->outputview(); +echo $OUTPUT->footer(); diff --git a/xapi-collector.js b/xapi-collector.js new file mode 100644 index 0000000..1ed2dfd --- /dev/null +++ b/xapi-collector.js @@ -0,0 +1,173 @@ +/** + * Collect results from xAPI events + */ +(function($) { + + /** + * Finds a H5P library instance in an array based on the content ID + * + * @param {Array} instances + * @param {number} contentId + * @returns {Object|undefined} Content instance + */ + function findInstanceInArray(instances, contentId) { + if (instances !== undefined && contentId !== undefined) { + for (var i = 0; i < instances.length; i++) { + if (instances[i].contentId === contentId) { + return instances[i]; + } + } + } + return undefined; + } + + /** + * Finds the global instance from content id by looking through the DOM + * + * @param {number} [contentId] Content identifier + * @returns {Object} Content instance + */ + function getH5PInstance(contentId) { + var iframes; + var instance = null; // Returning null means no instance is found. + + // No content id given, search for instance. + if (!contentId) { + instance = H5P.instances[0]; + if (!instance) { + iframes = document.getElementsByClassName('h5p-iframe'); + // Assume first iframe. + instance = iframes[0].contentWindow.H5P.instances[0]; + } + } else { + // Try this documents instances. + instance = findInstanceInArray(H5P.instances, contentId); + if (!instance) { + // Locate iframes. + iframes = document.getElementsByClassName('h5p-iframe'); + for (var i = 0; i < iframes.length; i++) { + // Search through each iframe for content. + instance = findInstanceInArray(iframes[i].contentWindow.H5P.instances, contentId); + if (instance) { + break; + } + } + } + } + + return instance; + } + + function getIframe(contentId) { + let iFrames; + + // No content id given. + if (!contentId) { + iFrames = document.getElementsByClassName('h5p-iframe'); + // Assume first iframe. + return iFrames[0]; + } + + // Locate iFrames. + iFrames = document.getElementsByClassName('h5p-iframe'); + for (let i = 0; i < iFrames.length; i++) { + // Search through each iframe for content. + if (findInstanceInArray(iFrames[i].contentWindow.H5P.instances, contentId)) { + return iFrames[i]; + } + } + + return null; + } + + /** + * Get xAPI data for content type and send off. + * + * @param {number} contentId Content id + * @param {Object} event Original xAPI event + */ + function storeXAPIData(contentId, event) { + var xAPIData; + var instance = getH5PInstance(contentId); + + // Use getXAPIData contract, needed to get children. + if (instance && instance.getXAPIData) { + xAPIData = instance.getXAPIData(); + } else { + // Fallback to event data. + xAPIData = { + statement: event.data.statement + }; + } + + // Ship the xAPI result. + var data = { + contentId: contentId, + xAPIResult: JSON.stringify(xAPIData) + }; + $.post(H5PIntegration.ajax.xAPIResult, data).done(function (data) { + if (data.error) { + console.error('Storing xAPI results failed with error message:', data); + } + }).fail(function () { + if (H5P.offlineRequestQueue) { + H5P.offlineRequestQueue.add(H5PIntegration.ajax.xAPIResult, data); + return; + } + + // Let H5P iframe know that we want to queue the request for late transmission. + const iframe = getIframe(contentId); + if (!iframe) { + return; + } + iframe.contentWindow.postMessage( { + url: H5PIntegration.ajax.xAPIResult, + data: data, + context: 'h5p', + action: 'queueRequest', + }); + }); + } + + $(document).ready(function() { + // No external dispatcher. + if (!(window.H5P && H5P.externalDispatcher)) { + console.error('External dispatcher not found'); + return; + } + + // No ajax path. + if (!(window.H5PIntegration && H5PIntegration.ajax && H5PIntegration.ajax.xAPIResult)) { + console.error('No ajax path found'); + return; + } + + // Get emitted xAPI data. + H5P.externalDispatcher.on('xAPI', function(event) { + // Skip malformed events. + var hasStatement = event && event.data && event.data.statement; + if (!hasStatement) { + return; + } + + var statement = event.data.statement; + var validVerb = statement.verb && statement.verb.display && statement.verb.display['en-US']; + if (!validVerb) { + return; + } + + var isCompleted = statement.verb.display['en-US'] === 'answered' || + statement.verb.display['en-US'] === 'completed'; + var isChild = statement.context && statement.context.contextActivities && + statement.context.contextActivities.parent && + statement.context.contextActivities.parent[0] && + statement.context.contextActivities.parent[0].id; + + // Store only completed root events. + if (isCompleted && !isChild) { + // Get xAPI data with children if possible. + storeXAPIData(this.contentId, event); + } + }); + }); +})(H5P.jQuery); diff --git a/xapi-custom-report.css b/xapi-custom-report.css new file mode 100644 index 0000000..c24f28c --- /dev/null +++ b/xapi-custom-report.css @@ -0,0 +1,69 @@ +body .h5p-result { + background: #FFF; + border: solid 1px #C9C9C9; + box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.12); + color: #5C5C5C; + font-size: 15px; + height: auto; + margin: 1em 0; + padding: 30px; +} + +body .h5p-compound-container { + border: none; + box-shadow: none; + margin: 0; + padding: 0; +} + +body .h5p-reporting-main-title { + display: inline-block; + font-size: 1.3em; + font-weight: 600; +} + +body .h5p-reporting-main-container { + margin: 10px; +} + +body .h5p-reporting-main-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 10px; + + background-color: #F3F3F3; + border-bottom: solid 1px #DFDFDF; + padding: 0.7em 2em; +} + +body .h5p-reporting-main-score-wrapper { + display: inline-block; + font-size: 0.95em; + font-weight: bold; + text-align: right; +} + +body .h5p-reporting-scaled-label, +body .h5p-reporting-main-score-label { + font-weight: normal; +} + +/* Properly formats content after it has been cleaned */ +body .h5p-reporting-main-score-container, +body .h5p-reporting-main-scaled-container { + display: block; +} + +body .h5p-reporting-main-score-label, +body .h5p-reporting-main-score, +body .h5p-reporting-score-label, +body .h5p-reporting-score, +body .h5p-reporting-scaled-label, +body .h5p-reporting-scaled-score { + display: inline-block; +} + +body .h5p-reporting-main-score { + margin-left: 0.4em; +}