From 45899564b354211d7435a6a5b3ecb01f0801e682 Mon Sep 17 00:00:00 2001 From: Amaia Anabitarte Date: Fri, 6 Sep 2019 16:52:32 +0800 Subject: [PATCH 01/22] MDL-66609 core_h5p: New core_h5p subsystem New H5P libraries have been added to Moodle core_h5p in /lib/h5p. --- .eslintignore | 3 +- .stylelintignore | 3 +- h5p/classes/privacy/provider.php | 45 + lang/en/h5p.php | 24 + lib/classes/component.php | 8 + lib/components.json | 1 + lib/h5p/LICENSE.txt | 674 +++ lib/h5p/README.txt | 14 + lib/h5p/doc/spec_en.html | 168 + lib/h5p/embed.php | 20 + lib/h5p/fonts/h5p-core-21.eot | Bin 0 -> 7784 bytes lib/h5p/fonts/h5p-core-21.svg | 56 + lib/h5p/fonts/h5p-core-21.ttf | Bin 0 -> 7604 bytes lib/h5p/fonts/h5p-core-21.woff | Bin 0 -> 7680 bytes lib/h5p/h5p-default-storage.class.php | 586 +++ lib/h5p/h5p-development.class.php | 189 + lib/h5p/h5p-event-base.class.php | 191 + lib/h5p/h5p-file-storage.interface.php | 222 + lib/h5p/h5p-metadata.class.php | 151 + lib/h5p/h5p.classes.php | 4890 ++++++++++++++++++++ lib/h5p/images/h5p.svg | 16 + lib/h5p/images/throbber.gif | Bin 0 -> 1638 bytes lib/h5p/js/h5p-action-bar.js | 100 + lib/h5p/js/h5p-confirmation-dialog.js | 410 ++ lib/h5p/js/h5p-content-type.js | 41 + lib/h5p/js/h5p-content-upgrade-process.js | 313 ++ lib/h5p/js/h5p-content-upgrade-worker.js | 63 + lib/h5p/js/h5p-content-upgrade.js | 445 ++ lib/h5p/js/h5p-data-view.js | 378 ++ lib/h5p/js/h5p-display-options.js | 54 + lib/h5p/js/h5p-embed.js | 75 + lib/h5p/js/h5p-event-dispatcher.js | 258 ++ lib/h5p/js/h5p-library-details.js | 297 ++ lib/h5p/js/h5p-library-list.js | 140 + lib/h5p/js/h5p-resizer.js | 131 + lib/h5p/js/h5p-utils.js | 506 ++ lib/h5p/js/h5p-version.js | 40 + lib/h5p/js/h5p-x-api-event.js | 319 ++ lib/h5p/js/h5p-x-api.js | 119 + lib/h5p/js/h5p.js | 2833 ++++++++++++ lib/h5p/js/jquery.js | 20 + lib/h5p/js/request-queue.js | 436 ++ lib/h5p/js/settings/h5p-disable-hub.js | 68 + lib/h5p/readme_moodle.txt | 17 + lib/h5p/styles/h5p-admin.css | 344 ++ lib/h5p/styles/h5p-confirmation-dialog.css | 183 + lib/h5p/styles/h5p-core-button.css | 60 + lib/h5p/styles/h5p.css | 562 +++ lib/tests/component_test.php | 2 +- lib/thirdpartylibs.xml | 6 + lib/upgrade.txt | 2 + 51 files changed, 15480 insertions(+), 3 deletions(-) create mode 100644 h5p/classes/privacy/provider.php create mode 100644 lang/en/h5p.php create mode 100644 lib/h5p/LICENSE.txt create mode 100644 lib/h5p/README.txt create mode 100644 lib/h5p/doc/spec_en.html create mode 100644 lib/h5p/embed.php create mode 100644 lib/h5p/fonts/h5p-core-21.eot create mode 100644 lib/h5p/fonts/h5p-core-21.svg create mode 100644 lib/h5p/fonts/h5p-core-21.ttf create mode 100644 lib/h5p/fonts/h5p-core-21.woff create mode 100644 lib/h5p/h5p-default-storage.class.php create mode 100644 lib/h5p/h5p-development.class.php create mode 100644 lib/h5p/h5p-event-base.class.php create mode 100644 lib/h5p/h5p-file-storage.interface.php create mode 100644 lib/h5p/h5p-metadata.class.php create mode 100644 lib/h5p/h5p.classes.php create mode 100644 lib/h5p/images/h5p.svg create mode 100644 lib/h5p/images/throbber.gif create mode 100644 lib/h5p/js/h5p-action-bar.js create mode 100644 lib/h5p/js/h5p-confirmation-dialog.js create mode 100644 lib/h5p/js/h5p-content-type.js create mode 100644 lib/h5p/js/h5p-content-upgrade-process.js create mode 100644 lib/h5p/js/h5p-content-upgrade-worker.js create mode 100644 lib/h5p/js/h5p-content-upgrade.js create mode 100644 lib/h5p/js/h5p-data-view.js create mode 100644 lib/h5p/js/h5p-display-options.js create mode 100644 lib/h5p/js/h5p-embed.js create mode 100644 lib/h5p/js/h5p-event-dispatcher.js create mode 100644 lib/h5p/js/h5p-library-details.js create mode 100644 lib/h5p/js/h5p-library-list.js create mode 100644 lib/h5p/js/h5p-resizer.js create mode 100644 lib/h5p/js/h5p-utils.js create mode 100644 lib/h5p/js/h5p-version.js create mode 100644 lib/h5p/js/h5p-x-api-event.js create mode 100644 lib/h5p/js/h5p-x-api.js create mode 100644 lib/h5p/js/h5p.js create mode 100644 lib/h5p/js/jquery.js create mode 100644 lib/h5p/js/request-queue.js create mode 100644 lib/h5p/js/settings/h5p-disable-hub.js create mode 100644 lib/h5p/readme_moodle.txt create mode 100644 lib/h5p/styles/h5p-admin.css create mode 100644 lib/h5p/styles/h5p-confirmation-dialog.css create mode 100644 lib/h5p/styles/h5p-core-button.css create mode 100644 lib/h5p/styles/h5p.css diff --git a/.eslintignore b/.eslintignore index c4a9e1be9d3..4992f80a9c9 100644 --- a/.eslintignore +++ b/.eslintignore @@ -63,6 +63,7 @@ lib/geopattern-php/ lib/php-jwt/ lib/babel-polyfill/ lib/emoji-data/ +lib/h5p/ media/player/videojs/amd/src/video-lazy.js media/player/videojs/amd/src/Youtube-lazy.js media/player/videojs/videojs/ @@ -86,4 +87,4 @@ theme/boost/amd/src/toast.js theme/boost/amd/src/tooltip.js theme/boost/amd/src/util.js theme/boost/amd/src/tether.js -theme/boost/scss/fontawesome/ \ No newline at end of file +theme/boost/scss/fontawesome/ diff --git a/.stylelintignore b/.stylelintignore index 7a0cbe50aae..af419831a91 100644 --- a/.stylelintignore +++ b/.stylelintignore @@ -64,6 +64,7 @@ lib/geopattern-php/ lib/php-jwt/ lib/babel-polyfill/ lib/emoji-data/ +lib/h5p/ media/player/videojs/amd/src/video-lazy.js media/player/videojs/amd/src/Youtube-lazy.js media/player/videojs/videojs/ @@ -87,4 +88,4 @@ theme/boost/amd/src/toast.js theme/boost/amd/src/tooltip.js theme/boost/amd/src/util.js theme/boost/amd/src/tether.js -theme/boost/scss/fontawesome/ \ No newline at end of file +theme/boost/scss/fontawesome/ diff --git a/h5p/classes/privacy/provider.php b/h5p/classes/privacy/provider.php new file mode 100644 index 00000000000..73f4e31095b --- /dev/null +++ b/h5p/classes/privacy/provider.php @@ -0,0 +1,45 @@ +. + +/** + * Privacy provider implementation for h5p core subsytem. + * + * @package core_h5p + * @copyright 2019 Amaia Anabitarte + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace core_h5p\privacy; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Privacy provider implementation for h5p core subsystem. + * + * @copyright 2019 Amaia Anabitarte + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class provider implements \core_privacy\local\metadata\null_provider { + /** + * Get the language string identifier with the component's language + * file to explain why this plugin stores no data. + * + * @return string + */ + public static function get_reason() : string { + return 'privacy:metadata'; + } +} diff --git a/lang/en/h5p.php b/lang/en/h5p.php new file mode 100644 index 00000000000..e616ef56f88 --- /dev/null +++ b/lang/en/h5p.php @@ -0,0 +1,24 @@ +. +/** + * Strings for component 'h5p', language 'en', branch 'master' + * + * @package core_h5p + * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +$string['privacy:metadata'] = 'H5P subsystem does not store any personal data.'; diff --git a/lib/classes/component.php b/lib/classes/component.php index 22edb6ba780..35bb9503a6d 100644 --- a/lib/classes/component.php +++ b/lib/classes/component.php @@ -90,6 +90,14 @@ class core_component { 'RedeyeVentures\\GeoPattern' => 'lib/geopattern-php/GeoPattern', 'MongoDB' => 'cache/stores/mongodb/MongoDB', 'Firebase\\JWT' => 'lib/php-jwt/src', + 'H5PCore' => '/lib/h5p/h5p.classes', + 'H5PFrameworkInterface' => '/lib/h5p/h5p.classes', + 'H5PContentValidator' => 'lib/h5p/h5p.classes', + 'H5PValidator' => '/lib/h5p/h5p.classes', + 'H5PStorage' => '/lib/h5p/h5p.classes', + 'H5PDevelopment' => '/lib/h5p/h5p-development.class', + 'H5PFileStorage' => '/lib/h5p/h5p-file-storage.interface', + 'H5PMetadata' => '/lib/h5p/h5p-metadata.class', ); /** diff --git a/lib/components.json b/lib/components.json index 8ca41cf220a..680f7c02197 100644 --- a/lib/components.json +++ b/lib/components.json @@ -77,6 +77,7 @@ "group": "group", "help": null, "hub": null, + "h5p": "h5p", "imscc": null, "install": null, "iso6392": null, diff --git a/lib/h5p/LICENSE.txt b/lib/h5p/LICENSE.txt new file mode 100644 index 00000000000..20d40b6bcec --- /dev/null +++ b/lib/h5p/LICENSE.txt @@ -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 +. \ No newline at end of file diff --git a/lib/h5p/README.txt b/lib/h5p/README.txt new file mode 100644 index 00000000000..95aa16f296b --- /dev/null +++ b/lib/h5p/README.txt @@ -0,0 +1,14 @@ +This folder contains the general H5P library. The files within this folder are not specific to any framework. + +Any interaction with an LMS, CMS or other frameworks is done through interfaces. Platforms need to implement +the H5PFrameworkInterface(in h5p.classes.php) and also do the following: + + - Provide a form for uploading H5P packages. + - Place the uploaded H5P packages in a temporary directory + +++ + +See existing implementations for details. For instance the Drupal H5P module located at drupal.org/project/h5p + +We will make available documentation and tutorials for creating platform integrations in the future. + +The H5P PHP library is GPL licensed due to GPL code being used for purifying HTML provided by authors. diff --git a/lib/h5p/doc/spec_en.html b/lib/h5p/doc/spec_en.html new file mode 100644 index 00000000000..de6ddf077ae --- /dev/null +++ b/lib/h5p/doc/spec_en.html @@ -0,0 +1,168 @@ +

Overview

+

H5P is a file format for content/applications made using modern, open web technologies (HTML5). The format enables easy installation and transfer of applications/content on different CMSes, LMSes and other platforms. An H5P can be uploaded and published on a platform in mostly the same way one would publish a Flash file today. H5P files may also be updated by simply uploading a new version of the file, the same way as one would using Flash.

+

H5P opens for extensive reuse of code and wide flexibility regarding what may be developed as an H5P.

+

The system uses package files containing all necessary files and libraries for the application to function. These files are based on open formats.

+

Overview of package files

+

Package files are normal zip files, with a naming convention of <filename>.h5p to distinguish from any random zip file. This zip file then requires a specific file structure as described below.

+

There will be a file in JSON format named h5p.json describing the contents of the package and how the system should interpret and use it. This file contains information about title, content type, usage, copyright, licensing, version, language etc. This is described in detail below.

+

There shall be a folder for each included H5P library used by the package. These generic libraries may be reused by other H5P packages. As an example, a multi-choice question task may be used as a standalone block, or be included in a larger H5P package generating a game with quizzes.

+

Package file structure

+

A package contains the following elements:

+
    +
  1. A mandatory file in the root folder named h5p.json
  2. +
  3. An optional image file named h5p.jpg. This is an icon or an image of the application, 512 × 512 pixels. This image may be used by the platform as a preview of the application, and could be included in OG meta tags for use with social media.
  4. +
  5. One content folder, named content. This will contain the preset configuration for the application, as well as any required media files.
  6. +
  7. One or more library directories named the same as the library's internal name.
  8. +
+

h5p.json

+

The h5p.json file is a normal JSON text file containing a JSON object with the following predefined properties.

+

Mandatory properties:

+
    +
  • title - Name of the package. Would typically be used as header for a page displaying the package.
  • +
  • language - Standard language code. Use 'en' for english, 'nb' for norwegian "bokmål". Neutral content use "und".
  • +
  • machineName - Machine readable name of the library. This is the name that will be used for the library folder in the package too.
  • +
  • preloadedDependencies - Libraries that must be loaded on init. Specified as a list of objects with machineName, majorVersion and minorVersion. One would normally list all dependencies here to allow the platform displaying the package to merge JS and CSS files before returning the page.
  • +
  • embedTypes - List of ways to embed the package in the web page. Currently "div" and "iframe" are supported.
  • +

Optional properties:

+
  • contentType - Textual description of the type of content.
  • +
  • description - Textual description of the package.
  • +
  • author - Name of author.
  • +
  • license - Code for the content license. Use the following Creative Commons codes: cc-by, cc-by-sa, cc-by-nd, cc-by-nc, cc-by-nc-sa, cc-by-nc-nd. In addition for public domain: pd, and closed license: cr. More may be added later.
  • +
  • dynamicDependencies - Libraries that may be loaded dynamically during execution.
  • +
  • width - Width of the package content in cases where the package is not dynamically resizable.
  • +
  • height - Height of the package content.
  • +
  • metaKeywords - Suggestion for keywords for the application, as a string. May be used for OG meta tags for social media.
  • +
  • metaDescription - Suggestion for application metaDescription. May be used for OG meta tags for social media.
  • +
+

Eksempel på h5p.json:

+{
+ "title": "Biologi-spillet",
+ "contentType": "Game",
+ "utilization": "Lær om biologi",
+ "language": "nb",
+ "author": "Amendor AS",
+ "license": "cc-by-sa",
+ "preloadedDependencies": [
+ {
+ "machineName": "H5P.Boardgame",
+ "majorVersion": 1,
+ "minorVersion": 0
+ }, {
+ "machineName": "H5P.QuestionSet",
+ "majorVersion": 1,
+ "minorVersion": 0
+ }, {
+ "machineName": "H5P.MultiChoice",
+ "majorVersion": 1, "minorVersion": 0
+ }, {
+ "machineName": "EmbeddedJS",
+ "majorVersion": 1,
+ "minorVersion": 0
+ } ],
+ "embedTypes": ["div", "iframe"],
+ "w": 635,
+ "h": 500
+}
+

The content folder

+

Contains all the content for the package and its libraries. There shall be no content inside the library folders. The content folder shall contain a file named content.json, containing the JSON object that will be passed to the initializer for the main package library.

+ +

Content required by libraries invoked from the main package library will get their contents passed from the main library. The JSON for this will be found within the main content.json for the package, and passed during initialization.

+ +

Library folders

+ +

A library folder contains all logic, stylesheets and graphics that will be common for all instances of a library. There shall be no content or interface text directly in these folders. All text displayed to the end user shall be passed as part of the library configuration. This make the libraries language independent.

+ +

The root of a library folder shall contain a file name library.json formatted similar to the package's hp5.json, but with a few differences. The library shall also have one or more images in the root folder, named library.jpg, library1.jpg etc. Image sizes 512px × 512px, and will be used in the H5P editor tool.

+ +

Libraries are not allowed to modify the document tree in ways that will have consequences for the web site or will be noticeable by the user without the library explicitly being initialized from the main package library or another invoked library.

+ +

The library shall always include a JavaScript object function named the same as the defined library machineName (defined in library.json and used as the library folder name). This object will be instantiated with the library options as parameter. The resulting object must contain a function attach(target) that will be called after instantiation to attach the library DOM to the main DOM inside target

+ +

Example

+

A library called H5P.multichoice would typically be instantiated and attached to the page like this:

+var multichoice = new H5P.multichoice(contentFromJson, contentId);
+multichoice.attach($multichoiceContainer);
+ +

library.json

+

Mandatory properties:

+
    +
  • title - Human readable name of the library. May be used in the H5P editor and overviews of installed libraries.
  • +
  • majorVersion - Version major number. (The x in x.y.z). Positive integer.
  • +
  • minorVersion - Version minor number. (The y in x.y.z). Positive integer.
  • +
  • patchVersion - Version patch number. (The z in x.y.z). Positive integer. The system will automatically update to the latest patchVersion installed for all packages that use the library with the same major and minor version number. A new patch version must therefore not change any behaviour of the library, only fix errors.
  • +
  • machineName - Machine readable name for the library. Same as the folder name used.
  • +
  • preloadedJs - List of path to the javascript files required for the library. At least one file need to be present (the one defining the library object). Paths are relative to the library root folder.
  • +
+

Optional properties:

+
    +
  • author - Author name as text.
  • +
  • license - Code describing the library license. Use the following creative commons codes: cc-by, cc-by-sa, cc-by-nd, cc-by-nc, cc-by-nc-sa, cc-by-nc-nd. In addition use pd for public domain, and cr for closed source
  • +
  • description - Textual description of the library.
  • +
  • preloadedDependencies - Libraries that need to be loaded for this library to work. Specified as a list of objects with machineName, majorVersion and minorVersion for the required libraries.
  • +
  • dynamicDependencies - Libraries that may be loaded dynamically during library execution. Specified as a list of objects like preloadedDependencies above.
  • +
  • preloadedCss - List of paths to CSS files to be loaded with the library. Paths are relative to the library root folder.
  • +
  • w - Width in pixels for libraries that use a fixed width. Mandatory if the library shall be embedded in an iframe (see embedTypes below).
  • +
  • h - Height in pixels for libraries that use a fixed height. Mandatory if the library shall be embedded in an iframe (see embedTypes below).
  • +
  • embedTypes - List of possible ways to embed the package in the page. Available values are div and iframe.
  • +
+

Eksempel på library.json:

+{
+ "title": "Boardgame",
+ "description": "The user is presented with a board with several hotspots. By clicking a hotspot he invokes a mini-game.",
+ "majorVersion": 1,
+ "minorVersion": 0,
+ "patchVersion": 6,
+ "runnable": 1,
+ "machineName": "H5P.Boardgame",
+ "author": "Amendor AS",
+ "license": "cc-by-sa",
+ "preloadedDependencies": [
+ {
+ "machineName": "EmbeddedJS",
+ "majorVersion": 1,
+ "minorVersion": 0
+ }, {
+ "machineName": "H5P.MultiChoice",
+ "majorVersion": 1,
+ "minorVersion": 0
+ }, {
+ "machineName": "H5P.QuestionSet",
+ "majorVersion": 1,
+ "minorVersion": 0
+ } ],
+ "preloadedCss": [ {"path": "css/boardgame.css"} ],
+ "preloadedJs": [ {"path": "js/boardgame.js"} ],
+ "w": 635,
+ "h": 500 }
+ +

Allowed file types

+

Files that require server side execution or that cannot be regarded an open standard shall not be used. Allowed file types: js, json, png, jpg, gif, svg, css, mp3, wav (audio: PCM), m4a (audio: AAC), mp4 (video: H.264, audio: AAC/MP3), ogg (video: Theora, audio: Vorbis) and webm (video VP8, audio: Vorbis). Administrators of web sites implementing H5P may open for accepting further formats. HTML files shall not be used. HTML for each library shall be inserted from the library scripts to ease code reuse. (By avoiding content being defined in said HTML).

+

API functions

+

The following JavaScript functions are available through h5p:

+
    +
  • H5P.getUserData(namespace, variable)
  • +
  • H5P.setUserData(namespace, variable, data)
  • +
  • H5P.getUserStart(namespace)
  • +
  • H5P.setUserStop(namespace)
  • +
  • H5P.deleteUserData(namespace, variable)
  • +
  • H5P.getGlobalData(namespace, variable)
  • +
  • H5P.setGlobalData(namespace, variable, data)
  • +
  • H5P.deleteGlobalData(namespace, variable)
  • +
+

I tillegg er følgende api funksjoner tilgjengelig via ndla:

+
    +
  • H5P.setUserScore(contentId, score, maxScore)
  • +
+

Best practices

+

H5P is a very open standard. This is positive for flexibility. Most content may be produces as H5P. But this also allows for bad code, security weaknesses, code that may be difficult to reuse. Therefore the following best practices should be followed to get the most from H5P:

+
    +
  • Think reusability when creating a library. H5P support dependencies between libraries, so the same small quiz-library may be used in various larger packages or libraries.
  • +
  • H5P supports library updates. This enables all content using a common library to be updated at once. This must be accounted for when writing new libraries. A library should be as general as possible. The content format should be thought out so there are no changes to the required content data when a library is updated. Note: Multiple versions of a library may exists at the same time, only patch level updates will be automatically installed.
  • +
  • An H5P should not interact directly with the containing web site. It shall only affect elements within its own generated DOM tree. Elements shall also only be injected within the target defined on initialization. This is to avoid dependencies to a specific platform or web page.
  • +
  • Prefix objects, global functions, etc with h5p to minimize the chance of namespace conflicts with the rest of the web page. Remember that there may also be multiple H5P objects inserted on a page, so plan ahead to avoid conflicts.
  • +
  • Content should be responsive.
  • +
  • Content should be WCAG 2 AA compliant
  • +
  • All generated HTML should validate.
  • +
  • All CSS should validate (some browser specific non-standard CSS may at times be required)
  • +
  • Best practices for JavaScript, HTML, etc. should of course also be followed when writing an H5P.
  • +
diff --git a/lib/h5p/embed.php b/lib/h5p/embed.php new file mode 100644 index 00000000000..f8851ece4f3 --- /dev/null +++ b/lib/h5p/embed.php @@ -0,0 +1,20 @@ + + + + + <?php print $content['title']; ?> + + + + + + + + + +
+ + + diff --git a/lib/h5p/fonts/h5p-core-21.eot b/lib/h5p/fonts/h5p-core-21.eot new file mode 100644 index 0000000000000000000000000000000000000000..3fe54449a159946d32dc7c12e800ae40ac38c4c7 GIT binary patch literal 7784 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 + + + + + +{ + "fontFamily": "h5p-core-21", + "description": "Font generated by IcoMoon.", + "majorVersion": 1, + "minorVersion": 1, + "version": "Version 1.1", + "fontId": "h5p-core-21", + "psName": "h5p-core-21", + "subFamily": "Regular", + "fullName": "h5p-core-21" +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/h5p/fonts/h5p-core-21.ttf b/lib/h5p/fonts/h5p-core-21.ttf new file mode 100644 index 0000000000000000000000000000000000000000..9c767365b4e4e7defadca9be4dc13b569b61e937 GIT binary patch literal 7604 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 KR~K?|&Hn)_cUHFm literal 0 HcmV?d00001 diff --git a/lib/h5p/fonts/h5p-core-21.woff b/lib/h5p/fonts/h5p-core-21.woff new file mode 100644 index 0000000000000000000000000000000000000000..32cc521e2a972a80fb3a5a9ff945c2c6a47173c0 GIT binary patch literal 7680 zcma)B36NYzdG7Al{f?P=GxO$nZ;qYanR&Z2+G}=>of#dg-IXQHO12y!VHsKI@Y+Z# z(6K^Cd~nH@quAI6s|*-p5>h6CBDf$V5K<|Vs2o+W34z3*sz4Ghu5q?w;E=cRGX;JpF_OWuE&Y${t3RmOh)`JW(fv>cHJBQzWJi z-Fj&L2ypvRzDK5i`pG?&h52I=_g^SWUYVi`2k+Pi+R?vnY3Dddr0^#}Ccl zj(YoKeR(fU(AeSmLwkW+hPwY!rlaS-Hg#n2*m3mp`&alBK#KATeTWD`*rV+0D1Xq; z>C2=+4V0HYG`h4T;aNgn3MpqVoh7ph5->|gFpn~7=%qf;B;1Fu_={sC@?B; z`5*54;Rk<2Uwr?I54`xHmqM2=Ub+N20e80m0pUB*v(Ve@U zyPT6wvZvJ(c+Cg%3QZBOR-eQOX|M2_dbPc8gu6g~PqFD^1bp!Vy}-u07wBW%3s6Yu zdq{wtVz#6WStwF9z(U>s^=O1ViVmNbV{A~Ztd$uWGIj3U6g_{*%OOw5UEukOe5Hpd)Ni^Rl}-{kT`KjmJAS=l*t&WLAsH2+eq4PkvCV- zq}!yY=H~w5jb3(PZf{KUOOW~32+wcBTqjCR)V2eF!bz&}&OeW?gs;$Y1%3LzZ z8lCRnPCnlF?gUJaavjx)6Kp_PkV=S7|J?!T_xy?gC7yLVsn@Z!+e z*o_{O9!Xsh86G|?M1hC-^*-C$-6TLBC&!f&Y=MNZ)?CcqO0u48Av@s<;l*gHaAvZvQ*Q`rDB9iQhNv*w1nMg z*ITu6TPlzwN3jZ)Qm_j2om}M$LJNug*UfN)J3`DXqdyijr1L|ZRc1JMfSy@al84ep^@uc5e-)|{c191#s)Th%az(sy_R2+{E65vgDdeeYpAMKxK& z!fUnt(UJrh3&gxv)-pwF-avu`=i`%V7|aiIS{W!-ElUiFj3bO9>JB$; zcoM9zVG|BF92B2&>UMS_!?>9?RJQ|Nn=~#cSi;epL|CVL1dYYHO2ycY8XAkr4bv2H zBW((*nn{yK#Cg@wO(3{wK#K^OW{gW#*&owx*s)y92pS^7jgTHzO`U(U-&9RGNJ8Og zDB}=DpA5zWhM)tpE|3Q0OmclxJgxiaKRm zLWUJF7(@4U3v(chc=)e$_z6@O5#gMD-Y_{L{pHxvN7nqN$l(VLH*P23=!$TQ@>80G zBb1+39j;G)B-vr4U7hG4nk43`6V2vC6#*lW=uA}G55gylh_QJyj~WFbZrIFukw^7w zd*#iW*a^Qey!Nkm+Hn~WU=Y7$K!_&`&4NJsI{ffKxErysZd&L( z2Di(Y=iv_udd0(ECj$Z3g6hKhtIoOLIcIqIap{~PJhSX5-P!$PI???fs?i^K0brky zKE4+yu9d!9s)0L4I6+Z&o~8eNncT1B*-kHh zuO`>ZwW|8z7*kbn5IjbK$8E7@kBgwR~5x6ob$bg^{TK^F|wcvK|B zqnsMuC%+ppI!5GoH^H#3N7A`~g?r$;dDt*mjGMY~clS@sXw;O6K4Tb9dT;3WjY!0J z@GhP27Ga@=U}?L#ZWs>=6CWN{k3`LIG#WPL5rondc`y43+m8JRfeH2Y3s+X=mHkF< zKT>7~PwV=$meEh2*34DRrULj;ONzhmOjH>}+zQ1tkXUZye3eg-V zFY3o4Rr+%IA`tn}s{$jJ;RbuRR@;v=USvlrB^qIkVl@4jT~g`TxkGbY zSNi)ZeG`cd@7y2)+W7GBns|az-N-ajx)lssnjSL(!AvuY%{F~F8;fN!NbHmqaR+y` z4O8tL?jVMj-fHR*Pl-YUfk0!ZG@dBOGxdzFA?{m7upG!Xvy5GQHkQp=u?)>%zd{Qn z$iBx;kU4UOJdIswQHJNDJ0&+Iy_kxyR-N=CCOXr`Ip2dW@tqO!lAT@wSYOdYB{Hx(!!b+()yYiw;4gR&5X$)$`z}T&n)kQLDEk` z+Dzz%9Th>nk@=`wZ(mZI};pBe89ilC+^L!P}6vP~gun`dtcc|en& zB0Ly8g>+-9AK|5mQx3jFxZ~ z%drC_L&l{Ks(Uu(IUjjW^iGVE(h7v{6Jb6GHuC5=L+O1}AD+!m#IvfJ$q!V~@4cgA zIoFLg@-!3(oK+1~)if1-ILi*WZlaR!vGfF1L%Nc9Rn4f2XlY3O0XnTHxS%4qyZJI% zu54sK#Z69uOp{GyhrHSGHpZACIfG3La}xJg4PbArB(0$ygjLfELrIUn>8hpX5Y|?2 zRY`yFIwkh(FKV4m?HBd+>+35Dsb4sSf`iY+mkX(%rwY^S>pz#2csy00U;Jd)vcjJX z#}c7m1F^YIz59L1O!M_l_du#pNYR}9cAx(YEl9obxU8!CT&*+1@)_3(hhwpD*xC&M zikAQw7fw!+Ey_vQjZQ4mz?qp~avZBdHKm~7Y;Pfo#NncFzN=6dUQMamk^_ra9(v?S zr&UuF(BR)d2CMYR-k~QBhPsU%Bti=KrJD2W-oLi--W6qb<7n%y$+`R2B}?1KOPgGG zQ)zsAX|}%F-7=D2ZQHB!BfnExU7s!G=Sny%=U1jPEAoLzz+In@4kcy>uPXyG&HQ?| zeBIzG+l@b&%amw((8zb6p{sIQx%+%6lcu-WSyjelrQhyO>AAS6@(doXgyT7lKGQuA zjqyZ0p5WnVz*OiT#*>PP{ks`b67lYCHSDixjL|l4j3#lfK&WubVd>YU=XWse)uMDX zxG!k7{i7WYaqt3I7`35>fW?DHvsJk|+KxO}!_Xb&w(foWyU|!wHDIn5Rj4w{nZm7r z77WCq@6Z^hw{vHy|jA)h6K$~N{*+$XIf+tC~Up6fODNxf4+%_^cJ zWvp>&vADimnW)y1D0m0s z25#5@{~9h}uX3S)+c%)ob$ zOMGk_BkK8HY{rrnegAc}PQ4T|3(h^14W?*2Zy4hP{Ub(T!1JE94%<+>Gnz_8t(5(A zKJ`ndV1~vEe^jU#Ci}MZc_Y)I^;#+_9U*0@!NZwCA>;ePPL1~0HkxUOrmSeXyIs0U zS_o&fLZwpBGU4uXun&1=`mi#}UM6XHLwO_S_7-{LvJKb{?!q($7LWU`w!Gc)jHBuH z%z`~Pd~EG>tG&fZT^F-f4-Z!w+Xp&d-SnKFy_U#MSK29OOS?5)86IA3#YP9g+uh-1 z|DS^9VLoOry{w#74#1KJV8Juk1ve}={yLVZyp9bkxGARJ+OcDN*Osk!x_Iu~x@Ff= z_}Vqs%=h7$zh=#~OW@mf?Dz*7q8}P`@7TI^=dP_=eBmuyckSG|^$vIN)$jD>=GR;U zku|qS@mtnF{F*iMxjy>i9kL(ta+{_<_R9zU?45feQ$Hg?tTjCU@=SW&)%?;&l&8>B z`9Br@weTLudH>~LAmpPwo)@9e=U;3s=<03Kx3{^pVKTNjV+9k1800c(;Y z*e2eJCLG0PdYsfrt+ROecz$8;;k`%akMDh3{+2uP8*g2_esS?|1sm=~a+n+^d9ncR z!$?QTJj#1<&7UW?kUQ|*=xMtioRYV4rXT{v-Y{wUcB^$X+#u8`-+(KnRB{3zZm{l?G#0ce_9n*aa+ literal 0 HcmV?d00001 diff --git a/lib/h5p/h5p-default-storage.class.php b/lib/h5p/h5p-default-storage.class.php new file mode 100644 index 00000000000..951b72f11ec --- /dev/null +++ b/lib/h5p/h5p-default-storage.class.php @@ -0,0 +1,586 @@ +path = $path; + $this->alteditorpath = $alteditorpath; + } + + /** + * Store the library folder. + * + * @param array $library + * Library properties + */ + public function saveLibrary($library) { + $dest = $this->path . '/libraries/' . \H5PCore::libraryToString($library, TRUE); + + // Make sure destination dir doesn't exist + \H5PCore::deleteFileTree($dest); + + // Move library folder + self::copyFileTree($library['uploadDirectory'], $dest); + } + + /** + * Store the content folder. + * + * @param string $source + * Path on file system to content directory. + * @param array $content + * Content properties + */ + public function saveContent($source, $content) { + $dest = "{$this->path}/content/{$content['id']}"; + + // Remove any old content + \H5PCore::deleteFileTree($dest); + + self::copyFileTree($source, $dest); + } + + /** + * Remove content folder. + * + * @param array $content + * Content properties + */ + public function deleteContent($content) { + \H5PCore::deleteFileTree("{$this->path}/content/{$content['id']}"); + } + + /** + * Creates a stored copy of the content folder. + * + * @param string $id + * Identifier of content to clone. + * @param int $newId + * The cloned content's identifier + */ + public function cloneContent($id, $newId) { + $path = $this->path . '/content/'; + if (file_exists($path . $id)) { + self::copyFileTree($path . $id, $path . $newId); + } + } + + /** + * Get path to a new unique tmp folder. + * + * @return string + * Path + */ + public function getTmpPath() { + $temp = "{$this->path}/temp"; + self::dirReady($temp); + return "{$temp}/" . uniqid('h5p-'); + } + + /** + * Fetch content folder and save in target directory. + * + * @param int $id + * Content identifier + * @param string $target + * Where the content folder will be saved + */ + public function exportContent($id, $target) { + $source = "{$this->path}/content/{$id}"; + if (file_exists($source)) { + // Copy content folder if it exists + self::copyFileTree($source, $target); + } + else { + // No contnet folder, create emty dir for content.json + self::dirReady($target); + } + } + + /** + * Fetch library folder and save in target directory. + * + * @param array $library + * Library properties + * @param string $target + * Where the library folder will be saved + * @param string $developmentPath + * Folder that library resides in + */ + public function exportLibrary($library, $target, $developmentPath=NULL) { + $folder = \H5PCore::libraryToString($library, TRUE); + $srcPath = ($developmentPath === NULL ? "/libraries/{$folder}" : $developmentPath); + self::copyFileTree("{$this->path}{$srcPath}", "{$target}/{$folder}"); + } + + /** + * Save export in file system + * + * @param string $source + * Path on file system to temporary export file. + * @param string $filename + * Name of export file. + * @throws Exception Unable to save the file + */ + public function saveExport($source, $filename) { + $this->deleteExport($filename); + + if (!self::dirReady("{$this->path}/exports")) { + throw new Exception("Unable to create directory for H5P export file."); + } + + if (!copy($source, "{$this->path}/exports/{$filename}")) { + throw new Exception("Unable to save H5P export file."); + } + } + + /** + * Removes given export file + * + * @param string $filename + */ + public function deleteExport($filename) { + $target = "{$this->path}/exports/{$filename}"; + if (file_exists($target)) { + unlink($target); + } + } + + /** + * Check if the given export file exists + * + * @param string $filename + * @return boolean + */ + public function hasExport($filename) { + $target = "{$this->path}/exports/{$filename}"; + return file_exists($target); + } + + /** + * 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 + */ + public function cacheAssets(&$files, $key) { + foreach ($files as $type => $assets) { + if (empty($assets)) { + continue; // Skip no assets + } + + $content = ''; + foreach ($assets as $asset) { + // Get content from asset file + $assetContent = file_get_contents($this->path . $asset->path); + $cssRelPath = preg_replace('/[^\/]+$/', '', $asset->path); + + // Get file content and concatenate + if ($type === 'scripts') { + $content .= $assetContent . ";\n"; + } + else { + // Rewrite relative URLs used inside stylesheets + $content .= preg_replace_callback( + '/url\([\'"]?([^"\')]+)[\'"]?\)/i', + function ($matches) use ($cssRelPath) { + if (preg_match("/^(data:|([a-z0-9]+:)?\/)/i", $matches[1]) === 1) { + return $matches[0]; // Not relative, skip + } + return 'url("../' . $cssRelPath . $matches[1] . '")'; + }, + $assetContent) . "\n"; + } + } + + self::dirReady("{$this->path}/cachedassets"); + $ext = ($type === 'scripts' ? 'js' : 'css'); + $outputfile = "/cachedassets/{$key}.{$ext}"; + file_put_contents($this->path . $outputfile, $content); + $files[$type] = array((object) array( + 'path' => $outputfile, + 'version' => '' + )); + } + } + + /** + * Will check if there are cache assets available for content. + * + * @param string $key + * Hashed key for cached asset + * @return array + */ + public function getCachedAssets($key) { + $files = array(); + + $js = "/cachedassets/{$key}.js"; + if (file_exists($this->path . $js)) { + $files['scripts'] = array((object) array( + 'path' => $js, + 'version' => '' + )); + } + + $css = "/cachedassets/{$key}.css"; + if (file_exists($this->path . $css)) { + $files['styles'] = array((object) array( + 'path' => $css, + 'version' => '' + )); + } + + return empty($files) ? NULL : $files; + } + + /** + * Remove the aggregated cache files. + * + * @param array $keys + * The hash keys of removed files + */ + public function deleteCachedAssets($keys) { + foreach ($keys as $hash) { + foreach (array('js', 'css') as $ext) { + $path = "{$this->path}/cachedassets/{$hash}.{$ext}"; + if (file_exists($path)) { + unlink($path); + } + } + } + } + + /** + * Read file content of given file and then return it. + * + * @param string $file_path + * @return string + */ + public function getContent($file_path) { + return file_get_contents($file_path); + } + + /** + * Save files uploaded through the editor. + * The files must be marked as temporary until the content form is saved. + * + * @param \H5peditorFile $file + * @param int $contentid + */ + public function saveFile($file, $contentId) { + // Prepare directory + if (empty($contentId)) { + // Should be in editor tmp folder + $path = $this->getEditorPath(); + } + else { + // Should be in content folder + $path = $this->path . '/content/' . $contentId; + } + $path .= '/' . $file->getType() . 's'; + self::dirReady($path); + + // Add filename to path + $path .= '/' . $file->getName(); + + copy($_FILES['file']['tmp_name'], $path); + + return $file; + } + + /** + * Copy a file from another content or editor tmp dir. + * Used when copy pasting content in H5P Editor. + * + * @param string $file path + name + * @param string|int $fromid Content ID or 'editor' string + * @param int $toid Target Content ID + */ + public function cloneContentFile($file, $fromId, $toId) { + // Determine source path + if ($fromId === 'editor') { + $sourcepath = $this->getEditorPath(); + } + else { + $sourcepath = "{$this->path}/content/{$fromId}"; + } + $sourcepath .= '/' . $file; + + // Determine target path + $filename = basename($file); + $filedir = str_replace($filename, '', $file); + $targetpath = "{$this->path}/content/{$toId}/{$filedir}"; + + // Make sure it's ready + self::dirReady($targetpath); + + $targetpath .= $filename; + + // Check to see if source exist and if target doesn't + if (!file_exists($sourcepath) || file_exists($targetpath)) { + return; // Nothing to copy from or target already exists + } + + copy($sourcepath, $targetpath); + } + + /** + * 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 Id of contentarray + */ + public function moveContentDirectory($source, $contentId = NULL) { + if ($source === NULL) { + return NULL; + } + + // TODO: Remove $contentId and never copy temporary files into content folder. JI-366 + if ($contentId === NULL || $contentId == 0) { + $target = $this->getEditorPath(); + } + else { + // Use content folder + $target = "{$this->path}/content/{$contentId}"; + } + + $contentSource = $source . DIRECTORY_SEPARATOR . 'content'; + $contentFiles = array_diff(scandir($contentSource), array('.','..', 'content.json')); + foreach ($contentFiles as $file) { + if (is_dir("{$contentSource}/{$file}")) { + self::copyFileTree("{$contentSource}/{$file}", "{$target}/{$file}"); + } + else { + copy("{$contentSource}/{$file}", "{$target}/{$file}"); + } + } + + // TODO: Return list of all files so that they can be marked as temporary. JI-366 + } + + /** + * Checks to see if content has the given file. + * Used when saving content. + * + * @param string $file path + name + * @param int $contentId + * @return string File ID or NULL if not found + */ + public function getContentFile($file, $contentId) { + $path = "{$this->path}/content/{$contentId}/{$file}"; + return file_exists($path) ? $path : NULL; + } + + /** + * Checks to see if content has the given file. + * Used when saving content. + * + * @param string $file path + name + * @param int $contentid + * @return string|int File ID or NULL if not found + */ + public function removeContentFile($file, $contentId) { + $path = "{$this->path}/content/{$contentId}/{$file}"; + if (file_exists($path)) { + unlink($path); + + // Clean up any empty parent directories to avoid cluttering the file system + $parts = explode('/', $path); + while (array_pop($parts) !== NULL) { + $dir = implode('/', $parts); + if (is_dir($dir) && count(scandir($dir)) === 2) { // empty contains '.' and '..' + rmdir($dir); // Remove empty parent + } + else { + return; // Not empty + } + } + } + } + + /** + * Check if server setup has write permission to + * the required folders + * + * @return bool True if site can write to the H5P files folder + */ + public function hasWriteAccess() { + return self::dirReady($this->path); + } + + /** + * Check if the file presave.js exists in the root of the library + * + * @param string $libraryFolder + * @param string $developmentPath + * @return bool + */ + public function hasPresave($libraryFolder, $developmentPath = null) { + $path = is_null($developmentPath) ? 'libraries' . DIRECTORY_SEPARATOR . $libraryFolder : $developmentPath; + $filePath = realpath($this->path . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . 'presave.js'); + return file_exists($filePath); + } + + /** + * Check if upgrades script exist for library. + * + * @param string $machineName + * @param int $majorVersion + * @param int $minorVersion + * @return string Relative path + */ + public function getUpgradeScript($machineName, $majorVersion, $minorVersion) { + $upgrades = "/libraries/{$machineName}-{$majorVersion}.{$minorVersion}/upgrades.js"; + if (file_exists($this->path . $upgrades)) { + return $upgrades; + } + else { + return NULL; + } + } + + /** + * Store the given stream into the given file. + * + * @param string $path + * @param string $file + * @param resource $stream + * @return bool + */ + public function saveFileFromZip($path, $file, $stream) { + $filePath = $path . '/' . $file; + + // Make sure the directory exists first + $matches = array(); + preg_match('/(.+)\/[^\/]*$/', $filePath, $matches); + self::dirReady($matches[1]); + + // Store in local storage folder + return file_put_contents($filePath, $stream); + } + + /** + * Recursive function for copying directories. + * + * @param string $source + * From path + * @param string $destination + * To path + * @return boolean + * Indicates if the directory existed. + * + * @throws Exception Unable to copy the file + */ + private static function copyFileTree($source, $destination) { + if (!self::dirReady($destination)) { + throw new \Exception('unabletocopy'); + } + + $ignoredFiles = self::getIgnoredFiles("{$source}/.h5pignore"); + + $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' && !in_array($file, $ignoredFiles)) { + if (is_dir("{$source}/{$file}")) { + self::copyFileTree("{$source}/{$file}", "{$destination}/{$file}"); + } + else { + copy("{$source}/{$file}", "{$destination}/{$file}"); + } + } + } + closedir($dir); + } + + /** + * Retrieve array of file names from file. + * + * @param string $file + * @return array Array with files that should be ignored + */ + private static function getIgnoredFiles($file) { + if (file_exists($file) === FALSE) { + return array(); + } + + $contents = file_get_contents($file); + if ($contents === FALSE) { + return array(); + } + + return preg_split('/\s+/', $contents); + } + + /** + * Recursive function that makes sure the specified directory exists and + * is writable. + * + * @param string $path + * @return bool + */ + private static function dirReady($path) { + if (!file_exists($path)) { + $parent = preg_replace("/\/[^\/]+\/?$/", '', $path); + if (!self::dirReady($parent)) { + return FALSE; + } + + mkdir($path, 0777, true); + } + + if (!is_dir($path)) { + trigger_error('Path is not a directory ' . $path, E_USER_WARNING); + return FALSE; + } + + if (!is_writable($path)) { + trigger_error('Unable to write to ' . $path . ' – check directory permissions –', E_USER_WARNING); + return FALSE; + } + + return TRUE; + } + + /** + * Easy helper function for retrieving the editor path + * + * @return string Path to editor files + */ + private function getEditorPath() { + return ($this->alteditorpath !== NULL ? $this->alteditorpath : "{$this->path}/editor"); + } +} diff --git a/lib/h5p/h5p-development.class.php b/lib/h5p/h5p-development.class.php new file mode 100644 index 00000000000..a60262a85d0 --- /dev/null +++ b/lib/h5p/h5p-development.class.php @@ -0,0 +1,189 @@ +h5pF = $H5PFramework; + $this->language = $language; + $this->filesPath = $filesPath; + if ($libraries !== NULL) { + $this->libraries = $libraries; + } + else { + $this->findLibraries($filesPath . '/development'); + } + } + + /** + * Get contents of file. + * + * @param string $file File path. + * @return mixed String on success or NULL on failure. + */ + private function getFileContents($file) { + if (file_exists($file) === FALSE) { + return NULL; + } + + $contents = file_get_contents($file); + if ($contents === FALSE) { + return NULL; + } + + return $contents; + } + + /** + * Scans development directory and find all libraries. + * + * @param string $path Libraries development folder + */ + private function findLibraries($path) { + $this->libraries = array(); + + if (is_dir($path) === FALSE) { + return; + } + + $contents = scandir($path); + + for ($i = 0, $s = count($contents); $i < $s; $i++) { + if ($contents[$i]{0} === '.') { + continue; // Skip hidden stuff. + } + + $libraryPath = $path . '/' . $contents[$i]; + $libraryJSON = $this->getFileContents($libraryPath . '/library.json'); + if ($libraryJSON === NULL) { + continue; // No JSON file, skip. + } + + $library = json_decode($libraryJSON, TRUE); + if ($library === NULL) { + continue; // Invalid JSON. + } + + // TODO: Validate props? Not really needed, is it? this is a dev site. + + $library['libraryId'] = $this->h5pF->getLibraryId($library['machineName'], $library['majorVersion'], $library['minorVersion']); + + // Convert metadataSettings values to boolean & json_encode it before saving + $library['metadataSettings'] = isset($library['metadataSettings']) ? + H5PMetadata::boolifyAndEncodeSettings($library['metadataSettings']) : + NULL; + + // Save/update library. + $this->h5pF->saveLibraryData($library, $library['libraryId'] === FALSE); + + // Need to decode it again, since it is served from here. + $library['metadataSettings'] = json_decode($library['metadataSettings']); + + $library['path'] = 'development/' . $contents[$i]; + $this->libraries[H5PDevelopment::libraryToString($library['machineName'], $library['majorVersion'], $library['minorVersion'])] = $library; + } + + // TODO: Should we remove libraries without files? Not really needed, but must be cleaned up some time, right? + + // Go trough libraries and insert dependencies. Missing deps. will just be ignored and not available. (I guess?!) + $this->h5pF->lockDependencyStorage(); + foreach ($this->libraries as $library) { + $this->h5pF->deleteLibraryDependencies($library['libraryId']); + // This isn't optimal, but without it we would get duplicate warnings. + // TODO: You might get PDOExceptions if two or more requests does this at the same time!! + $types = array('preloaded', 'dynamic', 'editor'); + foreach ($types as $type) { + if (isset($library[$type . 'Dependencies'])) { + $this->h5pF->saveLibraryDependencies($library['libraryId'], $library[$type . 'Dependencies'], $type); + } + } + } + $this->h5pF->unlockDependencyStorage(); + // TODO: Deps must be inserted into h5p_nodes_libraries as well... ? But only if they are used?! + } + + /** + * @return array Libraries in development folder. + */ + public function getLibraries() { + return $this->libraries; + } + + /** + * Get library + * + * @param string $name of the library. + * @param int $majorVersion of the library. + * @param int $minorVersion of the library. + * @return array library. + */ + public function getLibrary($name, $majorVersion, $minorVersion) { + $library = H5PDevelopment::libraryToString($name, $majorVersion, $minorVersion); + return isset($this->libraries[$library]) === TRUE ? $this->libraries[$library] : NULL; + } + + /** + * Get semantics for the given library. + * + * @param string $name of the library. + * @param int $majorVersion of the library. + * @param int $minorVersion of the library. + * @return string Semantics + */ + public function getSemantics($name, $majorVersion, $minorVersion) { + $library = H5PDevelopment::libraryToString($name, $majorVersion, $minorVersion); + if (isset($this->libraries[$library]) === FALSE) { + return NULL; + } + return $this->getFileContents($this->filesPath . $this->libraries[$library]['path'] . '/semantics.json'); + } + + /** + * Get translations for the given library. + * + * @param string $name of the library. + * @param int $majorVersion of the library. + * @param int $minorVersion of the library. + * @param $language + * @return string Translation + */ + public function getLanguage($name, $majorVersion, $minorVersion, $language) { + $library = H5PDevelopment::libraryToString($name, $majorVersion, $minorVersion); + + if (isset($this->libraries[$library]) === FALSE) { + return NULL; + } + + return $this->getFileContents($this->filesPath . $this->libraries[$library]['path'] . '/language/' . $language . '.json'); + } + + /** + * Writes library as string on the form "name majorVersion.minorVersion" + * + * @param string $name Machine readable library name + * @param integer $majorVersion + * @param $minorVersion + * @return string Library identifier. + */ + public static function libraryToString($name, $majorVersion, $minorVersion) { + return $name . ' ' . $majorVersion . '.' . $minorVersion; + } +} diff --git a/lib/h5p/h5p-event-base.class.php b/lib/h5p/h5p-event-base.class.php new file mode 100644 index 00000000000..454ea50de68 --- /dev/null +++ b/lib/h5p/h5p-event-base.class.php @@ -0,0 +1,191 @@ + – content view + * embed – viewed through embed code + * shortcode – viewed through internal shortcode + * edit – opened in editor + * delete – deleted + * create – created through editor + * create upload – created through upload + * update – updated through editor + * update upload – updated through upload + * upgrade – upgraded + * + * results, – view own results + * content – view results for content + * set – new results inserted or updated + * + * settings, – settings page loaded + * + * library, – loaded in editor + * create – new library installed + * update – old library updated + * + * @param string $type + * Name of event type + * @param string $sub_type + * Name of event sub type + * @param string $content_id + * Identifier for content affected by the event + * @param string $content_title + * Content title (makes it easier to know which content was deleted etc.) + * @param string $library_name + * Name of the library affected by the event + * @param string $library_version + * Library version + */ + function __construct($type, $sub_type = NULL, $content_id = NULL, $content_title = NULL, $library_name = NULL, $library_version = NULL) { + $this->type = $type; + $this->sub_type = $sub_type; + $this->content_id = $content_id; + $this->content_title = $content_title; + $this->library_name = $library_name; + $this->library_version = $library_version; + $this->time = time(); + + if (self::validLogLevel($type, $sub_type)) { + $this->save(); + } + if (self::validStats($type, $sub_type)) { + $this->saveStats(); + } + } + + /** + * Determines if the event type should be saved/logged. + * + * @param string $type + * Name of event type + * @param string $sub_type + * Name of event sub type + * @return boolean + */ + private static function validLogLevel($type, $sub_type) { + switch (self::$log_level) { + default: + case self::LOG_NONE: + return FALSE; + case self::LOG_ALL: + return TRUE; // Log everything + case self::LOG_ACTIONS: + if (self::isAction($type, $sub_type)) { + return TRUE; // Log actions + } + return FALSE; + } + } + + /** + * Check if the event should be included in the statistics counter. + * + * @param string $type + * Name of event type + * @param string $sub_type + * Name of event sub type + * @return boolean + */ + private static function validStats($type, $sub_type) { + if ( ($type === 'content' && $sub_type === 'shortcode insert') || // Count number of shortcode inserts + ($type === 'library' && $sub_type === NULL) || // Count number of times library is loaded in editor + ($type === 'results' && $sub_type === 'content') ) { // Count number of times results page has been opened + return TRUE; + } + elseif (self::isAction($type, $sub_type)) { // Count all actions + return TRUE; + } + return FALSE; + } + + /** + * Check if event type is an action. + * + * @param string $type + * Name of event type + * @param string $sub_type + * Name of event sub type + * @return boolean + */ + private static function isAction($type, $sub_type) { + if ( ($type === 'content' && in_array($sub_type, array('create', 'create upload', 'update', 'update upload', 'upgrade', 'delete'))) || + ($type === 'library' && in_array($sub_type, array('create', 'update'))) ) { + return TRUE; // Log actions + } + return FALSE; + } + + /** + * A helper which makes it easier for systems to save the data. + * Add all relevant properties to a assoc. array. + * There are no NULL values. Empty string or 0 is used instead. + * Used by both Drupal and WordPress. + * + * @return array with keyed values + */ + protected function getDataArray() { + return array( + 'created_at' => $this->time, + 'type' => $this->type, + 'sub_type' => empty($this->sub_type) ? '' : $this->sub_type, + 'content_id' => empty($this->content_id) ? 0 : $this->content_id, + 'content_title' => empty($this->content_title) ? '' : $this->content_title, + 'library_name' => empty($this->library_name) ? '' : $this->library_name, + 'library_version' => empty($this->library_version) ? '' : $this->library_version + ); + } + + /** + * A helper which makes it easier for systems to save the data. + * Used in WordPress. + * + * @return array with strings + */ + protected function getFormatArray() { + return array( + '%d', + '%s', + '%s', + '%d', + '%s', + '%s', + '%s' + ); + } + + /** + * Stores the event data in the database. + * + * Must be overridden by plugin. + */ + abstract protected function save(); + + /** + * Add current event data to statistics counter. + * + * Must be overridden by plugin. + */ + abstract protected function saveStats(); +} diff --git a/lib/h5p/h5p-file-storage.interface.php b/lib/h5p/h5p-file-storage.interface.php new file mode 100644 index 00000000000..29bd3204ef2 --- /dev/null +++ b/lib/h5p/h5p-file-storage.interface.php @@ -0,0 +1,222 @@ + array( + 'type' => 'text', + 'maxLength' => 255 + ), + 'authors' => array( + 'type' => 'json' + ), + 'changes' => array( + 'type' => 'json' + ), + 'source' => array( + 'type' => 'text', + 'maxLength' => 255 + ), + 'license' => array( + 'type' => 'text', + 'maxLength' => 32 + ), + 'licenseVersion' => array( + 'type' => 'text', + 'maxLength' => 10 + ), + 'licenseExtras' => array( + 'type' => 'text', + 'maxLength' => 5000 + ), + 'authorComments' => array( + 'type' => 'text', + 'maxLength' => 5000 + ), + 'yearFrom' => array( + 'type' => 'int' + ), + 'yearTo' => array( + 'type' => 'int' + ), + 'defaultLanguage' => array( + 'type' => 'text', + 'maxLength' => 32, + ) + ); + + /** + * JSON encode metadata + * + * @param object $content + * @return string + */ + public static function toJSON($content) { + // Note: deliberatly creating JSON string "manually" to improve performance + return + '{"title":' . (isset($content->title) ? json_encode($content->title) : 'null') . + ',"authors":' . (isset($content->authors) ? $content->authors : 'null') . + ',"source":' . (isset($content->source) ? '"' . $content->source . '"' : 'null') . + ',"license":' . (isset($content->license) ? '"' . $content->license . '"' : 'null') . + ',"licenseVersion":' . (isset($content->license_version) ? '"' . $content->license_version . '"' : 'null') . + ',"licenseExtras":' . (isset($content->license_extras) ? json_encode($content->license_extras) : 'null') . + ',"yearFrom":' . (isset($content->year_from) ? $content->year_from : 'null') . + ',"yearTo":' . (isset($content->year_to) ? $content->year_to : 'null') . + ',"changes":' . (isset($content->changes) ? $content->changes : 'null') . + ',"defaultLanguage":' . (isset($content->default_language) ? '"' . $content->default_language . '"' : 'null') . + ',"authorComments":' . (isset($content->author_comments) ? json_encode($content->author_comments) : 'null') . '}'; + } + + /** + * Make the metadata into an associative array keyed by the property names + * @param mixed $metadata Array or object containing metadata + * @param bool $include_title + * @param bool $include_missing For metadata fields not being set, skip 'em. + * Relevant for content upgrade + * @param array $types + * @return array + */ + public static function toDBArray($metadata, $include_title = true, $include_missing = true, &$types = array()) { + $fields = array(); + + if (!is_array($metadata)) { + $metadata = (array) $metadata; + } + + foreach (self::$fields as $key => $config) { + + // Ignore title? + if ($key === 'title' && !$include_title) { + continue; + } + + $exists = array_key_exists($key, $metadata); + + // Don't include missing fields + if (!$include_missing && !$exists) { + continue; + } + + $value = $exists ? $metadata[$key] : null; + + // lowerCamelCase to snake_case + $db_field_name = strtolower(preg_replace('/(? $config['maxLength']) { + $value = mb_substr($value, 0, $config['maxLength']); + } + $types[] = '%s'; + break; + + case 'int': + $value = ($value !== null) ? intval($value) : null; + $types[] = '%d'; + break; + + case 'json': + $value = ($value !== null) ? json_encode($value) : null; + $types[] = '%s'; + break; + } + + $fields[$db_field_name] = $value; + } + + return $fields; + } + + /** + * The metadataSettings field in libraryJson uses 1 for true and 0 for false. + * Here we are converting these to booleans, and also doing JSON encoding. + * This is invoked before the library data is beeing inserted/updated to DB. + * + * @param array $metadataSettings + * @return string + */ + public static function boolifyAndEncodeSettings($metadataSettings) { + // Convert metadataSettings values to boolean + if (isset($metadataSettings['disable'])) { + $metadataSettings['disable'] = $metadataSettings['disable'] === 1; + } + if (isset($metadataSettings['disableExtraTitleField'])) { + $metadataSettings['disableExtraTitleField'] = $metadataSettings['disableExtraTitleField'] === 1; + } + + return json_encode($metadataSettings); + } +} diff --git a/lib/h5p/h5p.classes.php b/lib/h5p/h5p.classes.php new file mode 100644 index 00000000000..c127185e551 --- /dev/null +++ b/lib/h5p/h5p.classes.php @@ -0,0 +1,4890 @@ + '/^.{1,255}$/', + 'language' => '/^[-a-zA-Z]{1,10}$/', + 'preloadedDependencies' => array( + 'machineName' => '/^[\w0-9\-\.]{1,255}$/i', + 'majorVersion' => '/^[0-9]{1,5}$/', + 'minorVersion' => '/^[0-9]{1,5}$/', + ), + 'mainLibrary' => '/^[$a-z_][0-9a-z_\.$]{1,254}$/i', + 'embedTypes' => array('iframe', 'div'), + ); + + private $h5pOptional = array( + 'contentType' => '/^.{1,255}$/', + 'dynamicDependencies' => array( + 'machineName' => '/^[\w0-9\-\.]{1,255}$/i', + 'majorVersion' => '/^[0-9]{1,5}$/', + 'minorVersion' => '/^[0-9]{1,5}$/', + ), + // deprecated + 'author' => '/^.{1,255}$/', + 'authors' => array( + 'name' => '/^.{1,255}$/', + 'role' => '/^\w+$/', + ), + 'source' => '/^(http[s]?:\/\/.+)$/', + 'license' => '/^(CC BY|CC BY-SA|CC BY-ND|CC BY-NC|CC BY-NC-SA|CC BY-NC-ND|CC0 1\.0|GNU GPL|PD|ODC PDDL|CC PDM|U|C)$/', + 'licenseVersion' => '/^(1\.0|2\.0|2\.5|3\.0|4\.0)$/', + 'licenseExtras' => '/^.{1,5000}$/', + 'yearsFrom' => '/^([0-9]{1,4})$/', + 'yearsTo' => '/^([0-9]{1,4})$/', + 'changes' => array( + 'date' => '/^[0-9]{2}-[0-9]{2}-[0-9]{2} [0-9]{1,2}:[0-9]{2}:[0-9]{2}$/', + 'author' => '/^.{1,255}$/', + 'log' => '/^.{1,5000}$/' + ), + 'authorComments' => '/^.{1,5000}$/', + 'w' => '/^[0-9]{1,4}$/', + 'h' => '/^[0-9]{1,4}$/', + // deprecated + 'metaKeywords' => '/^.{1,}$/', + // deprecated + 'metaDescription' => '/^.{1,}$/', + ); + + // Schemas used to validate the library files + private $libraryRequired = array( + 'title' => '/^.{1,255}$/', + 'majorVersion' => '/^[0-9]{1,5}$/', + 'minorVersion' => '/^[0-9]{1,5}$/', + 'patchVersion' => '/^[0-9]{1,5}$/', + 'machineName' => '/^[\w0-9\-\.]{1,255}$/i', + 'runnable' => '/^(0|1)$/', + ); + + private $libraryOptional = array( + 'author' => '/^.{1,255}$/', + 'license' => '/^(cc-by|cc-by-sa|cc-by-nd|cc-by-nc|cc-by-nc-sa|cc-by-nc-nd|pd|cr|MIT|GPL1|GPL2|GPL3|MPL|MPL2)$/', + 'description' => '/^.{1,}$/', + 'metadataSettings' => array( + 'disable' => '/^(0|1)$/', + 'disableExtraTitleField' => '/^(0|1)$/' + ), + 'dynamicDependencies' => array( + 'machineName' => '/^[\w0-9\-\.]{1,255}$/i', + 'majorVersion' => '/^[0-9]{1,5}$/', + 'minorVersion' => '/^[0-9]{1,5}$/', + ), + 'preloadedDependencies' => array( + 'machineName' => '/^[\w0-9\-\.]{1,255}$/i', + 'majorVersion' => '/^[0-9]{1,5}$/', + 'minorVersion' => '/^[0-9]{1,5}$/', + ), + 'editorDependencies' => array( + 'machineName' => '/^[\w0-9\-\.]{1,255}$/i', + 'majorVersion' => '/^[0-9]{1,5}$/', + 'minorVersion' => '/^[0-9]{1,5}$/', + ), + 'preloadedJs' => array( + 'path' => '/^((\\\|\/)?[a-z_\-\s0-9\.]+)+\.js$/i', + ), + 'preloadedCss' => array( + 'path' => '/^((\\\|\/)?[a-z_\-\s0-9\.]+)+\.css$/i', + ), + 'dropLibraryCss' => array( + 'machineName' => '/^[\w0-9\-\.]{1,255}$/i', + ), + 'w' => '/^[0-9]{1,4}$/', + 'h' => '/^[0-9]{1,4}$/', + 'embedTypes' => array('iframe', 'div'), + 'fullscreen' => '/^(0|1)$/', + 'coreApi' => array( + 'majorVersion' => '/^[0-9]{1,5}$/', + 'minorVersion' => '/^[0-9]{1,5}$/', + ), + ); + + /** + * Constructor for the H5PValidator + * + * @param H5PFrameworkInterface $H5PFramework + * The frameworks implementation of the H5PFrameworkInterface + * @param H5PCore $H5PCore + */ + public function __construct($H5PFramework, $H5PCore) { + $this->h5pF = $H5PFramework; + $this->h5pC = $H5PCore; + $this->h5pCV = new H5PContentValidator($this->h5pF, $this->h5pC); + } + + /** + * Validates a .h5p file + * + * @param bool $skipContent + * @param bool $upgradeOnly + * @return bool TRUE if the .h5p file is valid + * TRUE if the .h5p file is valid + */ + public function isValidPackage($skipContent = FALSE, $upgradeOnly = FALSE) { + // Check dependencies, make sure Zip is present + if (!class_exists('ZipArchive')) { + $this->h5pF->setErrorMessage($this->h5pF->t('Your PHP version does not support ZipArchive.'), 'zip-archive-unsupported'); + unlink($tmpPath); + return FALSE; + } + if (!extension_loaded('mbstring')) { + $this->h5pF->setErrorMessage($this->h5pF->t('The mbstring PHP extension is not loaded. H5P need this to function properly'), 'mbstring-unsupported'); + unlink($tmpPath); + return FALSE; + } + + // Create a temporary dir to extract package in. + $tmpDir = $this->h5pF->getUploadedH5pFolderPath(); + $tmpPath = $this->h5pF->getUploadedH5pPath(); + + // Only allow files with the .h5p extension: + if (strtolower(substr($tmpPath, -3)) !== 'h5p') { + $this->h5pF->setErrorMessage($this->h5pF->t('The file you uploaded is not a valid HTML5 Package (It does not have the .h5p file extension)'), 'missing-h5p-extension'); + unlink($tmpPath); + return FALSE; + } + + // Extract and then remove the package file. + $zip = new ZipArchive; + + // Open the package + if ($zip->open($tmpPath) !== TRUE) { + $this->h5pF->setErrorMessage($this->h5pF->t('The file you uploaded is not a valid HTML5 Package (We are unable to unzip it)'), 'unable-to-unzip'); + unlink($tmpPath); + return FALSE; + } + + if ($this->h5pC->disableFileCheck !== TRUE) { + list($contentWhitelist, $contentRegExp) = $this->getWhitelistRegExp(FALSE); + list($libraryWhitelist, $libraryRegExp) = $this->getWhitelistRegExp(TRUE); + } + $canInstall = $this->h5pC->mayUpdateLibraries(); + + $valid = TRUE; + $libraries = array(); + + $totalSize = 0; + $mainH5pExists = FALSE; + $contentExists = FALSE; + + // Check for valid file types, JSON files + file sizes before continuing to unpack. + for ($i = 0; $i < $zip->numFiles; $i++) { + $fileStat = $zip->statIndex($i); + + if (!empty($this->h5pC->maxFileSize) && $fileStat['size'] > $this->h5pC->maxFileSize) { + // Error file is too large + $this->h5pF->setErrorMessage($this->h5pF->t('One of the files inside the package exceeds the maximum file size allowed. (%file %used > %max)', array('%file' => $fileStat['name'], '%used' => ($fileStat['size'] / 1048576) . ' MB', '%max' => ($this->h5pC->maxFileSize / 1048576) . ' MB')), 'file-size-too-large'); + $valid = FALSE; + } + $totalSize += $fileStat['size']; + + $fileName = mb_strtolower($fileStat['name']); + if (preg_match('/(^[\._]|\/[\._])/', $fileName) !== 0) { + continue; // Skip any file or folder starting with a . or _ + } + elseif ($fileName === 'h5p.json') { + $mainH5pExists = TRUE; + } + elseif ($fileName === 'content/content.json') { + $contentExists = TRUE; + } + elseif (substr($fileName, 0, 8) === 'content/') { + // This is a content file, check that the file type is allowed + if ($skipContent === FALSE && $this->h5pC->disableFileCheck !== TRUE && !preg_match($contentRegExp, $fileName)) { + $this->h5pF->setErrorMessage($this->h5pF->t('File "%filename" not allowed. Only files with the following extensions are allowed: %files-allowed.', array('%filename' => $fileStat['name'], '%files-allowed' => $contentWhitelist)), 'not-in-whitelist'); + $valid = FALSE; + } + } + elseif ($canInstall && strpos($fileName, '/') !== FALSE) { + // This is a library file, check that the file type is allowed + if ($this->h5pC->disableFileCheck !== TRUE && !preg_match($libraryRegExp, $fileName)) { + $this->h5pF->setErrorMessage($this->h5pF->t('File "%filename" not allowed. Only files with the following extensions are allowed: %files-allowed.', array('%filename' => $fileStat['name'], '%files-allowed' => $libraryWhitelist)), 'not-in-whitelist'); + $valid = FALSE; + } + + // Further library validation happens after the files are extracted + } + } + + if (!empty($this->h5pC->maxTotalSize) && $totalSize > $this->h5pC->maxTotalSize) { + // Error total size of the zip is too large + $this->h5pF->setErrorMessage($this->h5pF->t('The total size of the unpacked files exceeds the maximum size allowed. (%used > %max)', array('%used' => ($totalSize / 1048576) . ' MB', '%max' => ($this->h5pC->maxTotalSize / 1048576) . ' MB')), 'total-size-too-large'); + $valid = FALSE; + } + + if ($skipContent === FALSE) { + // Not skipping content, require two valid JSON files from the package + if (!$contentExists) { + $this->h5pF->setErrorMessage($this->h5pF->t('A valid content folder is missing'), 'invalid-content-folder'); + $valid = FALSE; + } + else { + $contentJsonData = $this->getJson($tmpPath, $zip, 'content/content.json'); // TODO: Is this case-senstivie? + if ($contentJsonData === NULL) { + return FALSE; // Breaking error when reading from the archive. + } + elseif ($contentJsonData === FALSE) { + $valid = FALSE; // Validation error when parsing JSON + } + } + + if (!$mainH5pExists) { + $this->h5pF->setErrorMessage($this->h5pF->t('A valid main h5p.json file is missing'), 'invalid-h5p-json-file'); + $valid = FALSE; + } + else { + $mainH5pData = $this->getJson($tmpPath, $zip, 'h5p.json', TRUE); + if ($mainH5pData === NULL) { + return FALSE; // Breaking error when reading from the archive. + } + elseif ($mainH5pData === FALSE) { + $valid = FALSE; // Validation error when parsing JSON + } + elseif (!$this->isValidH5pData($mainH5pData, 'h5p.json', $this->h5pRequired, $this->h5pOptional)) { + $this->h5pF->setErrorMessage($this->h5pF->t('The main h5p.json file is not valid'), 'invalid-h5p-json-file'); // Is this message a bit redundant? + $valid = FALSE; + } + } + } + + if (!$valid) { + // If something has failed during the initial checks of the package + // we will not unpack it or continue validation. + $zip->close(); + unlink($tmpPath); + return FALSE; + } + + // Extract the files from the package + for ($i = 0; $i < $zip->numFiles; $i++) { + $fileName = $zip->statIndex($i)['name']; + + if (preg_match('/(^[\._]|\/[\._])/', $fileName) !== 0) { + continue; // Skip any file or folder starting with a . or _ + } + + $isContentFile = (substr($fileName, 0, 8) === 'content/'); + $isFolder = (strpos($fileName, '/') !== FALSE); + + if ($skipContent !== FALSE && $isContentFile) { + continue; // Skipping any content files + } + + if (!($isContentFile || ($canInstall && $isFolder))) { + continue; // Not something we want to unpack + } + + // Get file stream + $fileStream = $zip->getStream($fileName); + if (!$fileStream) { + // This is a breaking error, there's no need to continue. (the rest of the files will fail as well) + $this->h5pF->setErrorMessage($this->h5pF->t('Unable to read file from the package: %fileName', array('%fileName' => $fileName)), 'unable-to-read-package-file'); + $zip->close(); + unlink($path); + H5PCore::deleteFileTree($tmpDir); + return FALSE; + } + + // Use file interface to allow overrides + $this->h5pC->fs->saveFileFromZip($tmpDir, $fileName, $fileStream); + + // Clean up + if (is_resource($fileStream)) { + fclose($fileStream); + } + } + + // We're done with the zip file, clean up the stuff + $zip->close(); + unlink($tmpPath); + + if ($canInstall) { + // Process and validate libraries using the unpacked library folders + $files = scandir($tmpDir); + foreach ($files as $file) { + $filePath = $tmpDir . DIRECTORY_SEPARATOR . $file; + + if ($file === '.' || $file === '..' || $file === 'content' || !is_dir($filePath)) { + continue; // Skip + } + + $libraryH5PData = $this->getLibraryData($file, $filePath, $tmpDir); + if ($libraryH5PData === FALSE) { + $valid = FALSE; + continue; // Failed, but continue validating the rest of the libraries + } + + // Library's directory name must be: + // - + // - or - + // - -. + // where machineName, majorVersion and minorVersion is read from library.json + if ($libraryH5PData['machineName'] !== $file && H5PCore::libraryToString($libraryH5PData, TRUE) !== $file) { + $this->h5pF->setErrorMessage($this->h5pF->t('Library directory name must match machineName or machineName-majorVersion.minorVersion (from library.json). (Directory: %directoryName , machineName: %machineName, majorVersion: %majorVersion, minorVersion: %minorVersion)', array( + '%directoryName' => $file, + '%machineName' => $libraryH5PData['machineName'], + '%majorVersion' => $libraryH5PData['majorVersion'], + '%minorVersion' => $libraryH5PData['minorVersion'])), 'library-directory-name-mismatch'); + $valid = FALSE; + continue; // Failed, but continue validating the rest of the libraries + } + + $libraryH5PData['uploadDirectory'] = $filePath; + $libraries[H5PCore::libraryToString($libraryH5PData)] = $libraryH5PData; + } + } + + if ($valid) { + if ($upgradeOnly) { + // When upgrading, we only add the already installed libraries, and + // the new dependent libraries + $upgrades = array(); + foreach ($libraries as $libString => &$library) { + // Is this library already installed? + if ($this->h5pF->getLibraryId($library['machineName']) !== FALSE) { + $upgrades[$libString] = $library; + } + } + while ($missingLibraries = $this->getMissingLibraries($upgrades)) { + foreach ($missingLibraries as $libString => $missing) { + $library = $libraries[$libString]; + if ($library) { + $upgrades[$libString] = $library; + } + } + } + + $libraries = $upgrades; + } + + $this->h5pC->librariesJsonData = $libraries; + + if ($skipContent === FALSE) { + $this->h5pC->mainJsonData = $mainH5pData; + $this->h5pC->contentJsonData = $contentJsonData; + $libraries['mainH5pData'] = $mainH5pData; // Check for the dependencies in h5p.json as well as in the libraries + } + + $missingLibraries = $this->getMissingLibraries($libraries); + foreach ($missingLibraries as $libString => $missing) { + if ($this->h5pC->getLibraryId($missing, $libString)) { + unset($missingLibraries[$libString]); + } + } + + if (!empty($missingLibraries)) { + // We still have missing libraries, check if our main library has an upgrade (BUT only if we has content) + $mainDependency = NULL; + if (!$skipContent && !empty($mainH5pData)) { + foreach ($mainH5pData['preloadedDependencies'] as $dep) { + if ($dep['machineName'] === $mainH5pData['mainLibrary']) { + $mainDependency = $dep; + } + } + } + + if ($skipContent || !$mainDependency || !$this->h5pF->libraryHasUpgrade(array( + 'machineName' => $mainDependency['machineName'], + 'majorVersion' => $mainDependency['majorVersion'], + 'minorVersion' => $mainDependency['minorVersion'] + ))) { + foreach ($missingLibraries as $libString => $library) { + $this->h5pF->setErrorMessage($this->h5pF->t('Missing required library @library', array('@library' => $libString)), 'missing-required-library'); + $valid = FALSE; + } + if (!$this->h5pC->mayUpdateLibraries()) { + $this->h5pF->setInfoMessage($this->h5pF->t("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.")); + $valid = FALSE; + } + } + } + } + if (!$valid) { + H5PCore::deleteFileTree($tmpDir); + } + return $valid; + } + + /** + * Help read JSON from the archive + * + * @param string $path + * @param ZipArchive $zip + * @param string $file + * @return mixed JSON content if valid, FALSE for invalid, NULL for breaking error. + */ + private function getJson($path, $zip, $file, $assoc = FALSE) { + // Get stream + $stream = $zip->getStream($file); + if (!$stream) { + // Breaking error, no need to continue validating. + $this->h5pF->setErrorMessage($this->h5pF->t('Unable to read file from the package: %fileName', array('%fileName' => $file)), 'unable-to-read-package-file'); + $zip->close(); + unlink($path); + return NULL; + } + + // Read data + $contents = ''; + while (!feof($stream)) { + $contents .= fread($stream, 2); + } + + // Decode the data + $json = json_decode($contents, $assoc); + if ($json === NULL) { + // JSON cannot be decoded or the recursion limit has been reached. + $this->h5pF->setErrorMessage($this->h5pF->t('Unable to parse JSON from the package: %fileName', array('%fileName' => $file)), 'unable-to-parse-package'); + return FALSE; + } + + // All OK + return $json; + } + + /** + * Help retrieve file type regexp whitelist from plugin. + * + * @param bool $isLibrary Separate list with more allowed file types + * @return string RegExp + */ + private function getWhitelistRegExp($isLibrary) { + $whitelist = $this->h5pF->getWhitelist($isLibrary, H5PCore::$defaultContentWhitelist, H5PCore::$defaultLibraryWhitelistExtras); + return array($whitelist, '/\.(' . preg_replace('/ +/i', '|', preg_quote($whitelist)) . ')$/i'); + } + + /** + * Validates a H5P library + * + * @param string $file + * Name of the library folder + * @param string $filePath + * Path to the library folder + * @param string $tmpDir + * Path to the temporary upload directory + * @return boolean|array + * H5P data from library.json and semantics if the library is valid + * FALSE if the library isn't valid + */ + public function getLibraryData($file, $filePath, $tmpDir) { + if (preg_match('/^[\w0-9\-\.]{1,255}$/i', $file) === 0) { + $this->h5pF->setErrorMessage($this->h5pF->t('Invalid library name: %name', array('%name' => $file)), 'invalid-library-name'); + return FALSE; + } + $h5pData = $this->getJsonData($filePath . DIRECTORY_SEPARATOR . 'library.json'); + if ($h5pData === FALSE) { + $this->h5pF->setErrorMessage($this->h5pF->t('Could not find library.json file with valid json format for library %name', array('%name' => $file)), 'invalid-library-json-file'); + return FALSE; + } + + // validate json if a semantics file is provided + $semanticsPath = $filePath . DIRECTORY_SEPARATOR . 'semantics.json'; + if (file_exists($semanticsPath)) { + $semantics = $this->getJsonData($semanticsPath, TRUE); + if ($semantics === FALSE) { + $this->h5pF->setErrorMessage($this->h5pF->t('Invalid semantics.json file has been included in the library %name', array('%name' => $file)), 'invalid-semantics-json-file'); + return FALSE; + } + else { + $h5pData['semantics'] = $semantics; + } + } + + // validate language folder if it exists + $languagePath = $filePath . DIRECTORY_SEPARATOR . 'language'; + if (is_dir($languagePath)) { + $languageFiles = scandir($languagePath); + foreach ($languageFiles as $languageFile) { + if (in_array($languageFile, array('.', '..'))) { + continue; + } + if (preg_match('/^(-?[a-z]+){1,7}\.json$/i', $languageFile) === 0) { + $this->h5pF->setErrorMessage($this->h5pF->t('Invalid language file %file in library %library', array('%file' => $languageFile, '%library' => $file)), 'invalid-language-file'); + return FALSE; + } + $languageJson = $this->getJsonData($languagePath . DIRECTORY_SEPARATOR . $languageFile, TRUE); + if ($languageJson === FALSE) { + $this->h5pF->setErrorMessage($this->h5pF->t('Invalid language file %languageFile has been included in the library %name', array('%languageFile' => $languageFile, '%name' => $file)), 'invalid-language-file'); + return FALSE; + } + $parts = explode('.', $languageFile); // $parts[0] is the language code + $h5pData['language'][$parts[0]] = $languageJson; + } + } + + // Check for icon: + $h5pData['hasIcon'] = file_exists($filePath . DIRECTORY_SEPARATOR . 'icon.svg'); + + $validLibrary = $this->isValidH5pData($h5pData, $file, $this->libraryRequired, $this->libraryOptional); + + //$validLibrary = $this->h5pCV->validateContentFiles($filePath, TRUE) && $validLibrary; + + if (isset($h5pData['preloadedJs'])) { + $validLibrary = $this->isExistingFiles($h5pData['preloadedJs'], $tmpDir, $file) && $validLibrary; + } + if (isset($h5pData['preloadedCss'])) { + $validLibrary = $this->isExistingFiles($h5pData['preloadedCss'], $tmpDir, $file) && $validLibrary; + } + if ($validLibrary) { + return $h5pData; + } + else { + return FALSE; + } + } + + /** + * Use the dependency declarations to find any missing libraries + * + * @param array $libraries + * A multidimensional array of libraries keyed with machineName first and majorVersion second + * @return array + * A list of libraries that are missing keyed with machineName and holds objects with + * machineName, majorVersion and minorVersion properties + */ + private function getMissingLibraries($libraries) { + $missing = array(); + foreach ($libraries as $library) { + if (isset($library['preloadedDependencies'])) { + $missing = array_merge($missing, $this->getMissingDependencies($library['preloadedDependencies'], $libraries)); + } + if (isset($library['dynamicDependencies'])) { + $missing = array_merge($missing, $this->getMissingDependencies($library['dynamicDependencies'], $libraries)); + } + if (isset($library['editorDependencies'])) { + $missing = array_merge($missing, $this->getMissingDependencies($library['editorDependencies'], $libraries)); + } + } + return $missing; + } + + /** + * Helper function for getMissingLibraries, searches for dependency required libraries in + * the provided list of libraries + * + * @param array $dependencies + * A list of objects with machineName, majorVersion and minorVersion properties + * @param array $libraries + * An array of libraries keyed with machineName + * @return + * A list of libraries that are missing keyed with machineName and holds objects with + * machineName, majorVersion and minorVersion properties + */ + private function getMissingDependencies($dependencies, $libraries) { + $missing = array(); + foreach ($dependencies as $dependency) { + $libString = H5PCore::libraryToString($dependency); + if (!isset($libraries[$libString])) { + $missing[$libString] = $dependency; + } + } + return $missing; + } + + /** + * Figure out if the provided file paths exists + * + * Triggers error messages if files doesn't exist + * + * @param array $files + * List of file paths relative to $tmpDir + * @param string $tmpDir + * Path to the directory where the $files are stored. + * @param string $library + * Name of the library we are processing + * @return boolean + * TRUE if all the files excists + */ + private function isExistingFiles($files, $tmpDir, $library) { + foreach ($files as $file) { + $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $file['path']); + if (!file_exists($tmpDir . DIRECTORY_SEPARATOR . $library . DIRECTORY_SEPARATOR . $path)) { + $this->h5pF->setErrorMessage($this->h5pF->t('The file "%file" is missing from library: "%name"', array('%file' => $path, '%name' => $library)), 'library-missing-file'); + return FALSE; + } + } + return TRUE; + } + + /** + * Validates h5p.json and library.json data + * + * Error messages are triggered if the data isn't valid + * + * @param array $h5pData + * h5p data + * @param string $library_name + * Name of the library we are processing + * @param array $required + * Validation pattern for required properties + * @param array $optional + * Validation pattern for optional properties + * @return boolean + * TRUE if the $h5pData is valid + */ + private function isValidH5pData($h5pData, $library_name, $required, $optional) { + $valid = $this->isValidRequiredH5pData($h5pData, $required, $library_name); + $valid = $this->isValidOptionalH5pData($h5pData, $optional, $library_name) && $valid; + + // Check the library's required API version of Core. + // If no requirement is set this implicitly means 1.0. + if (isset($h5pData['coreApi']) && !empty($h5pData['coreApi'])) { + if (($h5pData['coreApi']['majorVersion'] > H5PCore::$coreApi['majorVersion']) || + ( ($h5pData['coreApi']['majorVersion'] == H5PCore::$coreApi['majorVersion']) && + ($h5pData['coreApi']['minorVersion'] > H5PCore::$coreApi['minorVersion']) )) { + + $this->h5pF->setErrorMessage( + $this->h5pF->t('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.', + array( + '%component' => (isset($h5pData['title']) ? $h5pData['title'] : $library_name), + '%current' => H5PCore::$coreApi['majorVersion'] . '.' . H5PCore::$coreApi['minorVersion'], + '%required' => $h5pData['coreApi']['majorVersion'] . '.' . $h5pData['coreApi']['minorVersion'] + ) + ), + 'api-version-unsupported' + ); + + $valid = false; + } + } + + return $valid; + } + + /** + * Helper function for isValidH5pData + * + * Validates the optional part of the h5pData + * + * Triggers error messages + * + * @param array $h5pData + * h5p data + * @param array $requirements + * Validation pattern + * @param string $library_name + * Name of the library we are processing + * @return boolean + * TRUE if the optional part of the $h5pData is valid + */ + private function isValidOptionalH5pData($h5pData, $requirements, $library_name) { + $valid = TRUE; + + foreach ($h5pData as $key => $value) { + if (isset($requirements[$key])) { + $valid = $this->isValidRequirement($value, $requirements[$key], $library_name, $key) && $valid; + } + // Else: ignore, a package can have parameters that this library doesn't care about, but that library + // specific implementations does care about... + } + + return $valid; + } + + /** + * Validate a requirement given as regexp or an array of requirements + * + * @param mixed $h5pData + * The data to be validated + * @param mixed $requirement + * The requirement the data is to be validated against, regexp or array of requirements + * @param string $library_name + * Name of the library we are validating(used in error messages) + * @param string $property_name + * Name of the property we are validating(used in error messages) + * @return boolean + * TRUE if valid, FALSE if invalid + */ + private function isValidRequirement($h5pData, $requirement, $library_name, $property_name) { + $valid = TRUE; + + if (is_string($requirement)) { + if ($requirement == 'boolean') { + if (!is_bool($h5pData)) { + $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library. Boolean expected.", array('%property' => $property_name, '%library' => $library_name))); + $valid = FALSE; + } + } + else { + // The requirement is a regexp, match it against the data + if (is_string($h5pData) || is_int($h5pData)) { + if (preg_match($requirement, $h5pData) === 0) { + $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library", array('%property' => $property_name, '%library' => $library_name))); + $valid = FALSE; + } + } + else { + $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library", array('%property' => $property_name, '%library' => $library_name))); + $valid = FALSE; + } + } + } + elseif (is_array($requirement)) { + // We have sub requirements + if (is_array($h5pData)) { + if (is_array(current($h5pData))) { + foreach ($h5pData as $sub_h5pData) { + $valid = $this->isValidRequiredH5pData($sub_h5pData, $requirement, $library_name) && $valid; + } + } + else { + $valid = $this->isValidRequiredH5pData($h5pData, $requirement, $library_name) && $valid; + } + } + else { + $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library", array('%property' => $property_name, '%library' => $library_name))); + $valid = FALSE; + } + } + else { + $this->h5pF->setErrorMessage($this->h5pF->t("Can't read the property %property in %library", array('%property' => $property_name, '%library' => $library_name))); + $valid = FALSE; + } + return $valid; + } + + /** + * Validates the required h5p data in libraray.json and h5p.json + * + * @param mixed $h5pData + * Data to be validated + * @param array $requirements + * Array with regexp to validate the data against + * @param string $library_name + * Name of the library we are validating (used in error messages) + * @return boolean + * TRUE if all the required data exists and is valid, FALSE otherwise + */ + private function isValidRequiredH5pData($h5pData, $requirements, $library_name) { + $valid = TRUE; + foreach ($requirements as $required => $requirement) { + if (is_int($required)) { + // We have an array of allowed options + return $this->isValidH5pDataOptions($h5pData, $requirements, $library_name); + } + if (isset($h5pData[$required])) { + $valid = $this->isValidRequirement($h5pData[$required], $requirement, $library_name, $required) && $valid; + } + else { + $this->h5pF->setErrorMessage($this->h5pF->t('The required property %property is missing from %library', array('%property' => $required, '%library' => $library_name)), 'missing-required-property'); + $valid = FALSE; + } + } + return $valid; + } + + /** + * Validates h5p data against a set of allowed values(options) + * + * @param array $selected + * The option(s) that has been specified + * @param array $allowed + * The allowed options + * @param string $library_name + * Name of the library we are validating (used in error messages) + * @return boolean + * TRUE if the specified data is valid, FALSE otherwise + */ + private function isValidH5pDataOptions($selected, $allowed, $library_name) { + $valid = TRUE; + foreach ($selected as $value) { + if (!in_array($value, $allowed)) { + $this->h5pF->setErrorMessage($this->h5pF->t('Illegal option %option in %library', array('%option' => $value, '%library' => $library_name)), 'illegal-option-in-library'); + $valid = FALSE; + } + } + return $valid; + } + + /** + * Fetch json data from file + * + * @param string $filePath + * Path to the file holding the json string + * @param boolean $return_as_string + * If true the json data will be decoded in order to validate it, but will be + * returned as string + * @return mixed + * FALSE if the file can't be read or the contents can't be decoded + * string if the $return as string parameter is set + * array otherwise + */ + private function getJsonData($filePath, $return_as_string = FALSE) { + $json = file_get_contents($filePath); + if ($json === FALSE) { + return FALSE; // Cannot read from file. + } + $jsonData = json_decode($json, TRUE); + if ($jsonData === NULL) { + return FALSE; // JSON cannot be decoded or the recursion limit has been reached. + } + return $return_as_string ? $json : $jsonData; + } + + /** + * Helper function that copies an array + * + * @param array $array + * The array to be copied + * @return array + * Copy of $array. All objects are cloned + */ + private function arrayCopy(array $array) { + $result = array(); + foreach ($array as $key => $val) { + if (is_array($val)) { + $result[$key] = self::arrayCopy($val); + } + elseif (is_object($val)) { + $result[$key] = clone $val; + } + else { + $result[$key] = $val; + } + } + return $result; + } +} + +/** + * This class is used for saving H5P files + */ +class H5PStorage { + + public $h5pF; + public $h5pC; + + public $contentId = NULL; // Quick fix so WP can get ID of new content. + + /** + * Constructor for the H5PStorage + * + * @param H5PFrameworkInterface|object $H5PFramework + * The frameworks implementation of the H5PFrameworkInterface + * @param H5PCore $H5PCore + */ + public function __construct(H5PFrameworkInterface $H5PFramework, H5PCore $H5PCore) { + $this->h5pF = $H5PFramework; + $this->h5pC = $H5PCore; + } + + /** + * Saves a H5P file + * + * @param null $content + * @param int $contentMainId + * The main id for the content we are saving. This is used if the framework + * we're integrating with uses content id's and version id's + * @param bool $skipContent + * @param array $options + * @return bool TRUE if one or more libraries were updated + * TRUE if one or more libraries were updated + * FALSE otherwise + */ + public function savePackage($content = NULL, $contentMainId = NULL, $skipContent = FALSE, $options = array()) { + if ($this->h5pC->mayUpdateLibraries()) { + // Save the libraries we processed during validation + $this->saveLibraries(); + } + + if (!$skipContent) { + $basePath = $this->h5pF->getUploadedH5pFolderPath(); + $current_path = $basePath . DIRECTORY_SEPARATOR . 'content'; + + // Save content + if ($content === NULL) { + $content = array(); + } + if (!is_array($content)) { + $content = array('id' => $content); + } + + // Find main library version + foreach ($this->h5pC->mainJsonData['preloadedDependencies'] as $dep) { + if ($dep['machineName'] === $this->h5pC->mainJsonData['mainLibrary']) { + $dep['libraryId'] = $this->h5pC->getLibraryId($dep); + $content['library'] = $dep; + break; + } + } + + $content['params'] = file_get_contents($current_path . DIRECTORY_SEPARATOR . 'content.json'); + + if (isset($options['disable'])) { + $content['disable'] = $options['disable']; + } + $content['id'] = $this->h5pC->saveContent($content, $contentMainId); + $this->contentId = $content['id']; + + try { + // Save content folder contents + $this->h5pC->fs->saveContent($current_path, $content); + } + catch (Exception $e) { + $this->h5pF->setErrorMessage($e->getMessage(), 'save-content-failed'); + } + + // Remove temp content folder + H5PCore::deleteFileTree($basePath); + } + } + + /** + * Helps savePackage. + * + * @return int Number of libraries saved + */ + private function saveLibraries() { + // Keep track of the number of libraries that have been saved + $newOnes = 0; + $oldOnes = 0; + + // Go through libraries that came with this package + foreach ($this->h5pC->librariesJsonData as $libString => &$library) { + // Find local library identifier + $libraryId = $this->h5pC->getLibraryId($library, $libString); + + // Assume new library + $new = TRUE; + if ($libraryId) { + // Found old library + $library['libraryId'] = $libraryId; + + if ($this->h5pF->isPatchedLibrary($library)) { + // This is a newer version than ours. Upgrade! + $new = FALSE; + } + else { + $library['saveDependencies'] = FALSE; + // This is an older version, no need to save. + continue; + } + } + + // Indicate that the dependencies of this library should be saved. + $library['saveDependencies'] = TRUE; + + // Convert metadataSettings values to boolean & json_encode it before saving + $library['metadataSettings'] = isset($library['metadataSettings']) ? + H5PMetadata::boolifyAndEncodeSettings($library['metadataSettings']) : + NULL; + + $this->h5pF->saveLibraryData($library, $new); + + // Save library folder + $this->h5pC->fs->saveLibrary($library); + + // Remove cached assets that uses this library + if ($this->h5pC->aggregateAssets && isset($library['libraryId'])) { + $removedKeys = $this->h5pF->deleteCachedAssets($library['libraryId']); + $this->h5pC->fs->deleteCachedAssets($removedKeys); + } + + // Remove tmp folder + H5PCore::deleteFileTree($library['uploadDirectory']); + + if ($new) { + $newOnes++; + } + else { + $oldOnes++; + } + } + + // Go through the libraries again to save dependencies. + $library_ids = []; + foreach ($this->h5pC->librariesJsonData as &$library) { + if (!$library['saveDependencies']) { + continue; + } + + // TODO: Should the table be locked for this operation? + + // Remove any old dependencies + $this->h5pF->deleteLibraryDependencies($library['libraryId']); + + // Insert the different new ones + if (isset($library['preloadedDependencies'])) { + $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['preloadedDependencies'], 'preloaded'); + } + if (isset($library['dynamicDependencies'])) { + $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['dynamicDependencies'], 'dynamic'); + } + if (isset($library['editorDependencies'])) { + $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['editorDependencies'], 'editor'); + } + + $library_ids[] = $library['libraryId']; + } + + // Make sure libraries dependencies, parameter filtering and export files gets regenerated for all content who uses these libraries. + if (!empty($library_ids)) { + $this->h5pF->clearFilteredParameters($library_ids); + } + + // Tell the user what we've done. + if ($newOnes && $oldOnes) { + if ($newOnes === 1) { + if ($oldOnes === 1) { + // Singular Singular + $message = $this->h5pF->t('Added %new new H5P library and updated %old old one.', array('%new' => $newOnes, '%old' => $oldOnes)); + } + else { + // Singular Plural + $message = $this->h5pF->t('Added %new new H5P library and updated %old old ones.', array('%new' => $newOnes, '%old' => $oldOnes)); + } + } + else { + // Plural + if ($oldOnes === 1) { + // Plural Singular + $message = $this->h5pF->t('Added %new new H5P libraries and updated %old old one.', array('%new' => $newOnes, '%old' => $oldOnes)); + } + else { + // Plural Plural + $message = $this->h5pF->t('Added %new new H5P libraries and updated %old old ones.', array('%new' => $newOnes, '%old' => $oldOnes)); + } + } + } + elseif ($newOnes) { + if ($newOnes === 1) { + // Singular + $message = $this->h5pF->t('Added %new new H5P library.', array('%new' => $newOnes)); + } + else { + // Plural + $message = $this->h5pF->t('Added %new new H5P libraries.', array('%new' => $newOnes)); + } + } + elseif ($oldOnes) { + if ($oldOnes === 1) { + // Singular + $message = $this->h5pF->t('Updated %old H5P library.', array('%old' => $oldOnes)); + } + else { + // Plural + $message = $this->h5pF->t('Updated %old H5P libraries.', array('%old' => $oldOnes)); + } + } + + if (isset($message)) { + $this->h5pF->setInfoMessage($message); + } + } + + /** + * Delete an H5P package + * + * @param $content + */ + public function deletePackage($content) { + $this->h5pC->fs->deleteContent($content); + $this->h5pC->fs->deleteExport(($content['slug'] ? $content['slug'] . '-' : '') . $content['id'] . '.h5p'); + $this->h5pF->deleteContentData($content['id']); + } + + /** + * Copy/clone an H5P package + * + * May for instance be used if the content is being revisioned without + * uploading a new H5P package + * + * @param int $contentId + * The new content id + * @param int $copyFromId + * The content id of the content that should be cloned + * @param int $contentMainId + * The main id of the new content (used in frameworks that support revisioning) + */ + public function copyPackage($contentId, $copyFromId, $contentMainId = NULL) { + $this->h5pC->fs->cloneContent($copyFromId, $contentId); + $this->h5pF->copyLibraryUsage($contentId, $copyFromId, $contentMainId); + } +} + +/** +* This class is used for exporting zips +*/ +Class H5PExport { + public $h5pF; + public $h5pC; + + /** + * Constructor for the H5PExport + * + * @param H5PFrameworkInterface|object $H5PFramework + * The frameworks implementation of the H5PFrameworkInterface + * @param H5PCore $H5PCore + * Reference to an instance of H5PCore + */ + public function __construct(H5PFrameworkInterface $H5PFramework, H5PCore $H5PCore) { + $this->h5pF = $H5PFramework; + $this->h5pC = $H5PCore; + } + + /** + * Reverts the replace pattern used by the text editor + * + * @param string $value + * @return string + */ + private static function revertH5PEditorTextEscape($value) { + return str_replace('<', '<', str_replace('>', '>', str_replace(''', "'", str_replace('"', '"', $value)))); + } + + /** + * Return path to h5p package. + * + * Creates package if not already created + * + * @param array $content + * @return string + */ + public function createExportFile($content) { + + // Get path to temporary folder, where export will be contained + $tmpPath = $this->h5pC->fs->getTmpPath(); + mkdir($tmpPath, 0777, true); + + try { + // Create content folder and populate with files + $this->h5pC->fs->exportContent($content['id'], "{$tmpPath}/content"); + } + catch (Exception $e) { + $this->h5pF->setErrorMessage($this->h5pF->t($e->getMessage()), 'failed-creating-export-file'); + H5PCore::deleteFileTree($tmpPath); + return FALSE; + } + + // Update content.json with content from database + file_put_contents("{$tmpPath}/content/content.json", $content['filtered']); + + // Make embedType into an array + $embedTypes = explode(', ', $content['embedType']); + + // Build h5p.json, the en-/de-coding will ensure proper escaping + $h5pJson = array ( + 'title' => self::revertH5PEditorTextEscape($content['title']), + 'language' => (isset($content['language']) && strlen(trim($content['language'])) !== 0) ? $content['language'] : 'und', + 'mainLibrary' => $content['library']['name'], + 'embedTypes' => $embedTypes + ); + + foreach(array('authors', 'source', 'license', 'licenseVersion', 'licenseExtras' ,'yearFrom', 'yearTo', 'changes', 'authorComments', 'defaultLanguage') as $field) { + if (isset($content['metadata'][$field]) && $content['metadata'][$field] !== '') { + if (($field !== 'authors' && $field !== 'changes') || (count($content['metadata'][$field]) > 0)) { + $h5pJson[$field] = json_decode(json_encode($content['metadata'][$field], TRUE)); + } + } + } + + // Remove all values that are not set + foreach ($h5pJson as $key => $value) { + if (!isset($value)) { + unset($h5pJson[$key]); + } + } + + // Add dependencies to h5p + foreach ($content['dependencies'] as $dependency) { + $library = $dependency['library']; + + try { + $exportFolder = NULL; + + // Determine path of export library + if (isset($this->h5pC) && isset($this->h5pC->h5pD)) { + + // Tries to find library in development folder + $isDevLibrary = $this->h5pC->h5pD->getLibrary( + $library['machineName'], + $library['majorVersion'], + $library['minorVersion'] + ); + + if ($isDevLibrary !== NULL && isset($library['path'])) { + $exportFolder = "/" . $library['path']; + } + } + + // Export required libraries + $this->h5pC->fs->exportLibrary($library, $tmpPath, $exportFolder); + } + catch (Exception $e) { + $this->h5pF->setErrorMessage($this->h5pF->t($e->getMessage()), 'failed-creating-export-file'); + H5PCore::deleteFileTree($tmpPath); + return FALSE; + } + + // Do not add editor dependencies to h5p json. + if ($dependency['type'] === 'editor') { + continue; + } + + // Add to h5p.json dependencies + $h5pJson[$dependency['type'] . 'Dependencies'][] = array( + 'machineName' => $library['machineName'], + 'majorVersion' => $library['majorVersion'], + 'minorVersion' => $library['minorVersion'] + ); + } + + // Save h5p.json + $results = print_r(json_encode($h5pJson), true); + file_put_contents("{$tmpPath}/h5p.json", $results); + + // Get a complete file list from our tmp dir + $files = array(); + self::populateFileList($tmpPath, $files); + + // Get path to temporary export target file + $tmpFile = $this->h5pC->fs->getTmpPath(); + + // Create new zip instance. + $zip = new ZipArchive(); + $zip->open($tmpFile, ZipArchive::CREATE | ZipArchive::OVERWRITE); + + // Add all the files from the tmp dir. + foreach ($files as $file) { + // Please note that the zip format has no concept of folders, we must + // use forward slashes to separate our directories. + if (file_exists(realpath($file->absolutePath))) { + $zip->addFile(realpath($file->absolutePath), $file->relativePath); + } + } + + // Close zip and remove tmp dir + $zip->close(); + H5PCore::deleteFileTree($tmpPath); + + $filename = $content['slug'] . '-' . $content['id'] . '.h5p'; + try { + // Save export + $this->h5pC->fs->saveExport($tmpFile, $filename); + } + catch (Exception $e) { + $this->h5pF->setErrorMessage($this->h5pF->t($e->getMessage()), 'failed-creating-export-file'); + return false; + } + + unlink($tmpFile); + $this->h5pF->afterExportCreated($content, $filename); + + return true; + } + + /** + * Recursive function the will add the files of the given directory to the + * given files list. All files are objects with an absolute path and + * a relative path. The relative path is forward slashes only! Great for + * use in zip files and URLs. + * + * @param string $dir path + * @param array $files list + * @param string $relative prefix. Optional + */ + private static function populateFileList($dir, &$files, $relative = '') { + $strip = strlen($dir) + 1; + $contents = glob($dir . DIRECTORY_SEPARATOR . '*'); + if (!empty($contents)) { + foreach ($contents as $file) { + $rel = $relative . substr($file, $strip); + if (is_dir($file)) { + self::populateFileList($file, $files, $rel . '/'); + } + else { + $files[] = (object) array( + 'absolutePath' => $file, + 'relativePath' => $rel + ); + } + } + } + } + + /** + * Delete .h5p file + * + * @param array $content object + */ + public function deleteExport($content) { + $this->h5pC->fs->deleteExport(($content['slug'] ? $content['slug'] . '-' : '') . $content['id'] . '.h5p'); + } + + /** + * Add editor libraries to the list of libraries + * + * These are not supposed to go into h5p.json, but must be included with the rest + * of the libraries + * + * TODO This is a private function that is not currently being used + * + * @param array $libraries + * List of libraries keyed by machineName + * @param array $editorLibraries + * List of libraries keyed by machineName + * @return array List of libraries keyed by machineName + */ + private function addEditorLibraries($libraries, $editorLibraries) { + foreach ($editorLibraries as $editorLibrary) { + $libraries[$editorLibrary['machineName']] = $editorLibrary; + } + return $libraries; + } +} + +abstract class H5PPermission { + const DOWNLOAD_H5P = 0; + const EMBED_H5P = 1; + const CREATE_RESTRICTED = 2; + const UPDATE_LIBRARIES = 3; + const INSTALL_RECOMMENDED = 4; + const COPY_H5P = 8; +} + +abstract class H5PDisplayOptionBehaviour { + const NEVER_SHOW = 0; + const CONTROLLED_BY_AUTHOR_DEFAULT_ON = 1; + const CONTROLLED_BY_AUTHOR_DEFAULT_OFF = 2; + const ALWAYS_SHOW = 3; + const CONTROLLED_BY_PERMISSIONS = 4; +} + +abstract class H5PHubEndpoints { + const CONTENT_TYPES = 'api.h5p.org/v1/content-types/'; + const SITES = 'api.h5p.org/v1/sites'; + + public static function createURL($endpoint) { + $protocol = (extension_loaded('openssl') ? 'https' : 'http'); + return "{$protocol}://{$endpoint}"; + } +} + +/** + * Functions and storage shared by the other H5P classes + */ +class H5PCore { + + public static $coreApi = array( + 'majorVersion' => 1, + 'minorVersion' => 23 + ); + public static $styles = array( + 'styles/h5p.css', + 'styles/h5p-confirmation-dialog.css', + 'styles/h5p-core-button.css' + ); + public static $scripts = array( + 'js/jquery.js', + 'js/h5p.js', + 'js/h5p-event-dispatcher.js', + 'js/h5p-x-api-event.js', + 'js/h5p-x-api.js', + 'js/h5p-content-type.js', + 'js/h5p-confirmation-dialog.js', + 'js/h5p-action-bar.js', + 'js/request-queue.js', + ); + public static $adminScripts = array( + 'js/jquery.js', + 'js/h5p-utils.js', + ); + + public static $defaultContentWhitelist = 'json png jpg jpeg gif bmp tif tiff svg eot ttf woff woff2 otf webm mp4 ogg mp3 m4a wav txt pdf rtf doc docx xls xlsx ppt pptx odt ods odp xml csv diff patch swf md textile vtt webvtt'; + public static $defaultLibraryWhitelistExtras = 'js css'; + + public $librariesJsonData, $contentJsonData, $mainJsonData, $h5pF, $fs, $h5pD, $disableFileCheck; + const SECONDS_IN_WEEK = 604800; + + private $exportEnabled; + + // Disable flags + const DISABLE_NONE = 0; + const DISABLE_FRAME = 1; + const DISABLE_DOWNLOAD = 2; + const DISABLE_EMBED = 4; + const DISABLE_COPYRIGHT = 8; + const DISABLE_ABOUT = 16; + + const DISPLAY_OPTION_FRAME = 'frame'; + const DISPLAY_OPTION_DOWNLOAD = 'export'; + const DISPLAY_OPTION_EMBED = 'embed'; + const DISPLAY_OPTION_COPYRIGHT = 'copyright'; + const DISPLAY_OPTION_ABOUT = 'icon'; + const DISPLAY_OPTION_COPY = 'copy'; + + // Map flags to string + public static $disable = array( + self::DISABLE_FRAME => self::DISPLAY_OPTION_FRAME, + self::DISABLE_DOWNLOAD => self::DISPLAY_OPTION_DOWNLOAD, + self::DISABLE_EMBED => self::DISPLAY_OPTION_EMBED, + self::DISABLE_COPYRIGHT => self::DISPLAY_OPTION_COPYRIGHT + ); + + /** + * Constructor for the H5PCore + * + * @param H5PFrameworkInterface $H5PFramework + * The frameworks implementation of the H5PFrameworkInterface + * @param string|\H5PFileStorage $path H5P file storage directory or class. + * @param string $url To file storage directory. + * @param string $language code. Defaults to english. + * @param boolean $export enabled? + */ + public function __construct(H5PFrameworkInterface $H5PFramework, $path, $url, $language = 'en', $export = FALSE) { + $this->h5pF = $H5PFramework; + + $this->fs = ($path instanceof \H5PFileStorage ? $path : new \H5PDefaultStorage($path)); + + $this->url = $url; + $this->exportEnabled = $export; + $this->development_mode = H5PDevelopment::MODE_NONE; + + $this->aggregateAssets = FALSE; // Off by default.. for now + + $this->detectSiteType(); + $this->fullPluginPath = preg_replace('/\/[^\/]+[\/]?$/', '' , dirname(__FILE__)); + + // Standard regex for converting copied files paths + $this->relativePathRegExp = '/^((\.\.\/){1,2})(.*content\/)?(\d+|editor)\/(.+)$/'; + } + + /** + * Save content and clear cache. + * + * @param array $content + * @param null|int $contentMainId + * @return int Content ID + */ + public function saveContent($content, $contentMainId = NULL) { + if (isset($content['id'])) { + $this->h5pF->updateContent($content, $contentMainId); + } + else { + $content['id'] = $this->h5pF->insertContent($content, $contentMainId); + } + + // Some user data for content has to be reset when the content changes. + $this->h5pF->resetContentUserData($contentMainId ? $contentMainId : $content['id']); + + return $content['id']; + } + + /** + * Load content. + * + * @param int $id for content. + * @return object + */ + public function loadContent($id) { + $content = $this->h5pF->loadContent($id); + + if ($content !== NULL) { + // Validate main content's metadata + $validator = new H5PContentValidator($this->h5pF, $this); + $content['metadata'] = $validator->validateMetadata($content['metadata']); + + $content['library'] = array( + 'id' => $content['libraryId'], + 'name' => $content['libraryName'], + 'majorVersion' => $content['libraryMajorVersion'], + 'minorVersion' => $content['libraryMinorVersion'], + 'embedTypes' => $content['libraryEmbedTypes'], + 'fullscreen' => $content['libraryFullscreen'], + ); + unset($content['libraryId'], $content['libraryName'], $content['libraryEmbedTypes'], $content['libraryFullscreen']); + +// // TODO: Move to filterParameters? +// if (isset($this->h5pD)) { +// // TODO: Remove Drupal specific stuff +// $json_content_path = file_create_path(file_directory_path() . '/' . variable_get('h5p_default_path', 'h5p') . '/content/' . $id . '/content.json'); +// if (file_exists($json_content_path) === TRUE) { +// $json_content = file_get_contents($json_content_path); +// if (json_decode($json_content, TRUE) !== FALSE) { +// drupal_set_message(t('Invalid json in json content'), 'warning'); +// } +// $content['params'] = $json_content; +// } +// } + } + + return $content; + } + + /** + * Filter content run parameters, rebuild content dependency cache and export file. + * + * @param Object|array $content + * @return Object NULL on failure. + */ + public function filterParameters(&$content) { + if (!empty($content['filtered']) && + (!$this->exportEnabled || + ($content['slug'] && + $this->fs->hasExport($content['slug'] . '-' . $content['id'] . '.h5p')))) { + return $content['filtered']; + } + + if (!(isset($content['library']) && isset($content['params']))) { + return NULL; + } + + // Validate and filter against main library semantics. + $validator = new H5PContentValidator($this->h5pF, $this); + $params = (object) array( + 'library' => H5PCore::libraryToString($content['library']), + 'params' => json_decode($content['params']) + ); + if (!$params->params) { + return NULL; + } + $validator->validateLibrary($params, (object) array('options' => array($params->library))); + + // Handle addons: + $addons = $this->h5pF->loadAddons(); + foreach ($addons as $addon) { + $add_to = json_decode($addon['addTo']); + + if (isset($add_to->content->types)) { + foreach($add_to->content->types as $type) { + + if (isset($type->text->regex) && + $this->textAddonMatches($params->params, $type->text->regex)) { + $validator->addon($addon); + + // An addon shall only be added once + break; + } + } + } + } + + $params = json_encode($params->params); + + // Update content dependencies. + $content['dependencies'] = $validator->getDependencies(); + + // Sometimes the parameters are filtered before content has been created + if ($content['id']) { + $this->h5pF->deleteLibraryUsage($content['id']); + $this->h5pF->saveLibraryUsage($content['id'], $content['dependencies']); + + if (!$content['slug']) { + $content['slug'] = $this->generateContentSlug($content); + + // Remove old export file + $this->fs->deleteExport($content['id'] . '.h5p'); + } + + if ($this->exportEnabled) { + // Recreate export file + $exporter = new H5PExport($this->h5pF, $this); + $content['filtered'] = $params; + $exporter->createExportFile($content); + } + + // Cache. + $this->h5pF->updateContentFields($content['id'], array( + 'filtered' => $params, + 'slug' => $content['slug'] + )); + } + return $params; + } + + /** + * Retrieve a value from a nested mixed array structure. + * + * @param Array $params Array to be looked in. + * @param String $path Supposed path to the value. + * @param String [$delimiter='.'] Property delimiter within the path. + * @return Object|NULL The object found or NULL. + */ + private function retrieveValue ($params, $path, $delimiter='.') { + $path = explode($delimiter, $path); + + // Property not found + if (!isset($params[$path[0]])) { + return NULL; + } + + $first = $params[$path[0]]; + + // End of path, done + if (sizeof($path) === 1) { + return $first; + } + + // We cannot go deeper + if (!is_array($first)) { + return NULL; + } + + // Regular Array + if (isset($first[0])) { + foreach($first as $number => $object) { + $found = $this->retrieveValue($object, implode($delimiter, array_slice($path, 1))); + if (isset($found)) { + return $found; + } + } + return NULL; + } + + // Associative Array + return $this->retrieveValue($first, implode('.', array_slice($path, 1))); + } + + /** + * Determine if params contain any match. + * + * @param {object} params - Parameters. + * @param {string} [pattern] - Regular expression to identify pattern. + * @param {boolean} [found] - Used for recursion. + * @return {boolean} True, if params matches pattern. + */ + private function textAddonMatches($params, $pattern, $found = false) { + $type = gettype($params); + if ($type === 'string') { + if (preg_match($pattern, $params) === 1) { + return true; + } + } + elseif ($type === 'array' || $type === 'object') { + foreach ($params as $value) { + $found = $this->textAddonMatches($value, $pattern, $found); + if ($found === true) { + return true; + } + } + } + return false; + } + + /** + * Generate content slug + * + * @param array $content object + * @return string unique content slug + */ + private function generateContentSlug($content) { + $slug = H5PCore::slugify($content['title']); + + $available = NULL; + while (!$available) { + if ($available === FALSE) { + // If not available, add number suffix. + $matches = array(); + if (preg_match('/(.+-)([0-9]+)$/', $slug, $matches)) { + $slug = $matches[1] . (intval($matches[2]) + 1); + } + else { + $slug .= '-2'; + } + } + $available = $this->h5pF->isContentSlugAvailable($slug); + } + + return $slug; + } + + /** + * Find the files required for this content to work. + * + * @param int $id for content. + * @param null $type + * @return array + */ + public function loadContentDependencies($id, $type = NULL) { + $dependencies = $this->h5pF->loadContentDependencies($id, $type); + + if (isset($this->h5pD)) { + $developmentLibraries = $this->h5pD->getLibraries(); + + foreach ($dependencies as $key => $dependency) { + $libraryString = H5PCore::libraryToString($dependency); + if (isset($developmentLibraries[$libraryString])) { + $developmentLibraries[$libraryString]['dependencyType'] = $dependencies[$key]['dependencyType']; + $dependencies[$key] = $developmentLibraries[$libraryString]; + } + } + } + + return $dependencies; + } + + /** + * Get all dependency assets of the given type + * + * @param array $dependency + * @param string $type + * @param array $assets + * @param string $prefix Optional. Make paths relative to another dir. + */ + private function getDependencyAssets($dependency, $type, &$assets, $prefix = '') { + // Check if dependency has any files of this type + if (empty($dependency[$type]) || $dependency[$type][0] === '') { + return; + } + + // Check if we should skip CSS. + if ($type === 'preloadedCss' && (isset($dependency['dropCss']) && $dependency['dropCss'] === '1')) { + return; + } + foreach ($dependency[$type] as $file) { + $assets[] = (object) array( + 'path' => $prefix . '/' . $dependency['path'] . '/' . trim(is_array($file) ? $file['path'] : $file), + 'version' => $dependency['version'] + ); + } + } + + /** + * Combines path with cache buster / version. + * + * @param array $assets + * @return array + */ + public function getAssetsUrls($assets) { + $urls = array(); + + foreach ($assets as $asset) { + $url = $asset->path; + + // Add URL prefix if not external + if (strpos($asset->path, '://') === FALSE) { + $url = $this->url . $url; + } + + // Add version/cache buster if set + if (isset($asset->version)) { + $url .= $asset->version; + } + + $urls[] = $url; + } + + return $urls; + } + + /** + * Return file paths for all dependencies files. + * + * @param array $dependencies + * @param string $prefix Optional. Make paths relative to another dir. + * @return array files. + */ + public function getDependenciesFiles($dependencies, $prefix = '') { + // Build files list for assets + $files = array( + 'scripts' => array(), + 'styles' => array() + ); + + $key = null; + + // Avoid caching empty files + if (empty($dependencies)) { + return $files; + } + + if ($this->aggregateAssets) { + // Get aggregated files for assets + $key = self::getDependenciesHash($dependencies); + + $cachedAssets = $this->fs->getCachedAssets($key); + if ($cachedAssets !== NULL) { + return array_merge($files, $cachedAssets); // Using cached assets + } + } + + // Using content dependencies + foreach ($dependencies as $dependency) { + if (isset($dependency['path']) === FALSE) { + $dependency['path'] = 'libraries/' . H5PCore::libraryToString($dependency, TRUE); + $dependency['preloadedJs'] = explode(',', $dependency['preloadedJs']); + $dependency['preloadedCss'] = explode(',', $dependency['preloadedCss']); + } + $dependency['version'] = "?ver={$dependency['majorVersion']}.{$dependency['minorVersion']}.{$dependency['patchVersion']}"; + $this->getDependencyAssets($dependency, 'preloadedJs', $files['scripts'], $prefix); + $this->getDependencyAssets($dependency, 'preloadedCss', $files['styles'], $prefix); + } + + if ($this->aggregateAssets) { + // Aggregate and store assets + $this->fs->cacheAssets($files, $key); + + // Keep track of which libraries have been cached in case they are updated + $this->h5pF->saveCachedAssets($key, $dependencies); + } + + return $files; + } + + private static function getDependenciesHash(&$dependencies) { + // Build hash of dependencies + $toHash = array(); + + // Use unique identifier for each library version + foreach ($dependencies as $dep) { + $toHash[] = "{$dep['machineName']}-{$dep['majorVersion']}.{$dep['minorVersion']}.{$dep['patchVersion']}"; + } + + // Sort in case the same dependencies comes in a different order + sort($toHash); + + // Calculate hash sum + return hash('sha1', implode('', $toHash)); + } + + /** + * Load library semantics. + * + * @param $name + * @param $majorVersion + * @param $minorVersion + * @return string + */ + public function loadLibrarySemantics($name, $majorVersion, $minorVersion) { + $semantics = NULL; + if (isset($this->h5pD)) { + // Try to load from dev lib + $semantics = $this->h5pD->getSemantics($name, $majorVersion, $minorVersion); + } + + if ($semantics === NULL) { + // Try to load from DB. + $semantics = $this->h5pF->loadLibrarySemantics($name, $majorVersion, $minorVersion); + } + + if ($semantics !== NULL) { + $semantics = json_decode($semantics); + $this->h5pF->alterLibrarySemantics($semantics, $name, $majorVersion, $minorVersion); + } + + return $semantics; + } + + /** + * Load library. + * + * @param $name + * @param $majorVersion + * @param $minorVersion + * @return array or null. + */ + public function loadLibrary($name, $majorVersion, $minorVersion) { + $library = NULL; + if (isset($this->h5pD)) { + // Try to load from dev + $library = $this->h5pD->getLibrary($name, $majorVersion, $minorVersion); + if ($library !== NULL) { + $library['semantics'] = $this->h5pD->getSemantics($name, $majorVersion, $minorVersion); + } + } + + if ($library === NULL) { + // Try to load from DB. + $library = $this->h5pF->loadLibrary($name, $majorVersion, $minorVersion); + } + + return $library; + } + + /** + * Deletes a library + * + * @param stdClass $libraryId + */ + public function deleteLibrary($libraryId) { + $this->h5pF->deleteLibrary($libraryId); + } + + /** + * Recursive. Goes through the dependency tree for the given library and + * adds all the dependencies to the given array in a flat format. + * + * @param $dependencies + * @param array $library To find all dependencies for. + * @param int $nextWeight An integer determining the order of the libraries + * when they are loaded + * @param bool $editor Used internally to force all preloaded sub dependencies + * of an editor dependency to be editor dependencies. + * @return int + */ + public function findLibraryDependencies(&$dependencies, $library, $nextWeight = 1, $editor = FALSE) { + foreach (array('dynamic', 'preloaded', 'editor') as $type) { + $property = $type . 'Dependencies'; + if (!isset($library[$property])) { + continue; // Skip, no such dependencies. + } + + if ($type === 'preloaded' && $editor === TRUE) { + // All preloaded dependencies of an editor library is set to editor. + $type = 'editor'; + } + + foreach ($library[$property] as $dependency) { + $dependencyKey = $type . '-' . $dependency['machineName']; + if (isset($dependencies[$dependencyKey]) === TRUE) { + continue; // Skip, already have this. + } + + $dependencyLibrary = $this->loadLibrary($dependency['machineName'], $dependency['majorVersion'], $dependency['minorVersion']); + if ($dependencyLibrary) { + $dependencies[$dependencyKey] = array( + 'library' => $dependencyLibrary, + 'type' => $type + ); + $nextWeight = $this->findLibraryDependencies($dependencies, $dependencyLibrary, $nextWeight, $type === 'editor'); + $dependencies[$dependencyKey]['weight'] = $nextWeight++; + } + else { + // This site is missing a dependency! + $this->h5pF->setErrorMessage($this->h5pF->t('Missing dependency @dep required by @lib.', array('@dep' => H5PCore::libraryToString($dependency), '@lib' => H5PCore::libraryToString($library))), 'missing-library-dependency'); + } + } + } + return $nextWeight; + } + + /** + * Check if a library is of the version we're looking for + * + * Same version means that the majorVersion and minorVersion is the same + * + * @param array $library + * Data from library.json + * @param array $dependency + * Definition of what library we're looking for + * @return boolean + * TRUE if the library is the same version as the dependency + * FALSE otherwise + */ + public function isSameVersion($library, $dependency) { + if ($library['machineName'] != $dependency['machineName']) { + return FALSE; + } + if ($library['majorVersion'] != $dependency['majorVersion']) { + return FALSE; + } + if ($library['minorVersion'] != $dependency['minorVersion']) { + return FALSE; + } + return TRUE; + } + + /** + * Recursive function for removing directories. + * + * @param string $dir + * Path to the directory we'll be deleting + * @return boolean + * Indicates if the directory existed. + */ + public static function deleteFileTree($dir) { + if (!is_dir($dir)) { + return false; + } + if (is_link($dir)) { + // Do not traverse and delete linked content, simply unlink. + unlink($dir); + return; + } + $files = array_diff(scandir($dir), array('.','..')); + foreach ($files as $file) { + $filepath = "$dir/$file"; + // Note that links may resolve as directories + if (!is_dir($filepath) || is_link($filepath)) { + // Unlink files and links + unlink($filepath); + } + else { + // Traverse subdir and delete files + self::deleteFileTree($filepath); + } + } + return rmdir($dir); + } + + /** + * Writes library data as string on the form {machineName} {majorVersion}.{minorVersion} + * + * @param array $library + * With keys machineName, majorVersion and minorVersion + * @param boolean $folderName + * Use hyphen instead of space in returned string. + * @return string + * On the form {machineName} {majorVersion}.{minorVersion} + */ + public static function libraryToString($library, $folderName = FALSE) { + return (isset($library['machineName']) ? $library['machineName'] : $library['name']) . ($folderName ? '-' : ' ') . $library['majorVersion'] . '.' . $library['minorVersion']; + } + + /** + * Parses library data from a string on the form {machineName} {majorVersion}.{minorVersion} + * + * @param string $libraryString + * On the form {machineName} {majorVersion}.{minorVersion} + * @return array|FALSE + * With keys machineName, majorVersion and minorVersion. + * Returns FALSE only if string is not parsable in the normal library + * string formats "Lib.Name-x.y" or "Lib.Name x.y" + */ + public static function libraryFromString($libraryString) { + $re = '/^([\w0-9\-\.]{1,255})[\-\ ]([0-9]{1,5})\.([0-9]{1,5})$/i'; + $matches = array(); + $res = preg_match($re, $libraryString, $matches); + if ($res) { + return array( + 'machineName' => $matches[1], + 'majorVersion' => $matches[2], + 'minorVersion' => $matches[3] + ); + } + return FALSE; + } + + /** + * Determine the correct embed type to use. + * + * @param $contentEmbedType + * @param $libraryEmbedTypes + * @return string 'div' or 'iframe'. + */ + public static function determineEmbedType($contentEmbedType, $libraryEmbedTypes) { + // Detect content embed type + $embedType = strpos(strtolower($contentEmbedType), 'div') !== FALSE ? 'div' : 'iframe'; + + if ($libraryEmbedTypes !== NULL && $libraryEmbedTypes !== '') { + // Check that embed type is available for library + $embedTypes = strtolower($libraryEmbedTypes); + if (strpos($embedTypes, $embedType) === FALSE) { + // Not available, pick default. + $embedType = strpos($embedTypes, 'div') !== FALSE ? 'div' : 'iframe'; + } + } + + return $embedType; + } + + /** + * Get the absolute version for the library as a human readable string. + * + * @param object $library + * @return string + */ + public static function libraryVersion($library) { + return $library->major_version . '.' . $library->minor_version . '.' . $library->patch_version; + } + + /** + * Determine which versions content with the given library can be upgraded to. + * + * @param object $library + * @param array $versions + * @return array + */ + public function getUpgrades($library, $versions) { + $upgrades = array(); + + foreach ($versions as $upgrade) { + if ($upgrade->major_version > $library->major_version || $upgrade->major_version === $library->major_version && $upgrade->minor_version > $library->minor_version) { + $upgrades[$upgrade->id] = H5PCore::libraryVersion($upgrade); + } + } + + return $upgrades; + } + + /** + * Converts all the properties of the given object or array from + * snake_case to camelCase. Useful after fetching data from the database. + * + * Note that some databases does not support camelCase. + * + * @param mixed $arr input + * @param boolean $obj return object + * @return mixed object or array + */ + public static function snakeToCamel($arr, $obj = false) { + $newArr = array(); + + foreach ($arr as $key => $val) { + $next = -1; + while (($next = strpos($key, '_', $next + 1)) !== FALSE) { + $key = substr_replace($key, strtoupper($key{$next + 1}), $next, 2); + } + + $newArr[$key] = $val; + } + + return $obj ? (object) $newArr : $newArr; + } + + /** + * Detects if the site was accessed from localhost, + * through a local network or from the internet. + */ + public function detectSiteType() { + $type = $this->h5pF->getOption('site_type', 'local'); + + // Determine remote/visitor origin + if ($type === 'network' || + ($type === 'local' && + isset($_SERVER['REMOTE_ADDR']) && + !preg_match('/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/i', $_SERVER['REMOTE_ADDR']))) { + if (isset($_SERVER['REMOTE_ADDR']) && filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) { + // Internet + $this->h5pF->setOption('site_type', 'internet'); + } + elseif ($type === 'local') { + // Local network + $this->h5pF->setOption('site_type', 'network'); + } + } + } + + /** + * Get a list of installed libraries, different minor versions will + * return separate entries. + * + * @return array + * A distinct array of installed libraries + */ + public function getLibrariesInstalled() { + $librariesInstalled = array(); + $libs = $this->h5pF->loadLibraries(); + + foreach($libs as $libName => $library) { + foreach($library as $libVersion) { + $librariesInstalled[$libName.' '.$libVersion->major_version.'.'.$libVersion->minor_version] = $libVersion->patch_version; + } + } + + return $librariesInstalled; + } + + /** + * Easy way to combine similar data sets. + * + * @param array $inputs Multiple arrays with data + * @return array + */ + public function combineArrayValues($inputs) { + $results = array(); + foreach ($inputs as $index => $values) { + foreach ($values as $key => $value) { + $results[$key][$index] = $value; + } + } + return $results; + } + + /** + * Communicate with H5P.org and get content type cache. Each platform + * implementation is responsible for invoking this, eg using cron + * + * @param bool $fetchingDisabled + * + * @return bool|object Returns endpoint data if found, otherwise FALSE + */ + public function fetchLibrariesMetadata($fetchingDisabled = FALSE) { + // Gather data + $uuid = $this->h5pF->getOption('site_uuid', ''); + $platform = $this->h5pF->getPlatformInfo(); + $registrationData = array( + 'uuid' => $uuid, + 'platform_name' => $platform['name'], + 'platform_version' => $platform['version'], + 'h5p_version' => $platform['h5pVersion'], + 'disabled' => $fetchingDisabled ? 1 : 0, + 'local_id' => hash('crc32', $this->fullPluginPath), + 'type' => $this->h5pF->getOption('site_type', 'local'), + 'core_api_version' => H5PCore::$coreApi['majorVersion'] . '.' . + H5PCore::$coreApi['minorVersion'] + ); + + // Register site if it is not registered + if (empty($uuid)) { + $registration = $this->h5pF->fetchExternalData(H5PHubEndpoints::createURL(H5PHubEndpoints::SITES), $registrationData); + + // Failed retrieving uuid + if (!$registration) { + $errorMessage = $this->h5pF->t('Site could not be registered with the hub. Please contact your site administrator.'); + $this->h5pF->setErrorMessage($errorMessage); + $this->h5pF->setErrorMessage( + $this->h5pF->t('The H5P Hub has been disabled until this problem can be resolved. You may still upload libraries through the "H5P Libraries" page.'), + 'registration-failed-hub-disabled' + ); + return FALSE; + } + + // Successfully retrieved new uuid + $json = json_decode($registration); + $registrationData['uuid'] = $json->uuid; + $this->h5pF->setOption('site_uuid', $json->uuid); + $this->h5pF->setInfoMessage( + $this->h5pF->t('Your site was successfully registered with the H5P Hub.') + ); + // TODO: Uncomment when key is once again available in H5P Settings +// $this->h5pF->setInfoMessage( +// $this->h5pF->t('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.') +// ); + } + + if ($this->h5pF->getOption('send_usage_statistics', TRUE)) { + $siteData = array_merge( + $registrationData, + array( + 'num_authors' => $this->h5pF->getNumAuthors(), + 'libraries' => json_encode($this->combineArrayValues(array( + 'patch' => $this->getLibrariesInstalled(), + 'content' => $this->h5pF->getLibraryContentCount(), + 'loaded' => $this->h5pF->getLibraryStats('library'), + 'created' => $this->h5pF->getLibraryStats('content create'), + 'createdUpload' => $this->h5pF->getLibraryStats('content create upload'), + 'deleted' => $this->h5pF->getLibraryStats('content delete'), + 'resultViews' => $this->h5pF->getLibraryStats('results content'), + 'shortcodeInserts' => $this->h5pF->getLibraryStats('content shortcode insert') + ))) + ) + ); + } + else { + $siteData = $registrationData; + } + + $result = $this->updateContentTypeCache($siteData); + + // No data received + if (!$result || empty($result)) { + return FALSE; + } + + // Handle libraries metadata + if (isset($result->libraries)) { + foreach ($result->libraries as $library) { + if (isset($library->tutorialUrl) && isset($library->machineName)) { + $this->h5pF->setLibraryTutorialUrl($library->machineNamee, $library->tutorialUrl); + } + } + } + + return $result; + } + + /** + * Create representation of display options as int + * + * @param array $sources + * @param int $current + * @return int + */ + public function getStorableDisplayOptions(&$sources, $current) { + // Download - force setting it if always on or always off + $download = $this->h5pF->getOption(self::DISPLAY_OPTION_DOWNLOAD, H5PDisplayOptionBehaviour::ALWAYS_SHOW); + if ($download == H5PDisplayOptionBehaviour::ALWAYS_SHOW || + $download == H5PDisplayOptionBehaviour::NEVER_SHOW) { + $sources[self::DISPLAY_OPTION_DOWNLOAD] = ($download == H5PDisplayOptionBehaviour::ALWAYS_SHOW); + } + + // Embed - force setting it if always on or always off + $embed = $this->h5pF->getOption(self::DISPLAY_OPTION_EMBED, H5PDisplayOptionBehaviour::ALWAYS_SHOW); + if ($embed == H5PDisplayOptionBehaviour::ALWAYS_SHOW || + $embed == H5PDisplayOptionBehaviour::NEVER_SHOW) { + $sources[self::DISPLAY_OPTION_EMBED] = ($embed == H5PDisplayOptionBehaviour::ALWAYS_SHOW); + } + + foreach (H5PCore::$disable as $bit => $option) { + if (!isset($sources[$option]) || !$sources[$option]) { + $current |= $bit; // Disable + } + else { + $current &= ~$bit; // Enable + } + } + return $current; + } + + /** + * Determine display options visibility and value on edit + * + * @param int $disable + * @return array + */ + public function getDisplayOptionsForEdit($disable = NULL) { + $display_options = array(); + + $current_display_options = $disable === NULL ? array() : $this->getDisplayOptionsAsArray($disable); + + if ($this->h5pF->getOption(self::DISPLAY_OPTION_FRAME, TRUE)) { + $display_options[self::DISPLAY_OPTION_FRAME] = + isset($current_display_options[self::DISPLAY_OPTION_FRAME]) ? + $current_display_options[self::DISPLAY_OPTION_FRAME] : + TRUE; + + // Download + $export = $this->h5pF->getOption(self::DISPLAY_OPTION_DOWNLOAD, H5PDisplayOptionBehaviour::ALWAYS_SHOW); + if ($export == H5PDisplayOptionBehaviour::CONTROLLED_BY_AUTHOR_DEFAULT_ON || + $export == H5PDisplayOptionBehaviour::CONTROLLED_BY_AUTHOR_DEFAULT_OFF) { + $display_options[self::DISPLAY_OPTION_DOWNLOAD] = + isset($current_display_options[self::DISPLAY_OPTION_DOWNLOAD]) ? + $current_display_options[self::DISPLAY_OPTION_DOWNLOAD] : + ($export == H5PDisplayOptionBehaviour::CONTROLLED_BY_AUTHOR_DEFAULT_ON); + } + + // Embed + $embed = $this->h5pF->getOption(self::DISPLAY_OPTION_EMBED, H5PDisplayOptionBehaviour::ALWAYS_SHOW); + if ($embed == H5PDisplayOptionBehaviour::CONTROLLED_BY_AUTHOR_DEFAULT_ON || + $embed == H5PDisplayOptionBehaviour::CONTROLLED_BY_AUTHOR_DEFAULT_OFF) { + $display_options[self::DISPLAY_OPTION_EMBED] = + isset($current_display_options[self::DISPLAY_OPTION_EMBED]) ? + $current_display_options[self::DISPLAY_OPTION_EMBED] : + ($embed == H5PDisplayOptionBehaviour::CONTROLLED_BY_AUTHOR_DEFAULT_ON); + } + + // Copyright + if ($this->h5pF->getOption(self::DISPLAY_OPTION_COPYRIGHT, TRUE)) { + $display_options[self::DISPLAY_OPTION_COPYRIGHT] = + isset($current_display_options[self::DISPLAY_OPTION_COPYRIGHT]) ? + $current_display_options[self::DISPLAY_OPTION_COPYRIGHT] : + TRUE; + } + } + + return $display_options; + } + + /** + * Helper function used to figure out embed & download behaviour + * + * @param string $option_name + * @param H5PPermission $permission + * @param int $id + * @param bool &$value + */ + private function setDisplayOptionOverrides($option_name, $permission, $id, &$value) { + $behaviour = $this->h5pF->getOption($option_name, H5PDisplayOptionBehaviour::ALWAYS_SHOW); + // If never show globally, force hide + if ($behaviour == H5PDisplayOptionBehaviour::NEVER_SHOW) { + $value = false; + } + elseif ($behaviour == H5PDisplayOptionBehaviour::ALWAYS_SHOW) { + // If always show or permissions say so, force show + $value = true; + } + elseif ($behaviour == H5PDisplayOptionBehaviour::CONTROLLED_BY_PERMISSIONS) { + $value = $this->h5pF->hasPermission($permission, $id); + } + } + + /** + * Determine display option visibility when viewing H5P + * + * @param int $display_options + * @param int $id Might be content id or user id. + * Depends on what the platform needs to be able to determine permissions. + * @return array + */ + public function getDisplayOptionsForView($disable, $id) { + $display_options = $this->getDisplayOptionsAsArray($disable); + + if ($this->h5pF->getOption(self::DISPLAY_OPTION_FRAME, TRUE) == FALSE) { + $display_options[self::DISPLAY_OPTION_FRAME] = false; + } + else { + $this->setDisplayOptionOverrides(self::DISPLAY_OPTION_DOWNLOAD, H5PPermission::DOWNLOAD_H5P, $id, $display_options[self::DISPLAY_OPTION_DOWNLOAD]); + $this->setDisplayOptionOverrides(self::DISPLAY_OPTION_EMBED, H5PPermission::EMBED_H5P, $id, $display_options[self::DISPLAY_OPTION_EMBED]); + + if ($this->h5pF->getOption(self::DISPLAY_OPTION_COPYRIGHT, TRUE) == FALSE) { + $display_options[self::DISPLAY_OPTION_COPYRIGHT] = false; + } + } + $display_options[self::DISPLAY_OPTION_COPY] = $this->h5pF->hasPermission(H5PPermission::COPY_H5P, $id); + + return $display_options; + } + + /** + * Convert display options as single byte to array + * + * @param int $disable + * @return array + */ + private function getDisplayOptionsAsArray($disable) { + return array( + self::DISPLAY_OPTION_FRAME => !($disable & H5PCore::DISABLE_FRAME), + self::DISPLAY_OPTION_DOWNLOAD => !($disable & H5PCore::DISABLE_DOWNLOAD), + self::DISPLAY_OPTION_EMBED => !($disable & H5PCore::DISABLE_EMBED), + self::DISPLAY_OPTION_COPYRIGHT => !($disable & H5PCore::DISABLE_COPYRIGHT), + self::DISPLAY_OPTION_ABOUT => !!$this->h5pF->getOption(self::DISPLAY_OPTION_ABOUT, TRUE), + ); + } + + /** + * Small helper for getting the library's ID. + * + * @param array $library + * @param string [$libString] + * @return int Identifier, or FALSE if non-existent + */ + public function getLibraryId($library, $libString = NULL) { + if (!$libString) { + $libString = self::libraryToString($library); + } + + if (!isset($libraryIdMap[$libString])) { + $libraryIdMap[$libString] = $this->h5pF->getLibraryId($library['machineName'], $library['majorVersion'], $library['minorVersion']); + } + + return $libraryIdMap[$libString]; + } + + /** + * Convert strings of text into simple kebab case slugs. + * Very useful for readable urls etc. + * + * @param string $input + * @return string + */ + public static function slugify($input) { + // Down low + $input = strtolower($input); + + // Replace common chars + $input = str_replace( + array('æ', 'ø', 'ö', 'ó', 'ô', 'Ò', 'Õ', 'Ý', 'ý', 'ÿ', 'ā', 'ă', 'ą', 'œ', 'å', 'ä', 'á', 'à', 'â', 'ã', 'ç', 'ć', 'ĉ', 'ċ', 'č', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ú', 'ñ', 'ü', 'ù', 'û', 'ß', 'ď', 'đ', 'ē', 'ĕ', 'ė', 'ę', 'ě', 'ĝ', 'ğ', 'ġ', 'ģ', 'ĥ', 'ħ', 'ĩ', 'ī', 'ĭ', 'į', 'ı', 'ij', 'ĵ', 'ķ', 'ĺ', 'ļ', 'ľ', 'ŀ', 'ł', 'ń', 'ņ', 'ň', 'ʼn', 'ō', 'ŏ', 'ő', 'ŕ', 'ŗ', 'ř', 'ś', 'ŝ', 'ş', 'š', 'ţ', 'ť', 'ŧ', 'ũ', 'ū', 'ŭ', 'ů', 'ű', 'ų', 'ŵ', 'ŷ', 'ź', 'ż', 'ž', 'ſ', 'ƒ', 'ơ', 'ư', 'ǎ', 'ǐ', 'ǒ', 'ǔ', 'ǖ', 'ǘ', 'ǚ', 'ǜ', 'ǻ', 'ǽ', 'ǿ'), + array('ae', 'oe', 'o', 'o', 'o', 'oe', 'o', 'o', 'y', 'y', 'y', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'c', 'c', 'c', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'u', 'n', 'u', 'u', 'u', 'es', 'd', 'd', 'e', 'e', 'e', 'e', 'e', 'g', 'g', 'g', 'g', 'h', 'h', 'i', 'i', 'i', 'i', 'i', 'ij', 'j', 'k', 'l', 'l', 'l', 'l', 'l', 'n', 'n', 'n', 'n', 'o', 'o', 'o', 'r', 'r', 'r', 's', 's', 's', 's', 't', 't', 't', 'u', 'u', 'u', 'u', 'u', 'u', 'w', 'y', 'z', 'z', 'z', 's', 'f', 'o', 'u', 'a', 'i', 'o', 'u', 'u', 'u', 'u', 'u', 'a', 'ae', 'oe'), + $input); + + // Replace everything else + $input = preg_replace('/[^a-z0-9]/', '-', $input); + + // Prevent double hyphen + $input = preg_replace('/-{2,}/', '-', $input); + + // Prevent hyphen in beginning or end + $input = trim($input, '-'); + + // Prevent to long slug + if (strlen($input) > 91) { + $input = substr($input, 0, 92); + } + + // Prevent empty slug + if ($input === '') { + $input = 'interactive'; + } + + return $input; + } + + /** + * Makes it easier to print response when AJAX request succeeds. + * + * @param mixed $data + * @since 1.6.0 + */ + public static function ajaxSuccess($data = NULL, $only_data = FALSE) { + $response = array( + 'success' => TRUE + ); + if ($data !== NULL) { + $response['data'] = $data; + + // Pass data flatly to support old methods + if ($only_data) { + $response = $data; + } + } + self::printJson($response); + } + + /** + * Makes it easier to print response when AJAX request fails. + * Will exit after printing error. + * + * @param string $message A human readable error message + * @param string $error_code An machine readable error code that a client + * should be able to interpret + * @param null|int $status_code Http response code + * @param array [$details=null] Better description of the error and possible which action to take + * @since 1.6.0 + */ + public static function ajaxError($message = NULL, $error_code = NULL, $status_code = NULL, $details = NULL) { + $response = array( + 'success' => FALSE + ); + if ($message !== NULL) { + $response['message'] = $message; + } + + if ($error_code !== NULL) { + $response['errorCode'] = $error_code; + } + + if ($details !== NULL) { + $response['details'] = $details; + } + + self::printJson($response, $status_code); + } + + /** + * Print JSON headers with UTF-8 charset and json encode response data. + * Makes it easier to respond using JSON. + * + * @param mixed $data + * @param null|int $status_code Http response code + */ + private static function printJson($data, $status_code = NULL) { + header('Cache-Control: no-cache'); + header('Content-Type: application/json; charset=utf-8'); + print json_encode($data); + } + + /** + * Get a new H5P security token for the given action. + * + * @param string $action + * @return string token + */ + public static function createToken($action) { + // Create and return token + return self::hashToken($action, self::getTimeFactor()); + } + + /** + * Create a time based number which is unique for each 12 hour. + * @return int + */ + private static function getTimeFactor() { + return ceil(time() / (86400 / 2)); + } + + /** + * Generate a unique hash string based on action, time and token + * + * @param string $action + * @param int $time_factor + * @return string + */ + private static function hashToken($action, $time_factor) { + if (!isset($_SESSION['h5p_token'])) { + // Create an unique key which is used to create action tokens for this session. + if (function_exists('random_bytes')) { + $_SESSION['h5p_token'] = base64_encode(random_bytes(15)); + } + else if (function_exists('openssl_random_pseudo_bytes')) { + $_SESSION['h5p_token'] = base64_encode(openssl_random_pseudo_bytes(15)); + } + else { + $_SESSION['h5p_token'] = uniqid('', TRUE); + } + } + + // Create hash and return + return substr(hash('md5', $action . $time_factor . $_SESSION['h5p_token']), -16, 13); + } + + /** + * Verify if the given token is valid for the given action. + * + * @param string $action + * @param string $token + * @return boolean valid token + */ + public static function validToken($action, $token) { + // Get the timefactor + $time_factor = self::getTimeFactor(); + + // Check token to see if it's valid + return $token === self::hashToken($action, $time_factor) || // Under 12 hours + $token === self::hashToken($action, $time_factor - 1); // Between 12-24 hours + } + + /** + * Update content type cache + * + * @param object $postData Data sent to the hub + * + * @return bool|object Returns endpoint data if found, otherwise FALSE + */ + public function updateContentTypeCache($postData = NULL) { + $interface = $this->h5pF; + + // Make sure data is sent! + if (!isset($postData) || !isset($postData['uuid'])) { + return $this->fetchLibrariesMetadata(); + } + + $postData['current_cache'] = $this->h5pF->getOption('content_type_cache_updated_at', 0); + + $data = $interface->fetchExternalData(H5PHubEndpoints::createURL(H5PHubEndpoints::CONTENT_TYPES), $postData); + + if (! $this->h5pF->getOption('hub_is_enabled', TRUE)) { + return TRUE; + } + + // No data received + if (!$data) { + $interface->setErrorMessage( + $interface->t("Couldn't communicate with the H5P Hub. Please try again later."), + 'failed-communicationg-with-hub' + ); + return FALSE; + } + + $json = json_decode($data); + + // No libraries received + if (!isset($json->contentTypes) || empty($json->contentTypes)) { + $interface->setErrorMessage( + $interface->t('No content types were received from the H5P Hub. Please try again later.'), + 'no-content-types-from-hub' + ); + return FALSE; + } + + // Replace content type cache + $interface->replaceContentTypeCache($json); + + // Inform of the changes and update timestamp + $interface->setInfoMessage($interface->t('Library cache was successfully updated!')); + $interface->setOption('content_type_cache_updated_at', time()); + return $data; + } + + /** + * Check if the current server setup is valid and set error messages + * + * @return object Setup object with errors and disable hub properties + */ + public function checkSetupErrorMessage() { + $setup = (object) array( + 'errors' => array(), + 'disable_hub' => FALSE + ); + + if (!class_exists('ZipArchive')) { + $setup->errors[] = $this->h5pF->t('Your PHP version does not support ZipArchive.'); + $setup->disable_hub = TRUE; + } + + if (!extension_loaded('mbstring')) { + $setup->errors[] = $this->h5pF->t( + 'The mbstring PHP extension is not loaded. H5P needs this to function properly' + ); + $setup->disable_hub = TRUE; + } + + // Check php version >= 5.2 + $php_version = explode('.', phpversion()); + if ($php_version[0] < 5 || ($php_version[0] === 5 && $php_version[1] < 2)) { + $setup->errors[] = $this->h5pF->t('Your PHP version is outdated. H5P requires version 5.2 to function properly. Version 5.6 or later is recommended.'); + $setup->disable_hub = TRUE; + } + + // Check write access + if (!$this->fs->hasWriteAccess()) { + $setup->errors[] = $this->h5pF->t('A problem with the server write access was detected. Please make sure that your server can write to your data folder.'); + $setup->disable_hub = TRUE; + } + + $max_upload_size = self::returnBytes(ini_get('upload_max_filesize')); + $max_post_size = self::returnBytes(ini_get('post_max_size')); + $byte_threshold = 5000000; // 5MB + if ($max_upload_size < $byte_threshold) { + $setup->errors[] = + $this->h5pF->t('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.', array('%number' => number_format($max_upload_size / 1024 / 1024, 2, '.', ' '))); + } + + if ($max_post_size < $byte_threshold) { + $setup->errors[] = + $this->h5pF->t('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', array('%number' => number_format($max_upload_size / 1024 / 1024, 2, '.', ' '))); + } + + if ($max_upload_size > $max_post_size) { + $setup->errors[] = + $this->h5pF->t('Your PHP max upload size is bigger than your max post size. This is known to cause issues in some installations.'); + } + + // Check SSL + if (!extension_loaded('openssl')) { + $setup->errors[] = + $this->h5pF->t('Your server does not have SSL enabled. SSL should be enabled to ensure a secure connection with the H5P hub.'); + $setup->disable_hub = TRUE; + } + + return $setup; + } + + /** + * Check that all H5P requirements for the server setup is met. + */ + public function checkSetupForRequirements() { + $setup = $this->checkSetupErrorMessage(); + + $this->h5pF->setOption('hub_is_enabled', !$setup->disable_hub); + if (!empty($setup->errors)) { + foreach ($setup->errors as $err) { + $this->h5pF->setErrorMessage($err); + } + } + + if ($setup->disable_hub) { + // Inform how to re-enable hub + $this->h5pF->setErrorMessage( + $this->h5pF->t('H5P hub communication has been disabled because one or more H5P requirements failed.') + ); + $this->h5pF->setErrorMessage( + $this->h5pF->t('When you have revised your server setup you may re-enable H5P hub communication in H5P Settings.') + ); + } + } + + /** + * Return bytes from php_ini string value + * + * @param string $val + * + * @return int|string + */ + public static function returnBytes($val) { + $val = trim($val); + $last = strtolower($val[strlen($val) - 1]); + $bytes = (int) $val; + + switch ($last) { + case 'g': + $bytes *= 1024; + case 'm': + $bytes *= 1024; + case 'k': + $bytes *= 1024; + } + + return $bytes; + } + + /** + * Check if the current user has permission to update and install new + * libraries. + * + * @param bool [$set] Optional, sets the permission + * @return bool + */ + public function mayUpdateLibraries($set = null) { + static $can; + + if ($set !== null) { + // Use value set + $can = $set; + } + + if ($can === null) { + // Ask our framework + $can = $this->h5pF->mayUpdateLibraries(); + } + + return $can; + } + + /** + * Provide localization for the Core JS + * @return array + */ + public function getLocalization() { + return array( + 'fullscreen' => $this->h5pF->t('Fullscreen'), + 'disableFullscreen' => $this->h5pF->t('Disable fullscreen'), + 'download' => $this->h5pF->t('Download'), + 'copyrights' => $this->h5pF->t('Rights of use'), + 'embed' => $this->h5pF->t('Embed'), + 'size' => $this->h5pF->t('Size'), + 'showAdvanced' => $this->h5pF->t('Show advanced'), + 'hideAdvanced' => $this->h5pF->t('Hide advanced'), + 'advancedHelp' => $this->h5pF->t('Include this script on your website if you want dynamic sizing of the embedded content:'), + 'copyrightInformation' => $this->h5pF->t('Rights of use'), + 'close' => $this->h5pF->t('Close'), + 'title' => $this->h5pF->t('Title'), + 'author' => $this->h5pF->t('Author'), + 'year' => $this->h5pF->t('Year'), + 'source' => $this->h5pF->t('Source'), + 'license' => $this->h5pF->t('License'), + 'thumbnail' => $this->h5pF->t('Thumbnail'), + 'noCopyrights' => $this->h5pF->t('No copyright information available for this content.'), + 'reuse' => $this->h5pF->t('Reuse'), + 'reuseContent' => $this->h5pF->t('Reuse Content'), + 'reuseDescription' => $this->h5pF->t('Reuse this content.'), + 'downloadDescription' => $this->h5pF->t('Download this content as a H5P file.'), + 'copyrightsDescription' => $this->h5pF->t('View copyright information for this content.'), + 'embedDescription' => $this->h5pF->t('View the embed code for this content.'), + 'h5pDescription' => $this->h5pF->t('Visit H5P.org to check out more cool content.'), + 'contentChanged' => $this->h5pF->t('This content has changed since you last used it.'), + 'startingOver' => $this->h5pF->t("You'll be starting over."), + 'by' => $this->h5pF->t('by'), + 'showMore' => $this->h5pF->t('Show more'), + 'showLess' => $this->h5pF->t('Show less'), + 'subLevel' => $this->h5pF->t('Sublevel'), + 'confirmDialogHeader' => $this->h5pF->t('Confirm action'), + 'confirmDialogBody' => $this->h5pF->t('Please confirm that you wish to proceed. This action is not reversible.'), + 'cancelLabel' => $this->h5pF->t('Cancel'), + 'confirmLabel' => $this->h5pF->t('Confirm'), + 'licenseU' => $this->h5pF->t('Undisclosed'), + 'licenseCCBY' => $this->h5pF->t('Attribution'), + 'licenseCCBYSA' => $this->h5pF->t('Attribution-ShareAlike'), + 'licenseCCBYND' => $this->h5pF->t('Attribution-NoDerivs'), + 'licenseCCBYNC' => $this->h5pF->t('Attribution-NonCommercial'), + 'licenseCCBYNCSA' => $this->h5pF->t('Attribution-NonCommercial-ShareAlike'), + 'licenseCCBYNCND' => $this->h5pF->t('Attribution-NonCommercial-NoDerivs'), + 'licenseCC40' => $this->h5pF->t('4.0 International'), + 'licenseCC30' => $this->h5pF->t('3.0 Unported'), + 'licenseCC25' => $this->h5pF->t('2.5 Generic'), + 'licenseCC20' => $this->h5pF->t('2.0 Generic'), + 'licenseCC10' => $this->h5pF->t('1.0 Generic'), + 'licenseGPL' => $this->h5pF->t('General Public License'), + 'licenseV3' => $this->h5pF->t('Version 3'), + 'licenseV2' => $this->h5pF->t('Version 2'), + 'licenseV1' => $this->h5pF->t('Version 1'), + 'licensePD' => $this->h5pF->t('Public Domain'), + 'licenseCC010' => $this->h5pF->t('CC0 1.0 Universal (CC0 1.0) Public Domain Dedication'), + 'licensePDM' => $this->h5pF->t('Public Domain Mark'), + 'licenseC' => $this->h5pF->t('Copyright'), + 'contentType' => $this->h5pF->t('Content Type'), + 'licenseExtras' => $this->h5pF->t('License Extras'), + 'changes' => $this->h5pF->t('Changelog'), + 'contentCopied' => $this->h5pF->t('Content is copied to the clipboard'), + 'connectionLost' => $this->h5pF->t('Connection lost. Results will be stored and sent when you regain connection.'), + 'connectionReestablished' => $this->h5pF->t('Connection reestablished.'), + 'resubmitScores' => $this->h5pF->t('Attempting to submit stored results.'), + 'offlineDialogHeader' => $this->h5pF->t('Your connection to the server was lost'), + 'offlineDialogBody' => $this->h5pF->t('We were unable to send information about your completion of this task. Please check your internet connection.'), + 'offlineDialogRetryMessage' => $this->h5pF->t('Retrying in :num....'), + 'offlineDialogRetryButtonLabel' => $this->h5pF->t('Retry now'), + 'offlineSuccessfulSubmit' => $this->h5pF->t('Successfully submitted results.'), + ); + } +} + +/** + * Functions for validating basic types from H5P library semantics. + * @property bool allowedStyles + */ +class H5PContentValidator { + public $h5pF; + public $h5pC; + private $typeMap, $libraries, $dependencies, $nextWeight; + private static $allowed_styleable_tags = array('span', 'p', 'div','h1','h2','h3', 'td'); + + /** + * Constructor for the H5PContentValidator + * + * @param object $H5PFramework + * The frameworks implementation of the H5PFrameworkInterface + * @param object $H5PCore + * The main H5PCore instance + */ + public function __construct($H5PFramework, $H5PCore) { + $this->h5pF = $H5PFramework; + $this->h5pC = $H5PCore; + $this->typeMap = array( + 'text' => 'validateText', + 'number' => 'validateNumber', + 'boolean' => 'validateBoolean', + 'list' => 'validateList', + 'group' => 'validateGroup', + 'file' => 'validateFile', + 'image' => 'validateImage', + 'video' => 'validateVideo', + 'audio' => 'validateAudio', + 'select' => 'validateSelect', + 'library' => 'validateLibrary', + ); + $this->nextWeight = 1; + + // Keep track of the libraries we load to avoid loading it multiple times. + $this->libraries = array(); + + // Keep track of all dependencies for the given content. + $this->dependencies = array(); + } + + /** + * Add Addon library. + */ + public function addon($library) { + $depKey = 'preloaded-' . $library['machineName']; + $this->dependencies[$depKey] = array( + 'library' => $library, + 'type' => 'preloaded' + ); + $this->nextWeight = $this->h5pC->findLibraryDependencies($this->dependencies, $library, $this->nextWeight); + $this->dependencies[$depKey]['weight'] = $this->nextWeight++; + } + + /** + * Get the flat dependency tree. + * + * @return array + */ + public function getDependencies() { + return $this->dependencies; + } + + /** + * Validate metadata + * + * @param array $metadata + * @return array Validated & filtered + */ + public function validateMetadata($metadata) { + $semantics = $this->getMetadataSemantics(); + $group = (object)$metadata; + + // Stop complaining about "invalid selected option in select" for + // old content without license chosen. + if (!isset($group->license)) { + $group->license = 'U'; + } + + $this->validateGroup($group, (object) array( + 'type' => 'group', + 'fields' => $semantics, + ), FALSE); + + return (array)$group; + } + + /** + * Validate given text value against text semantics. + * @param $text + * @param $semantics + */ + public function validateText(&$text, $semantics) { + if (!is_string($text)) { + $text = ''; + } + if (isset($semantics->tags)) { + // Not testing for empty array allows us to use the 4 defaults without + // specifying them in semantics. + $tags = array_merge(array('div', 'span', 'p', 'br'), $semantics->tags); + + // Add related tags for table etc. + if (in_array('table', $tags)) { + $tags = array_merge($tags, array('tr', 'td', 'th', 'colgroup', 'thead', 'tbody', 'tfoot')); + } + if (in_array('b', $tags) && ! in_array('strong', $tags)) { + $tags[] = 'strong'; + } + if (in_array('i', $tags) && ! in_array('em', $tags)) { + $tags[] = 'em'; + } + if (in_array('ul', $tags) || in_array('ol', $tags) && ! in_array('li', $tags)) { + $tags[] = 'li'; + } + if (in_array('del', $tags) || in_array('strike', $tags) && ! in_array('s', $tags)) { + $tags[] = 's'; + } + + // Determine allowed style tags + $stylePatterns = array(); + // All styles must be start to end patterns (^...$) + if (isset($semantics->font)) { + if (isset($semantics->font->size) && $semantics->font->size) { + $stylePatterns[] = '/^font-size: *[0-9.]+(em|px|%) *;?$/i'; + } + if (isset($semantics->font->family) && $semantics->font->family) { + $stylePatterns[] = '/^font-family: *[-a-z0-9," ]+;?$/i'; + } + if (isset($semantics->font->color) && $semantics->font->color) { + $stylePatterns[] = '/^color: *(#[a-f0-9]{3}[a-f0-9]{3}?|rgba?\([0-9, ]+\)) *;?$/i'; + } + if (isset($semantics->font->background) && $semantics->font->background) { + $stylePatterns[] = '/^background-color: *(#[a-f0-9]{3}[a-f0-9]{3}?|rgba?\([0-9, ]+\)) *;?$/i'; + } + if (isset($semantics->font->spacing) && $semantics->font->spacing) { + $stylePatterns[] = '/^letter-spacing: *[0-9.]+(em|px|%) *;?$/i'; + } + if (isset($semantics->font->height) && $semantics->font->height) { + $stylePatterns[] = '/^line-height: *[0-9.]+(em|px|%|) *;?$/i'; + } + } + + // Alignment is allowed for all wysiwyg texts + $stylePatterns[] = '/^text-align: *(center|left|right);?$/i'; + + // Strip invalid HTML tags. + $text = $this->filter_xss($text, $tags, $stylePatterns); + } + else { + // Filter text to plain text. + $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8', FALSE); + } + + // Check if string is within allowed length + if (isset($semantics->maxLength)) { + if (!extension_loaded('mbstring')) { + $this->h5pF->setErrorMessage($this->h5pF->t('The mbstring PHP extension is not loaded. H5P need this to function properly'), 'mbstring-unsupported'); + } + else { + $text = mb_substr($text, 0, $semantics->maxLength); + } + } + + // Check if string is according to optional regexp in semantics + if (!($text === '' && isset($semantics->optional) && $semantics->optional) && isset($semantics->regexp)) { + // Escaping '/' found in patterns, so that it does not break regexp fencing. + $pattern = '/' . str_replace('/', '\\/', $semantics->regexp->pattern) . '/'; + $pattern .= isset($semantics->regexp->modifiers) ? $semantics->regexp->modifiers : ''; + if (preg_match($pattern, $text) === 0) { + // Note: explicitly ignore return value FALSE, to avoid removing text + // if regexp is invalid... + $this->h5pF->setErrorMessage($this->h5pF->t('Provided string is not valid according to regexp in semantics. (value: "%value", regexp: "%regexp")', array('%value' => $text, '%regexp' => $pattern)), 'semantics-invalid-according-regexp'); + $text = ''; + } + } + } + + /** + * Validates content files + * + * @param string $contentPath + * The path containing content files to validate. + * @param bool $isLibrary + * @return bool TRUE if all files are valid + * TRUE if all files are valid + * FALSE if one or more files fail validation. Error message should be set accordingly by validator. + */ + public function validateContentFiles($contentPath, $isLibrary = FALSE) { + if ($this->h5pC->disableFileCheck === TRUE) { + return TRUE; + } + + // Scan content directory for files, recurse into sub directories. + $files = array_diff(scandir($contentPath), array('.','..')); + $valid = TRUE; + $whitelist = $this->h5pF->getWhitelist($isLibrary, H5PCore::$defaultContentWhitelist, H5PCore::$defaultLibraryWhitelistExtras); + + $wl_regex = '/\.(' . preg_replace('/ +/i', '|', preg_quote($whitelist)) . ')$/i'; + + foreach ($files as $file) { + $filePath = $contentPath . DIRECTORY_SEPARATOR . $file; + if (is_dir($filePath)) { + $valid = $this->validateContentFiles($filePath, $isLibrary) && $valid; + } + else { + // Snipped from drupal 6 "file_validate_extensions". Using own code + // to avoid 1. creating a file-like object just to test for the known + // file name, 2. testing against a returned error array that could + // never be more than 1 element long anyway, 3. recreating the regex + // for every file. + if (!extension_loaded('mbstring')) { + $this->h5pF->setErrorMessage($this->h5pF->t('The mbstring PHP extension is not loaded. H5P need this to function properly'), 'mbstring-unsupported'); + $valid = FALSE; + } + else if (!preg_match($wl_regex, mb_strtolower($file))) { + $this->h5pF->setErrorMessage($this->h5pF->t('File "%filename" not allowed. Only files with the following extensions are allowed: %files-allowed.', array('%filename' => $file, '%files-allowed' => $whitelist)), 'not-in-whitelist'); + $valid = FALSE; + } + } + } + return $valid; + } + + /** + * Validate given value against number semantics + * @param $number + * @param $semantics + */ + public function validateNumber(&$number, $semantics) { + // Validate that $number is indeed a number + if (!is_numeric($number)) { + $number = 0; + } + // Check if number is within valid bounds. Move within bounds if not. + if (isset($semantics->min) && $number < $semantics->min) { + $number = $semantics->min; + } + if (isset($semantics->max) && $number > $semantics->max) { + $number = $semantics->max; + } + // Check if number is within allowed bounds even if step value is set. + if (isset($semantics->step)) { + $testNumber = $number - (isset($semantics->min) ? $semantics->min : 0); + $rest = $testNumber % $semantics->step; + if ($rest !== 0) { + $number -= $rest; + } + } + // Check if number has proper number of decimals. + if (isset($semantics->decimals)) { + $number = round($number, $semantics->decimals); + } + } + + /** + * Validate given value against boolean semantics + * @param $bool + * @return bool + */ + public function validateBoolean(&$bool) { + return is_bool($bool); + } + + /** + * Validate select values + * @param $select + * @param $semantics + */ + public function validateSelect(&$select, $semantics) { + $optional = isset($semantics->optional) && $semantics->optional; + $strict = FALSE; + if (isset($semantics->options) && !empty($semantics->options)) { + // We have a strict set of options to choose from. + $strict = TRUE; + $options = array(); + + foreach ($semantics->options as $option) { + // Support optgroup - just flatten options into one + if (isset($option->type) && $option->type === 'optgroup') { + foreach ($option->options as $suboption) { + $options[$suboption->value] = TRUE; + } + } + elseif (isset($option->value)) { + $options[$option->value] = TRUE; + } + } + } + + if (isset($semantics->multiple) && $semantics->multiple) { + // Multi-choice generates array of values. Test each one against valid + // options, if we are strict. First make sure we are working on an + // array. + if (!is_array($select)) { + $select = array($select); + } + + foreach ($select as $key => &$value) { + if ($strict && !$optional && !isset($options[$value])) { + $this->h5pF->setErrorMessage($this->h5pF->t('Invalid selected option in multi-select.')); + unset($select[$key]); + } + else { + $select[$key] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8', FALSE); + } + } + } + else { + // Single mode. If we get an array in here, we chop off the first + // element and use that instead. + if (is_array($select)) { + $select = $select[0]; + } + + if ($strict && !$optional && !isset($options[$select])) { + $this->h5pF->setErrorMessage($this->h5pF->t('Invalid selected option in select.')); + $select = $semantics->options[0]->value; + } + $select = htmlspecialchars($select, ENT_QUOTES, 'UTF-8', FALSE); + } + } + + /** + * Validate given list value against list semantics. + * Will recurse into validating each item in the list according to the type. + * @param $list + * @param $semantics + */ + public function validateList(&$list, $semantics) { + $field = $semantics->field; + $function = $this->typeMap[$field->type]; + + // Check that list is not longer than allowed length. We do this before + // iterating to avoid unnecessary work. + if (isset($semantics->max)) { + array_splice($list, $semantics->max); + } + + if (!is_array($list)) { + $list = array(); + } + + // Validate each element in list. + foreach ($list as $key => &$value) { + if (!is_int($key)) { + array_splice($list, $key, 1); + continue; + } + $this->$function($value, $field); + if ($value === NULL) { + array_splice($list, $key, 1); + } + } + + if (count($list) === 0) { + $list = NULL; + } + } + + /** + * Validate a file like object, such as video, image, audio and file. + * @param $file + * @param $semantics + * @param array $typeValidKeys + */ + private function _validateFilelike(&$file, $semantics, $typeValidKeys = array()) { + // Do not allow to use files from other content folders. + $matches = array(); + if (preg_match($this->h5pC->relativePathRegExp, $file->path, $matches)) { + $file->path = $matches[5]; + } + + // Remove temporary files suffix + if (substr($file->path, -4, 4) === '#tmp') { + $file->path = substr($file->path, 0, strlen($file->path) - 4); + } + + // Make sure path and mime does not have any special chars + $file->path = htmlspecialchars($file->path, ENT_QUOTES, 'UTF-8', FALSE); + if (isset($file->mime)) { + $file->mime = htmlspecialchars($file->mime, ENT_QUOTES, 'UTF-8', FALSE); + } + + // Remove attributes that should not exist, they may contain JSON escape + // code. + $validKeys = array_merge(array('path', 'mime', 'copyright'), $typeValidKeys); + if (isset($semantics->extraAttributes)) { + $validKeys = array_merge($validKeys, $semantics->extraAttributes); // TODO: Validate extraAttributes + } + $this->filterParams($file, $validKeys); + + if (isset($file->width)) { + $file->width = intval($file->width); + } + + if (isset($file->height)) { + $file->height = intval($file->height); + } + + if (isset($file->codecs)) { + $file->codecs = htmlspecialchars($file->codecs, ENT_QUOTES, 'UTF-8', FALSE); + } + + if (isset($file->bitrate)) { + $file->bitrate = intval($file->bitrate); + } + + if (isset($file->quality)) { + if (!is_object($file->quality) || !isset($file->quality->level) || !isset($file->quality->label)) { + unset($file->quality); + } + else { + $this->filterParams($file->quality, array('level', 'label')); + $file->quality->level = intval($file->quality->level); + $file->quality->label = htmlspecialchars($file->quality->label, ENT_QUOTES, 'UTF-8', FALSE); + } + } + + if (isset($file->copyright)) { + $this->validateGroup($file->copyright, $this->getCopyrightSemantics()); + } + } + + /** + * Validate given file data + * @param $file + * @param $semantics + */ + public function validateFile(&$file, $semantics) { + $this->_validateFilelike($file, $semantics); + } + + /** + * Validate given image data + * @param $image + * @param $semantics + */ + public function validateImage(&$image, $semantics) { + $this->_validateFilelike($image, $semantics, array('width', 'height', 'originalImage')); + } + + /** + * Validate given video data + * @param $video + * @param $semantics + */ + public function validateVideo(&$video, $semantics) { + foreach ($video as &$variant) { + $this->_validateFilelike($variant, $semantics, array('width', 'height', 'codecs', 'quality', 'bitrate')); + } + } + + /** + * Validate given audio data + * @param $audio + * @param $semantics + */ + public function validateAudio(&$audio, $semantics) { + foreach ($audio as &$variant) { + $this->_validateFilelike($variant, $semantics); + } + } + + /** + * Validate given group value against group semantics. + * Will recurse into validating each group member. + * @param $group + * @param $semantics + * @param bool $flatten + */ + public function validateGroup(&$group, $semantics, $flatten = TRUE) { + // Groups with just one field are compressed in the editor to only output + // the child content. (Exemption for fake groups created by + // "validateBySemantics" above) + $function = null; + $field = null; + + $isSubContent = isset($semantics->isSubContent) && $semantics->isSubContent === TRUE; + + if (count($semantics->fields) == 1 && $flatten && !$isSubContent) { + $field = $semantics->fields[0]; + $function = $this->typeMap[$field->type]; + $this->$function($group, $field); + } + else { + foreach ($group as $key => &$value) { + // If subContentId is set, keep value + if($isSubContent && ($key == 'subContentId')){ + continue; + } + + // Find semantics for name=$key + $found = FALSE; + foreach ($semantics->fields as $field) { + if ($field->name == $key) { + if (isset($semantics->optional) && $semantics->optional) { + $field->optional = TRUE; + } + $function = $this->typeMap[$field->type]; + $found = TRUE; + break; + } + } + if ($found) { + if ($function) { + $this->$function($value, $field); + if ($value === NULL) { + unset($group->$key); + } + } + else { + // We have a field type in semantics for which we don't have a + // known validator. + $this->h5pF->setErrorMessage($this->h5pF->t('H5P internal error: unknown content type "@type" in semantics. Removing content!', array('@type' => $field->type)), 'semantics-unknown-type'); + unset($group->$key); + } + } + else { + // If validator is not found, something exists in content that does + // not have a corresponding semantics field. Remove it. + // $this->h5pF->setErrorMessage($this->h5pF->t('H5P internal error: no validator exists for @key', array('@key' => $key))); + unset($group->$key); + } + } + } + if (!(isset($semantics->optional) && $semantics->optional)) { + if ($group === NULL) { + // Error no value. Errors aren't printed... + return; + } + foreach ($semantics->fields as $field) { + if (!(isset($field->optional) && $field->optional)) { + // Check if field is in group. + if (! property_exists($group, $field->name)) { + //$this->h5pF->setErrorMessage($this->h5pF->t('No value given for mandatory field ' . $field->name)); + } + } + } + } + } + + /** + * Validate given library value against library semantics. + * Check if provided library is within allowed options. + * + * Will recurse into validating the library's semantics too. + * @param $value + * @param $semantics + */ + public function validateLibrary(&$value, $semantics) { + if (!isset($value->library)) { + $value = NULL; + return; + } + + // Check for array of objects or array of strings + if (is_object($semantics->options[0])) { + $getLibraryNames = function ($item) { + return $item->name; + }; + $libraryNames = array_map($getLibraryNames, $semantics->options); + } + else { + $libraryNames = $semantics->options; + } + + if (!in_array($value->library, $libraryNames)) { + $message = NULL; + // Create an understandable error message: + $machineNameArray = explode(' ', $value->library); + $machineName = $machineNameArray[0]; + foreach ($libraryNames as $semanticsLibrary) { + $semanticsMachineNameArray = explode(' ', $semanticsLibrary); + $semanticsMachineName = $semanticsMachineNameArray[0]; + if ($machineName === $semanticsMachineName) { + // Using the wrong version of the library in the content + $message = $this->h5pF->t('The version of the H5P library %machineName used in this content is not valid. Content contains %contentLibrary, but it should be %semanticsLibrary.', array( + '%machineName' => $machineName, + '%contentLibrary' => $value->library, + '%semanticsLibrary' => $semanticsLibrary + )); + break; + } + } + + // Using a library in content that is not present at all in semantics + if ($message === NULL) { + $message = $this->h5pF->t('The H5P library %library used in the content is not valid', array( + '%library' => $value->library + )); + } + + $this->h5pF->setErrorMessage($message); + $value = NULL; + return; + } + + if (!isset($this->libraries[$value->library])) { + $libSpec = H5PCore::libraryFromString($value->library); + $library = $this->h5pC->loadLibrary($libSpec['machineName'], $libSpec['majorVersion'], $libSpec['minorVersion']); + $library['semantics'] = $this->h5pC->loadLibrarySemantics($libSpec['machineName'], $libSpec['majorVersion'], $libSpec['minorVersion']); + $this->libraries[$value->library] = $library; + } + else { + $library = $this->libraries[$value->library]; + } + + // Validate parameters + $this->validateGroup($value->params, (object) array( + 'type' => 'group', + 'fields' => $library['semantics'], + ), FALSE); + + // Validate subcontent's metadata + if (isset($value->metadata)) { + $value->metadata = $this->validateMetadata($value->metadata); + } + + $validKeys = array('library', 'params', 'subContentId', 'metadata'); + if (isset($semantics->extraAttributes)) { + $validKeys = array_merge($validKeys, $semantics->extraAttributes); + } + + $this->filterParams($value, $validKeys); + if (isset($value->subContentId) && ! preg_match('/^\{?[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\}?$/', $value->subContentId)) { + unset($value->subContentId); + } + + // Find all dependencies for this library + $depKey = 'preloaded-' . $library['machineName']; + if (!isset($this->dependencies[$depKey])) { + $this->dependencies[$depKey] = array( + 'library' => $library, + 'type' => 'preloaded' + ); + + $this->nextWeight = $this->h5pC->findLibraryDependencies($this->dependencies, $library, $this->nextWeight); + $this->dependencies[$depKey]['weight'] = $this->nextWeight++; + } + } + + /** + * Check params for a whitelist of allowed properties + * + * @param array/object $params + * @param array $whitelist + */ + public function filterParams(&$params, $whitelist) { + foreach ($params as $key => $value) { + if (!in_array($key, $whitelist)) { + unset($params->{$key}); + } + } + } + + // XSS filters copied from drupal 7 common.inc. Some modifications done to + // replace Drupal one-liner functions with corresponding flat PHP. + + /** + * Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities. + * + * Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses. + * For examples of various XSS attacks, see: http://ha.ckers.org/xss.html. + * + * This code does four things: + * - Removes characters and constructs that can trick browsers. + * - Makes sure all HTML entities are well-formed. + * - Makes sure all HTML tags and attributes are well-formed. + * - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g. + * javascript:). + * + * @param $string + * The string with raw HTML in it. It will be stripped of everything that can + * cause an XSS attack. + * @param array $allowed_tags + * An array of allowed tags. + * + * @param bool $allowedStyles + * @return mixed|string An XSS safe version of $string, or an empty string if $string is not + * An XSS safe version of $string, or an empty string if $string is not + * valid UTF-8. + * @ingroup sanitation + */ + private function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd'), $allowedStyles = FALSE) { + if (strlen($string) == 0) { + return $string; + } + // Only operate on valid UTF-8 strings. This is necessary to prevent cross + // site scripting issues on Internet Explorer 6. (Line copied from + // drupal_validate_utf8) + if (preg_match('/^./us', $string) != 1) { + return ''; + } + + $this->allowedStyles = $allowedStyles; + + // Store the text format. + $this->_filter_xss_split($allowed_tags, TRUE); + // Remove NULL characters (ignored by some browsers). + $string = str_replace(chr(0), '', $string); + // Remove Netscape 4 JS entities. + $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string); + + // Defuse all HTML entities. + $string = str_replace('&', '&', $string); + // Change back only well-formed entities in our whitelist: + // Decimal numeric entities. + $string = preg_replace('/&#([0-9]+;)/', '&#\1', $string); + // Hexadecimal numeric entities. + $string = preg_replace('/&#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string); + // Named entities. + $string = preg_replace('/&([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string); + return preg_replace_callback('% + ( + <(?=[^a-zA-Z!/]) # a lone < + | # or + # a comment + | # or + <[^>]*(>|$) # a string that starts with a <, up until the > or the end of the string + | # or + > # just a > + )%x', array($this, '_filter_xss_split'), $string); + } + + /** + * Processes an HTML tag. + * + * @param $m + * An array with various meaning depending on the value of $store. + * If $store is TRUE then the array contains the allowed tags. + * If $store is FALSE then the array has one element, the HTML tag to process. + * @param bool $store + * Whether to store $m. + * @return string If the element isn't allowed, an empty string. Otherwise, the cleaned up + * If the element isn't allowed, an empty string. Otherwise, the cleaned up + * version of the HTML element. + */ + private function _filter_xss_split($m, $store = FALSE) { + static $allowed_html; + + if ($store) { + $allowed_html = array_flip($m); + return $allowed_html; + } + + $string = $m[1]; + + if (substr($string, 0, 1) != '<') { + // We matched a lone ">" character. + return '>'; + } + elseif (strlen($string) == 1) { + // We matched a lone "<" character. + return '<'; + } + + if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)([^>]*)>?|()$%', $string, $matches)) { + // Seriously malformed. + return ''; + } + + $slash = trim($matches[1]); + $elem = &$matches[2]; + $attrList = &$matches[3]; + $comment = &$matches[4]; + + if ($comment) { + $elem = '!--'; + } + + if (!isset($allowed_html[strtolower($elem)])) { + // Disallowed HTML element. + return ''; + } + + if ($comment) { + return $comment; + } + + if ($slash != '') { + return ""; + } + + // Is there a closing XHTML slash at the end of the attributes? + $attrList = preg_replace('%(\s?)/\s*$%', '\1', $attrList, -1, $count); + $xhtml_slash = $count ? ' /' : ''; + + // Clean up attributes. + + $attr2 = implode(' ', $this->_filter_xss_attributes($attrList, (in_array($elem, self::$allowed_styleable_tags) ? $this->allowedStyles : FALSE))); + $attr2 = preg_replace('/[<>]/', '', $attr2); + $attr2 = strlen($attr2) ? ' ' . $attr2 : ''; + + return "<$elem$attr2$xhtml_slash>"; + } + + /** + * Processes a string of HTML attributes. + * + * @param $attr + * @param array|bool|object $allowedStyles + * @return array Cleaned up version of the HTML attributes. + * Cleaned up version of the HTML attributes. + */ + private function _filter_xss_attributes($attr, $allowedStyles = FALSE) { + $attrArr = array(); + $mode = 0; + $attrName = ''; + $skip = false; + + while (strlen($attr) != 0) { + // Was the last operation successful? + $working = 0; + switch ($mode) { + case 0: + // Attribute name, href for instance. + if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) { + $attrName = strtolower($match[1]); + $skip = ($attrName == 'style' || substr($attrName, 0, 2) == 'on'); + $working = $mode = 1; + $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr); + } + break; + + case 1: + // Equals sign or valueless ("selected"). + if (preg_match('/^\s*=\s*/', $attr)) { + $working = 1; $mode = 2; + $attr = preg_replace('/^\s*=\s*/', '', $attr); + break; + } + + if (preg_match('/^\s+/', $attr)) { + $working = 1; $mode = 0; + if (!$skip) { + $attrArr[] = $attrName; + } + $attr = preg_replace('/^\s+/', '', $attr); + } + break; + + case 2: + // Attribute value, a URL after href= for instance. + if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) { + if ($allowedStyles && $attrName === 'style') { + // Allow certain styles + foreach ($allowedStyles as $pattern) { + if (preg_match($pattern, $match[1])) { + // All patterns are start to end patterns, and CKEditor adds one span per style + $attrArr[] = 'style="' . $match[1] . '"'; + break; + } + } + break; + } + + $thisVal = $this->filter_xss_bad_protocol($match[1]); + + if (!$skip) { + $attrArr[] = "$attrName=\"$thisVal\""; + } + $working = 1; + $mode = 0; + $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr); + break; + } + + if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) { + $thisVal = $this->filter_xss_bad_protocol($match[1]); + + if (!$skip) { + $attrArr[] = "$attrName='$thisVal'"; + } + $working = 1; $mode = 0; + $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr); + break; + } + + if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) { + $thisVal = $this->filter_xss_bad_protocol($match[1]); + + if (!$skip) { + $attrArr[] = "$attrName=\"$thisVal\""; + } + $working = 1; $mode = 0; + $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr); + } + break; + } + + if ($working == 0) { + // Not well formed; remove and try again. + $attr = preg_replace('/ + ^ + ( + "[^"]*("|$) # - a string that starts with a double quote, up until the next double quote or the end of the string + | # or + \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string + | # or + \S # - a non-whitespace character + )* # any number of the above three + \s* # any number of whitespaces + /x', '', $attr); + $mode = 0; + } + } + + // The attribute list ends with a valueless attribute like "selected". + if ($mode == 1 && !$skip) { + $attrArr[] = $attrName; + } + return $attrArr; + } + +// TODO: Remove Drupal related stuff in docs. + + /** + * Processes an HTML attribute value and strips dangerous protocols from URLs. + * + * @param $string + * The string with the attribute value. + * @param bool $decode + * (deprecated) Whether to decode entities in the $string. Set to FALSE if the + * $string is in plain text, TRUE otherwise. Defaults to TRUE. This parameter + * is deprecated and will be removed in Drupal 8. To process a plain-text URI, + * call _strip_dangerous_protocols() or check_url() instead. + * @return string Cleaned up and HTML-escaped version of $string. + * Cleaned up and HTML-escaped version of $string. + */ + private function filter_xss_bad_protocol($string, $decode = TRUE) { + // Get the plain text representation of the attribute value (i.e. its meaning). + // @todo Remove the $decode parameter in Drupal 8, and always assume an HTML + // string that needs decoding. + if ($decode) { + $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8'); + } + return htmlspecialchars($this->_strip_dangerous_protocols($string), ENT_QUOTES, 'UTF-8', FALSE); + } + + /** + * Strips dangerous protocols (e.g. 'javascript:') from a URI. + * + * This function must be called for all URIs within user-entered input prior + * to being output to an HTML attribute value. It is often called as part of + * check_url() or filter_xss(), but those functions return an HTML-encoded + * string, so this function can be called independently when the output needs to + * be a plain-text string for passing to t(), l(), drupal_attributes(), or + * another function that will call check_plain() separately. + * + * @param $uri + * A plain-text URI that might contain dangerous protocols. + * @return string A plain-text URI stripped of dangerous protocols. As with all plain-text + * A plain-text URI stripped of dangerous protocols. As with all plain-text + * strings, this return value must not be output to an HTML page without + * check_plain() being called on it. However, it can be passed to functions + * expecting plain-text strings. + * @see check_url() + */ + private function _strip_dangerous_protocols($uri) { + static $allowed_protocols; + + if (!isset($allowed_protocols)) { + $allowed_protocols = array_flip(array('ftp', 'http', 'https', 'mailto')); + } + + // Iteratively remove any invalid protocol found. + do { + $before = $uri; + $colonPos = strpos($uri, ':'); + if ($colonPos > 0) { + // We found a colon, possibly a protocol. Verify. + $protocol = substr($uri, 0, $colonPos); + // If a colon is preceded by a slash, question mark or hash, it cannot + // possibly be part of the URL scheme. This must be a relative URL, which + // inherits the (safe) protocol of the base document. + if (preg_match('![/?#]!', $protocol)) { + break; + } + // Check if this is a disallowed protocol. Per RFC2616, section 3.2.3 + // (URI Comparison) scheme comparison must be case-insensitive. + if (!isset($allowed_protocols[strtolower($protocol)])) { + $uri = substr($uri, $colonPos + 1); + } + } + } while ($before != $uri); + + return $uri; + } + + public function getMetadataSemantics() { + static $semantics; + + $cc_versions = array( + (object) array( + 'value' => '4.0', + 'label' => $this->h5pF->t('4.0 International') + ), + (object) array( + 'value' => '3.0', + 'label' => $this->h5pF->t('3.0 Unported') + ), + (object) array( + 'value' => '2.5', + 'label' => $this->h5pF->t('2.5 Generic') + ), + (object) array( + 'value' => '2.0', + 'label' => $this->h5pF->t('2.0 Generic') + ), + (object) array( + 'value' => '1.0', + 'label' => $this->h5pF->t('1.0 Generic') + ) + ); + + $semantics = array( + (object) array( + 'name' => 'title', + 'type' => 'text', + 'label' => $this->h5pF->t('Title'), + 'placeholder' => 'La Gioconda' + ), + (object) array( + 'name' => 'license', + 'type' => 'select', + 'label' => $this->h5pF->t('License'), + 'default' => 'U', + 'options' => array( + (object) array( + 'value' => 'U', + 'label' => $this->h5pF->t('Undisclosed') + ), + (object) array( + 'type' => 'optgroup', + 'label' => $this->h5pF->t('Creative Commons'), + 'options' => array( + (object) array( + 'value' => 'CC BY', + 'label' => $this->h5pF->t('Attribution (CC BY)'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'CC BY-SA', + 'label' => $this->h5pF->t('Attribution-ShareAlike (CC BY-SA)'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'CC BY-ND', + 'label' => $this->h5pF->t('Attribution-NoDerivs (CC BY-ND)'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'CC BY-NC', + 'label' => $this->h5pF->t('Attribution-NonCommercial (CC BY-NC)'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'CC BY-NC-SA', + 'label' => $this->h5pF->t('Attribution-NonCommercial-ShareAlike (CC BY-NC-SA)'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'CC BY-NC-ND', + 'label' => $this->h5pF->t('Attribution-NonCommercial-NoDerivs (CC BY-NC-ND)'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'CC0 1.0', + 'label' => $this->h5pF->t('Public Domain Dedication (CC0)') + ), + (object) array( + 'value' => 'CC PDM', + 'label' => $this->h5pF->t('Public Domain Mark (PDM)') + ), + ) + ), + (object) array( + 'value' => 'GNU GPL', + 'label' => $this->h5pF->t('General Public License v3') + ), + (object) array( + 'value' => 'PD', + 'label' => $this->h5pF->t('Public Domain') + ), + (object) array( + 'value' => 'ODC PDDL', + 'label' => $this->h5pF->t('Public Domain Dedication and Licence') + ), + (object) array( + 'value' => 'C', + 'label' => $this->h5pF->t('Copyright') + ) + ) + ), + (object) array( + 'name' => 'licenseVersion', + 'type' => 'select', + 'label' => $this->h5pF->t('License Version'), + 'options' => $cc_versions, + 'optional' => TRUE + ), + (object) array( + 'name' => 'yearFrom', + 'type' => 'number', + 'label' => $this->h5pF->t('Years (from)'), + 'placeholder' => '1991', + 'min' => '-9999', + 'max' => '9999', + 'optional' => TRUE + ), + (object) array( + 'name' => 'yearTo', + 'type' => 'number', + 'label' => $this->h5pF->t('Years (to)'), + 'placeholder' => '1992', + 'min' => '-9999', + 'max' => '9999', + 'optional' => TRUE + ), + (object) array( + 'name' => 'source', + 'type' => 'text', + 'label' => $this->h5pF->t('Source'), + 'placeholder' => 'https://', + 'optional' => TRUE + ), + (object) array( + 'name' => 'authors', + 'type' => 'list', + 'field' => (object) array ( + 'name' => 'author', + 'type' => 'group', + 'fields'=> array( + (object) array( + 'label' => $this->h5pF->t("Author's name"), + 'name' => 'name', + 'optional' => TRUE, + 'type' => 'text' + ), + (object) array( + 'name' => 'role', + 'type' => 'select', + 'label' => $this->h5pF->t("Author's role"), + 'default' => 'Author', + 'options' => array( + (object) array( + 'value' => 'Author', + 'label' => $this->h5pF->t('Author') + ), + (object) array( + 'value' => 'Editor', + 'label' => $this->h5pF->t('Editor') + ), + (object) array( + 'value' => 'Licensee', + 'label' => $this->h5pF->t('Licensee') + ), + (object) array( + 'value' => 'Originator', + 'label' => $this->h5pF->t('Originator') + ) + ) + ) + ) + ) + ), + (object) array( + 'name' => 'licenseExtras', + 'type' => 'text', + 'widget' => 'textarea', + 'label' => $this->h5pF->t('License Extras'), + 'optional' => TRUE, + 'description' => $this->h5pF->t('Any additional information about the license') + ), + (object) array( + 'name' => 'changes', + 'type' => 'list', + 'field' => (object) array( + 'name' => 'change', + 'type' => 'group', + 'label' => $this->h5pF->t('Changelog'), + 'fields' => array( + (object) array( + 'name' => 'date', + 'type' => 'text', + 'label' => $this->h5pF->t('Date'), + 'optional' => TRUE + ), + (object) array( + 'name' => 'author', + 'type' => 'text', + 'label' => $this->h5pF->t('Changed by'), + 'optional' => TRUE + ), + (object) array( + 'name' => 'log', + 'type' => 'text', + 'widget' => 'textarea', + 'label' => $this->h5pF->t('Description of change'), + 'placeholder' => $this->h5pF->t('Photo cropped, text changed, etc.'), + 'optional' => TRUE + ) + ) + ) + ), + (object) array ( + 'name' => 'authorComments', + 'type' => 'text', + 'widget' => 'textarea', + 'label' => $this->h5pF->t('Author comments'), + 'description' => $this->h5pF->t('Comments for the editor of the content (This text will not be published as a part of copyright info)'), + 'optional' => TRUE + ), + (object) array( + 'name' => 'contentType', + 'type' => 'text', + 'widget' => 'none' + ), + (object) array( + 'name' => 'defaultLanguage', + 'type' => 'text', + 'widget' => 'none' + ) + ); + + return $semantics; + } + + public function getCopyrightSemantics() { + static $semantics; + + if ($semantics === NULL) { + $cc_versions = array( + (object) array( + 'value' => '4.0', + 'label' => $this->h5pF->t('4.0 International') + ), + (object) array( + 'value' => '3.0', + 'label' => $this->h5pF->t('3.0 Unported') + ), + (object) array( + 'value' => '2.5', + 'label' => $this->h5pF->t('2.5 Generic') + ), + (object) array( + 'value' => '2.0', + 'label' => $this->h5pF->t('2.0 Generic') + ), + (object) array( + 'value' => '1.0', + 'label' => $this->h5pF->t('1.0 Generic') + ) + ); + + $semantics = (object) array( + 'name' => 'copyright', + 'type' => 'group', + 'label' => $this->h5pF->t('Copyright information'), + 'fields' => array( + (object) array( + 'name' => 'title', + 'type' => 'text', + 'label' => $this->h5pF->t('Title'), + 'placeholder' => 'La Gioconda', + 'optional' => TRUE + ), + (object) array( + 'name' => 'author', + 'type' => 'text', + 'label' => $this->h5pF->t('Author'), + 'placeholder' => 'Leonardo da Vinci', + 'optional' => TRUE + ), + (object) array( + 'name' => 'year', + 'type' => 'text', + 'label' => $this->h5pF->t('Year(s)'), + 'placeholder' => '1503 - 1517', + 'optional' => TRUE + ), + (object) array( + 'name' => 'source', + 'type' => 'text', + 'label' => $this->h5pF->t('Source'), + 'placeholder' => 'http://en.wikipedia.org/wiki/Mona_Lisa', + 'optional' => true, + 'regexp' => (object) array( + 'pattern' => '^http[s]?://.+', + 'modifiers' => 'i' + ) + ), + (object) array( + 'name' => 'license', + 'type' => 'select', + 'label' => $this->h5pF->t('License'), + 'default' => 'U', + 'options' => array( + (object) array( + 'value' => 'U', + 'label' => $this->h5pF->t('Undisclosed') + ), + (object) array( + 'value' => 'CC BY', + 'label' => $this->h5pF->t('Attribution'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'CC BY-SA', + 'label' => $this->h5pF->t('Attribution-ShareAlike'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'CC BY-ND', + 'label' => $this->h5pF->t('Attribution-NoDerivs'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'CC BY-NC', + 'label' => $this->h5pF->t('Attribution-NonCommercial'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'CC BY-NC-SA', + 'label' => $this->h5pF->t('Attribution-NonCommercial-ShareAlike'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'CC BY-NC-ND', + 'label' => $this->h5pF->t('Attribution-NonCommercial-NoDerivs'), + 'versions' => $cc_versions + ), + (object) array( + 'value' => 'GNU GPL', + 'label' => $this->h5pF->t('General Public License'), + 'versions' => array( + (object) array( + 'value' => 'v3', + 'label' => $this->h5pF->t('Version 3') + ), + (object) array( + 'value' => 'v2', + 'label' => $this->h5pF->t('Version 2') + ), + (object) array( + 'value' => 'v1', + 'label' => $this->h5pF->t('Version 1') + ) + ) + ), + (object) array( + 'value' => 'PD', + 'label' => $this->h5pF->t('Public Domain'), + 'versions' => array( + (object) array( + 'value' => '-', + 'label' => '-' + ), + (object) array( + 'value' => 'CC0 1.0', + 'label' => $this->h5pF->t('CC0 1.0 Universal') + ), + (object) array( + 'value' => 'CC PDM', + 'label' => $this->h5pF->t('Public Domain Mark') + ) + ) + ), + (object) array( + 'value' => 'C', + 'label' => $this->h5pF->t('Copyright') + ) + ) + ), + (object) array( + 'name' => 'version', + 'type' => 'select', + 'label' => $this->h5pF->t('License Version'), + 'options' => array() + ) + ) + ); + } + + return $semantics; + } +} diff --git a/lib/h5p/images/h5p.svg b/lib/h5p/images/h5p.svg new file mode 100644 index 00000000000..07191aa8b2a --- /dev/null +++ b/lib/h5p/images/h5p.svg @@ -0,0 +1,16 @@ + + + + + + + + + diff --git a/lib/h5p/images/throbber.gif b/lib/h5p/images/throbber.gif new file mode 100644 index 0000000000000000000000000000000000000000..acddb91dacf5380214216e7ff2e063f6e5e60d5f GIT binary patch literal 1638 zcmY+@c}x>o90%~3c6tq^Gqi;koYD(=*=q{a3RnT59MaliTR96Nmcw%Bx~^-Ci?2wG zz8GVSy2cozhCo9M;qU;L5K!ZyF|ILcj4{Tz#u(QaLx^ik*qXR2``(}L_s1u{@As9K zyBw=GlL(0{GLTp-cI(!yU@$m8KmYmj=hv@a-@kwV(xpq`aJad-`Q5vB{r&w53kzq? zoSB@Qym#;3+qZ9z969pn(W9qNpMLo8L8sGcG@378zC3vFps1**s;X*uc=+STkBf_o zr%#{0eED)$SJ#_2Zw3YiK7IOh@ZiDQw{Mq~l|6g*?B&asqobovr_<~8UcGwt*s)_R zEiErzyf}aU{QLLsGcq#L)6;8fYlTAL$jHd<-MeRIW^6W_*=)Xe@ge|VdV2c#^XL2a z?c;K}M~@!m^Z6AO6-`Y|yLRo8N~I|&DSP+s4TVA;k4L3aS*=zGVP9Wgc6RoO6DJ-% ze28HfMNu6c9fuAbdiCm+!COqv17;h_;_1en^-J%xm>xq zxdjCUy}i9XJw1NEU!hP$B9Wz~C1lxAE+u$M{2SL5dP{6(D-(@BDgVZJIKn`TU&p@2 zRKS6~3=r)*03w}qKadbo;EQZ@_hUFNi3-ZMCbIc5t;5Q(9I)m6T(`cFoY&> zR0y>Gl}NwP9-{izlyMbZAKDmy&hXl}apHeK6hRR|{34ua94Kt6-ke;K!3L1Ca+58~ zmD9E%5$aP{*9mY^Z?4G!qT+2QA@IPwNW##Fgi+VnJ~E`niqphbAVqPrscC@I0UmKv z&7yn!)|;eL91N7KxuW!0Fb30;-=kHlm9?2{8WM>~-d02(?jT11$L)$$?ZUl$88 zE_bnjHm`eK#O(C}7*;e!44sw98WnVy8HMdM9WGg)Y-Q=z@;DF{y0)>6{)Sl0U!URa zmX1Mvk;YTUp8{mF%bhQqi**G=cVMO|deLn5J0#iqn)h9Q-Mkcl1# zgbf?ggv=y)ELNA?r1xsapkRHqszE&k@Qs^RsAlKL(v%Q~HHYZy8%1*I171x6mFdvU zRaFv*GLxy}1Ib@VI>c*zS{*5tVN+_H#lrauG>&~s@_(|vxD4-DVR9!5f&gmm>83z_ zUAHF$Eu6fNQzrA}ZTGK1CQsF!x1cD; zm6fuRGe#t=vn4Z3!tYVW|K|6K^~S3&5eJ1*VSLq4OgNGsoW4zShaBf*JZ`~h%QI{(u)FAqNZq?!lDq9 zQ8>$D5l0gtP~){i93?87PXUsU$`WdL7l1ZoX>79(qj;EU%OS@xy)oG}HLOPLj4b)M zrBz_EZ5bDM318#p^b4VYb!x@77EimFB2;AocGSK#Rg;!&R=7J(iL9&2xdC}Fx*y5= E2RJh7g8%>k literal 0 HcmV?d00001 diff --git a/lib/h5p/js/h5p-action-bar.js b/lib/h5p/js/h5p-action-bar.js new file mode 100644 index 00000000000..608a848b3d9 --- /dev/null +++ b/lib/h5p/js/h5p-action-bar.js @@ -0,0 +1,100 @@ +/** + * @class + * @augments H5P.EventDispatcher + * @param {Object} displayOptions + * @param {boolean} displayOptions.export Triggers the display of the 'Download' button + * @param {boolean} displayOptions.copyright Triggers the display of the 'Copyright' button + * @param {boolean} displayOptions.embed Triggers the display of the 'Embed' button + * @param {boolean} displayOptions.icon Triggers the display of the 'H5P icon' link + */ +H5P.ActionBar = (function ($, EventDispatcher) { + "use strict"; + + function ActionBar(displayOptions) { + EventDispatcher.call(this); + + /** @alias H5P.ActionBar# */ + var self = this; + + var hasActions = false; + + // Create action bar + var $actions = H5P.jQuery('
    '); + + /** + * Helper for creating action bar buttons. + * + * @private + * @param {string} type + * @param {string} customClass Instead of type class + */ + var addActionButton = function (type, customClass) { + /** + * Handles selection of action + */ + var handler = function () { + self.trigger(type); + }; + H5P.jQuery('
  • ', { + 'class': 'h5p-button h5p-noselect h5p-' + (customClass ? customClass : type), + role: 'button', + tabindex: 0, + title: H5P.t(type + 'Description'), + html: H5P.t(type), + on: { + click: handler, + keypress: function (e) { + if (e.which === 32) { + handler(); + e.preventDefault(); // (since return false will block other inputs) + } + } + }, + appendTo: $actions + }); + + hasActions = true; + }; + + // Register action bar buttons + if (displayOptions.export || displayOptions.copy) { + // Add export button + addActionButton('reuse', 'export'); + } + if (displayOptions.copyright) { + addActionButton('copyrights'); + } + if (displayOptions.embed) { + addActionButton('embed'); + } + if (displayOptions.icon) { + // Add about H5P button icon + H5P.jQuery('
  • ').appendTo($actions); + hasActions = true; + } + + /** + * Returns a reference to the dom element + * + * @return {H5P.jQuery} + */ + self.getDOMElement = function () { + return $actions; + }; + + /** + * Does the actionbar contain actions? + * + * @return {Boolean} + */ + self.hasActions = function () { + return hasActions; + }; + } + + ActionBar.prototype = Object.create(EventDispatcher.prototype); + ActionBar.prototype.constructor = ActionBar; + + return ActionBar; + +})(H5P.jQuery, H5P.EventDispatcher); diff --git a/lib/h5p/js/h5p-confirmation-dialog.js b/lib/h5p/js/h5p-confirmation-dialog.js new file mode 100644 index 00000000000..cd3536e7a40 --- /dev/null +++ b/lib/h5p/js/h5p-confirmation-dialog.js @@ -0,0 +1,410 @@ +/*global H5P*/ +H5P.ConfirmationDialog = (function (EventDispatcher) { + "use strict"; + + /** + * Create a confirmation dialog + * + * @param [options] Options for confirmation dialog + * @param [options.instance] Instance that uses confirmation dialog + * @param [options.headerText] Header text + * @param [options.dialogText] Dialog text + * @param [options.cancelText] Cancel dialog button text + * @param [options.confirmText] Confirm dialog button text + * @param [options.hideCancel] Hide cancel button + * @param [options.hideExit] Hide exit button + * @param [options.skipRestoreFocus] Skip restoring focus when hiding the dialog + * @param [options.classes] Extra classes for popup + * @constructor + */ + function ConfirmationDialog(options) { + EventDispatcher.call(this); + var self = this; + + // Make sure confirmation dialogs have unique id + H5P.ConfirmationDialog.uniqueId += 1; + var uniqueId = H5P.ConfirmationDialog.uniqueId; + + // Default options + options = options || {}; + options.headerText = options.headerText || H5P.t('confirmDialogHeader'); + options.dialogText = options.dialogText || H5P.t('confirmDialogBody'); + options.cancelText = options.cancelText || H5P.t('cancelLabel'); + options.confirmText = options.confirmText || H5P.t('confirmLabel'); + + /** + * Handle confirming event + * @param {Event} e + */ + function dialogConfirmed(e) { + self.hide(); + self.trigger('confirmed'); + e.preventDefault(); + } + + /** + * Handle dialog canceled + * @param {Event} e + */ + function dialogCanceled(e) { + self.hide(); + self.trigger('canceled'); + e.preventDefault(); + } + + /** + * Flow focus to element + * @param {HTMLElement} element Next element to be focused + * @param {Event} e Original tab event + */ + function flowTo(element, e) { + element.focus(); + e.preventDefault(); + } + + // Offset of exit button + var exitButtonOffset = 2 * 16; + var shadowOffset = 8; + + // Determine if we are too large for our container and must resize + var resizeIFrame = false; + + // Create background + var popupBackground = document.createElement('div'); + popupBackground.classList + .add('h5p-confirmation-dialog-background', 'hidden', 'hiding'); + + // Create outer popup + var popup = document.createElement('div'); + popup.classList.add('h5p-confirmation-dialog-popup', 'hidden'); + if (options.classes) { + options.classes.forEach(function (popupClass) { + popup.classList.add(popupClass); + }); + } + + popup.setAttribute('role', 'dialog'); + popup.setAttribute('aria-labelledby', 'h5p-confirmation-dialog-dialog-text-' + uniqueId); + popupBackground.appendChild(popup); + popup.addEventListener('keydown', function (e) { + if (e.which === 27) {// Esc key + // Exit dialog + dialogCanceled(e); + } + }); + + // Popup header + var header = document.createElement('div'); + header.classList.add('h5p-confirmation-dialog-header'); + popup.appendChild(header); + + // Header text + var headerText = document.createElement('div'); + headerText.classList.add('h5p-confirmation-dialog-header-text'); + headerText.innerHTML = options.headerText; + header.appendChild(headerText); + + // Popup body + var body = document.createElement('div'); + body.classList.add('h5p-confirmation-dialog-body'); + popup.appendChild(body); + + // Popup text + var text = document.createElement('div'); + text.classList.add('h5p-confirmation-dialog-text'); + text.innerHTML = options.dialogText; + text.id = 'h5p-confirmation-dialog-dialog-text-' + uniqueId; + body.appendChild(text); + + // Popup buttons + var buttons = document.createElement('div'); + buttons.classList.add('h5p-confirmation-dialog-buttons'); + body.appendChild(buttons); + + // Cancel button + var cancelButton = document.createElement('button'); + cancelButton.classList.add('h5p-core-cancel-button'); + cancelButton.textContent = options.cancelText; + + // Confirm button + var confirmButton = document.createElement('button'); + confirmButton.classList.add('h5p-core-button'); + confirmButton.classList.add('h5p-confirmation-dialog-confirm-button'); + confirmButton.textContent = options.confirmText; + + // Exit button + var exitButton = document.createElement('button'); + exitButton.classList.add('h5p-confirmation-dialog-exit'); + exitButton.setAttribute('aria-hidden', 'true'); + exitButton.tabIndex = -1; + exitButton.title = options.cancelText; + + // Cancel handler + cancelButton.addEventListener('click', dialogCanceled); + cancelButton.addEventListener('keydown', function (e) { + if (e.which === 32) { // Space + dialogCanceled(e); + } + else if (e.which === 9 && e.shiftKey) { // Shift-tab + flowTo(confirmButton, e); + } + }); + + if (!options.hideCancel) { + buttons.appendChild(cancelButton); + } + else { + // Center buttons + buttons.classList.add('center'); + } + + // Confirm handler + confirmButton.addEventListener('click', dialogConfirmed); + confirmButton.addEventListener('keydown', function (e) { + if (e.which === 32) { // Space + dialogConfirmed(e); + } + else if (e.which === 9 && !e.shiftKey) { // Tab + const nextButton = !options.hideCancel ? cancelButton : confirmButton; + flowTo(nextButton, e); + } + }); + buttons.appendChild(confirmButton); + + // Exit handler + exitButton.addEventListener('click', dialogCanceled); + exitButton.addEventListener('keydown', function (e) { + if (e.which === 32) { // Space + dialogCanceled(e); + } + }); + if (!options.hideExit) { + popup.appendChild(exitButton); + } + + // Wrapper element + var wrapperElement; + + // Focus capturing + var focusPredator; + + // Maintains hidden state of elements + var wrapperSiblingsHidden = []; + var popupSiblingsHidden = []; + + // Element with focus before dialog + var previouslyFocused; + + /** + * Set parent of confirmation dialog + * @param {HTMLElement} wrapper + * @returns {H5P.ConfirmationDialog} + */ + this.appendTo = function (wrapper) { + wrapperElement = wrapper; + return this; + }; + + /** + * Capture the focus element, send it to confirmation button + * @param {Event} e Original focus event + */ + var captureFocus = function (e) { + if (!popupBackground.contains(e.target)) { + e.preventDefault(); + confirmButton.focus(); + } + }; + + /** + * Hide siblings of element from assistive technology + * + * @param {HTMLElement} element + * @returns {Array} The previous hidden state of all siblings + */ + var hideSiblings = function (element) { + var hiddenSiblings = []; + var siblings = element.parentNode.children; + var i; + for (i = 0; i < siblings.length; i += 1) { + // Preserve hidden state + hiddenSiblings[i] = siblings[i].getAttribute('aria-hidden') ? + true : false; + + if (siblings[i] !== element) { + siblings[i].setAttribute('aria-hidden', true); + } + } + return hiddenSiblings; + }; + + /** + * Restores assistive technology state of element's siblings + * + * @param {HTMLElement} element + * @param {Array} hiddenSiblings Hidden state of all siblings + */ + var restoreSiblings = function (element, hiddenSiblings) { + var siblings = element.parentNode.children; + var i; + for (i = 0; i < siblings.length; i += 1) { + if (siblings[i] !== element && !hiddenSiblings[i]) { + siblings[i].removeAttribute('aria-hidden'); + } + } + }; + + /** + * Start capturing focus of parent and send it to dialog + */ + var startCapturingFocus = function () { + focusPredator = wrapperElement.parentNode || wrapperElement; + focusPredator.addEventListener('focus', captureFocus, true); + }; + + /** + * Clean up event listener for capturing focus + */ + var stopCapturingFocus = function () { + focusPredator.removeAttribute('aria-hidden'); + focusPredator.removeEventListener('focus', captureFocus, true); + }; + + /** + * Hide siblings in underlay from assistive technologies + */ + var disableUnderlay = function () { + wrapperSiblingsHidden = hideSiblings(wrapperElement); + popupSiblingsHidden = hideSiblings(popupBackground); + }; + + /** + * Restore state of underlay for assistive technologies + */ + var restoreUnderlay = function () { + restoreSiblings(wrapperElement, wrapperSiblingsHidden); + restoreSiblings(popupBackground, popupSiblingsHidden); + }; + + /** + * Fit popup to container. Makes sure it doesn't overflow. + * @params {number} [offsetTop] Offset of popup + */ + var fitToContainer = function (offsetTop) { + var popupOffsetTop = parseInt(popup.style.top, 10); + if (offsetTop !== undefined) { + popupOffsetTop = offsetTop; + } + + if (!popupOffsetTop) { + popupOffsetTop = 0; + } + + // Overflows height + if (popupOffsetTop + popup.offsetHeight > wrapperElement.offsetHeight) { + popupOffsetTop = wrapperElement.offsetHeight - popup.offsetHeight - shadowOffset; + } + + if (popupOffsetTop - exitButtonOffset <= 0) { + popupOffsetTop = exitButtonOffset + shadowOffset; + + // We are too big and must resize + resizeIFrame = true; + } + popup.style.top = popupOffsetTop + 'px'; + }; + + /** + * Show confirmation dialog + * @params {number} offsetTop Offset top + * @returns {H5P.ConfirmationDialog} + */ + this.show = function (offsetTop) { + // Capture focused item + previouslyFocused = document.activeElement; + wrapperElement.appendChild(popupBackground); + startCapturingFocus(); + disableUnderlay(); + popupBackground.classList.remove('hidden'); + fitToContainer(offsetTop); + setTimeout(function () { + popup.classList.remove('hidden'); + popupBackground.classList.remove('hiding'); + + setTimeout(function () { + // Focus confirm button + confirmButton.focus(); + + // Resize iFrame if necessary + if (resizeIFrame && options.instance) { + var minHeight = parseInt(popup.offsetHeight, 10) + + exitButtonOffset + (2 * shadowOffset); + self.setViewPortMinimumHeight(minHeight); + options.instance.trigger('resize'); + resizeIFrame = false; + } + }, 100); + }, 0); + + return this; + }; + + /** + * Hide confirmation dialog + * @returns {H5P.ConfirmationDialog} + */ + this.hide = function () { + popupBackground.classList.add('hiding'); + popup.classList.add('hidden'); + + // Restore focus + stopCapturingFocus(); + if (!options.skipRestoreFocus) { + previouslyFocused.focus(); + } + restoreUnderlay(); + setTimeout(function () { + popupBackground.classList.add('hidden'); + wrapperElement.removeChild(popupBackground); + self.setViewPortMinimumHeight(null); + }, 100); + + return this; + }; + + /** + * Retrieve element + * + * @return {HTMLElement} + */ + this.getElement = function () { + return popup; + }; + + /** + * Get previously focused element + * @return {HTMLElement} + */ + this.getPreviouslyFocused = function () { + return previouslyFocused; + }; + + /** + * Sets the minimum height of the view port + * + * @param {number|null} minHeight + */ + this.setViewPortMinimumHeight = function (minHeight) { + var container = document.querySelector('.h5p-container') || document.body; + container.style.minHeight = (typeof minHeight === 'number') ? (minHeight + 'px') : minHeight; + }; + } + + ConfirmationDialog.prototype = Object.create(EventDispatcher.prototype); + ConfirmationDialog.prototype.constructor = ConfirmationDialog; + + return ConfirmationDialog; + +}(H5P.EventDispatcher)); + +H5P.ConfirmationDialog.uniqueId = -1; diff --git a/lib/h5p/js/h5p-content-type.js b/lib/h5p/js/h5p-content-type.js new file mode 100644 index 00000000000..47c4d21bf75 --- /dev/null +++ b/lib/h5p/js/h5p-content-type.js @@ -0,0 +1,41 @@ +/** + * H5P.ContentType is a base class for all content types. Used by newRunnable() + * + * Functions here may be overridable by the libraries. In special cases, + * it is also possible to override H5P.ContentType on a global level. + * + * NOTE that this doesn't actually 'extend' the event dispatcher but instead + * it creates a single instance which all content types shares as their base + * prototype. (in some cases this may be the root of strange event behavior) + * + * @class + * @augments H5P.EventDispatcher + */ +H5P.ContentType = function (isRootLibrary) { + + function ContentType() {} + + // Inherit from EventDispatcher. + ContentType.prototype = new H5P.EventDispatcher(); + + /** + * Is library standalone or not? Not beeing standalone, means it is + * included in another library + * + * @return {Boolean} + */ + ContentType.prototype.isRoot = function () { + return isRootLibrary; + }; + + /** + * Returns the file path of a file in the current library + * @param {string} filePath The path to the file relative to the library folder + * @return {string} The full path to the file + */ + ContentType.prototype.getLibraryFilePath = function (filePath) { + return H5P.getLibraryPath(this.libraryInfo.versionedNameNoSpaces) + '/' + filePath; + }; + + return ContentType; +}; diff --git a/lib/h5p/js/h5p-content-upgrade-process.js b/lib/h5p/js/h5p-content-upgrade-process.js new file mode 100644 index 00000000000..fbaa4f2bf07 --- /dev/null +++ b/lib/h5p/js/h5p-content-upgrade-process.js @@ -0,0 +1,313 @@ +/*jshint -W083 */ +var H5PUpgrades = H5PUpgrades || {}; + +H5P.ContentUpgradeProcess = (function (Version) { + + /** + * @class + * @namespace H5P + */ + function ContentUpgradeProcess(name, oldVersion, newVersion, params, id, loadLibrary, done) { + var self = this; + + // Make params possible to work with + try { + params = JSON.parse(params); + if (!(params instanceof Object)) { + throw true; + } + } + catch (event) { + return done({ + type: 'errorParamsBroken', + id: id + }); + } + + self.loadLibrary = loadLibrary; + self.upgrade(name, oldVersion, newVersion, params.params, params.metadata, function (err, upgradedParams, upgradedMetadata) { + if (err) { + err.id = id; + return done(err); + } + + done(null, JSON.stringify({params: upgradedParams, metadata: upgradedMetadata})); + }); + } + + /** + * Run content upgrade. + * + * @public + * @param {string} name + * @param {Version} oldVersion + * @param {Version} newVersion + * @param {Object} params + * @param {Object} metadata + * @param {Function} done + */ + ContentUpgradeProcess.prototype.upgrade = function (name, oldVersion, newVersion, params, metadata, done) { + var self = this; + + // Load library details and upgrade routines + self.loadLibrary(name, newVersion, function (err, library) { + if (err) { + return done(err); + } + if (library.semantics === null) { + return done({ + type: 'libraryMissing', + library: library.name + ' ' + library.version.major + '.' + library.version.minor + }); + } + + // Run upgrade routines on params + self.processParams(library, oldVersion, newVersion, params, metadata, function (err, params, metadata) { + if (err) { + return done(err); + } + + // Check if any of the sub-libraries need upgrading + asyncSerial(library.semantics, function (index, field, next) { + self.processField(field, params[field.name], function (err, upgradedParams) { + if (upgradedParams) { + params[field.name] = upgradedParams; + } + next(err); + }); + }, function (err) { + done(err, params, metadata); + }); + }); + }); + }; + + /** + * Run upgrade hooks on params. + * + * @public + * @param {Object} library + * @param {Version} oldVersion + * @param {Version} newVersion + * @param {Object} params + * @param {Function} next + */ + ContentUpgradeProcess.prototype.processParams = function (library, oldVersion, newVersion, params, metadata, next) { + if (H5PUpgrades[library.name] === undefined) { + if (library.upgradesScript) { + // Upgrades script should be loaded so the upgrades should be here. + return next({ + type: 'scriptMissing', + library: library.name + ' ' + newVersion + }); + } + + // No upgrades script. Move on + return next(null, params, metadata); + } + + // Run upgrade hooks. Start by going through major versions + asyncSerial(H5PUpgrades[library.name], function (major, minors, nextMajor) { + if (major < oldVersion.major || major > newVersion.major) { + // Older than the current version or newer than the selected + nextMajor(); + } + else { + // Go through the minor versions for this major version + asyncSerial(minors, function (minor, upgrade, nextMinor) { + minor =+ minor; + if (minor <= oldVersion.minor || minor > newVersion.minor) { + // Older than or equal to the current version or newer than the selected + nextMinor(); + } + else { + // We found an upgrade hook, run it + var unnecessaryWrapper = (upgrade.contentUpgrade !== undefined ? upgrade.contentUpgrade : upgrade); + + try { + unnecessaryWrapper(params, function (err, upgradedParams, upgradedExtras) { + params = upgradedParams; + if (upgradedExtras && upgradedExtras.metadata) { // Optional + metadata = upgradedExtras.metadata; + } + nextMinor(err); + }, {metadata: metadata}); + } + catch (err) { + if (console && console.error) { + console.error("Error", err.stack); + console.error("Error", err.name); + console.error("Error", err.message); + } + next(err); + } + } + }, nextMajor); + } + }, function (err) { + next(err, params, metadata); + }); + }; + + /** + * Process parameter fields to find and upgrade sub-libraries. + * + * @public + * @param {Object} field + * @param {Object} params + * @param {Function} done + */ + ContentUpgradeProcess.prototype.processField = function (field, params, done) { + var self = this; + + if (params === undefined) { + return done(); + } + + switch (field.type) { + case 'library': + if (params.library === undefined || params.params === undefined) { + return done(); + } + + // Look for available upgrades + var usedLib = params.library.split(' ', 2); + for (var i = 0; i < field.options.length; i++) { + var availableLib = (typeof field.options[i] === 'string') ? field.options[i].split(' ', 2) : field.options[i].name.split(' ', 2); + if (availableLib[0] === usedLib[0]) { + if (availableLib[1] === usedLib[1]) { + return done(); // Same version + } + + // We have different versions + var usedVer = new Version(usedLib[1]); + var availableVer = new Version(availableLib[1]); + if (usedVer.major > availableVer.major || (usedVer.major === availableVer.major && usedVer.minor >= availableVer.minor)) { + return done({ + type: 'errorTooHighVersion', + used: usedLib[0] + ' ' + usedVer, + supported: availableLib[0] + ' ' + availableVer + }); // Larger or same version that's available + } + + // A newer version is available, upgrade params + return self.upgrade(availableLib[0], usedVer, availableVer, params.params, params.metadata, function (err, upgradedParams, upgradedMetadata) { + if (!err) { + params.library = availableLib[0] + ' ' + availableVer.major + '.' + availableVer.minor; + params.params = upgradedParams; + if (upgradedMetadata) { + params.metadata = upgradedMetadata; + } + } + done(err, params); + }); + } + } + + // Content type was not supporte by the higher version + done({ + type: 'errorNotSupported', + used: usedLib[0] + ' ' + usedVer + }); + break; + + case 'group': + if (field.fields.length === 1 && field.isSubContent !== true) { + // Single field to process, wrapper will be skipped + self.processField(field.fields[0], params, function (err, upgradedParams) { + if (upgradedParams) { + params = upgradedParams; + } + done(err, params); + }); + } + else { + // Go through all fields in the group + asyncSerial(field.fields, function (index, subField, next) { + var paramsToProcess = params ? params[subField.name] : null; + self.processField(subField, paramsToProcess, function (err, upgradedParams) { + if (upgradedParams) { + params[subField.name] = upgradedParams; + } + next(err); + }); + + }, function (err) { + done(err, params); + }); + } + break; + + case 'list': + // Go trough all params in the list + asyncSerial(params, function (index, subParams, next) { + self.processField(field.field, subParams, function (err, upgradedParams) { + if (upgradedParams) { + params[index] = upgradedParams; + } + next(err); + }); + }, function (err) { + done(err, params); + }); + break; + + default: + done(); + } + }; + + /** + * Helps process each property on the given object asynchronously in serial order. + * + * @private + * @param {Object} obj + * @param {Function} process + * @param {Function} finished + */ + var asyncSerial = function (obj, process, finished) { + var id, isArray = obj instanceof Array; + + // Keep track of each property that belongs to this object. + if (!isArray) { + var ids = []; + for (id in obj) { + if (obj.hasOwnProperty(id)) { + ids.push(id); + } + } + } + + var i = -1; // Keeps track of the current property + + /** + * Private. Process the next property + */ + var next = function () { + id = isArray ? i : ids[i]; + process(id, obj[id], check); + }; + + /** + * Private. Check if we're done or have an error. + * + * @param {String} err + */ + var check = function (err) { + // We need to use a real async function in order for the stack to clear. + setTimeout(function () { + i++; + if (i === (isArray ? obj.length : ids.length) || (err !== undefined && err !== null)) { + finished(err); + } + else { + next(); + } + }, 0); + }; + + check(); // Start + }; + + return ContentUpgradeProcess; +})(H5P.Version); diff --git a/lib/h5p/js/h5p-content-upgrade-worker.js b/lib/h5p/js/h5p-content-upgrade-worker.js new file mode 100644 index 00000000000..3507a358a1a --- /dev/null +++ b/lib/h5p/js/h5p-content-upgrade-worker.js @@ -0,0 +1,63 @@ +/* global importScripts */ +var H5P = H5P || {}; +importScripts('h5p-version.js', 'h5p-content-upgrade-process.js'); + +var libraryLoadedCallback; + +/** + * Register message handlers + */ +var messageHandlers = { + newJob: function (job) { + // Start new job + new H5P.ContentUpgradeProcess(job.name, new H5P.Version(job.oldVersion), new H5P.Version(job.newVersion), job.params, job.id, function loadLibrary(name, version, next) { + // TODO: Cache? + postMessage({ + action: 'loadLibrary', + name: name, + version: version.toString() + }); + libraryLoadedCallback = next; + }, function done(err, result) { + if (err) { + // Return error + postMessage({ + action: 'error', + id: job.id, + err: err.message ? err.message : err + }); + + return; + } + + // Return upgraded content + postMessage({ + action: 'done', + id: job.id, + params: result + }); + }); + }, + libraryLoaded: function (data) { + var library = data.library; + if (library.upgradesScript) { + try { + importScripts(library.upgradesScript); + } + catch (err) { + libraryLoadedCallback(err); + return; + } + } + libraryLoadedCallback(null, data.library); + } +}; + +/** + * Handle messages from our master + */ +onmessage = function (event) { + if (event.data.action !== undefined && messageHandlers[event.data.action]) { + messageHandlers[event.data.action].call(this, event.data); + } +}; diff --git a/lib/h5p/js/h5p-content-upgrade.js b/lib/h5p/js/h5p-content-upgrade.js new file mode 100644 index 00000000000..9dc066c5c25 --- /dev/null +++ b/lib/h5p/js/h5p-content-upgrade.js @@ -0,0 +1,445 @@ +/* global H5PAdminIntegration H5PUtils */ + +(function ($, Version) { + var info, $log, $container, librariesCache = {}, scriptsCache = {}; + + // Initialize + $(document).ready(function () { + // Get library info + info = H5PAdminIntegration.libraryInfo; + + // Get and reset container + const $wrapper = $('#h5p-admin-container').html(''); + $log = $('
      ').appendTo($wrapper); + $container = $('

      ' + info.message + '

      ').appendTo($wrapper); + + // Make it possible to select version + var $version = $(getVersionSelect(info.versions)).appendTo($container); + + // Add "go" button + $(''); + H5PLibraryDetails.$next = $(''); + + H5PLibraryDetails.$previous.on('click', function () { + if (H5PLibraryDetails.$previous.hasClass('disabled')) { + return; + } + + H5PLibraryDetails.currentPage--; + H5PLibraryDetails.updatePager(); + H5PLibraryDetails.createContentTable(); + }); + + H5PLibraryDetails.$next.on('click', function () { + if (H5PLibraryDetails.$next.hasClass('disabled')) { + return; + } + + H5PLibraryDetails.currentPage++; + H5PLibraryDetails.updatePager(); + H5PLibraryDetails.createContentTable(); + }); + + // This is the Page x of y widget: + H5PLibraryDetails.$pagerInfo = $(''); + + H5PLibraryDetails.$pager = $('
      ').append(H5PLibraryDetails.$previous, H5PLibraryDetails.$pagerInfo, H5PLibraryDetails.$next); + H5PLibraryDetails.$content.append(H5PLibraryDetails.$pager); + + H5PLibraryDetails.$pagerInfo.on('click', function () { + var width = H5PLibraryDetails.$pagerInfo.innerWidth(); + H5PLibraryDetails.$pagerInfo.hide(); + + // User has updated the pageNumber + var pageNumerUpdated = function () { + var newPageNum = $gotoInput.val()-1; + var intRegex = /^\d+$/; + + $goto.remove(); + H5PLibraryDetails.$pagerInfo.css({display: 'inline-block'}); + + // Check if input value is valid, and that it has actually changed + if (!(intRegex.test(newPageNum) && newPageNum >= 0 && newPageNum < H5PLibraryDetails.getNumPages() && newPageNum != H5PLibraryDetails.currentPage)) { + return; + } + + H5PLibraryDetails.currentPage = newPageNum; + H5PLibraryDetails.updatePager(); + H5PLibraryDetails.createContentTable(); + }; + + // We create an input box where the user may type in the page number + // he wants to be displayed. + // Reson for doing this is when user has ten-thousands of elements in list, + // this is the easiest way of getting to a specified page + var $gotoInput = $('', { + type: 'number', + min : 1, + max: H5PLibraryDetails.getNumPages(), + on: { + // Listen to blur, and the enter-key: + 'blur': pageNumerUpdated, + 'keyup': function (event) { + if (event.keyCode === 13) { + pageNumerUpdated(); + } + } + } + }).css({width: width}); + var $goto = $('', { + 'class': 'h5p-pager-goto' + }).css({width: width}).append($gotoInput).insertAfter(H5PLibraryDetails.$pagerInfo); + + $gotoInput.focus(); + }); + + H5PLibraryDetails.updatePager(); + }; + + /** + * Calculates number of pages + */ + H5PLibraryDetails.getNumPages = function () { + return Math.ceil(H5PLibraryDetails.currentContent.length / H5PLibraryDetails.PAGER_SIZE); + }; + + /** + * Update the pager text, and enables/disables the next and previous buttons as needed + */ + H5PLibraryDetails.updatePager = function () { + H5PLibraryDetails.$pagerInfo.css({display: 'inline-block'}); + + if (H5PLibraryDetails.getNumPages() > 0) { + var message = H5PUtils.translateReplace(H5PLibraryDetails.library.translations.pageXOfY, { + '$x': (H5PLibraryDetails.currentPage+1), + '$y': H5PLibraryDetails.getNumPages() + }); + H5PLibraryDetails.$pagerInfo.html(message); + } + else { + H5PLibraryDetails.$pagerInfo.html(''); + } + + H5PLibraryDetails.$previous.toggleClass('disabled', H5PLibraryDetails.currentPage <= 0); + H5PLibraryDetails.$next.toggleClass('disabled', H5PLibraryDetails.currentContent.length < (H5PLibraryDetails.currentPage+1)*H5PLibraryDetails.PAGER_SIZE); + }; + + /** + * Creates the search element + */ + H5PLibraryDetails.createSearchElement = function () { + + H5PLibraryDetails.$search = $(''); + + var performSeach = function () { + var searchString = $('.h5p-content-search > input').val(); + + // If search string same as previous, just do nothing + if (H5PLibraryDetails.currentFilter === searchString) { + return; + } + + if (searchString.trim().length === 0) { + // If empty search, use the complete list + H5PLibraryDetails.currentContent = H5PLibraryDetails.library.content; + } + else if (H5PLibraryDetails.filterCache[searchString]) { + // If search is cached, no need to filter + H5PLibraryDetails.currentContent = H5PLibraryDetails.filterCache[searchString]; + } + else { + var listToFilter = H5PLibraryDetails.library.content; + + // Check if we can filter the already filtered results (for performance) + if (searchString.length > 1 && H5PLibraryDetails.currentFilter === searchString.substr(0, H5PLibraryDetails.currentFilter.length)) { + listToFilter = H5PLibraryDetails.currentContent; + } + H5PLibraryDetails.currentContent = $.grep(listToFilter, function (content) { + return content.title && content.title.match(new RegExp(searchString, 'i')); + }); + } + + H5PLibraryDetails.currentFilter = searchString; + // Cache the current result + H5PLibraryDetails.filterCache[searchString] = H5PLibraryDetails.currentContent; + H5PLibraryDetails.currentPage = 0; + H5PLibraryDetails.createContentTable(); + + // Display search results: + if (H5PLibraryDetails.$searchResults) { + H5PLibraryDetails.$searchResults.remove(); + } + if (searchString.trim().length > 0) { + H5PLibraryDetails.$searchResults = $('' + H5PLibraryDetails.currentContent.length + ' hits on ' + H5PLibraryDetails.currentFilter + ''); + H5PLibraryDetails.$search.append(H5PLibraryDetails.$searchResults); + } + H5PLibraryDetails.updatePager(); + }; + + var inputTimer; + $('input', H5PLibraryDetails.$search).on('change keypress paste input', function () { + // Here we start the filtering + // We wait at least 500 ms after last input to perform search + if (inputTimer) { + clearTimeout(inputTimer); + } + + inputTimer = setTimeout( function () { + performSeach(); + }, 500); + }); + + H5PLibraryDetails.$content.append(H5PLibraryDetails.$search); + }; + + /** + * Creates the page size selector + */ + H5PLibraryDetails.createPageSizeSelector = function () { + H5PLibraryDetails.$search.append('
      ' + H5PLibraryDetails.library.translations.pageSizeSelectorLabel + ':102050100200
      '); + + // Listen to clicks on the page size selector: + $('.h5p-admin-pager-size-selector > span', H5PLibraryDetails.$search).on('click', function () { + H5PLibraryDetails.PAGER_SIZE = $(this).data('page-size'); + $('.h5p-admin-pager-size-selector > span', H5PLibraryDetails.$search).removeClass('selected'); + $(this).addClass('selected'); + H5PLibraryDetails.currentPage = 0; + H5PLibraryDetails.createContentTable(); + H5PLibraryDetails.updatePager(); + }); + }; + + // Initialize me: + $(document).ready(function () { + if (!H5PLibraryDetails.initialized) { + H5PLibraryDetails.initialized = true; + H5PLibraryDetails.init(); + } + }); + +})(H5P.jQuery); diff --git a/lib/h5p/js/h5p-library-list.js b/lib/h5p/js/h5p-library-list.js new file mode 100644 index 00000000000..344b7367234 --- /dev/null +++ b/lib/h5p/js/h5p-library-list.js @@ -0,0 +1,140 @@ +/* global H5PAdminIntegration H5PUtils */ +var H5PLibraryList = H5PLibraryList || {}; + +(function ($) { + + /** + * Initializing + */ + H5PLibraryList.init = function () { + var $adminContainer = H5P.jQuery(H5PAdminIntegration.containerSelector).html(''); + + var libraryList = H5PAdminIntegration.libraryList; + if (libraryList.notCached) { + $adminContainer.append(H5PUtils.getRebuildCache(libraryList.notCached)); + } + + // Create library list + $adminContainer.append(H5PLibraryList.createLibraryList(H5PAdminIntegration.libraryList)); + }; + + /** + * Create the library list + * + * @param {object} libraries List of libraries and headers + */ + H5PLibraryList.createLibraryList = function (libraries) { + var t = H5PAdminIntegration.l10n; + if (libraries.listData === undefined || libraries.listData.length === 0) { + return $('
      ' + t.NA + '
      '); + } + + // Create table + var $table = H5PUtils.createTable(libraries.listHeaders); + $table.addClass('libraries'); + + // Add libraries + $.each (libraries.listData, function (index, library) { + var $libraryRow = H5PUtils.createTableRow([ + library.title, + '', + { + text: library.numContent, + class: 'h5p-admin-center' + }, + { + text: library.numContentDependencies, + class: 'h5p-admin-center' + }, + { + text: library.numLibraryDependencies, + class: 'h5p-admin-center' + }, + '
      ' + + '' + + (library.detailsUrl ? '' : '') + + (library.deleteUrl ? '' : '') + + '
      ' + ]); + + H5PLibraryList.addRestricted($('.h5p-admin-restricted', $libraryRow), library.restrictedUrl, library.restricted); + + var hasContent = !(library.numContent === '' || library.numContent === 0); + if (library.upgradeUrl === null) { + $('.h5p-admin-upgrade-library', $libraryRow).remove(); + } + else if (library.upgradeUrl === false || !hasContent) { + $('.h5p-admin-upgrade-library', $libraryRow).attr('disabled', true); + } + else { + $('.h5p-admin-upgrade-library', $libraryRow).attr('title', t.upgradeLibrary).click(function () { + window.location.href = library.upgradeUrl; + }); + } + + // Open details view when clicked + $('.h5p-admin-view-library', $libraryRow).on('click', function () { + window.location.href = library.detailsUrl; + }); + + var $deleteButton = $('.h5p-admin-delete-library', $libraryRow); + if (libraries.notCached !== undefined || + hasContent || + (library.numContentDependencies !== '' && + library.numContentDependencies !== 0) || + (library.numLibraryDependencies !== '' && + library.numLibraryDependencies !== 0)) { + // Disabled delete if content. + $deleteButton.attr('disabled', true); + } + else { + // Go to delete page om click. + $deleteButton.attr('title', t.deleteLibrary).on('click', function () { + window.location.href = library.deleteUrl; + }); + } + + $table.append($libraryRow); + }); + + return $table; + }; + + H5PLibraryList.addRestricted = function ($checkbox, url, selected) { + if (selected === null) { + $checkbox.remove(); + } + else { + $checkbox.change(function () { + $checkbox.attr('disabled', true); + + $.ajax({ + dataType: 'json', + url: url, + cache: false + }).fail(function () { + $checkbox.attr('disabled', false); + + // Reset + $checkbox.attr('checked', !$checkbox.is(':checked')); + }).done(function (result) { + url = result.url; + $checkbox.attr('disabled', false); + }); + }); + + if (selected) { + $checkbox.attr('checked', true); + } + } + }; + + // Initialize me: + $(document).ready(function () { + if (!H5PLibraryList.initialized) { + H5PLibraryList.initialized = true; + H5PLibraryList.init(); + } + }); + +})(H5P.jQuery); diff --git a/lib/h5p/js/h5p-resizer.js b/lib/h5p/js/h5p-resizer.js new file mode 100644 index 00000000000..ed78724ec1a --- /dev/null +++ b/lib/h5p/js/h5p-resizer.js @@ -0,0 +1,131 @@ +// H5P iframe Resizer +(function () { + if (!window.postMessage || !window.addEventListener || window.h5pResizerInitialized) { + return; // Not supported + } + window.h5pResizerInitialized = true; + + // Map actions to handlers + var actionHandlers = {}; + + /** + * Prepare iframe resize. + * + * @private + * @param {Object} iframe Element + * @param {Object} data Payload + * @param {Function} respond Send a response to the iframe + */ + actionHandlers.hello = function (iframe, data, respond) { + // Make iframe responsive + iframe.style.width = '100%'; + + // Bugfix for Chrome: Force update of iframe width. If this is not done the + // document size may not be updated before the content resizes. + iframe.getBoundingClientRect(); + + // Tell iframe that it needs to resize when our window resizes + var resize = function () { + if (iframe.contentWindow) { + // Limit resize calls to avoid flickering + respond('resize'); + } + else { + // Frame is gone, unregister. + window.removeEventListener('resize', resize); + } + }; + window.addEventListener('resize', resize, false); + + // Respond to let the iframe know we can resize it + respond('hello'); + }; + + /** + * Prepare iframe resize. + * + * @private + * @param {Object} iframe Element + * @param {Object} data Payload + * @param {Function} respond Send a response to the iframe + */ + actionHandlers.prepareResize = function (iframe, data, respond) { + // Do not resize unless page and scrolling differs + if (iframe.clientHeight !== data.scrollHeight || + data.scrollHeight !== data.clientHeight) { + + // Reset iframe height, in case content has shrinked. + iframe.style.height = data.clientHeight + 'px'; + respond('resizePrepared'); + } + }; + + /** + * Resize parent and iframe to desired height. + * + * @private + * @param {Object} iframe Element + * @param {Object} data Payload + * @param {Function} respond Send a response to the iframe + */ + actionHandlers.resize = function (iframe, data) { + // Resize iframe so all content is visible. Use scrollHeight to make sure we get everything + iframe.style.height = data.scrollHeight + 'px'; + }; + + /** + * Keyup event handler. Exits full screen on escape. + * + * @param {Event} event + */ + var escape = function (event) { + if (event.keyCode === 27) { + exitFullScreen(); + } + }; + + // Listen for messages from iframes + window.addEventListener('message', function receiveMessage(event) { + if (event.data.context !== 'h5p') { + return; // Only handle h5p requests. + } + + // Find out who sent the message + var iframe, iframes = document.getElementsByTagName('iframe'); + for (var i = 0; i < iframes.length; i++) { + if (iframes[i].contentWindow === event.source) { + iframe = iframes[i]; + break; + } + } + + if (!iframe) { + return; // Cannot find sender + } + + // Find action handler handler + if (actionHandlers[event.data.action]) { + actionHandlers[event.data.action](iframe, event.data, function respond(action, data) { + if (data === undefined) { + data = {}; + } + data.action = action; + data.context = 'h5p'; + event.source.postMessage(data, event.origin); + }); + } + }, false); + + // Let h5p iframes know we're ready! + var iframes = document.getElementsByTagName('iframe'); + var ready = { + context: 'h5p', + action: 'ready' + }; + for (var i = 0; i < iframes.length; i++) { + if (iframes[i].src.indexOf('h5p') !== -1) { + iframes[i].contentWindow.postMessage(ready, '*'); + } + } + +})(); diff --git a/lib/h5p/js/h5p-utils.js b/lib/h5p/js/h5p-utils.js new file mode 100644 index 00000000000..b5aa3334e0e --- /dev/null +++ b/lib/h5p/js/h5p-utils.js @@ -0,0 +1,506 @@ +/* global H5PAdminIntegration*/ +var H5PUtils = H5PUtils || {}; + +(function ($) { + /** + * Generic function for creating a table including the headers + * + * @param {array} headers List of headers + */ + H5PUtils.createTable = function (headers) { + var $table = $('
      '); + + if (headers) { + var $thead = $(''); + var $tr = $(''); + + $.each(headers, function (index, value) { + if (!(value instanceof Object)) { + value = { + html: value + }; + } + + $('', value).appendTo($tr); + }); + + $table.append($thead.append($tr)); + } + + return $table; + }; + + /** + * Generic function for creating a table row + * + * @param {array} rows Value list. Object name is used as class name in + */ + H5PUtils.createTableRow = function (rows) { + var $tr = $(''); + + $.each(rows, function (index, value) { + if (!(value instanceof Object)) { + value = { + html: value + }; + } + + $('', value).appendTo($tr); + }); + + return $tr; + }; + + /** + * Generic function for creating a field containing label and value + * + * @param {string} label The label displayed in front of the value + * @param {string} value The value + */ + H5PUtils.createLabeledField = function (label, value) { + var $field = $('
      '); + + $field.append('
      ' + label + '
      '); + $field.append('
      ' + value + '
      '); + + return $field; + }; + + /** + * Replaces placeholder fields in translation strings + * + * @param {string} template The translation template string in the following format: "$name is a $sex" + * @param {array} replacors An js object with key and values. Eg: {'$name': 'Frode', '$sex': 'male'} + */ + H5PUtils.translateReplace = function (template, replacors) { + $.each(replacors, function (key, value) { + template = template.replace(new RegExp('\\'+key, 'g'), value); + }); + return template; + }; + + /** + * Get throbber with given text. + * + * @param {String} text + * @returns {$} + */ + H5PUtils.throbber = function (text) { + return $('
      ', { + class: 'h5p-throbber', + text: text + }); + }; + + /** + * Makes it possbile to rebuild all content caches from admin UI. + * @param {Object} notCached + * @returns {$} + */ + H5PUtils.getRebuildCache = function (notCached) { + var $container = $('

      ' + notCached.message + '

      ' + notCached.progress + '

      '); + var $button = $('').appendTo($container).click(function () { + var $spinner = $('
      ', {class: 'h5p-spinner'}).replaceAll($button); + var parts = ['|', '/', '-', '\\']; + var current = 0; + var spinning = setInterval(function () { + $spinner.text(parts[current]); + current++; + if (current === parts.length) current = 0; + }, 100); + + var $counter = $container.find('.progress'); + var build = function () { + $.post(notCached.url, function (left) { + if (left === '0') { + clearInterval(spinning); + $container.remove(); + location.reload(); + } + else { + var counter = $counter.text().split(' '); + counter[0] = left; + $counter.text(counter.join(' ')); + build(); + } + }); + }; + build(); + }); + + return $container; + }; + + /** + * Generic table class with useful helpers. + * + * @class + * @param {Object} classes + * Custom html classes to use on elements. + * e.g. {tableClass: 'fixed'}. + */ + H5PUtils.Table = function (classes) { + var numCols; + var sortByCol; + var $sortCol; + var sortCol; + var sortDir; + + // Create basic table + var tableOptions = {}; + if (classes.table !== undefined) { + tableOptions['class'] = classes.table; + } + var $table = $('', tableOptions); + var $thead = $('').appendTo($table); + var $tfoot = $('').appendTo($table); + var $tbody = $('').appendTo($table); + + /** + * Add columns to given table row. + * + * @private + * @param {jQuery} $tr Table row + * @param {(String|Object)} col Column properties + * @param {Number} id Used to seperate the columns + */ + var addCol = function ($tr, col, id) { + var options = { + on: {} + }; + + if (!(col instanceof Object)) { + options.text = col; + } + else { + if (col.text !== undefined) { + options.text = col.text; + } + if (col.class !== undefined) { + options.class = col.class; + } + + if (sortByCol !== undefined && col.sortable === true) { + // Make sortable + options.role = 'button'; + options.tabIndex = 0; + + // This is the first sortable column, use as default sort + if (sortCol === undefined) { + sortCol = id; + sortDir = 0; + } + + // This is the sort column + if (sortCol === id) { + options['class'] = 'h5p-sort'; + if (sortDir === 1) { + options['class'] += ' h5p-reverse'; + } + } + + options.on.click = function () { + sort($th, id); + }; + options.on.keypress = function (event) { + if ((event.charCode || event.keyCode) === 32) { // Space + sort($th, id); + } + }; + } + } + + // Append + var $th = $(''); + var $tr = $('').appendTo($newThead); + for (var i = 0; i < cols.length; i++) { + addCol($tr, cols[i], i); + } + + // Update DOM + $thead.replaceWith($newThead); + $thead = $newThead; + }; + + /** + * Set table rows. + * + * @public + * @param {Array} rows Table rows with cols: [[1,'hello',3],[2,'asd',6]] + */ + this.setRows = function (rows) { + var $newTbody = $(''); + + for (var i = 0; i < rows.length; i++) { + var $tr = $('').appendTo($newTbody); + + for (var j = 0; j < rows[i].length; j++) { + $(''); + var $tr = $('').appendTo($newTbody); + $(''); + var $tr = $('').appendTo($newTfoot); + $('\s*$/g,At={option:[1,""],legend:[1,"
      ","
      "],area:[1,"",""],param:[1,"",""],thead:[1,"
      ', options).appendTo($tr); + if (sortCol === id) { + $sortCol = $th; // Default sort column + } + }; + + /** + * Updates the UI when a column header has been clicked. + * Triggers sorting callback. + * + * @private + * @param {jQuery} $th Table header + * @param {Number} id Used to seperate the columns + */ + var sort = function ($th, id) { + if (id === sortCol) { + // Change sorting direction + if (sortDir === 0) { + sortDir = 1; + $th.addClass('h5p-reverse'); + } + else { + sortDir = 0; + $th.removeClass('h5p-reverse'); + } + } + else { + // Change sorting column + $sortCol.removeClass('h5p-sort').removeClass('h5p-reverse'); + $sortCol = $th.addClass('h5p-sort'); + sortCol = id; + sortDir = 0; + } + + sortByCol({ + by: sortCol, + dir: sortDir + }); + }; + + /** + * Set table headers. + * + * @public + * @param {Array} cols + * Table header data. Can be strings or objects with options like + * "text" and "sortable". E.g. + * [{text: 'Col 1', sortable: true}, 'Col 2', 'Col 3'] + * @param {Function} sort Callback which is runned when sorting changes + * @param {Object} [order] + */ + this.setHeaders = function (cols, sort, order) { + numCols = cols.length; + sortByCol = sort; + + if (order) { + sortCol = order.by; + sortDir = order.dir; + } + + // Create new head + var $newThead = $('
      ', { + html: rows[i][j] + }).appendTo($tr); + } + } + + $tbody.replaceWith($newTbody); + $tbody = $newTbody; + + return $tbody; + }; + + /** + * Set custom table body content. This can be a message or a throbber. + * Will cover all table columns. + * + * @public + * @param {jQuery} $content Custom content + */ + this.setBody = function ($content) { + var $newTbody = $('
      ', { + colspan: numCols + }).append($content).appendTo($tr); + $tbody.replaceWith($newTbody); + $tbody = $newTbody; + }; + + /** + * Set custom table foot content. This can be a pagination widget. + * Will cover all table columns. + * + * @public + * @param {jQuery} $content Custom content + */ + this.setFoot = function ($content) { + var $newTfoot = $('
      ', { + colspan: numCols + }).append($content).appendTo($tr); + $tfoot.replaceWith($newTfoot); + }; + + + /** + * Appends the table to the given container. + * + * @public + * @param {jQuery} $container + */ + this.appendTo = function ($container) { + $table.appendTo($container); + }; + }; + + /** + * Generic pagination class. Creates a useful pagination widget. + * + * @class + * @param {Number} num Total number of items to pagiate. + * @param {Number} limit Number of items to dispaly per page. + * @param {Function} goneTo + * Callback which is fired when the user wants to go to another page. + * @param {Object} l10n + * Localization / translations. e.g. + * { + * currentPage: 'Page $current of $total', + * nextPage: 'Next page', + * previousPage: 'Previous page' + * } + */ + H5PUtils.Pagination = function (num, limit, goneTo, l10n) { + var current = 0; + var pages = Math.ceil(num / limit); + + // Create components + + // Previous button + var $left = $(''; + } + if (contentData.displayOptions.export && contentData.displayOptions.copy) { + html += '
      or
      '; + } + if (contentData.displayOptions.copy) { + html += ''; + } + + const dialog = new H5P.Dialog('reuse', H5P.t('reuseContent'), html, $element); + + // Selecting embed code when dialog is opened + H5P.jQuery(dialog).on('dialog-opened', function (e, $dialog) { + H5P.jQuery('More Info').click(function (e) { + e.stopPropagation(); + }).appendTo($dialog.find('h2')); + $dialog.find('.h5p-download-button').click(function () { + window.location.href = contentData.exportUrl; + instance.triggerXAPI('downloaded'); + dialog.close(); + }); + $dialog.find('.h5p-copy-button').click(function () { + const item = new H5P.ClipboardItem(library); + item.contentId = contentId; + H5P.setClipboard(item); + instance.triggerXAPI('copied'); + dialog.close(); + H5P.attachToastTo( + H5P.jQuery('.h5p-content:first')[0], + H5P.t('contentCopied'), + { + position: { + horizontal: 'centered', + vertical: 'centered', + noOverflowX: true + } + } + ); + }); + H5P.trigger(instance, 'resize'); + }).on('dialog-closed', function () { + H5P.trigger(instance, 'resize'); + }); + + dialog.open(); +}; + +/** + * Display a dialog containing the embed code. + * + * @param {H5P.jQuery} $element + * Element to insert dialog after. + * @param {string} embedCode + * The embed code. + * @param {string} resizeCode + * The advanced resize code + * @param {Object} size + * The content's size. + * @param {number} size.width + * @param {number} size.height + */ +H5P.openEmbedDialog = function ($element, embedCode, resizeCode, size, instance) { + var fullEmbedCode = embedCode + resizeCode; + var dialog = new H5P.Dialog('embed', H5P.t('embed'), '' + H5P.t('size') + ': × px
      ' + H5P.t('showAdvanced') + '

      ' + H5P.t('advancedHelp') + '

      ', $element); + + // Selecting embed code when dialog is opened + H5P.jQuery(dialog).on('dialog-opened', function (event, $dialog) { + var $inner = $dialog.find('.h5p-inner'); + var $scroll = $inner.find('.h5p-scroll-content'); + var diff = $scroll.outerHeight() - $scroll.innerHeight(); + var positionInner = function () { + H5P.trigger(instance, 'resize'); + }; + + // Handle changing of width/height + var $w = $dialog.find('.h5p-embed-size:eq(0)'); + var $h = $dialog.find('.h5p-embed-size:eq(1)'); + var getNum = function ($e, d) { + var num = parseFloat($e.val()); + if (isNaN(num)) { + return d; + } + return Math.ceil(num); + }; + var updateEmbed = function () { + $dialog.find('.h5p-embed-code-container:first').val(fullEmbedCode.replace(':w', getNum($w, size.width)).replace(':h', getNum($h, size.height))); + }; + + $w.change(updateEmbed); + $h.change(updateEmbed); + updateEmbed(); + + // Select text and expand textareas + $dialog.find('.h5p-embed-code-container').each(function () { + H5P.jQuery(this).css('height', this.scrollHeight + 'px').focus(function () { + H5P.jQuery(this).select(); + }); + }); + $dialog.find('.h5p-embed-code-container').eq(0).select(); + positionInner(); + + // Expand advanced embed + var expand = function () { + var $expander = H5P.jQuery(this); + var $content = $expander.next(); + if ($content.is(':visible')) { + $expander.removeClass('h5p-open').text(H5P.t('showAdvanced')); + $content.hide(); + } + else { + $expander.addClass('h5p-open').text(H5P.t('hideAdvanced')); + $content.show(); + } + $dialog.find('.h5p-embed-code-container').each(function () { + H5P.jQuery(this).css('height', this.scrollHeight + 'px'); + }); + positionInner(); + }; + $dialog.find('.h5p-expander').click(expand).keypress(function (event) { + if (event.keyCode === 32) { + expand.apply(this); + } + }); + }).on('dialog-closed', function () { + H5P.trigger(instance, 'resize'); + }); + + dialog.open(); +}; + +/** + * Show a toast message. + * + * The reference element could be dom elements the toast should be attached to, + * or e.g. the document body for general toast messages. + * + * @param {DOM} element Reference element to show toast message for. + * @param {string} message Message to show. + * @param {object} [config] Configuration. + * @param {string} [config.style=h5p-toast] Style name for the tooltip. + * @param {number} [config.duration=3000] Toast message length in ms. + * @param {object} [config.position] Relative positioning of the toast. + * @param {string} [config.position.horizontal=centered] [before|left|centered|right|after]. + * @param {string} [config.position.vertical=below] [above|top|centered|bottom|below]. + * @param {number} [config.position.offsetHorizontal=0] Extra horizontal offset. + * @param {number} [config.position.offsetVertical=0] Extra vetical offset. + * @param {boolean} [config.position.noOverflowLeft=false] True to prevent overflow left. + * @param {boolean} [config.position.noOverflowRight=false] True to prevent overflow right. + * @param {boolean} [config.position.noOverflowTop=false] True to prevent overflow top. + * @param {boolean} [config.position.noOverflowBottom=false] True to prevent overflow bottom. + * @param {boolean} [config.position.noOverflowX=false] True to prevent overflow left and right. + * @param {boolean} [config.position.noOverflowY=false] True to prevent overflow top and bottom. + * @param {object} [config.position.overflowReference=document.body] DOM reference for overflow. + */ +H5P.attachToastTo = function (element, message, config) { + if (element === undefined || message === undefined) { + return; + } + + const eventPath = function (evt) { + var path = (evt.composedPath && evt.composedPath()) || evt.path; + var target = evt.target; + + if (path != null) { + // Safari doesn't include Window, but it should. + return (path.indexOf(window) < 0) ? path.concat(window) : path; + } + + if (target === window) { + return [window]; + } + + function getParents(node, memo) { + memo = memo || []; + var parentNode = node.parentNode; + + if (!parentNode) { + return memo; + } + else { + return getParents(parentNode, memo.concat(parentNode)); + } + } + + return [target].concat(getParents(target), window); + }; + + /** + * Handle click while toast is showing. + */ + const clickHandler = function (event) { + /* + * A common use case will be to attach toasts to buttons that are clicked. + * The click would remove the toast message instantly without this check. + * Children of the clicked element are also ignored. + */ + var path = eventPath(event); + if (path.indexOf(element) !== -1) { + return; + } + clearTimeout(timer); + removeToast(); + }; + + + + /** + * Remove the toast message. + */ + const removeToast = function () { + document.removeEventListener('click', clickHandler); + if (toast.parentNode) { + toast.parentNode.removeChild(toast); + } + }; + + /** + * Get absolute coordinates for the toast. + * + * @param {DOM} element Reference element to show toast message for. + * @param {DOM} toast Toast element. + * @param {object} [position={}] Relative positioning of the toast message. + * @param {string} [position.horizontal=centered] [before|left|centered|right|after]. + * @param {string} [position.vertical=below] [above|top|centered|bottom|below]. + * @param {number} [position.offsetHorizontal=0] Extra horizontal offset. + * @param {number} [position.offsetVertical=0] Extra vetical offset. + * @param {boolean} [position.noOverflowLeft=false] True to prevent overflow left. + * @param {boolean} [position.noOverflowRight=false] True to prevent overflow right. + * @param {boolean} [position.noOverflowTop=false] True to prevent overflow top. + * @param {boolean} [position.noOverflowBottom=false] True to prevent overflow bottom. + * @param {boolean} [position.noOverflowX=false] True to prevent overflow left and right. + * @param {boolean} [position.noOverflowY=false] True to prevent overflow top and bottom. + * @return {object} + */ + const getToastCoordinates = function (element, toast, position) { + position = position || {}; + position.offsetHorizontal = position.offsetHorizontal || 0; + position.offsetVertical = position.offsetVertical || 0; + + const toastRect = toast.getBoundingClientRect(); + const elementRect = element.getBoundingClientRect(); + + let left = 0; + let top = 0; + + // Compute horizontal position + switch (position.horizontal) { + case 'before': + left = elementRect.left - toastRect.width - position.offsetHorizontal; + break; + case 'after': + left = elementRect.left + elementRect.width + position.offsetHorizontal; + break; + case 'left': + left = elementRect.left + position.offsetHorizontal; + break; + case 'right': + left = elementRect.left + elementRect.width - toastRect.width - position.offsetHorizontal; + break; + case 'centered': + left = elementRect.left + elementRect.width / 2 - toastRect.width / 2 + position.offsetHorizontal; + break; + default: + left = elementRect.left + elementRect.width / 2 - toastRect.width / 2 + position.offsetHorizontal; + } + + // Compute vertical position + switch (position.vertical) { + case 'above': + top = elementRect.top - toastRect.height - position.offsetVertical; + break; + case 'below': + top = elementRect.top + elementRect.height + position.offsetVertical; + break; + case 'top': + top = elementRect.top + position.offsetVertical; + break; + case 'bottom': + top = elementRect.top + elementRect.height - toastRect.height - position.offsetVertical; + break; + case 'centered': + top = elementRect.top + elementRect.height / 2 - toastRect.height / 2 + position.offsetVertical; + break; + default: + top = elementRect.top + elementRect.height + position.offsetVertical; + } + + // Prevent overflow + const overflowElement = document.body; + const bounds = overflowElement.getBoundingClientRect(); + if ((position.noOverflowLeft || position.noOverflowX) && (left < bounds.x)) { + left = bounds.x; + } + if ((position.noOverflowRight || position.noOverflowX) && ((left + toastRect.width) > (bounds.x + bounds.width))) { + left = bounds.x + bounds.width - toastRect.width; + } + if ((position.noOverflowTop || position.noOverflowY) && (top < bounds.y)) { + top = bounds.y; + } + if ((position.noOverflowBottom || position.noOverflowY) && ((top + toastRect.height) > (bounds.y + bounds.height))) { + left = bounds.y + bounds.height - toastRect.height; + } + + return {left: left, top: top}; + }; + + // Sanitization + config = config || {}; + config.style = config.style || 'h5p-toast'; + config.duration = config.duration || 3000; + + // Build toast + const toast = document.createElement('div'); + toast.setAttribute('id', config.style); + toast.classList.add('h5p-toast-disabled'); + toast.classList.add(config.style); + + const msg = document.createElement('span'); + msg.innerHTML = message; + toast.appendChild(msg); + + document.body.appendChild(toast); + + // The message has to be set before getting the coordinates + const coordinates = getToastCoordinates(element, toast, config.position); + toast.style.left = Math.round(coordinates.left) + 'px'; + toast.style.top = Math.round(coordinates.top) + 'px'; + + toast.classList.remove('h5p-toast-disabled'); + const timer = setTimeout(removeToast, config.duration); + + // The toast can also be removed by clicking somewhere + document.addEventListener('click', clickHandler); +}; + +/** + * Copyrights for a H5P Content Library. + * + * @class + */ +H5P.ContentCopyrights = function () { + var label; + var media = []; + var content = []; + + /** + * Set label. + * + * @param {string} newLabel + */ + this.setLabel = function (newLabel) { + label = newLabel; + }; + + /** + * Add sub content. + * + * @param {H5P.MediaCopyright} newMedia + */ + this.addMedia = function (newMedia) { + if (newMedia !== undefined) { + media.push(newMedia); + } + }; + + /** + * Add sub content in front. + * + * @param {H5P.MediaCopyright} newMedia + */ + this.addMediaInFront = function (newMedia) { + if (newMedia !== undefined) { + media.unshift(newMedia); + } + }; + + /** + * Add sub content. + * + * @param {H5P.ContentCopyrights} newContent + */ + this.addContent = function (newContent) { + if (newContent !== undefined) { + content.push(newContent); + } + }; + + /** + * Print content copyright. + * + * @returns {string} HTML. + */ + this.toString = function () { + var html = ''; + + // Add media rights + for (var i = 0; i < media.length; i++) { + html += media[i]; + } + + // Add sub content rights + for (i = 0; i < content.length; i++) { + html += content[i]; + } + + + if (html !== '') { + // Add a label to this info + if (label !== undefined) { + html = '

      ' + label + '

      ' + html; + } + + // Add wrapper + html = '
      ' + html + '
      '; + } + + return html; + }; +}; + +/** + * A ordered list of copyright fields for media. + * + * @class + * @param {Object} copyright + * Copyright information fields. + * @param {Object} [labels] + * Translation of labels. + * @param {Array} [order] + * Order of the fields. + * @param {Object} [extraFields] + * Add extra copyright fields. + */ +H5P.MediaCopyright = function (copyright, labels, order, extraFields) { + var thumbnail; + var list = new H5P.DefinitionList(); + + /** + * Get translated label for field. + * + * @private + * @param {string} fieldName + * @returns {string} + */ + var getLabel = function (fieldName) { + if (labels === undefined || labels[fieldName] === undefined) { + return H5P.t(fieldName); + } + + return labels[fieldName]; + }; + + /** + * Get humanized value for the license field. + * + * @private + * @param {string} license + * @param {string} [version] + * @returns {string} + */ + var humanizeLicense = function (license, version) { + var copyrightLicense = H5P.copyrightLicenses[license]; + + // Build license string + var value = ''; + if (!(license === 'PD' && version)) { + // Add license label + value += (copyrightLicense.hasOwnProperty('label') ? copyrightLicense.label : copyrightLicense); + } + + // Check for version info + var versionInfo; + if (copyrightLicense.versions) { + if (copyrightLicense.versions.default && (!version || !copyrightLicense.versions[version])) { + version = copyrightLicense.versions.default; + } + if (version && copyrightLicense.versions[version]) { + versionInfo = copyrightLicense.versions[version]; + } + } + + if (versionInfo) { + // Add license version + if (value) { + value += ' '; + } + value += (versionInfo.hasOwnProperty('label') ? versionInfo.label : versionInfo); + } + + // Add link if specified + var link; + if (copyrightLicense.hasOwnProperty('link')) { + link = copyrightLicense.link.replace(':version', copyrightLicense.linkVersions ? copyrightLicense.linkVersions[version] : version); + } + else if (versionInfo && copyrightLicense.hasOwnProperty('link')) { + link = versionInfo.link; + } + if (link) { + value = '' + value + ''; + } + + // Generate parenthesis + var parenthesis = ''; + if (license !== 'PD' && license !== 'C') { + parenthesis += license; + } + if (version && version !== 'CC0 1.0') { + if (parenthesis && license !== 'GNU GPL') { + parenthesis += ' '; + } + parenthesis += version; + } + if (parenthesis) { + value += ' (' + parenthesis + ')'; + } + if (license === 'C') { + value += ' ©'; + } + + return value; + }; + + if (copyright !== undefined) { + // Add the extra fields + for (var field in extraFields) { + if (extraFields.hasOwnProperty(field)) { + copyright[field] = extraFields[field]; + } + } + + if (order === undefined) { + // Set default order + order = ['contentType', 'title', 'license', 'author', 'year', 'source', 'licenseExtras', 'changes']; + } + + for (var i = 0; i < order.length; i++) { + var fieldName = order[i]; + if (copyright[fieldName] !== undefined && copyright[fieldName] !== '') { + var humanValue = copyright[fieldName]; + if (fieldName === 'license') { + humanValue = humanizeLicense(copyright.license, copyright.version); + } + if (fieldName === 'source') { + humanValue = (humanValue) ? '' + humanValue + '' : undefined; + } + list.add(new H5P.Field(getLabel(fieldName), humanValue)); + } + } + } + + /** + * Set thumbnail. + * + * @param {H5P.Thumbnail} newThumbnail + */ + this.setThumbnail = function (newThumbnail) { + thumbnail = newThumbnail; + }; + + /** + * Checks if this copyright is undisclosed. + * I.e. only has the license attribute set, and it's undisclosed. + * + * @returns {boolean} + */ + this.undisclosed = function () { + if (list.size() === 1) { + var field = list.get(0); + if (field.getLabel() === getLabel('license') && field.getValue() === humanizeLicense('U')) { + return true; + } + } + return false; + }; + + /** + * Print media copyright. + * + * @returns {string} HTML. + */ + this.toString = function () { + var html = ''; + + if (this.undisclosed()) { + return html; // No need to print a copyright with a single undisclosed license. + } + + if (thumbnail !== undefined) { + html += thumbnail; + } + html += list; + + if (html !== '') { + html = ''; + } + + return html; + }; +}; + +/** + * A simple and elegant class for creating thumbnails of images. + * + * @class + * @param {string} source + * @param {number} width + * @param {number} height + */ +H5P.Thumbnail = function (source, width, height) { + var thumbWidth, thumbHeight = 100; + if (width !== undefined) { + thumbWidth = Math.round(thumbHeight * (width / height)); + } + + /** + * Print thumbnail. + * + * @returns {string} HTML. + */ + this.toString = function () { + return '' + H5P.t('thumbnail') + ''; + }; +}; + +/** + * Simple data structure class for storing a single field. + * + * @class + * @param {string} label + * @param {string} value + */ +H5P.Field = function (label, value) { + /** + * Public. Get field label. + * + * @returns {String} + */ + this.getLabel = function () { + return label; + }; + + /** + * Public. Get field value. + * + * @returns {String} + */ + this.getValue = function () { + return value; + }; +}; + +/** + * Simple class for creating a definition list. + * + * @class + */ +H5P.DefinitionList = function () { + var fields = []; + + /** + * Add field to list. + * + * @param {H5P.Field} field + */ + this.add = function (field) { + fields.push(field); + }; + + /** + * Get Number of fields. + * + * @returns {number} + */ + this.size = function () { + return fields.length; + }; + + /** + * Get field at given index. + * + * @param {number} index + * @returns {H5P.Field} + */ + this.get = function (index) { + return fields[index]; + }; + + /** + * Print definition list. + * + * @returns {string} HTML. + */ + this.toString = function () { + var html = ''; + for (var i = 0; i < fields.length; i++) { + var field = fields[i]; + html += '
      ' + field.getLabel() + '
      ' + field.getValue() + '
      '; + } + return (html === '' ? html : '
      ' + html + '
      '); + }; +}; + +/** + * THIS FUNCTION/CLASS IS DEPRECATED AND WILL BE REMOVED. + * + * Helper object for keeping coordinates in the same format all over. + * + * @deprecated + * Will be removed march 2016. + * @class + * @param {number} x + * @param {number} y + * @param {number} w + * @param {number} h + */ +H5P.Coords = function (x, y, w, h) { + if ( !(this instanceof H5P.Coords) ) + return new H5P.Coords(x, y, w, h); + + /** @member {number} */ + this.x = 0; + /** @member {number} */ + this.y = 0; + /** @member {number} */ + this.w = 1; + /** @member {number} */ + this.h = 1; + + if (typeof(x) === 'object') { + this.x = x.x; + this.y = x.y; + this.w = x.w; + this.h = x.h; + } + else { + if (x !== undefined) { + this.x = x; + } + if (y !== undefined) { + this.y = y; + } + if (w !== undefined) { + this.w = w; + } + if (h !== undefined) { + this.h = h; + } + } + return this; +}; + +/** + * Parse library string into values. + * + * @param {string} library + * library in the format "machineName majorVersion.minorVersion" + * @returns {Object} + * library as an object with machineName, majorVersion and minorVersion properties + * return false if the library parameter is invalid + */ +H5P.libraryFromString = function (library) { + var regExp = /(.+)\s(\d+)\.(\d+)$/g; + var res = regExp.exec(library); + if (res !== null) { + return { + 'machineName': res[1], + 'majorVersion': parseInt(res[2]), + 'minorVersion': parseInt(res[3]) + }; + } + else { + return false; + } +}; + +/** + * Get the path to the library + * + * @param {string} library + * The library identifier in the format "machineName-majorVersion.minorVersion". + * @returns {string} + * The full path to the library. + */ +H5P.getLibraryPath = function (library) { + if (H5PIntegration.urlLibraries !== undefined) { + // This is an override for those implementations that has a different libraries URL, e.g. Moodle + return H5PIntegration.urlLibraries + '/' + library; + } + else { + return H5PIntegration.url + '/libraries/' + library; + } +}; + +/** + * Recursivly clone the given object. + * + * @param {Object|Array} object + * Object to clone. + * @param {boolean} [recursive] + * @returns {Object|Array} + * A clone of object. + */ +H5P.cloneObject = function (object, recursive) { + // TODO: Consider if this needs to be in core. Doesn't $.extend do the same? + var clone = object instanceof Array ? [] : {}; + + for (var i in object) { + if (object.hasOwnProperty(i)) { + if (recursive !== undefined && recursive && typeof object[i] === 'object') { + clone[i] = H5P.cloneObject(object[i], recursive); + } + else { + clone[i] = object[i]; + } + } + } + + return clone; +}; + +/** + * Remove all empty spaces before and after the value. + * + * @param {string} value + * @returns {string} + */ +H5P.trim = function (value) { + return value.replace(/^\s+|\s+$/g, ''); + + // TODO: Only include this or String.trim(). What is best? + // I'm leaning towards implementing the missing ones: http://kangax.github.io/compat-table/es5/ + // So should we make this function deprecated? +}; + +/** + * Check if JavaScript path/key is loaded. + * + * @param {string} path + * @returns {boolean} + */ +H5P.jsLoaded = function (path) { + H5PIntegration.loadedJs = H5PIntegration.loadedJs || []; + return H5P.jQuery.inArray(path, H5PIntegration.loadedJs) !== -1; +}; + +/** + * Check if styles path/key is loaded. + * + * @param {string} path + * @returns {boolean} + */ +H5P.cssLoaded = function (path) { + H5PIntegration.loadedCss = H5PIntegration.loadedCss || []; + return H5P.jQuery.inArray(path, H5PIntegration.loadedCss) !== -1; +}; + +/** + * Shuffle an array in place. + * + * @param {Array} array + * Array to shuffle + * @returns {Array} + * The passed array is returned for chaining. + */ +H5P.shuffleArray = function (array) { + // TODO: Consider if this should be a part of core. I'm guessing very few libraries are going to use it. + if (!(array instanceof Array)) { + return; + } + + var i = array.length, j, tempi, tempj; + if ( i === 0 ) return false; + while ( --i ) { + j = Math.floor( Math.random() * ( i + 1 ) ); + tempi = array[i]; + tempj = array[j]; + array[i] = tempj; + array[j] = tempi; + } + return array; +}; + +/** + * Post finished results for user. + * + * @deprecated + * Do not use this function directly, trigger the finish event instead. + * Will be removed march 2016 + * @param {number} contentId + * Identifies the content + * @param {number} score + * Achieved score/points + * @param {number} maxScore + * The maximum score/points that can be achieved + * @param {number} [time] + * Reported time consumption/usage + */ +H5P.setFinished = function (contentId, score, maxScore, time) { + var validScore = typeof score === 'number' || score instanceof Number; + if (validScore && H5PIntegration.postUserStatistics === true) { + /** + * Return unix timestamp for the given JS Date. + * + * @private + * @param {Date} date + * @returns {Number} + */ + var toUnix = function (date) { + return Math.round(date.getTime() / 1000); + }; + + // Post the results + const data = { + contentId: contentId, + score: score, + maxScore: maxScore, + opened: toUnix(H5P.opened[contentId]), + finished: toUnix(new Date()), + time: time + }; + H5P.jQuery.post(H5PIntegration.ajax.setFinished, data) + .fail(function () { + H5P.offlineRequestQueue.add(H5PIntegration.ajax.setFinished, data); + }); + } +}; + +// Add indexOf to browsers that lack them. (IEs) +if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function (needle) { + for (var i = 0; i < this.length; i++) { + if (this[i] === needle) { + return i; + } + } + return -1; + }; +} + +// Need to define trim() since this is not available on older IEs, +// and trim is used in several libs +if (String.prototype.trim === undefined) { + String.prototype.trim = function () { + return H5P.trim(this); + }; +} + +/** + * Trigger an event on an instance + * + * Helper function that triggers an event if the instance supports event handling + * + * @param {Object} instance + * Instance of H5P content + * @param {string} eventType + * Type of event to trigger + * @param {*} data + * @param {Object} extras + */ +H5P.trigger = function (instance, eventType, data, extras) { + // Try new event system first + if (instance.trigger !== undefined) { + instance.trigger(eventType, data, extras); + } + // Try deprecated event system + else if (instance.$ !== undefined && instance.$.trigger !== undefined) { + instance.$.trigger(eventType); + } +}; + +/** + * Register an event handler + * + * Helper function that registers an event handler for an event type if + * the instance supports event handling + * + * @param {Object} instance + * Instance of H5P content + * @param {string} eventType + * Type of event to listen for + * @param {H5P.EventCallback} handler + * Callback that gets triggered for events of the specified type + */ +H5P.on = function (instance, eventType, handler) { + // Try new event system first + if (instance.on !== undefined) { + instance.on(eventType, handler); + } + // Try deprecated event system + else if (instance.$ !== undefined && instance.$.on !== undefined) { + instance.$.on(eventType, handler); + } +}; + +/** + * Generate random UUID + * + * @returns {string} UUID + */ +H5P.createUUID = function () { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (char) { + var random = Math.random()*16|0, newChar = char === 'x' ? random : (random&0x3|0x8); + return newChar.toString(16); + }); +}; + +/** + * Create title + * + * @param {string} rawTitle + * @param {number} maxLength + * @returns {string} + */ +H5P.createTitle = function (rawTitle, maxLength) { + if (!rawTitle) { + return ''; + } + if (maxLength === undefined) { + maxLength = 60; + } + var title = H5P.jQuery('
      ') + .text( + // Strip tags + rawTitle.replace(/(<([^>]+)>)/ig,"") + // Escape + ).text(); + if (title.length > maxLength) { + title = title.substr(0, maxLength - 3) + '...'; + } + return title; +}; + +// Wrap in privates +(function ($) { + + /** + * Creates ajax requests for inserting, updateing and deleteing + * content user data. + * + * @private + * @param {number} contentId What content to store the data for. + * @param {string} dataType Identifies the set of data for this content. + * @param {string} subContentId Identifies sub content + * @param {function} [done] Callback when ajax is done. + * @param {object} [data] To be stored for future use. + * @param {boolean} [preload=false] Data is loaded when content is loaded. + * @param {boolean} [invalidate=false] Data is invalidated when content changes. + * @param {boolean} [async=true] + */ + function contentUserDataAjax(contentId, dataType, subContentId, done, data, preload, invalidate, async) { + if (H5PIntegration.user === undefined) { + // Not logged in, no use in saving. + done('Not signed in.'); + return; + } + + var options = { + url: H5PIntegration.ajax.contentUserData.replace(':contentId', contentId).replace(':dataType', dataType).replace(':subContentId', subContentId ? subContentId : 0), + dataType: 'json', + async: async === undefined ? true : async + }; + if (data !== undefined) { + options.type = 'POST'; + options.data = { + data: (data === null ? 0 : data), + preload: (preload ? 1 : 0), + invalidate: (invalidate ? 1 : 0) + }; + } + else { + options.type = 'GET'; + } + if (done !== undefined) { + options.error = function (xhr, error) { + done(error); + }; + options.success = function (response) { + if (!response.success) { + done(response.message); + return; + } + + if (response.data === false || response.data === undefined) { + done(); + return; + } + + done(undefined, response.data); + }; + } + + $.ajax(options); + } + + /** + * Get user data for given content. + * + * @param {number} contentId + * What content to get data for. + * @param {string} dataId + * Identifies the set of data for this content. + * @param {function} done + * Callback with error and data parameters. + * @param {string} [subContentId] + * Identifies which data belongs to sub content. + */ + H5P.getUserData = function (contentId, dataId, done, subContentId) { + if (!subContentId) { + subContentId = 0; // Default + } + + H5PIntegration.contents = H5PIntegration.contents || {}; + var content = H5PIntegration.contents['cid-' + contentId] || {}; + var preloadedData = content.contentUserData; + if (preloadedData && preloadedData[subContentId] && preloadedData[subContentId][dataId] !== undefined) { + if (preloadedData[subContentId][dataId] === 'RESET') { + done(undefined, null); + return; + } + try { + done(undefined, JSON.parse(preloadedData[subContentId][dataId])); + } + catch (err) { + done(err); + } + } + else { + contentUserDataAjax(contentId, dataId, subContentId, function (err, data) { + if (err || data === undefined) { + done(err, data); + return; // Error or no data + } + + // Cache in preloaded + if (content.contentUserData === undefined) { + content.contentUserData = preloadedData = {}; + } + if (preloadedData[subContentId] === undefined) { + preloadedData[subContentId] = {}; + } + preloadedData[subContentId][dataId] = data; + + // Done. Try to decode JSON + try { + done(undefined, JSON.parse(data)); + } + catch (e) { + done(e); + } + }); + } + }; + + /** + * Async error handling. + * + * @callback H5P.ErrorCallback + * @param {*} error + */ + + /** + * Set user data for given content. + * + * @param {number} contentId + * What content to get data for. + * @param {string} dataId + * Identifies the set of data for this content. + * @param {Object} data + * The data that is to be stored. + * @param {Object} [extras] + * Extra properties + * @param {string} [extras.subContentId] + * Identifies which data belongs to sub content. + * @param {boolean} [extras.preloaded=true] + * If the data should be loaded when content is loaded. + * @param {boolean} [extras.deleteOnChange=false] + * If the data should be invalidated when the content changes. + * @param {H5P.ErrorCallback} [extras.errorCallback] + * Callback with error as parameters. + * @param {boolean} [extras.async=true] + */ + H5P.setUserData = function (contentId, dataId, data, extras) { + var options = H5P.jQuery.extend(true, {}, { + subContentId: 0, + preloaded: true, + deleteOnChange: false, + async: true + }, extras); + + try { + data = JSON.stringify(data); + } + catch (err) { + if (options.errorCallback) { + options.errorCallback(err); + } + return; // Failed to serialize. + } + + var content = H5PIntegration.contents['cid-' + contentId]; + if (content === undefined) { + content = H5PIntegration.contents['cid-' + contentId] = {}; + } + if (!content.contentUserData) { + content.contentUserData = {}; + } + var preloadedData = content.contentUserData; + if (preloadedData[options.subContentId] === undefined) { + preloadedData[options.subContentId] = {}; + } + if (data === preloadedData[options.subContentId][dataId]) { + return; // No need to save this twice. + } + + preloadedData[options.subContentId][dataId] = data; + contentUserDataAjax(contentId, dataId, options.subContentId, function (error) { + if (options.errorCallback && error) { + options.errorCallback(error); + } + }, data, options.preloaded, options.deleteOnChange, options.async); + }; + + /** + * Delete user data for given content. + * + * @param {number} contentId + * What content to remove data for. + * @param {string} dataId + * Identifies the set of data for this content. + * @param {string} [subContentId] + * Identifies which data belongs to sub content. + */ + H5P.deleteUserData = function (contentId, dataId, subContentId) { + if (!subContentId) { + subContentId = 0; // Default + } + + // Remove from preloaded/cache + var preloadedData = H5PIntegration.contents['cid-' + contentId].contentUserData; + if (preloadedData && preloadedData[subContentId] && preloadedData[subContentId][dataId]) { + delete preloadedData[subContentId][dataId]; + } + + contentUserDataAjax(contentId, dataId, subContentId, undefined, null); + }; + + /** + * Function for getting content for a certain ID + * + * @param {number} contentId + * @return {Object} + */ + H5P.getContentForInstance = function (contentId) { + var key = 'cid-' + contentId; + var exists = H5PIntegration && H5PIntegration.contents && + H5PIntegration.contents[key]; + + return exists ? H5PIntegration.contents[key] : undefined; + }; + + /** + * Prepares the content parameters for storing in the clipboard. + * + * @class + * @param {Object} parameters The parameters for the content to store + * @param {string} [genericProperty] If only part of the parameters are generic, which part + * @param {string} [specificKey] If the parameters are specific, what content type does it fit + * @returns {Object} Ready for the clipboard + */ + H5P.ClipboardItem = function (parameters, genericProperty, specificKey) { + var self = this; + + /** + * Set relative dimensions when params contains a file with a width and a height. + * Very useful to be compatible with wysiwyg editors. + * + * @private + */ + var setDimensionsFromFile = function () { + if (!self.generic) { + return; + } + var params = self.specific[self.generic]; + if (!params.params.file || !params.params.file.width || !params.params.file.height) { + return; + } + + self.width = 20; // % + self.height = (params.params.file.height / params.params.file.width) * self.width; + }; + + if (!genericProperty) { + genericProperty = 'action'; + parameters = { + action: parameters + }; + } + + self.specific = parameters; + + if (genericProperty && parameters[genericProperty]) { + self.generic = genericProperty; + } + if (specificKey) { + self.from = specificKey; + } + + if (window.H5PEditor && H5PEditor.contentId) { + self.contentId = H5PEditor.contentId; + } + + if (!self.specific.width && !self.specific.height) { + setDimensionsFromFile(); + } + }; + + /** + * Store item in the H5P Clipboard. + * + * @param {H5P.ClipboardItem|*} clipboardItem + */ + H5P.clipboardify = function (clipboardItem) { + if (!(clipboardItem instanceof H5P.ClipboardItem)) { + clipboardItem = new H5P.ClipboardItem(clipboardItem); + } + H5P.setClipboard(clipboardItem); + }; + + /** + * Retrieve parsed clipboard data. + * + * @return {Object} + */ + H5P.getClipboard = function () { + return parseClipboard(); + }; + + /** + * Set item in the H5P Clipboard. + * + * @param {H5P.ClipboardItem|object} clipboardItem - Data to be set. + */ + H5P.setClipboard = function (clipboardItem) { + localStorage.setItem('h5pClipboard', JSON.stringify(clipboardItem)); + + // Trigger an event so all 'Paste' buttons may be enabled. + H5P.externalDispatcher.trigger('datainclipboard', {reset: false}); + }; + + /** + * Get config for a library + * + * @param string machineName + * @return Object + */ + H5P.getLibraryConfig = function (machineName) { + var hasConfig = H5PIntegration.libraryConfig && H5PIntegration.libraryConfig[machineName]; + return hasConfig ? H5PIntegration.libraryConfig[machineName] : {}; + }; + + /** + * Get item from the H5P Clipboard. + * + * @private + * @return {Object} + */ + var parseClipboard = function () { + var clipboardData = localStorage.getItem('h5pClipboard'); + if (!clipboardData) { + return; + } + + // Try to parse clipboard dat + try { + clipboardData = JSON.parse(clipboardData); + } + catch (err) { + console.error('Unable to parse JSON from clipboard.', err); + return; + } + + // Update file URLs and reset content Ids + recursiveUpdate(clipboardData.specific, function (path) { + var isTmpFile = (path.substr(-4, 4) === '#tmp'); + if (!isTmpFile && clipboardData.contentId && !path.match(/^https?:\/\//i)) { + // Comes from existing content + + if (H5PEditor.contentId) { + // .. to existing content + return '../' + clipboardData.contentId + '/' + path; + } + else { + // .. to new content + return (H5PEditor.contentRelUrl ? H5PEditor.contentRelUrl : '../content/') + clipboardData.contentId + '/' + path; + } + } + return path; // Will automatically be looked for in tmp folder + }); + + + if (clipboardData.generic) { + // Use reference instead of key + clipboardData.generic = clipboardData.specific[clipboardData.generic]; + } + + return clipboardData; + }; + + /** + * Update file URLs and reset content IDs. + * Useful when copying content. + * + * @private + * @param {object} params Reference + * @param {function} handler Modifies the path to work when pasted + */ + var recursiveUpdate = function (params, handler) { + for (var prop in params) { + if (params.hasOwnProperty(prop) && params[prop] instanceof Object) { + var obj = params[prop]; + if (obj.path !== undefined && obj.mime !== undefined) { + obj.path = handler(obj.path); + } + else { + if (obj.library !== undefined && obj.subContentId !== undefined) { + // Avoid multiple content with same ID + delete obj.subContentId; + } + recursiveUpdate(obj, handler); + } + } + } + }; + + // Init H5P when page is fully loadded + $(document).ready(function () { + + window.addEventListener('storage', function (event) { + // Pick up clipboard changes from other tabs + if (event.key === 'h5pClipboard') { + // Trigger an event so all 'Paste' buttons may be enabled. + H5P.externalDispatcher.trigger('datainclipboard', {reset: event.newValue === null}); + } + }); + + var ccVersions = { + 'default': '4.0', + '4.0': H5P.t('licenseCC40'), + '3.0': H5P.t('licenseCC30'), + '2.5': H5P.t('licenseCC25'), + '2.0': H5P.t('licenseCC20'), + '1.0': H5P.t('licenseCC10'), + }; + + /** + * Maps copyright license codes to their human readable counterpart. + * + * @type {Object} + */ + H5P.copyrightLicenses = { + 'U': H5P.t('licenseU'), + 'CC BY': { + label: H5P.t('licenseCCBY'), + link: 'http://creativecommons.org/licenses/by/:version', + versions: ccVersions + }, + 'CC BY-SA': { + label: H5P.t('licenseCCBYSA'), + link: 'http://creativecommons.org/licenses/by-sa/:version', + versions: ccVersions + }, + 'CC BY-ND': { + label: H5P.t('licenseCCBYND'), + link: 'http://creativecommons.org/licenses/by-nd/:version', + versions: ccVersions + }, + 'CC BY-NC': { + label: H5P.t('licenseCCBYNC'), + link: 'http://creativecommons.org/licenses/by-nc/:version', + versions: ccVersions + }, + 'CC BY-NC-SA': { + label: H5P.t('licenseCCBYNCSA'), + link: 'http://creativecommons.org/licenses/by-nc-sa/:version', + versions: ccVersions + }, + 'CC BY-NC-ND': { + label: H5P.t('licenseCCBYNCND'), + link: 'http://creativecommons.org/licenses/by-nc-nd/:version', + versions: ccVersions + }, + 'CC0 1.0': { + label: H5P.t('licenseCC010'), + link: 'https://creativecommons.org/publicdomain/zero/1.0/' + }, + 'GNU GPL': { + label: H5P.t('licenseGPL'), + link: 'http://www.gnu.org/licenses/gpl-:version-standalone.html', + linkVersions: { + 'v3': '3.0', + 'v2': '2.0', + 'v1': '1.0' + }, + versions: { + 'default': 'v3', + 'v3': H5P.t('licenseV3'), + 'v2': H5P.t('licenseV2'), + 'v1': H5P.t('licenseV1') + } + }, + 'PD': { + label: H5P.t('licensePD'), + versions: { + 'CC0 1.0': { + label: H5P.t('licenseCC010'), + link: 'https://creativecommons.org/publicdomain/zero/1.0/' + }, + 'CC PDM': { + label: H5P.t('licensePDM'), + link: 'https://creativecommons.org/publicdomain/mark/1.0/' + } + } + }, + 'ODC PDDL': 'Public Domain Dedication and Licence', + 'CC PDM': { + label: H5P.t('licensePDM'), + link: 'https://creativecommons.org/publicdomain/mark/1.0/' + }, + 'C': H5P.t('licenseC'), + }; + + /** + * Indicates if H5P is embedded on an external page using iframe. + * @member {boolean} H5P.externalEmbed + */ + + // Relay events to top window. This must be done before H5P.init + // since events may be fired on initialization. + if (H5P.isFramed && H5P.externalEmbed === false) { + H5P.externalDispatcher.on('*', function (event) { + window.parent.H5P.externalDispatcher.trigger.call(this, event); + }); + } + + /** + * Prevent H5P Core from initializing. Must be overriden before document ready. + * @member {boolean} H5P.preventInit + */ + if (!H5P.preventInit) { + // Note that this start script has to be an external resource for it to + // load in correct order in IE9. + H5P.init(document.body); + } + + if (H5PIntegration.saveFreq !== false) { + // When was the last state stored + var lastStoredOn = 0; + // Store the current state of the H5P when leaving the page. + var storeCurrentState = function () { + // Make sure at least 250 ms has passed since last save + var currentTime = new Date().getTime(); + if (currentTime - lastStoredOn > 250) { + lastStoredOn = currentTime; + for (var i = 0; i < H5P.instances.length; i++) { + var instance = H5P.instances[i]; + if (instance.getCurrentState instanceof Function || + typeof instance.getCurrentState === 'function') { + var state = instance.getCurrentState(); + if (state !== undefined) { + // Async is not used to prevent the request from being cancelled. + H5P.setUserData(instance.contentId, 'state', state, {deleteOnChange: true, async: false}); + } + } + } + } + }; + // iPad does not support beforeunload, therefore using unload + H5P.$window.one('beforeunload unload', function () { + // Only want to do this once + H5P.$window.off('pagehide beforeunload unload'); + storeCurrentState(); + }); + // pagehide is used on iPad when tabs are switched + H5P.$window.on('pagehide', storeCurrentState); + } + }); + +})(H5P.jQuery); diff --git a/lib/h5p/js/jquery.js b/lib/h5p/js/jquery.js new file mode 100644 index 00000000000..a05d5568b9c --- /dev/null +++ b/lib/h5p/js/jquery.js @@ -0,0 +1,20 @@ +/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license +*/(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML="
      a",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="
      t
      ",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="
      ",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; +return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="
      ",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&>(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/
      ","
      "],tr:[2,"","
      "],col:[2,"","
      "],td:[3,"","
      "],_default:b.support.htmlSerialize?[0,"",""]:[1,"X
      ","
      "]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?""!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) +}b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b(" \ No newline at end of file diff --git a/h5p/templates/h5perror.mustache b/h5p/templates/h5perror.mustache new file mode 100644 index 00000000000..9c0d9d9c313 --- /dev/null +++ b/h5p/templates/h5perror.mustache @@ -0,0 +1,51 @@ +{{! + 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 . +}} +{{! + @template core_message/h5perror + + This template will render the embed code shown in the H5P content embed popup. + + Variables required for this template: + * h5picon - The icon + * message - The error message to display. + + Example context (json): + { + "embedurl": "http://example.com/h5p/embed.php?url=testurl" + } + +}} + +
      +
      +
      + {{#str}}h5p, core_h5p{{/str}} +
      +
      +
      + {{#exception}} + + {{/exception}} + {{#error}} + + {{/error}} +
      +
      \ No newline at end of file diff --git a/h5p/templates/h5piframe.mustache b/h5p/templates/h5piframe.mustache new file mode 100644 index 00000000000..66403561a10 --- /dev/null +++ b/h5p/templates/h5piframe.mustache @@ -0,0 +1,35 @@ +{{! + 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 . +}} +{{! + @template core_h5p/h5piframe + + This template will render an iframe for h5p content. + + Variables required for this template: + * h5pid - The database id for the H5P content + + Example context (json): + { + "h5pid": 123 + } + +}} +
      + +
      \ No newline at end of file diff --git a/h5p/templates/h5presize.mustache b/h5p/templates/h5presize.mustache new file mode 100644 index 00000000000..4400b608c0b --- /dev/null +++ b/h5p/templates/h5presize.mustache @@ -0,0 +1,32 @@ +{{! + 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 . +}} +{{! + @template core_message/h5presize + + This template will render the resize JS code. + + Variables required for this template: + * resizeurl - The database id for the H5P content + + Example context (json): + { + "resizeurl": "http://example.com/lib/h5p/js/h5p-resizer.js" + } + +}} + + \ No newline at end of file diff --git a/lang/en/h5p.php b/lang/en/h5p.php index e616ef56f88..f0866ec170a 100644 --- a/lang/en/h5p.php +++ b/lang/en/h5p.php @@ -20,5 +20,5 @@ * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - $string['privacy:metadata'] = 'H5P subsystem does not store any personal data.'; +$string['h5pfilenotfound'] = 'H5P file not found'; \ No newline at end of file From 09d8143d843cd5cb48fb970fb787d6ab61c01c91 Mon Sep 17 00:00:00 2001 From: Mihail Geshoski Date: Thu, 26 Sep 2019 16:58:33 +0800 Subject: [PATCH 06/22] MDL-66609 core_h5p: Framework interface implementation --- h5p/classes/factory.php | 132 +++ h5p/classes/framework.php | 1625 +++++++++++++++++++++++++++++++++++++ 2 files changed, 1757 insertions(+) create mode 100644 h5p/classes/factory.php create mode 100644 h5p/classes/framework.php diff --git a/h5p/classes/factory.php b/h5p/classes/factory.php new file mode 100644 index 00000000000..f4edb4dd519 --- /dev/null +++ b/h5p/classes/factory.php @@ -0,0 +1,132 @@ +. + +/** + * H5P factory class. + * This class is used to decouple the construction of H5P related objects. + * + * @package core_h5p + * @copyright 2019 Mihail Geshoski + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace core_h5p; + +defined('MOODLE_INTERNAL') || die(); + +use \core_h5p\framework as framework; +use \core_h5p\core as core; +use \H5PStorage as storage; +use \H5PValidator as validator; +use \H5PContentValidator as content_validator; + +/** + * H5P factory class. + * This class is used to decouple the construction of H5P related objects. + * + * @package core_h5p + * @copyright 2019 Mihail Geshoski + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class factory { + + /** @var \core_h5p\core The Moodle H5PCore implementation */ + protected $core; + + /** @var \core_h5p\framework The Moodle H5PFramework implementation */ + protected $framework; + + /** @var \core_h5p\file_storage The Moodle H5PStorage implementation */ + protected $storage; + + /** @var validator The Moodle H5PValidator implementation */ + protected $validator; + + /** @var content_validator The Moodle H5PContentValidator implementation */ + protected $content_validator; + + /** + * Returns an instance of the \core_h5p\framework class. + * + * @return \core_h5p\framework + */ + public function get_framework(): framework { + if (null === $this->framework) { + $this->framework = new framework(); + } + + return $this->framework; + } + + /** + * Returns an instance of the \core_h5p\core class. + * + * @return \core_h5p\core + */ + public function get_core(): core { + if (null === $this->core) { + $fs = new \core_h5p\file_storage(); + $language = \core_h5p\framework::get_language(); + $context = \context_system::instance(); + + $url = \moodle_url::make_pluginfile_url($context->id, 'core_h5p', '', null, + '', '')->out(); + + $this->core = new core($this->get_framework(), $fs, $url, $language, true); + } + + return $this->core; + } + + /** + * Returns an instance of the \H5PStorage class. + * + * @return \H5PStorage + */ + public function get_storage(): storage { + if (null === $this->storage) { + $this->storage = new storage($this->get_framework(), $this->get_core()); + } + + return $this->storage; + } + + /** + * Returns an instance of the \H5PValidator class. + * + * @return \H5PValidator + */ + public function get_validator(): validator { + if (null === $this->validator) { + $this->validator = new validator($this->get_framework(), $this->get_core()); + } + + return $this->validator; + } + + /** + * Returns an instance of the \H5PContentValidator class. + * + * @return \H5PContentValidator + */ + public function get_content_validator(): content_validator { + if (null === $this->content_validator) { + $this->content_validator = new content_validator($this->get_framework(), $this->get_core()); + } + + return $this->content_validator; + } +} diff --git a/h5p/classes/framework.php b/h5p/classes/framework.php new file mode 100644 index 00000000000..54d15ff1e27 --- /dev/null +++ b/h5p/classes/framework.php @@ -0,0 +1,1625 @@ +. + +/** + * \core_h5p\framework class + * + * @package core_h5p + * @copyright 2019 Mihail Geshoski + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace core_h5p; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Moodle's implementation of the H5P framework interface. + * + * @package core_h5p + * @copyright 2019 Mihail Geshoski + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class framework implements \H5PFrameworkInterface { + + /** @var string The path to the last uploaded h5p */ + private $lastuploadedfolder; + + /** @var string The path to the last uploaded h5p file */ + private $lastuploadedfile; + + /** + * Returns info for the current platform. + * Implements getPlatformInfo. + * + * @return array An associative array containing: + * - name: The name of the platform, for instance "Moodle" + * - version: The version of the platform, for instance "3.8" + * - h5pVersion: The version of the H5P component + */ + public function getPlatformInfo() { + global $CFG; + + return array( + 'name' => 'Moodle', + 'version' => $CFG->version, + 'h5pVersion' => $CFG->version, + ); + } + + /** + * Fetches a file from a remote server using HTTP GET. + * Implements fetchExternalData. + * + * @param string $url Where you want to get or send data + * @param array $data Data to post to the URL + * @param bool $blocking Set to 'FALSE' to instantly time out (fire and forget) + * @param string $stream Path to where the file should be saved + * @return string The content (response body). NULL if something went wrong + */ + public function fetchExternalData($url, $data = null, $blocking = true, $stream = null) { + + if ($stream === null) { + // Download file. + set_time_limit(0); + + // Get the extension of the remote file. + $parsedurl = parse_url($url); + $ext = pathinfo($parsedurl['path'], PATHINFO_EXTENSION); + + // Generate local tmp file path. + $fs = new \core_h5p\file_storage(); + $localfolder = $fs->getTmpPath(); + $stream = $localfolder; + + // Add the remote file's extension to the temp file. + if ($ext) { + $stream .= '.' . $ext; + } + + $this->getUploadedH5pFolderPath($localfolder); + $this->getUploadedH5pPath($stream); + } + + $response = download_file_content($url, null, $data, true, 300, 20, + false, $stream); + + if (empty($response->error)) { + return $response->results; + } else { + $this->setErrorMessage($response->error, 'failed-fetching-external-data'); + } + } + + /** + * Set the tutorial URL for a library. All versions of the library is set. + * Implements setLibraryTutorialUrl. + * + * @param string $libraryname + * @param string $url + */ + public function setLibraryTutorialUrl($libraryname, $url) { + // Tutorial url is currently not being used or stored in libraries. + } + + /** + * Set an error message. + * Implements setErrorMessage. + * + * @param string $message The error message + * @param string $code An optional code + */ + public function setErrorMessage($message, $code = null) { + if ($message !== null) { + $this->set_message('error', $message, $code); + } + } + + /** + * Set an info message. + * Implements setInfoMessage. + * + * @param string $message The info message + */ + public function setInfoMessage($message) { + if ($message !== null) { + $this->set_message('info', $message); + } + } + + /** + * Return messages. + * Implements getMessages. + * + * @param string $type The message type, e.g. 'info' or 'error' + * @return string[] Array of messages + */ + public function getMessages($type) { + global $SESSION; + + // Return and reset messages. + $messages = array(); + if (isset($SESSION->core_h5p_messages[$type])) { + $messages = $SESSION->core_h5p_messages[$type]; + unset($SESSION->core_h5p_messages[$type]); + if (empty($SESSION->core_h5p_messages)) { + unset($SESSION->core_h5p_messages); + } + } + + return $messages; + } + + /** + * Translation function. + * The purpose of this function is to map the strings used in the core h5p methods + * and replace them with the translated ones. If a translation for a particular string + * is not available, the default message (key) will be returned. + * Implements t. + * + * @param string $message The english string to be translated + * @param array $replacements An associative array of replacements to make after translation + * @return string Translated string or the english string if a translation is not available + */ + public function t($message, $replacements = array()) { + + // Create mapping. + $translationsmap = [ + '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', + 'The main h5p.json file is not valid' => 'nojson', + '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', + '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', + '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', + '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 (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', + 'Date' => 'date', + 'Changed by' => 'changedby', + 'Description of change' => 'changedescription', + 'Photo cropped, text changed, etc.' => 'changeplaceholder', + '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', + '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', + 'A problem with the server write access was detected. Please make sure that your server can write to your data folder.' => 'nowriteaccess', + 'H5P hub communication has been disabled because one or more H5P requirements failed.' => 'hubcommunicationdisabled', + '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', + 'When you have revised your server setup you may re-enable H5P hub communication in H5P Settings.' => 'reviseserversetupandretry', + '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', + 'Your PHP max post size is quite small. With your current setup, you may not upload files larger than {$a->%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 PHP max upload size is bigger than your max post size. This is known to cause issues in some installations.' => 'uploadsizelargerthanpostsize', + 'Your PHP max upload size is quite small. With your current setup, you may not upload files larger than {$a->%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 version does not support ZipArchive.' => 'noziparchive', + 'Your PHP version is outdated. H5P requires version 5.2 to function properly. Version 5.6 or later is recommended.' => 'oldphpversion', + 'Your server does not have SSL enabled. SSL should be enabled to ensure a secure connection with the H5P hub.' => 'sslnotenabled', + 'Your site was successfully registered with the H5P Hub.' => 'successfullyregisteredwithhub' + ]; + + if (isset($translationsmap[$message])) { + return get_string($translationsmap[$message], 'core_h5p', $replacements); + } + + debugging("String translation cannot be found. Please add a string definition for '" . + $message . "' in the core_h5p component.", DEBUG_DEVELOPER); + + return $message; + } + + /** + * Get URL to file in the specifimake_pluginfile_urlc library. + * Implements getLibraryFileUrl. + * + * @param string $libraryfoldername The name or path of the library's folder + * @param string $filename The file name + * @return string URL to file + */ + public function getLibraryFileUrl($libraryfoldername, $filename) { + global $DB; + + // Remove unnecessary slashes (first and last, if present) from the path to the folder + // of the library file. + $libraryfilepath = trim($libraryfoldername, '/'); + + // Get the folder name of the library from the path. + // The first element should represent the folder name of the library. + $libfoldername = explode('/', $libraryfilepath)[0]; + + $factory = new \core_h5p\factory(); + $core = $factory->get_core(); + + // The provided folder name of the library must have a valid format (can be parsed). + // The folder name is parsed with a purpose of getting the library related information + // such as 'machineName', 'majorVersion' and 'minorVersion'. + // This information is later used to retrieve the library ID. + if (!$libdata = $core->libraryFromString($libfoldername, true)) { + debugging('The provided string value "' . $libfoldername . + '" is not a valid name for a library folder.', DEBUG_DEVELOPER); + + return; + } + + $params = array( + 'machinename' => $libdata['machineName'], + 'majorversion' => $libdata['majorVersion'], + 'minorversion' => $libdata['minorVersion'] + ); + + $libraries = $DB->get_records('h5p_libraries', $params, 'patchversion DESC', 'id', + 0, 1); + + if (!$library = reset($libraries)) { + debugging('The library "' . $libfoldername . '" does not exist.', DEBUG_DEVELOPER); + + return; + } + + $context = \context_system::instance(); + + return \moodle_url::make_pluginfile_url($context->id, 'core_h5p', 'libraries', + $library->id, '/' . $libraryfilepath . '/', $filename)->out(); + } + + /** + * Get the Path to the last uploaded h5p. + * Implements getUploadedH5PFolderPath. + * + * @param string $setpath The path to the folder of the last uploaded h5p + * @return string Path to the folder where the last uploaded h5p for this session is located + */ + public function getUploadedH5pFolderPath($setpath = null) { + if ($setpath !== null) { + $this->lastuploadedfolder = $setpath; + } + + if (!isset($this->lastuploadedfolder)) { + throw new \coding_exception('Using getUploadedH5pFolderPath() before path is set'); + } + + return $this->lastuploadedfolder; + } + + /** + * Get the path to the last uploaded h5p file. + * Implements getUploadedH5PPath. + * + * @param string $setpath The path to the last uploaded h5p + * @return string Path to the last uploaded h5p + */ + public function getUploadedH5pPath($setpath = null) { + if ($setpath !== null) { + $this->lastuploadedfile = $setpath; + } + + if (!isset($this->lastuploadedfile)) { + throw new \coding_exception('Using getUploadedH5pPath() before path is set'); + } + + return $this->lastuploadedfile; + } + + /** + * Load addon libraries. + * Implements loadAddons. + * + * @return array The array containing the addon libraries + */ + public function loadAddons() { + global $DB; + + $addons = array(); + + $records = $DB->get_records_sql( + "SELECT l1.id AS library_id, + l1.machinename AS machine_name, + l1.majorversion AS major_version, + l1.minorversion AS minor_version, + l1.patchversion AS patch_version, + l1.addto AS add_to, + l1.preloadedjs AS preloaded_js, + l1.preloadedcss AS preloaded_css + FROM {h5p_libraries} l1 + LEFT JOIN {h5p_libraries} l2 + ON l1.machinename = l2.machinename + AND (l1.majorversion < l2.majorversion + OR (l1.majorversion = l2.majorversion + AND l1.minorversion < l2.minorversion)) + WHERE l1.addto IS NOT NULL + AND l2.machinename IS NULL"); + + // NOTE: These are treated as library objects but are missing the following properties: + // title, droplibrarycss, fullscreen, runnable, semantics. + + // Extract num from records. + foreach ($records as $addon) { + $addons[] = \H5PCore::snakeToCamel($addon); + } + + return $addons; + } + + /** + * Load config for libraries. + * Implements getLibraryConfig. + * + * @param array|null $libraries List of libraries + * @return array|null The library config if it exists, null otherwise + */ + public function getLibraryConfig($libraries = null) { + global $CFG; + return isset($CFG->core_h5p_library_config) ? $CFG->core_h5p_library_config : null; + } + + /** + * Get a list of the current installed libraries. + * Implements loadLibraries. + * + * @return array Associative array containing one entry per machine name. + * For each machineName there is a list of libraries(with different versions). + */ + public function loadLibraries() { + global $DB; + + $results = $DB->get_records('h5p_libraries', [], 'title ASC, majorversion ASC, minorversion ASC', + 'machinename AS machine_name, majorversion AS major_version, minorversion AS minor_version, + patchversion AS patch_version'); + + $libraries = array(); + foreach ($results as $library) { + $libraries[$library->machine_name][] = $library; + } + + return $libraries; + } + + /** + * Returns the URL to the library admin page. + * Implements getAdminUrl. + * + * @return string URL to admin page + */ + public function getAdminUrl() { + // Not supported. + } + + /** + * Return the library's ID. + * Implements getLibraryId. + * + * @param string $machinename The librarys machine name + * @param string $majorversion Major version number for library (optional) + * @param string $minorversion Minor version number for library (optional) + * @return int|bool Identifier, or false if non-existent + */ + public function getLibraryId($machinename, $majorversion = null, $minorversion = null) { + global $DB; + + $params = array( + 'machinename' => $machinename + ); + + if ($majorversion !== null) { + $params['majorversion'] = $majorversion; + } + + if ($minorversion !== null) { + $params['minorversion'] = $minorversion; + } + + $libraries = $DB->get_records('h5p_libraries', $params, + 'majorversion DESC, minorversion DESC, patchversion DESC', 'id', 0, 1); + + // Get the latest version which matches the input parameters. + if ($libraries) { + $library = reset($libraries); + return $library->id ?? false; + } + + return false; + } + + /** + * Get file extension whitelist. + * Implements getWhitelist. + * + * The default extension list is part of h5p, but admins should be allowed to modify it. + * + * @param boolean $islibrary TRUE if this is the whitelist for a library. FALSE if it is the whitelist + * for the content folder we are getting. + * @param string $defaultcontentwhitelist A string of file extensions separated by whitespace. + * @param string $defaultlibrarywhitelist A string of file extensions separated by whitespace. + * @return string A string containing the allowed file extensions separated by whitespace. + */ + public function getWhitelist($islibrary, $defaultcontentwhitelist, $defaultlibrarywhitelist) { + return $defaultcontentwhitelist . ($islibrary ? ' ' . $defaultlibrarywhitelist : ''); + } + + /** + * Is the library a patched version of an existing library? + * Implements isPatchedLibrary. + * + * @param array $library An associative array containing: + * - machineName: The library machine name + * - majorVersion: The librarys major version + * - minorVersion: The librarys minor version + * - patchVersion: The librarys patch version + * @return boolean TRUE if the library is a patched version of an existing library FALSE otherwise + */ + public function isPatchedLibrary($library) { + global $DB; + + $sql = "SELECT id + FROM {h5p_libraries} + WHERE machinename = :machinename + AND majorversion = :majorversion + AND minorversion = :minorversion + AND patchversion < :patchversion"; + + $library = $DB->get_records_sql( + $sql, + array( + 'machinename' => $library['machineName'], + 'majorversion' => $library['majorVersion'], + 'minorversion' => $library['minorVersion'], + 'patchversion' => $library['patchVersion'] + ), + 0, + 1 + ); + + return !empty($library); + } + + /** + * Is H5P in development mode? + * Implements isInDevMode. + * + * @return boolean TRUE if H5P development mode is active FALSE otherwise + */ + public function isInDevMode() { + return false; // Not supported (Files in moodle not editable). + } + + /** + * Is the current user allowed to update libraries? + * Implements mayUpdateLibraries. + * + * @return boolean TRUE if the user is allowed to update libraries, + * FALSE if the user is not allowed to update libraries. + */ + public function mayUpdateLibraries() { + // Currently, capabilities are not being set/used, so everyone can update libraries. + return true; + } + + /** + * Store data about a library. + * Implements saveLibraryData. + * + * Also fills in the libraryId in the libraryData object if the object is new. + * + * @param array $librarydata Associative array containing: + * - libraryId: The id of the library if it is an existing library + * - title: The library's name + * - machineName: The library machineName + * - majorVersion: The library's majorVersion + * - minorVersion: The library's minorVersion + * - patchVersion: The library's patchVersion + * - runnable: 1 if the library is a content type, 0 otherwise + * - fullscreen(optional): 1 if the library supports fullscreen, 0 otherwise + * - embedtypes: list of supported embed types + * - preloadedJs(optional): list of associative arrays containing: + * - path: path to a js file relative to the library root folder + * - preloadedCss(optional): list of associative arrays containing: + * - path: path to css file relative to the library root folder + * - dropLibraryCss(optional): list of associative arrays containing: + * - machineName: machine name for the librarys that are to drop their css + * - semantics(optional): Json describing the content structure for the library + * @param bool $new Whether it is a new or existing library. + */ + public function saveLibraryData(&$librarydata, $new = true) { + global $DB; + + // Some special properties needs some checking and converting before they can be saved. + $preloadedjs = $this->library_parameter_values_to_csv($librarydata, 'preloadedJs', 'path'); + $preloadedcss = $this->library_parameter_values_to_csv($librarydata, 'preloadedCss', 'path'); + $droplibrarycss = $this->library_parameter_values_to_csv($librarydata, 'dropLibraryCss', 'machineName'); + + if (!isset($librarydata['semantics'])) { + $librarydata['semantics'] = ''; + } + if (!isset($librarydata['fullscreen'])) { + $librarydata['fullscreen'] = 0; + } + $embedtypes = ''; + if (isset($librarydata['embedTypes'])) { + $embedtypes = implode(', ', $librarydata['embedTypes']); + } + + $library = (object) array( + 'title' => $librarydata['title'], + 'machinename' => $librarydata['machineName'], + 'majorversion' => $librarydata['majorVersion'], + 'minorversion' => $librarydata['minorVersion'], + 'patchversion' => $librarydata['patchVersion'], + 'runnable' => $librarydata['runnable'], + 'fullscreen' => $librarydata['fullscreen'], + 'embedtypes' => $embedtypes, + 'preloadedjs' => $preloadedjs, + 'preloadedcss' => $preloadedcss, + 'droplibrarycss' => $droplibrarycss, + 'semantics' => $librarydata['semantics'], + 'addto' => isset($librarydata['addTo']) ? json_encode($librarydata['addTo']) : null, + ); + + if ($new) { + // Create new library and keep track of id. + $library->id = $DB->insert_record('h5p_libraries', $library); + $librarydata['libraryId'] = $library->id; + } else { + // Update library data. + $library->id = $librarydata['libraryId']; + // Save library data. + $DB->update_record('h5p_libraries', $library); + // Remove old dependencies. + $this->deleteLibraryDependencies($librarydata['libraryId']); + } + } + + /** + * Insert new content. + * Implements insertContent. + * + * @param array $content An associative array containing: + * - id: The content id + * - params: The content in json format + * - library: An associative array containing: + * - libraryId: The id of the main library for this content + * - disable: H5P Button display options + * - pathnamehash: The pathnamehash linking the record with the entry in the mdl_files table + * - contenthash: The contenthash linking the record with the entry in the mdl_files table + * @param int $contentmainid Main id for the content if this is a system that supports versions + * @return int The ID of the newly inserted content + */ + public function insertContent($content, $contentmainid = null) { + return $this->updateContent($content); + } + + /** + * Update old content or insert new content. + * Implements updateContent. + * + * @param array $content An associative array containing: + * - id: The content id + * - params: The content in json format + * - library: An associative array containing: + * - libraryId: The id of the main library for this content + * - disable: H5P Button display options + * - pathnamehash: The pathnamehash linking the record with the entry in the mdl_files table + * - contenthash: The contenthash linking the record with the entry in the mdl_files table + * @param int $contentmainid Main id for the content if this is a system that supports versions + * @return int The ID of the newly inserted or updated content + */ + public function updateContent($content, $contentmainid = null) { + global $DB; + + if (!isset($content['pathnamehash'])) { + $content['pathnamehash'] = ''; + } + + if (!isset($content['contenthash'])) { + $content['contenthash'] = ''; + } + + $data = array( + 'jsoncontent' => $content['params'], + 'displayoptions' => $content['disable'], + 'mainlibraryid' => $content['library']['libraryId'], + 'timemodified' => time(), + 'filtered' => null, + 'pathnamehash' => $content['pathnamehash'], + 'contenthash' => $content['contenthash'] + ); + + if (!isset($content['id'])) { + $data['timecreated'] = $data['timemodified']; + $id = $DB->insert_record('h5p', $data); + } else { + $id = $data['id'] = $content['id']; + $DB->update_record('h5p', $data); + } + + return $id; + } + + /** + * Resets marked user data for the given content. + * Implements resetContentUserData. + * + * @param int $contentid The h5p content id + */ + public function resetContentUserData($contentid) { + // Currently, we do not store user data for a content. + } + + /** + * Save what libraries a library is depending on. + * Implements saveLibraryDependencies. + * + * @param int $libraryid Library Id for the library we're saving dependencies for + * @param array $dependencies List of dependencies as associative arrays containing: + * - machineName: The library machineName + * - majorVersion: The library's majorVersion + * - minorVersion: The library's minorVersion + * @param string $dependencytype The type of dependency + */ + public function saveLibraryDependencies($libraryid, $dependencies, $dependencytype) { + global $DB; + + foreach ($dependencies as $dependency) { + // Find dependency library. + $dependencylibrary = $DB->get_record('h5p_libraries', + array( + 'machinename' => $dependency['machineName'], + 'majorversion' => $dependency['majorVersion'], + 'minorversion' => $dependency['minorVersion'] + ) + ); + + // Create relation. + $DB->insert_record('h5p_library_dependencies', array( + 'libraryid' => $libraryid, + 'requiredlibraryid' => $dependencylibrary->id, + 'dependencytype' => $dependencytype + )); + } + } + + /** + * Give an H5P the same library dependencies as a given H5P. + * Implements copyLibraryUsage. + * + * @param int $contentid Id identifying the content + * @param int $copyfromid Id identifying the content to be copied + * @param int $contentmainid Main id for the content, typically used in frameworks + */ + public function copyLibraryUsage($contentid, $copyfromid, $contentmainid = null) { + // Currently not being called. + } + + /** + * Deletes content data. + * Implements deleteContentData. + * + * @param int $contentid Id identifying the content + */ + public function deleteContentData($contentid) { + global $DB; + + // Remove content. + $DB->delete_records('h5p', array('id' => $contentid)); + + // Remove content library dependencies. + $this->deleteLibraryUsage($contentid); + } + + /** + * Delete what libraries a content item is using. + * Implements deleteLibraryUsage. + * + * @param int $contentid Content Id of the content we'll be deleting library usage for + */ + public function deleteLibraryUsage($contentid) { + global $DB; + + $DB->delete_records('h5p_contents_libraries', array('h5pid' => $contentid)); + } + + /** + * Saves what libraries the content uses. + * Implements saveLibraryUsage. + * + * @param int $contentid Id identifying the content + * @param array $librariesinuse List of libraries the content uses + */ + 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'])); + } + } + + foreach ($librariesinuse as $dependency) { + $dropcss = in_array($dependency['library']['machineName'], $droplibrarycsslist) ? 1 : 0; + $DB->insert_record('h5p_contents_libraries', array( + 'h5pid' => $contentid, + 'libraryid' => $dependency['library']['libraryId'], + 'dependencytype' => $dependency['type'], + 'dropcss' => $dropcss, + 'weight' => $dependency['weight'] + )); + } + } + + /** + * Get number of content/nodes using a library, and the number of dependencies to other libraries. + * Implements getLibraryUsage. + * + * @param int $id Library identifier + * @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 + */ + public function getLibraryUsage($id, $skipcontent = false) { + global $DB; + + if ($skipcontent) { + $content = -1; + } else { + $sql = "SELECT COUNT(distinct c.id) + FROM {h5p_libraries} l + JOIN {h5p_contents_libraries} cl ON l.id = cl.libraryid + JOIN {h5p} c ON cl.h5pid = c.id + WHERE l.id = :libraryid"; + + $sqlargs = array( + 'libraryid' => $id + ); + + $content = $DB->count_records_sql($sql, $sqlargs); + } + + $libraries = $DB->count_records('h5p_library_dependencies', ['requiredlibraryid' => $id]); + + return array( + 'content' => $content, + 'libraries' => $libraries, + ); + } + + /** + * Loads a library. + * Implements loadLibrary. + * + * @param string $machinename The library's machine name + * @param int $majorversion The library's major version + * @param int $minorversion The library's minor version + * @return array|bool Returns FALSE if the library does not exist + * Otherwise an associative array containing: + * - libraryId: The id of the library if it is an existing library, + * - title: The library's name, + * - machineName: The library machineName + * - majorVersion: The library's majorVersion + * - minorVersion: The library's minorVersion + * - patchVersion: The library's patchVersion + * - runnable: 1 if the library is a content type, 0 otherwise + * - fullscreen: 1 if the library supports fullscreen, 0 otherwise + * - embedTypes: list of supported embed types + * - preloadedJs: comma separated string with js file paths + * - preloadedCss: comma separated sting with css file paths + * - dropLibraryCss: list of associative arrays containing: + * - machineName: machine name for the librarys that are to drop their css + * - semantics: Json describing the content structure for the library + * - preloadedDependencies(optional): list of associative arrays containing: + * - machineName: Machine name for a library this library is depending on + * - majorVersion: Major version for a library this library is depending on + * - minorVersion: Minor for a library this library is depending on + * - dynamicDependencies(optional): list of associative arrays containing: + * - machineName: Machine name for a library this library is depending on + * - majorVersion: Major version for a library this library is depending on + * - minorVersion: Minor for a library this library is depending on + */ + public function loadLibrary($machinename, $majorversion, $minorversion) { + global $DB; + + $library = $DB->get_record('h5p_libraries', array( + 'machinename' => $machinename, + 'majorversion' => $majorversion, + 'minorversion' => $minorversion + )); + + if (!$library) { + return false; + } + + $librarydata = array( + 'libraryId' => $library->id, + 'title' => $library->title, + 'machineName' => $library->machinename, + 'majorVersion' => $library->majorversion, + 'minorVersion' => $library->minorversion, + 'patchVersion' => $library->patchversion, + 'runnable' => $library->runnable, + 'fullscreen' => $library->fullscreen, + 'embedTypes' => $library->embedtypes, + 'preloadedJs' => $library->preloadedjs, + 'preloadedCss' => $library->preloadedcss, + 'dropLibraryCss' => $library->droplibrarycss, + 'semantics' => $library->semantics + ); + + $sql = 'SELECT hl.id, hl.machinename, hl.majorversion, hl.minorversion, hll.dependencytype + FROM {h5p_library_dependencies} hll + JOIN {h5p_libraries} hl ON hll.requiredlibraryid = hl.id + WHERE hll.libraryid = :libraryid + ORDER BY hl.id ASC'; + + $sqlargs = array( + 'libraryid' => $library->id + ); + + $dependencies = $DB->get_records_sql($sql, $sqlargs); + + foreach ($dependencies as $dependency) { + $librarydata[$dependency->dependencytype . 'Dependencies'][] = array( + 'machineName' => $dependency->machinename, + 'majorVersion' => $dependency->majorversion, + 'minorVersion' => $dependency->minorversion + ); + } + + return $librarydata; + } + + /** + * Loads library semantics. + * Implements loadLibrarySemantics. + * + * @param string $name Machine name for the library + * @param int $majorversion The library's major version + * @param int $minorversion The library's minor version + * @return string The library's semantics as json + */ + public function loadLibrarySemantics($name, $majorversion, $minorversion) { + global $DB; + + $semantics = $DB->get_field('h5p_libraries', 'semantics', + array( + 'machinename' => $name, + 'majorversion' => $majorversion, + 'minorversion' => $minorversion + ) + ); + + return ($semantics === false ? null : $semantics); + } + + /** + * Makes it possible to alter the semantics, adding custom fields, etc. + * Implements alterLibrarySemantics. + * + * @param array $semantics Associative array representing the semantics + * @param string $name The library's machine name + * @param int $majorversion The library's major version + * @param int $minorversion The library's minor version + */ + public function alterLibrarySemantics(&$semantics, $name, $majorversion, $minorversion) { + global $DB; + + $library = $DB->get_record('h5p_libraries', + array( + 'machinename' => $name, + 'majorversion' => $majorversion, + 'minorversion' => $minorversion, + ) + ); + + if ($library) { + $library->semantics = json_encode($semantics); + $DB->update_record('h5p_libraries', $library); + } + } + + /** + * Delete all dependencies belonging to given library. + * Implements deleteLibraryDependencies. + * + * @param int $libraryid Library identifier + */ + public function deleteLibraryDependencies($libraryid) { + global $DB; + + $DB->delete_records('h5p_library_dependencies', array('libraryid' => $libraryid)); + } + + /** + * Start an atomic operation against the dependency storage. + * Implements lockDependencyStorage. + */ + public function lockDependencyStorage() { + // Library development mode not supported. + } + + /** + * Start an atomic operation against the dependency storage. + * Implements unlockDependencyStorage. + */ + public function unlockDependencyStorage() { + // Library development mode not supported. + } + + /** + * Delete a library from database and file system. + * Implements deleteLibrary. + * + * @param stdClass $library Library object with id, name, major version and minor version + */ + public function deleteLibrary($library) { + global $DB; + + $fs = new \core_h5p\file_storage(); + // Delete the library from the file system. + $fs->delete_library(array('libraryId' => $library->id)); + + // Remove library data from database. + $DB->delete_records('h5p_library_dependencies', array('libraryid' => $library->id)); + $DB->delete_records('h5p_libraries', array('id' => $library->id)); + } + + /** + * Load content. + * Implements loadContent. + * + * @param int $id Content identifier + * @return array Associative array containing: + * - id: Identifier for the content + * - params: json content as string + * - embedType: list of supported embed types + * - disable: H5P Button display options + * - title: H5P content title + * - slug: Human readable content identifier that is unique + * - libraryId: Id for the main library + * - libraryName: The library machine name + * - libraryMajorVersion: The library's majorVersion + * - libraryMinorVersion: The library's minorVersion + * - libraryEmbedTypes: CSV of the main library's embed types + * - libraryFullscreen: 1 if fullscreen is supported. 0 otherwise + * - metadata: The content's metadata + */ + public function loadContent($id) { + global $DB; + + $sql = "SELECT hc.id, hc.jsoncontent, hc.displayoptions, hl.id AS libraryid, + hl.machinename, hl.title, hl.majorversion, hl.minorversion, hl.fullscreen, + hl.embedtypes, hl.semantics, hc.filtered + FROM {h5p} hc + JOIN {h5p_libraries} hl ON hl.id = hc.mainlibraryid + WHERE hc.id = :h5pid"; + + $sqlargs = array( + 'h5pid' => $id + ); + + $data = $DB->get_record_sql($sql, $sqlargs); + + // 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, + 'params' => $data->jsoncontent, + // It has been decided that the embedtype will be always set to 'iframe' (at least for now) because the 'div' + // may cause conflicts with CSS and JS in some cases. + 'embedType' => 'iframe', + 'disable' => $data->displayoptions, + 'title' => $data->title, + 'slug' => \H5PCore::slugify($data->title) . '-' . $data->id, + 'filtered' => $data->filtered, + 'libraryId' => $data->libraryid, + 'libraryName' => $data->machinename, + 'libraryMajorVersion' => $data->majorversion, + 'libraryMinorVersion' => $data->minorversion, + 'libraryEmbedTypes' => $data->embedtypes, + 'libraryFullscreen' => $data->fullscreen, + 'metadata' => '' + ); + + return $content; + } + + /** + * Load dependencies for the given content of the given type. + * Implements loadContentDependencies. + * + * @param int $id Content identifier + * @param int $type The dependency type + * @return array List of associative arrays containing: + * - libraryId: The id of the library if it is an existing library + * - machineName: The library machineName + * - majorVersion: The library's majorVersion + * - minorVersion: The library's minorVersion + * - patchVersion: The library's patchVersion + * - preloadedJs(optional): comma separated string with js file paths + * - preloadedCss(optional): comma separated sting with css file paths + * - dropCss(optional): csv of machine names + * - dependencyType: The dependency type + */ + public function loadContentDependencies($id, $type = null) { + global $DB; + + $query = "SELECT hcl.id AS unidepid, hl.id AS library_id, hl.machinename AS machine_name, + hl.majorversion AS major_version, hl.minorversion AS minor_version, + hl.patchversion AS patch_version, hl.preloadedcss AS preloaded_css, + hl.preloadedjs AS preloaded_js, hcl.dropcss AS drop_css, + hcl.dependencytype as dependency_type + FROM {h5p_contents_libraries} hcl + JOIN {h5p_libraries} hl ON hcl.libraryid = hl.id + WHERE hcl.h5pid = :h5pid"; + $queryargs = array( + 'h5pid' => $id + ); + + if ($type !== null) { + $query .= " AND hcl.dependencytype = :dependencytype"; + $queryargs['dependencytype'] = $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; + } + + /** + * Get the default behaviour for the display option defined. + * Implements getOption. + * + * @param string $name Identifier for the setting + * @param string $default Optional default value if settings is not set + * @return mixed Return The default \H5PDisplayOptionBehaviour for this display option + */ + public function getOption($name, $default = false) { + // TODO: Define the default behaviour for each display option. + // For now, all them are disabled by default, so only will be rendered when defined in the displayoptions DB field. + return \H5PDisplayOptionBehaviour::CONTROLLED_BY_AUTHOR_DEFAULT_OFF; + } + + /** + * Stores the given setting. + * Implements setOption. + * + * @param string $name Identifier for the setting + * @param mixed $value Data Whatever we want to store as the setting + */ + public function setOption($name, $value) { + // Currently not storing settings. + } + + /** + * This will update selected fields on the given content. + * Implements updateContentFields(). + * + * @param int $id Content identifier + * @param array $fields Content fields, e.g. filtered + */ + public function updateContentFields($id, $fields) { + global $DB; + + $content = new \stdClass(); + $content->id = $id; + + foreach ($fields as $name => $value) { + // Skip 'slug' as it currently does not exist in the h5p content table. + if ($name == 'slug') { + continue; + } + + $content->$name = $value; + } + + $DB->update_record('h5p', $content); + } + + /** + * Will clear filtered params for all the content that uses the specified. + * libraries. This means that the content dependencies will have to be rebuilt and the parameters re-filtered. + * Implements clearFilteredParameters(). + * + * @param array $libraryids Array of library ids + */ + public function clearFilteredParameters($libraryids) { + global $DB; + + if (empty($libraryids)) { + return; + } + + list($insql, $inparams) = $DB->get_in_or_equal($libraryids); + + $DB->set_field_select('h5p', 'filtered', null, + "mainlibraryid $insql", $inparams); + } + + /** + * Get number of contents that has to get their content dependencies rebuilt. + * and parameters re-filtered. + * Implements getNumNotFiltered(). + * + * @return int The number of contents that has to get their content dependencies rebuilt + * and parameters re-filtered + */ + public function getNumNotFiltered() { + global $DB; + + $sql = "SELECT COUNT(id) + FROM {h5p} + WHERE " . $DB->sql_compare_text('filtered') . " IS NULL"; + + return $DB->count_records_sql($sql); + } + + /** + * Get number of contents using library as main library. + * Implements getNumContent(). + * + * @param int $libraryid The library ID + * @param array $skip The array of h5p content ID's that should be ignored + * @return int The number of contents using library as main library + */ + public function getNumContent($libraryid, $skip = null) { + global $DB; + + $notinsql = ''; + $params = array(); + + if (!empty($skip)) { + list($sql, $params) = $DB->get_in_or_equal($skip, SQL_PARAMS_NAMED, 'param', false); + $notinsql = " AND id {$sql}"; + } + + $sql = "SELECT COUNT(id) + FROM {h5p} + WHERE mainlibraryid = :libraryid {$notinsql}"; + + $params['libraryid'] = $libraryid; + + return $DB->count_records_sql($sql, $params); + } + + /** + * Determines if content slug is used. + * Implements isContentSlugAvailable. + * + * @param string $slug The content slug + * @return boolean Whether the content slug is used + */ + public function isContentSlugAvailable($slug) { + // By default the slug should be available as it's currently generated as a unique + // value for each h5p content (not stored in the h5p table). + return true; + } + + /** + * Generates statistics from the event log per library. + * Implements getLibraryStats. + * + * @param string $type Type of event to generate stats for + * @return array Number values indexed by library name and version + */ + public function getLibraryStats($type) { + // Event logs are not being stored. + } + + /** + * Aggregate the current number of H5P authors. + * Implements getNumAuthors. + * + * @return int The current number of H5P authors + */ + public function getNumAuthors() { + // Currently, H5P authors are not being stored. + } + + /** + * Stores hash keys for cached assets, aggregated JavaScripts and + * stylesheets, and connects it to libraries so that we know which cache file + * to delete when a library is updated. + * Implements saveCachedAssets. + * + * @param string $key Hash key for the given libraries + * @param array $libraries List of dependencies(libraries) used to create the key + */ + public function saveCachedAssets($key, $libraries) { + global $DB; + + foreach ($libraries as $library) { + $cachedasset = new \stdClass(); + $cachedasset->libraryid = $library['libraryId']; + $cachedasset->hash = $key; + + $DB->insert_record('h5p_libraries_cachedassets', $cachedasset); + } + } + + /** + * Locate hash keys for given library and delete them. + * Used when cache file are deleted. + * Implements deleteCachedAssets. + * + * @param int $libraryid Library identifier + * @return array List of hash keys removed + */ + public function deleteCachedAssets($libraryid) { + global $DB; + + // Get all the keys so we can remove the files. + $results = $DB->get_records('h5p_libraries_cachedassets', ['libraryid' => $libraryid]); + + $hashes = array_map(function($result) { + return $result->hash; + }, $results); + + if (!empty($hashes)) { + list($sql, $params) = $DB->get_in_or_equal($hashes, SQL_PARAMS_NAMED); + // Remove all invalid keys. + $DB->delete_records_select('h5p_libraries_cachedassets', 'hash ' . $sql, $params); + } + + return $hashes; + } + + /** + * Get the amount of content items associated to a library. + * Implements getLibraryContentCount. + * + * return array The number of content items associated to a library + */ + public function getLibraryContentCount() { + global $DB; + + $contentcount = array(); + + $sql = "SELECT h.mainlibraryid, + l.machinename, + l.majorversion, + l.minorversion, + COUNT(h.id) AS count + FROM {h5p} h + LEFT JOIN {h5p_libraries} l + ON h.mainlibraryid = l.id + GROUP BY h.mainlibraryid, l.machinename, l.majorversion, l.minorversion"; + + // Count content using the same content type. + $res = $DB->get_records_sql($sql); + + // Extract results. + foreach ($res as $lib) { + $contentcount["{$lib->machinename} {$lib->majorversion}.{$lib->minorversion}"] = $lib->count; + } + + return $contentcount; + } + + /** + * Will trigger after the export file is created. + * Implements afterExportCreated. + * + * @param array $content The content + * @param string $filename The file name + */ + public function afterExportCreated($content, $filename) { + // Not being used. + } + + /** + * Check whether a user has permissions to execute an action, such as embed H5P content. + * Implements hasPermission. + * + * @param \H5PPermission $permission Permission type + * @param int $id Id need by platform to determine permission + * @return boolean true if the user can execute the action defined in $permission; false otherwise + */ + public function hasPermission($permission, $id = null) { + // H5P capabilities have not been introduced. + } + + /** + * Replaces existing content type cache with the one passed in. + * Implements replaceContentTypeCache. + * + * @param object $contenttypecache Json with an array called 'libraries' containing the new content type cache + * that should replace the old one + */ + public function replaceContentTypeCache($contenttypecache) { + // Currently, content type caches are not being stored. + } + + /** + * Checks if the given library has a higher version. + * Implements libraryHasUpgrade. + * + * @param array $library An associative array containing: + * - machineName: The library machineName + * - majorVersion: The library's majorVersion + * - minorVersion: The library's minorVersion + * @return boolean Whether the library has a higher version + */ + public function libraryHasUpgrade($library) { + global $DB; + + $sql = "SELECT id + FROM {h5p_libraries} + WHERE machinename = :machinename + AND (majorversion > :majorversion1 + OR (majorversion = :majorversion2 AND minorversion > :minorversion))"; + + $results = $DB->get_records_sql( + $sql, + array( + 'machinename' => $library['machineName'], + 'majorversion1' => $library['majorVersion'], + 'majorversion2' => $library['majorVersion'], + 'minorversion' => $library['minorVersion'] + ), + 0, + 1 + ); + + return !empty($results); + } + + /** + * Get type of h5p instance + * + * @param string|null $type Type of h5p instance to get + * @return \H5PContentValidator|\H5PCore|\H5PStorage|\H5PValidator|\core_h5p\framework|\H5peditor + */ + public static function instance($type = null) { + global $CFG; + static $interface, $core; + + if (!isset($interface)) { + $interface = new \core_h5p\framework(); + $fs = new \core_h5p\file_storage(); + $language = self::get_language(); + + $context = \context_system::instance(); + $url = "{$CFG->wwwroot}/pluginfile.php/{$context->id}/core_h5p"; + + $core = new \H5PCore($interface, $fs, $url, $language, true); + $core->aggregateAssets = !(isset($CFG->core_h5p_aggregate_assets) && $CFG->core_h5p_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 'core': + default: + return $core; + } + } + + /** + * 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 $map[$language] ?? $language; + } + + /** + * Store messages until they can be printed to the current user. + * + * @param string $type Type of messages, e.g. 'info', 'error', etc + * @param string $newmessage The message + * @param string $code The message code + */ + private function set_message(string $type, string $newmessage = null, string $code = null) { + global $SESSION; + + // 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->core_h5p_messages[$type][] = (object) array( + 'code' => $code, + 'message' => $newmessage + ); + } else { + $SESSION->core_h5p_messages[$type][] = $newmessage; + } + } + + /** + * Convert list of library parameter values to csv. + * + * @param array $librarydata Library data as found in library.json files + * @param string $key Key that should be found in $librarydata + * @param string $searchparam The library parameter (Default: 'path') + * @return string Library parameter values separated by ', ' + */ + private function library_parameter_values_to_csv(array $librarydata, string $key, string $searchparam = 'path'): string { + if (isset($librarydata[$key])) { + $parametervalues = array(); + foreach ($librarydata[$key] as $file) { + foreach ($file as $index => $value) { + if ($index === $searchparam) { + $parametervalues[] = $value; + } + } + } + return implode(', ', $parametervalues); + } + return ''; + } +} From 27fa4ba3d4b735e6171aa8a0eb0a286d4ef2b86c Mon Sep 17 00:00:00 2001 From: Mihail Geshoski Date: Thu, 26 Sep 2019 16:59:12 +0800 Subject: [PATCH 07/22] MDL-66609 core_h5p: Unit test framework interface implementation --- h5p/tests/framework_test.php | 2017 ++++++++++++++++++++++++++++++++++ h5p/tests/generator/lib.php | 226 +++- h5p/tests/generator_test.php | 478 ++++++++ 3 files changed, 2717 insertions(+), 4 deletions(-) create mode 100644 h5p/tests/framework_test.php create mode 100644 h5p/tests/generator_test.php diff --git a/h5p/tests/framework_test.php b/h5p/tests/framework_test.php new file mode 100644 index 00000000000..0eb5ee01b1a --- /dev/null +++ b/h5p/tests/framework_test.php @@ -0,0 +1,2017 @@ +. + +/** + * Testing the H5PFrameworkInterface interface implementation. + * + * @package core_h5p + * @category test + * @copyright 2019 Mihail Geshoski + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace core_h5p; + +defined('MOODLE_INTERNAL') || die(); + +/** + * + * Test class covering the H5PFrameworkInterface interface implementation. + * + * @package core_h5p + * @copyright 2019 Mihail Geshoski + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class framework_testcase extends \advanced_testcase { + + /** @var \core_h5p\framework */ + private $framework; + + /** + * Set up function for tests. + */ + public function setUp() { + $factory = new \core_h5p\factory(); + $this->framework = $factory->get_framework(); + } + + /** + * Test the behaviour of getPlatformInfo(). + */ + public function test_getPlatformInfo() { + global $CFG; + + $platforminfo = $this->framework->getPlatformInfo(); + + $expected = array( + 'name' => 'Moodle', + 'version' => $CFG->version, + 'h5pVersion' => $CFG->version + ); + + $this->assertEquals($expected, $platforminfo); + } + + /** + * Test the behaviour of fetchExternalData() when the store path is not defined. + */ + public function test_fetchExternalData_no_path_defined() { + $this->resetAfterTest(); + + // Provide a valid URL to an external H5P content. + $url = "https://h5p.org/sites/default/files/h5p/exports/arithmetic-quiz-22-57860.h5p"; + + // Test fetching an external H5P content without defining a path to where the file should be stored. + $data = $this->framework->fetchExternalData($url, null, true); + + // The response should not be empty and return true if the file was successfully downloaded. + $this->assertNotEmpty($data); + $this->assertTrue($data); + + $h5pfolderpath = $this->framework->getUploadedH5pFolderPath(); + // The uploaded file should exist on the filesystem. + $this->assertTrue(file_exists($h5pfolderpath . '.h5p')); + } + + /** + * Test the behaviour of fetchExternalData() when the store path is defined. + */ + public function test_fetchExternalData_path_defined() { + global $CFG; + + $this->resetAfterTest(); + + // Provide a valid URL to an external H5P content. + $url = "https://h5p.org/sites/default/files/h5p/exports/arithmetic-quiz-22-57860.h5p"; + + $h5pfolderpath = $CFG->tempdir . uniqid('/h5p-'); + + $data = $this->framework->fetchExternalData($url, null, true, $h5pfolderpath . '.h5p'); + + // The response should not be empty and return true if the content has been successfully saved to a file. + $this->assertNotEmpty($data); + $this->assertTrue($data); + + // The uploaded file should exist on the filesystem. + $this->assertTrue(file_exists($h5pfolderpath . '.h5p')); + } + + /** + * Test the behaviour of fetchExternalData() when the URL is pointing to an external file that is + * not an h5p content. + */ + public function test_fetchExternalData_url_not_h5p() { + $this->resetAfterTest(); + + // Provide an URL to an external file that is not an H5P content file. + $url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"; + + $data = $this->framework->fetchExternalData($url, null, true); + + // The response should not be empty and return true if the content has been successfully saved to a file. + $this->assertNotEmpty($data); + $this->assertTrue($data); + + // The uploaded file should exist on the filesystem with it's original extension. + // NOTE: The file would be later validated by the H5P Validator. + $h5pfolderpath = $this->framework->getUploadedH5pFolderPath(); + $this->assertTrue(file_exists($h5pfolderpath . '.pdf')); + } + + /** + * Test the behaviour of fetchExternalData() when the URL is invalid. + */ + public function test_fetchExternalData_url_invalid() { + // Provide an invalid URL to an external file. + $url = "someprotocol://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"; + + $data = $this->framework->fetchExternalData($url, null, true); + + // The response should be empty. + $this->assertEmpty($data); + } + + /** + * Test the behaviour of setErrorMessage(). + */ + public function test_setErrorMessage() { + // Set an error message and an error code. + $message = "Error message"; + $code = '404'; + + // Set an error message. + $this->framework->setErrorMessage($message, $code); + + // Get the error messages. + $errormessages = $this->framework->getMessages('error'); + + $expected = new \stdClass(); + $expected->code = 404; + $expected->message = 'Error message'; + + $this->assertEquals($expected, $errormessages[0]); + } + + /** + * Test the behaviour of setInfoMessage(). + */ + public function test_setInfoMessage() { + $message = "Info message"; + + // Set an info message. + $this->framework->setInfoMessage($message); + + // Get the info messages. + $infomessages = $this->framework->getMessages('info'); + + $expected = 'Info message'; + + $this->assertEquals($expected, $infomessages[0]); + } + + /** + * Test the behaviour of getMessages() when requesting the info messages. + */ + public function test_getMessages_info() { + // Set an info message. + $this->framework->setInfoMessage("Info message"); + // Set an error message. + $this->framework->setErrorMessage("Error message 1", 404); + + // Get the info messages. + $infomessages = $this->framework->getMessages('info'); + + $expected = 'Info message'; + + // Make sure that only the info message has been returned. + $this->assertCount(1, $infomessages); + $this->assertEquals($expected, $infomessages[0]); + + $infomessages = $this->framework->getMessages('info'); + + // Make sure the info messages have now been removed. + $this->assertEmpty($infomessages); + } + + /** + * Test the behaviour of getMessages() when requesting the error messages. + */ + public function test_getMessages_error() { + // Set an info message. + $this->framework->setInfoMessage("Info message"); + // Set an error message. + $this->framework->setErrorMessage("Error message 1", 404); + // Set another error message. + $this->framework->setErrorMessage("Error message 2", 403); + + // Get the error messages. + $errormessages = $this->framework->getMessages('error'); + + // Make sure that only the error messages are being returned. + $this->assertEquals(2, count($errormessages)); + + $expected1 = (object) [ + 'code' => 404, + 'message' => 'Error message 1' + ]; + + $expected2 = (object) [ + 'code' => 403, + 'message' => 'Error message 2' + ]; + + $this->assertEquals($expected1, $errormessages[0]); + $this->assertEquals($expected2, $errormessages[1]); + + $errormessages = $this->framework->getMessages('error'); + + // Make sure the info messages have now been removed. + $this->assertEmpty($errormessages); + } + + /** + * Test the behaviour of t() when translating existing string that does not require any arguments. + */ + public function test_t_existing_string_no_args() { + // Existing language string without passed arguments. + $translation = $this->framework->t('No copyright information available for this content.'); + + // Make sure the string translation has been returned. + $this->assertEquals('No copyright information available for this content.', $translation); + } + + /** + * Test the behaviour of t() when translating existing string that does require parameters. + */ + public function test_t_existing_string_args() { + // Existing language string with passed arguments. + $translation = $this->framework->t('Illegal option %option in %library', + ['%option' => 'example', '%library' => 'Test library']); + + // Make sure the string translation has been returned. + $this->assertEquals('Illegal option example in Test library', $translation); + } + + /** + * Test the behaviour of t() when translating non-existent string. + */ + public function test_t_non_existent_string() { + // Non-existing language string. + $message = 'Random message %option'; + + $translation = $this->framework->t($message); + + // Make sure a debugging message is triggered. + $this->assertDebuggingCalled("String translation cannot be found. Please add a string definition for '" . + $message . "' in the core_h5p component."); + // As the string does not exist in the mapping array, make sure the passed message is returned. + $this->assertEquals($message, $translation); + } + + /** + * Test the behaviour of getLibraryFileUrl() when requesting a file URL from an existing library and + * the folder name is parsable. + **/ + public function test_getLibraryFileUrl() { + global $CFG; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + // Create a library record. + $lib = $generator->create_library_record('Library', 'Lib', 1, 1); + + $expected = "{$CFG->wwwroot}/pluginfile.php/1/core_h5p/libraries/{$lib->id}/Library-1.1/library.json"; + + // Get the URL of a file from an existing library. The provided folder name is parsable. + $actual = $this->framework->getLibraryFileUrl('Library-1.1', 'library.json'); + + // Make sure the expected URL is returned. + $this->assertEquals($expected, $actual); + } + + /** + * Test the behaviour of getLibraryFileUrl() when requesting a file URL from a non-existent library and + * the folder name is parsable. + **/ + public function test_getLibraryFileUrl_non_existent_library() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + // Create a library record. + $generator->create_library_record('Library', 'Lib', 1, 1); + + // Get the URL of a file from a non-existent library. The provided folder name is parsable. + $actual = $this->framework->getLibraryFileUrl('Library2-1.1', 'library.json'); + + // Make sure a debugging message is triggered. + $this->assertDebuggingCalled('The library "Library2-1.1" does not exist.'); + + // Make sure that an URL is not returned. + $this->assertEquals(null, $actual); + } + + /** + * Test the behaviour of getLibraryFileUrl() when requesting a file URL from an existing library and + * the folder name is not parsable. + **/ + public function test_getLibraryFileUrl_not_parsable_folder_name() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + // Create a library record. + $generator->create_library_record('Library', 'Lib', 1, 1); + + // Get the URL of a file from an existing library. The provided folder name is not parsable. + $actual = $this->framework->getLibraryFileUrl('Library1.1', 'library.json'); + + // Make sure a debugging message is triggered. + $this->assertDebuggingCalled( + 'The provided string value "Library1.1" is not a valid name for a library folder.'); + + // Make sure that an URL is not returned. + $this->assertEquals(null, $actual); + } + + /** + * Test the behaviour of getLibraryFileUrl() when requesting a file URL from a library that has multiple + * versions and the folder name is parsable. + **/ + public function test_getLibraryFileUrl_library_has_multiple_versions() { + global $CFG; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + // Create library records with a different minor version. + $lib1 = $generator->create_library_record('Library', 'Lib', 1, 1); + $lib2 = $generator->create_library_record('Library', 'Lib', 1, 3); + + $expected = "{$CFG->wwwroot}/pluginfile.php/1/core_h5p/libraries/{$lib2->id}/Library-1.3/library.json"; + + // Get the URL of a file from an existing library (Library 1.3). The provided folder name is parsable. + $actual = $this->framework->getLibraryFileUrl('Library-1.3', 'library.json'); + + // Make sure the proper URL (from the requested library version) is returned. + $this->assertEquals($expected, $actual); + } + + /** + * Test the behaviour of getLibraryFileUrl() when requesting a file URL from a library that has multiple + * patch versions and the folder name is parsable. + **/ + public function test_getLibraryFileUrl_library_has_multiple_patch_versions() { + global $CFG; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + // Create library records with a different patch version. + $lib1 = $generator->create_library_record('Library', 'Lib', 1, 1, 2); + $lib2 = $generator->create_library_record('Library', 'Lib', 1, 1, 4); + $lib3 = $generator->create_library_record('Library', 'Lib', 1, 1, 3); + + $expected = "{$CFG->wwwroot}/pluginfile.php/1/core_h5p/libraries/{$lib2->id}/Library-1.1/library.json"; + + // Get the URL of a file from an existing library. The provided folder name is parsable. + $actual = $this->framework->getLibraryFileUrl('Library-1.1', 'library.json'); + + // Make sure the proper URL (from the latest library patch) is returned. + $this->assertEquals($expected, $actual); + } + + /** + * Test the behaviour of getLibraryFileUrl() when requesting a file URL from a sub-folder + * of an existing library and the folder name is parsable. + **/ + public function test_getLibraryFileUrl_library_subfolder() { + global $CFG; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + // Create a library record. + $lib = $generator->create_library_record('Library', 'Lib', 1, 1); + + $expected = "{$CFG->wwwroot}/pluginfile.php/1/core_h5p/libraries/{$lib->id}/Library-1.1/css/example.css"; + + // Get the URL of a file from a sub-folder from an existing library. The provided folder name is parsable. + $actual = $this->framework->getLibraryFileUrl('Library-1.1/css', 'example.css'); + + // Make sure the proper URL is returned. + $this->assertEquals($expected, $actual); + } + + /** + * Test the behaviour of loadAddons(). + */ + public function test_loadAddons() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create a Library addon (1.1). + $generator->create_library_record('Library', 'Lib', 1, 1, 2, + '', '/regex1/'); + // Create a Library addon (1.3). + $generator->create_library_record('Library', 'Lib', 1, 3, 2, + '', '/regex2/'); + // Create a Library addon (1.2). + $generator->create_library_record('Library', 'Lib', 1, 2, 2, + '', '/regex3/'); + // Create a Library1 addon (1.2) + $generator->create_library_record('Library1', 'Lib1', 1, 2, 2, + '', '/regex11/'); + + // Load the latest version of each addon. + $addons = $this->framework->loadAddons(); + + // The addons array should return 2 results (Library and Library1 addon). + $this->assertCount(2, $addons); + + // Make sure the version 1.3 is the latest 'Library' addon version. + $this->assertEquals('Library', $addons[0]['machineName']); + $this->assertEquals(1, $addons[0]['majorVersion']); + $this->assertEquals(3, $addons[0]['minorVersion']); + + // Make sure the version 1.2 is the latest 'Library1' addon version. + $this->assertEquals('Library1', $addons[1]['machineName']); + $this->assertEquals(1, $addons[1]['majorVersion']); + $this->assertEquals(2, $addons[1]['minorVersion']); + } + + /** + * Test the behaviour of loadLibraries(). + */ + public function test_loadLibraries() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $generator->generate_h5p_data(); + + // Load all libraries. + $libraries = $this->framework->loadLibraries(); + + // Make sure all libraries are returned. + $this->assertNotEmpty($libraries); + $this->assertCount(6, $libraries); + $this->assertEquals('MainLibrary', $libraries['MainLibrary'][0]->machine_name); + $this->assertEquals('1', $libraries['MainLibrary'][0]->major_version); + $this->assertEquals('0', $libraries['MainLibrary'][0]->minor_version); + $this->assertEquals('1', $libraries['MainLibrary'][0]->patch_version); + $this->assertEquals('MainLibrary', $libraries['MainLibrary'][0]->machine_name); + } + + /** + * Test the behaviour of test_getLibraryId() when requesting an existing machine name. + */ + public function test_getLibraryId_existing_machine_name() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create a library. + $lib = $generator->create_library_record('Library', 'Lib', 1, 1, 2); + + // Request the library ID of the library with machine name 'Library'. + $libraryid = $this->framework->getLibraryId('Library'); + + // Make sure the library ID is being returned. + $this->assertNotFalse($libraryid); + $this->assertEquals($lib->id, $libraryid); + } + + /** + * Test the behaviour of test_getLibraryId() when requesting a non-existent machine name. + */ + public function test_getLibraryId_non_existent_machine_name() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create a library. + $generator->create_library_record('Library', 'Lib', 1, 1, 2); + + // Request the library ID of the library with machinename => 'TestLibrary' (non-existent). + $libraryid = $this->framework->getLibraryId('TestLibrary'); + + // Make sure the library ID not being returned. + $this->assertFalse($libraryid); + } + + /** + * Test the behaviour of test_getLibraryId() when requesting a non-existent major version. + */ + public function test_getLibraryId_non_existent_major_version() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create a library. + $generator->create_library_record('Library', 'Lib', 1, 1, 2); + + // Request the library ID of the library with machine name => 'Library', majorversion => 2 (non-existent). + $libraryid = $this->framework->getLibraryId('Library', 2); + + // Make sure the library ID not being returned. + $this->assertFalse($libraryid); + } + + /** + * Test the behaviour of test_getLibraryId() when requesting a non-existent minor version. + */ + public function test_getLibraryId_non_existent_minor_version() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create a library. + $generator->create_library_record('Library', 'Lib', 1, 1, 2); + + // Request the library ID of the library with machine name => 'Library', + // majorversion => 1, minorversion => 2 (non-existent). + $libraryid = $this->framework->getLibraryId('Library', 1, 2); + + // Make sure the library ID not being returned. + $this->assertFalse($libraryid); + } + + /** + * Test the behaviour of isPatchedLibrary(). + * + * @dataProvider test_isPatchedLibrary_provider + * @param array $libraryrecords Array containing data for the library creation + * @param array $testlibrary Array containing the test library data + * @param bool $expected The expectation whether the library is patched or not + **/ + public function test_isPatchedLibrary(array $libraryrecords, array $testlibrary, bool $expected): void { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + foreach ($libraryrecords as $library) { + call_user_func_array([$generator, 'create_library_record'], $library); + } + + $this->assertEquals($expected, $this->framework->isPatchedLibrary($testlibrary)); + } + + /** + * Data provider for test_isPatchedLibrary(). + * + * @return array + */ + public function test_isPatchedLibrary_provider(): array { + return [ + 'Unpatched library. No different versioning' => [ + [ + ['TestLibrary', 'Test', 1, 1, 2], + ], + [ + 'machineName' => 'TestLibrary', + 'majorVersion' => 1, + 'minorVersion' => 1, + 'patchVersion' => 2 + ], + false, + ], + 'Major version identical; Minor version identical; Patch version newer' => [ + [ + ['TestLibrary', 'Test', 1, 1, 2], + ], + [ + 'machineName' => 'TestLibrary', + 'majorVersion' => 1, + 'minorVersion' => 1, + 'patchVersion' => 3 + ], + true, + ], + 'Major version identical; Minor version newer; Patch version newer' => [ + [ + ['TestLibrary', 'Test', 1, 1, 2], + ], + [ + 'machineName' => 'TestLibrary', + 'majorVersion' => 1, + 'minorVersion' => 2, + 'patchVersion' => 3 + ], + false, + ], + 'Major version identical; Minor version identical; Patch version older' => [ + [ + ['TestLibrary', 'Test', 1, 1, 2], + ], + [ + 'machineName' => 'TestLibrary', + 'majorVersion' => 1, + 'minorVersion' => 1, + 'patchVersion' => 1 + ], + false, + ], + 'Major version identical; Minor version newer; Patch version older' => [ + [ + ['TestLibrary', 'Test', 1, 1, 2], + ], + [ + 'machineName' => 'TestLibrary', + 'majorVersion' => 1, + 'minorVersion' => 2, + 'patchVersion' => 1 + ], + false, + ], + 'Major version newer; Minor version identical; Patch version older' => [ + [ + ['TestLibrary', 'Test', 1, 1, 2], + ], + [ + 'machineName' => 'TestLibrary', + 'majorVersion' => 2, + 'minorVersion' => 1, + 'patchVersion' => 1 + ], + false, + ], + 'Major version newer; Minor version identical; Patch version newer' => [ + [ + ['TestLibrary', 'Test', 1, 1, 2], + ], + [ + 'machineName' => 'TestLibrary', + 'majorVersion' => 2, + 'minorVersion' => 1, + 'patchVersion' => 3 + ], + false, + ], + + 'Major version older; Minor version identical; Patch version older' => [ + [ + ['TestLibrary', 'Test', 1, 1, 2], + ], + [ + 'machineName' => 'TestLibrary', + 'majorVersion' => 0, + 'minorVersion' => 1, + 'patchVersion' => 1 + ], + false, + ], + 'Major version older; Minor version identical; Patch version newer' => [ + [ + ['TestLibrary', 'Test', 1, 1, 2], + ], + [ + 'machineName' => 'TestLibrary', + 'majorVersion' => 0, + 'minorVersion' => 1, + 'patchVersion' => 3 + ], + false, + ], + ]; + } + + /** + * Test the behaviour of isInDevMode(). + */ + public function test_isInDevMode() { + $isdevmode = $this->framework->isInDevMode(); + + $this->assertFalse($isdevmode); + } + + /** + * Test the behaviour of mayUpdateLibraries(). + */ + public function test_mayUpdateLibraries() { + $mayupdatelib = $this->framework->mayUpdateLibraries(); + + $this->assertTrue($mayupdatelib); + } + + /** + * Test the behaviour of saveLibraryData() when saving data for a new library. + */ + public function test_saveLibraryData_new_library() { + global $DB; + + $this->resetAfterTest(); + + $librarydata = array( + 'title' => 'Test', + 'machineName' => 'TestLibrary', + 'majorVersion' => '1', + 'minorVersion' => '0', + 'patchVersion' => '2', + 'runnable' => 1, + 'fullscreen' => 1, + 'preloadedJs' => array( + array( + 'path' => 'js/name.min.js' + ) + ), + 'preloadedCss' => array( + array( + 'path' => 'css/name.css' + ) + ), + 'dropLibraryCss' => array( + array( + 'machineName' => 'Name2' + ) + ) + ); + + // Create a new library. + $this->framework->saveLibraryData($librarydata); + + $library = $DB->get_record('h5p_libraries', ['machinename' => $librarydata['machineName']]); + + // Make sure the library data was properly saved. + $this->assertNotEmpty($library); + $this->assertNotEmpty($librarydata['libraryId']); + $this->assertEquals($librarydata['title'], $library->title); + $this->assertEquals($librarydata['machineName'], $library->machinename); + $this->assertEquals($librarydata['majorVersion'], $library->majorversion); + $this->assertEquals($librarydata['minorVersion'], $library->minorversion); + $this->assertEquals($librarydata['patchVersion'], $library->patchversion); + $this->assertEquals($librarydata['preloadedJs'][0]['path'], $library->preloadedjs); + $this->assertEquals($librarydata['preloadedCss'][0]['path'], $library->preloadedcss); + $this->assertEquals($librarydata['dropLibraryCss'][0]['machineName'], $library->droplibrarycss); + } + + /** + * Test the behaviour of saveLibraryData() when saving (updating) data for an existing library. + */ + public function test_saveLibraryData_existing_library() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create a library record. + $library = $generator->create_library_record('TestLibrary', 'Test', 1, 0, 2); + + $librarydata = array( + 'libraryId' => $library->id, + 'title' => 'Test1', + 'machineName' => 'TestLibrary', + 'majorVersion' => '1', + 'minorVersion' => '2', + 'patchVersion' => '2', + 'runnable' => 1, + 'fullscreen' => 1, + 'preloadedJs' => array( + array( + 'path' => 'js/name.min.js' + ) + ), + 'preloadedCss' => array( + array( + 'path' => 'css/name.css' + ) + ), + 'dropLibraryCss' => array( + array( + 'machineName' => 'Name2' + ) + ) + ); + + // Update the library. + $this->framework->saveLibraryData($librarydata, false); + + $library = $DB->get_record('h5p_libraries', ['machinename' => $librarydata['machineName']]); + + // Make sure the library data was properly updated. + $this->assertNotEmpty($library); + $this->assertNotEmpty($librarydata['libraryId']); + $this->assertEquals($librarydata['title'], $library->title); + $this->assertEquals($librarydata['machineName'], $library->machinename); + $this->assertEquals($librarydata['majorVersion'], $library->majorversion); + $this->assertEquals($librarydata['minorVersion'], $library->minorversion); + $this->assertEquals($librarydata['patchVersion'], $library->patchversion); + $this->assertEquals($librarydata['preloadedJs'][0]['path'], $library->preloadedjs); + $this->assertEquals($librarydata['preloadedCss'][0]['path'], $library->preloadedcss); + $this->assertEquals($librarydata['dropLibraryCss'][0]['machineName'], $library->droplibrarycss); + } + + /** + * Test the behaviour of insertContent(). + */ + public function test_insertContent() { + global $DB; + + $this->resetAfterTest(); + + $content = array( + 'params' => json_encode(['param1' => 'Test']), + 'library' => array( + 'libraryId' => 1 + ), + 'disable' => 8 + ); + + // Insert h5p content. + $contentid = $this->framework->insertContent($content); + + // Get the entered content from the db. + $dbcontent = $DB->get_record('h5p', ['id' => $contentid]); + + // Make sure the h5p content was properly inserted. + $this->assertNotEmpty($dbcontent); + $this->assertEquals($content['params'], $dbcontent->jsoncontent); + $this->assertEquals($content['library']['libraryId'], $dbcontent->mainlibraryid); + $this->assertEquals($content['disable'], $dbcontent->displayoptions); + } + + /** + * Test the behaviour of updateContent(). + */ + public function test_updateContent() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create a library record. + $lib = $generator->create_library_record('TestLibrary', 'Test', 1, 1, 2); + + // Create an h5p content with 'TestLibrary' as it's main library. + $contentid = $generator->create_h5p_record($lib->id); + + $content = array( + 'id' => $contentid, + 'params' => json_encode(['param2' => 'Test2']), + 'library' => array( + 'libraryId' => $lib->id + ), + 'disable' => 8 + ); + + // Update the h5p content. + $this->framework->updateContent($content); + + $h5pcontent = $DB->get_record('h5p', ['id' => $contentid]); + + // Make sure the h5p content was properly updated. + $this->assertNotEmpty($h5pcontent); + $this->assertEquals($content['params'], $h5pcontent->jsoncontent); + $this->assertEquals($content['library']['libraryId'], $h5pcontent->mainlibraryid); + $this->assertEquals($content['disable'], $h5pcontent->displayoptions); + } + + /** + * Test the behaviour of saveLibraryDependencies(). + */ + public function test_saveLibraryDependencies() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create a library 'Library'. + $library = $generator->create_library_record('Library', 'Title'); + // Create a library 'DependencyLibrary1'. + $dependency1 = $generator->create_library_record('DependencyLibrary1', 'DependencyTitle1'); + // Create a library 'DependencyLibrary2'. + $dependency2 = $generator->create_library_record('DependencyLibrary2', 'DependencyTitle2'); + + $dependencies = array( + array( + 'machineName' => $dependency1->machinename, + 'majorVersion' => $dependency1->majorversion, + 'minorVersion' => $dependency1->minorversion + ), + array( + 'machineName' => $dependency2->machinename, + 'majorVersion' => $dependency2->majorversion, + 'minorVersion' => $dependency2->minorversion + ), + ); + + // Set 'DependencyLibrary1' and 'DependencyLibrary2' as library dependencies of 'Library'. + $this->framework->saveLibraryDependencies($library->id, $dependencies, 'preloaded'); + + $libdependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library->id], 'id ASC'); + + // Make sure the library dependencies for 'Library' are properly set. + $this->assertEquals(2, count($libdependencies)); + $this->assertEquals($dependency1->id, reset($libdependencies)->requiredlibraryid); + $this->assertEquals($dependency2->id, end($libdependencies)->requiredlibraryid); + } + + /** + * Test the behaviour of deleteContentData(). + */ + public function test_deleteContentData() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate some h5p related data. + $data = $generator->generate_h5p_data(); + $h5pid = $data->h5pcontent->h5pid; + + $h5pcontent = $DB->get_record('h5p', ['id' => $h5pid]); + // Make sure the particular h5p content exists in the DB. + $this->assertNotEmpty($h5pcontent); + + // Get the h5p content libraries from the DB. + $h5pcontentlibraries = $DB->get_records('h5p_contents_libraries', ['h5pid' => $h5pid]); + + // Make sure the content libraries exists in the DB. + $this->assertNotEmpty($h5pcontentlibraries); + $this->assertCount(5, $h5pcontentlibraries); + + // Delete the h5p content and it's related data. + $this->framework->deleteContentData($h5pid); + + $h5pcontent = $DB->get_record('h5p', ['id' => $h5pid]); + $h5pcontentlibraries = $DB->get_record('h5p_contents_libraries', ['h5pid' => $h5pid]); + + // The particular h5p content should no longer exist in the db. + $this->assertEmpty($h5pcontent); + // The particular content libraries should no longer exist in the db. + $this->assertEmpty($h5pcontentlibraries); + } + + /** + * Test the behaviour of deleteLibraryUsage(). + */ + public function test_deleteLibraryUsage() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate some h5p related data. + $data = $generator->generate_h5p_data(); + $h5pid = $data->h5pcontent->h5pid; + + // Get the h5p content libraries from the DB. + $h5pcontentlibraries = $DB->get_records('h5p_contents_libraries', ['h5pid' => $h5pid]); + + // The particular h5p content should have 5 content libraries. + $this->assertNotEmpty($h5pcontentlibraries); + $this->assertCount(5, $h5pcontentlibraries); + + // Delete the h5p content and it's related data. + $this->framework->deleteLibraryUsage($h5pid); + + // Get the h5p content libraries from the DB. + $h5pcontentlibraries = $DB->get_record('h5p_contents_libraries', ['h5pid' => $h5pid]); + + // The particular h5p content libraries should no longer exist in the db. + $this->assertEmpty($h5pcontentlibraries); + } + + /** + * Test the behaviour of test_saveLibraryUsage(). + */ + public function test_saveLibraryUsage() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create a library 'Library'. + $library = $generator->create_library_record('Library', 'Title'); + // Create a library 'DependencyLibrary1'. + $dependency1 = $generator->create_library_record('DependencyLibrary1', 'DependencyTitle1'); + // Create a library 'DependencyLibrary2'. + $dependency2 = $generator->create_library_record('DependencyLibrary2', 'DependencyTitle2'); + // Create an h5p content with 'Library' as it's main library. + $contentid = $generator->create_h5p_record($library->id); + + $dependencies = array( + array( + 'library' => array( + 'libraryId' => $dependency1->id, + 'machineName' => $dependency1->machinename, + 'dropLibraryCss' => $dependency1->droplibrarycss + ), + 'type' => 'preloaded', + 'weight' => 1 + ), + array( + 'library' => array( + 'libraryId' => $dependency2->id, + 'machineName' => $dependency2->machinename, + 'dropLibraryCss' => $dependency2->droplibrarycss + ), + 'type' => 'preloaded', + 'weight' => 2 + ), + ); + + // Save 'DependencyLibrary1' and 'DependencyLibrary2' as h5p content libraries. + $this->framework->saveLibraryUsage($contentid, $dependencies); + + // Get the h5p content libraries from the DB. + $libdependencies = $DB->get_records('h5p_contents_libraries', ['h5pid' => $contentid], 'id ASC'); + + // Make sure that 'DependencyLibrary1' and 'DependencyLibrary2' are properly set as h5p content libraries. + $this->assertEquals(2, count($libdependencies)); + $this->assertEquals($dependency1->id, reset($libdependencies)->libraryid); + $this->assertEquals($dependency2->id, end($libdependencies)->libraryid); + } + + /** + * Test the behaviour of getLibraryUsage() without skipping a particular h5p content. + */ + public function test_getLibraryUsage_no_skip_content() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $generateddata = $generator->generate_h5p_data(); + // The Id of the library 'Library1'. + $library1id = $generateddata->lib1->data->id; + // The Id of the library 'Library2'. + $library2id = $generateddata->lib2->data->id; + // The Id of the library 'Library5'. + $library5id = $generateddata->lib5->data->id; + + // Get the library usage for 'Library1' (do not skip content). + $data = $this->framework->getLibraryUsage($library1id); + + $expected = array( + 'content' => 1, + 'libraries' => 1 + ); + + // Make sure 'Library1' is used by 1 content and is a dependency to 1 library. + $this->assertEquals($expected, $data); + + // Get the library usage for 'Library2' (do not skip content). + $data = $this->framework->getLibraryUsage($library2id); + + $expected = array( + 'content' => 1, + 'libraries' => 2, + ); + + // Make sure 'Library2' is used by 1 content and is a dependency to 2 libraries. + $this->assertEquals($expected, $data); + + // Get the library usage for 'Library5' (do not skip content). + $data = $this->framework->getLibraryUsage($library5id); + + $expected = array( + 'content' => 0, + 'libraries' => 1, + ); + + // Make sure 'Library5' is not used by any content and is a dependency to 1 library. + $this->assertEquals($expected, $data); + } + + /** + * Test the behaviour of getLibraryUsage() when skipping a particular content. + */ + public function test_getLibraryUsage_skip_content() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $generateddata = $generator->generate_h5p_data(); + // The Id of the library 'Library1'. + $library1id = $generateddata->lib1->data->id; + + // Get the library usage for 'Library1' (skip content). + $data = $this->framework->getLibraryUsage($library1id, true); + $expected = array( + 'content' => -1, + 'libraries' => 1, + ); + + // Make sure 'Library1' is a dependency to 1 library. + $this->assertEquals($expected, $data); + } + + /** + * Test the behaviour of loadLibrary() when requesting an existing library. + */ + public function test_loadLibrary_existing_library() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $generateddata = $generator->generate_h5p_data(); + // The library data of 'Library1'. + $library1 = $generateddata->lib1->data; + // The library data of 'Library5'. + $library5 = $generateddata->lib5->data; + + // The preloaded dependencies. + $preloadeddependencies = array(); + + foreach ($generateddata->lib1->dependencies as $preloadeddependency) { + $preloadeddependencies[] = array( + 'machineName' => $preloadeddependency->machinename, + 'majorVersion' => $preloadeddependency->majorversion, + 'minorVersion' => $preloadeddependency->minorversion + ); + } + + // Create a dynamic dependency. + $generator->create_library_dependency_record($library1->id, $library5->id, 'dynamic'); + + $dynamicdependencies[] = array( + 'machineName' => $library5->machinename, + 'majorVersion' => $library5->majorversion, + 'minorVersion' => $library5->minorversion + ); + + // Load 'Library1' data. + $data = $this->framework->loadLibrary($library1->machinename, $library1->majorversion, + $library1->minorversion); + + $expected = array( + 'libraryId' => $library1->id, + 'title' => $library1->title, + 'machineName' => $library1->machinename, + 'majorVersion' => $library1->majorversion, + 'minorVersion' => $library1->minorversion, + 'patchVersion' => $library1->patchversion, + 'runnable' => $library1->runnable, + 'fullscreen' => $library1->fullscreen, + 'embedTypes' => $library1->embedtypes, + 'preloadedJs' => $library1->preloadedjs, + 'preloadedCss' => $library1->preloadedcss, + 'dropLibraryCss' => $library1->droplibrarycss, + 'semantics' => $library1->semantics, + 'preloadedDependencies' => $preloadeddependencies, + 'dynamicDependencies' => $dynamicdependencies + ); + + // Make sure the 'Library1' data is properly loaded. + $this->assertEquals($expected, $data); + } + + /** + * Test the behaviour of loadLibrary() when requesting a non-existent library. + */ + public function test_loadLibrary_non_existent_library() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $generator->generate_h5p_data(); + + // Attempt to load a non-existent library. + $data = $this->framework->loadLibrary('MissingLibrary', 1, 2); + + // Make sure nothing is loaded. + $this->assertFalse($data); + } + + /** + * Test the behaviour of loadLibrarySemantics(). + * + * @dataProvider test_loadLibrarySemantics_provider + * @param array $libraryrecords Array containing data for the library creation + * @param array $testlibrary Array containing the test library data + * @param string $expected The expected semantics value + **/ + public function test_loadLibrarySemantics(array $libraryrecords, array $testlibrary, string $expected): void { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + foreach ($libraryrecords as $library) { + call_user_func_array([$generator, 'create_library_record'], $library); + } + + $this->assertEquals($expected, $this->framework->loadLibrarySemantics( + $testlibrary['machinename'], $testlibrary['majorversion'], $testlibrary['minorversion'])); + } + + /** + * Data provider for test_loadLibrarySemantics(). + * + * @return array + */ + public function test_loadLibrarySemantics_provider(): array { + + $semantics = json_encode( + [ + 'type' => 'text', + 'name' => 'text', + 'label' => 'Plain text', + 'description' => 'Please add some text' + ] + ); + + return [ + 'Library with semantics' => [ + [ + ['Library1', 'Lib1', 1, 1, 2, $semantics], + ], + [ + 'machinename' => 'Library1', + 'majorversion' => 1, + 'minorversion' => 1 + ], + $semantics, + ], + 'Library without semantics' => [ + [ + ['Library2', 'Lib2', 1, 2, 2, ''], + ], + [ + 'machinename' => 'Library2', + 'majorversion' => 1, + 'minorversion' => 2 + ], + '', + ] + ]; + } + + /** + * Test the behaviour of alterLibrarySemantics(). + */ + public function test_alterLibrarySemantics() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + $semantics = json_encode( + array( + 'type' => 'text', + 'name' => 'text', + 'label' => 'Plain text', + 'description' => 'Please add some text' + ) + ); + + // Create a library 'Library1' with semantics. + $library1 = $generator->create_library_record('Library1', 'Lib1', 1, 1, 2, $semantics); + + $updatedsemantics = array( + 'type' => 'text', + 'name' => 'updated text', + 'label' => 'Updated text', + 'description' => 'Please add some text' + ); + + // Alter the semantics of 'Library1'. + $this->framework->alterLibrarySemantics($updatedsemantics, 'Library1', 1, 1); + + // Get the semantics of 'Library1' from the DB. + $currentsemantics = $DB->get_field('h5p_libraries', 'semantics', array('id' => $library1->id)); + + // The semantics for Library1 should be successfully updated. + $this->assertEquals(json_encode($updatedsemantics), $currentsemantics); + } + + /** + * Test the behaviour of deleteLibraryDependencies() when requesting to delete the + * dependencies of an existing library. + */ + public function test_deleteLibraryDependencies_existing_library() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $data = $generator->generate_h5p_data(); + // The data of the library 'Library1'. + $library1 = $data->lib1->data; + + // Get the dependencies of 'Library1'. + $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]); + // The 'Library1' should have 3 dependencies ('Library2', 'Library3', 'Library4'). + $this->assertCount(3, $dependencies); + + // Delete the dependencies of 'Library1'. + $this->framework->deleteLibraryDependencies($library1->id); + + $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]); + // The 'Library1' should have 0 dependencies. + $this->assertCount(0, $dependencies); + } + + /** + * Test the behaviour of deleteLibraryDependencies() when requesting to delete the + * dependencies of a non-existent library. + */ + public function test_deleteLibraryDependencies_non_existent_library() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $data = $generator->generate_h5p_data(); + // The data of the library 'Library1'. + $library1 = $data->lib1->data; + + // Get the dependencies of 'Library1'. + $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]); + // The 'Library1' should have 3 dependencies ('Library2', 'Library3', 'Library4'). + $this->assertCount(3, $dependencies); + + // Delete the dependencies of a non-existent library. + $this->framework->deleteLibraryDependencies(0); + + $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]); + // The 'Library1' should have 3 dependencies. + $this->assertCount(3, $dependencies); + } + + /** + * Test the behaviour of deleteLibrary(). + */ + public function test_deleteLibrary() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $data = $generator->generate_h5p_data(true); + // The data of the 'Library1' library. + $library1 = $data->lib1->data; + + // Get the library dependencies of 'Library1'. + $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]); + + // The 'Library1' should have 3 library dependencies ('Library2', 'Library3', 'Library4'). + $this->assertCount(3, $dependencies); + + // Return the created 'Library1' files. + $libraryfiles = $DB->get_records('files', + array( + 'component' => \core_h5p\file_storage::COMPONENT, + 'filearea' => \core_h5p\file_storage::LIBRARY_FILEAREA, + 'itemid' => $library1->id + ) + ); + + // The library ('Library1') should have 7 related folders/files. + $this->assertCount(7, $libraryfiles); + + // Delete the library. + $this->framework->deleteLibrary($library1); + + $lib1 = $DB->get_record('h5p_libraries', ['machinename' => $library1->machinename]); + $dependencies = $DB->get_records('h5p_library_dependencies', ['libraryid' => $library1->id]); + $libraryfiles = $DB->get_records('files', + array( + 'component' => \core_h5p\file_storage::COMPONENT, + 'filearea' => \core_h5p\file_storage::LIBRARY_FILEAREA, + 'itemid' => $library1->id + ) + ); + + // The 'Library1' should not exist. + $this->assertEmpty($lib1); + // The library ('Library1') should have 0 dependencies. + $this->assertCount(0, $dependencies); + // The library (library1) should have 0 related folders/files. + $this->assertCount(0, $libraryfiles); + } + + /** + * Test the behaviour of loadContent(). + */ + public function test_loadContent() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $data = $generator->generate_h5p_data(); + // The Id of the created h5p content. + $h5pid = $data->h5pcontent->h5pid; + // Get the h5p content data from the DB. + $h5p = $DB->get_record('h5p', ['id' => $h5pid]); + // The data of content's main library ('MainLibrary'). + $mainlibrary = $data->mainlib->data; + + // Load the h5p content. + $content = $this->framework->loadContent($h5pid); + + $expected = array( + 'id' => $h5p->id, + 'params' => $h5p->jsoncontent, + 'embedType' => 'iframe', + 'disable' => $h5p->displayoptions, + 'title' => $mainlibrary->title, + 'slug' => \H5PCore::slugify($mainlibrary->title) . '-' . $h5p->id, + 'filtered' => $h5p->filtered, + 'libraryId' => $mainlibrary->id, + 'libraryName' => $mainlibrary->machinename, + 'libraryMajorVersion' => $mainlibrary->majorversion, + 'libraryMinorVersion' => $mainlibrary->minorversion, + 'libraryEmbedTypes' => $mainlibrary->embedtypes, + 'libraryFullscreen' => $mainlibrary->fullscreen, + 'metadata' => '' + ); + + // The returned content should match the expected array. + $this->assertEquals($expected, $content); + } + + /** + * Test the behaviour of loadContentDependencies() when requesting content dependencies + * without specifying the dependency type. + */ + public function test_loadContentDependencies_no_type_defined() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $data = $generator->generate_h5p_data(); + // The Id of the h5p content. + $h5pid = $data->h5pcontent->h5pid; + // The content dependencies. + $dependencies = $data->h5pcontent->contentdependencies; + + // Add Library5 as a content dependency (dynamic dependency type). + $library5 = $data->lib5->data; + $generator->create_contents_libraries_record($h5pid, $library5->id, 'dynamic'); + + // Get all content dependencies. + $contentdependencies = $this->framework->loadContentDependencies($h5pid); + + $expected = array(); + foreach ($dependencies as $dependency) { + $expected[$dependency->machinename] = array( + 'libraryId' => $dependency->id, + 'machineName' => $dependency->machinename, + 'majorVersion' => $dependency->majorversion, + 'minorVersion' => $dependency->minorversion, + 'patchVersion' => $dependency->patchversion, + 'preloadedCss' => $dependency->preloadedcss, + 'preloadedJs' => $dependency->preloadedjs, + 'dropCss' => '0', + 'dependencyType' => 'preloaded' + ); + } + + $expected = array_merge($expected, + array( + 'Library5' => array( + 'libraryId' => $library5->id, + 'machineName' => $library5->machinename, + 'majorVersion' => $library5->majorversion, + 'minorVersion' => $library5->minorversion, + 'patchVersion' => $library5->patchversion, + 'preloadedCss' => $library5->preloadedcss, + 'preloadedJs' => $library5->preloadedjs, + 'dropCss' => '0', + 'dependencyType' => 'dynamic' + ) + ) + ); + + // The loaded content dependencies should return 6 libraries. + $this->assertCount(6, $contentdependencies); + $this->assertEquals($expected, $contentdependencies); + } + + /** + * Test the behaviour of loadContentDependencies() when requesting content dependencies + * with specifying the dependency type. + */ + public function test_loadContentDependencies_type_defined() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $data = $generator->generate_h5p_data(); + // The Id of the h5p content. + $h5pid = $data->h5pcontent->h5pid; + // The content dependencies. + $dependencies = $data->h5pcontent->contentdependencies; + + // Add Library5 as a content dependency (dynamic dependency type). + $library5 = $data->lib5->data; + $generator->create_contents_libraries_record($h5pid, $library5->id, 'dynamic'); + + // Load all content dependencies of dependency type 'preloaded'. + $preloadeddependencies = $this->framework->loadContentDependencies($h5pid, 'preloaded'); + + $expected = array(); + foreach ($dependencies as $dependency) { + $expected[$dependency->machinename] = array( + 'libraryId' => $dependency->id, + 'machineName' => $dependency->machinename, + 'majorVersion' => $dependency->majorversion, + 'minorVersion' => $dependency->minorversion, + 'patchVersion' => $dependency->patchversion, + 'preloadedCss' => $dependency->preloadedcss, + 'preloadedJs' => $dependency->preloadedjs, + 'dropCss' => '0', + 'dependencyType' => 'preloaded' + ); + } + + // The loaded content dependencies should return 5 libraries. + $this->assertCount(5, $preloadeddependencies); + $this->assertEquals($expected, $preloadeddependencies); + + // Load all content dependencies of dependency type 'dynamic'. + $dynamicdependencies = $this->framework->loadContentDependencies($h5pid, 'dynamic'); + + $expected = array( + 'Library5' => array( + 'libraryId' => $library5->id, + 'machineName' => $library5->machinename, + 'majorVersion' => $library5->majorversion, + 'minorVersion' => $library5->minorversion, + 'patchVersion' => $library5->patchversion, + 'preloadedCss' => $library5->preloadedcss, + 'preloadedJs' => $library5->preloadedjs, + 'dropCss' => '0', + 'dependencyType' => 'dynamic' + ) + ); + + // The loaded content dependencies should now return 1 library. + $this->assertCount(1, $dynamicdependencies); + $this->assertEquals($expected, $dynamicdependencies); + } + + /** + * Test the behaviour of updateContentFields(). + */ + public function test_updateContentFields() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create 'Library1' library. + $library1 = $generator->create_library_record('Library1', 'Lib1', 1, 1, 2); + // Create 'Library2' library. + $library2 = $generator->create_library_record('Library2', 'Lib2', 1, 1, 2); + + // Create an h5p content with 'Library1' as it's main library. + $h5pid = $generator->create_h5p_record($library1->id, 'iframe'); + + $updatedata = array( + 'jsoncontent' => json_encode(['value' => 'test']), + 'mainlibraryid' => $library2->id + ); + + // Update h5p content fields. + $this->framework->updateContentFields($h5pid, $updatedata); + + // Get the h5p content from the DB. + $h5p = $DB->get_record('h5p', ['id' => $h5pid]); + + $expected = json_encode(['value' => 'test']); + + // Make sure the h5p content fields are properly updated. + $this->assertEquals($expected, $h5p->jsoncontent); + $this->assertEquals($library2->id, $h5p->mainlibraryid); + } + + /** + * Test the behaviour of clearFilteredParameters(). + */ + public function test_clearFilteredParameters() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create 3 libraries. + $library1 = $generator->create_library_record('Library1', 'Lib1', 1, 1, 2); + $library2 = $generator->create_library_record('Library2', 'Lib2', 1, 1, 2); + $library3 = $generator->create_library_record('Library3', 'Lib3', 1, 1, 2); + + // Create h5p content with 'Library1' as a main library. + $h5pcontentid1 = $generator->create_h5p_record($library1->id); + // Create h5p content with 'Library1' as a main library. + $h5pcontentid2 = $generator->create_h5p_record($library1->id); + // Create h5p content with 'Library2' as a main library. + $h5pcontentid3 = $generator->create_h5p_record($library2->id); + // Create h5p content with 'Library3' as a main library. + $h5pcontentid4 = $generator->create_h5p_record($library3->id); + + $h5pcontent1 = $DB->get_record('h5p', ['id' => $h5pcontentid1]); + $h5pcontent2 = $DB->get_record('h5p', ['id' => $h5pcontentid2]); + $h5pcontent3 = $DB->get_record('h5p', ['id' => $h5pcontentid3]); + $h5pcontent4 = $DB->get_record('h5p', ['id' => $h5pcontentid4]); + + // The filtered parameters should be present in each h5p content. + $this->assertNotEmpty($h5pcontent1->filtered); + $this->assertNotEmpty($h5pcontent2->filtered); + $this->assertNotEmpty($h5pcontent3->filtered); + $this->assertNotEmpty($h5pcontent4->filtered); + + // Clear the filtered parameters for contents that have library1 and library3 as + // their main library. + $this->framework->clearFilteredParameters([$library1->id, $library3->id]); + + $h5pcontent1 = $DB->get_record('h5p', ['id' => $h5pcontentid1]); + $h5pcontent2 = $DB->get_record('h5p', ['id' => $h5pcontentid2]); + $h5pcontent3 = $DB->get_record('h5p', ['id' => $h5pcontentid3]); + $h5pcontent4 = $DB->get_record('h5p', ['id' => $h5pcontentid4]); + + // The filtered parameters should be still present only for the content that has + // library 2 as a main library. + $this->assertEmpty($h5pcontent1->filtered); + $this->assertEmpty($h5pcontent2->filtered); + $this->assertNotEmpty($h5pcontent3->filtered); + $this->assertEmpty($h5pcontent4->filtered); + } + + /** + * Test the behaviour of getNumNotFiltered(). + */ + public function test_getNumNotFiltered() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Create 3 libraries. + $library1 = $generator->create_library_record('Library1', 'Lib1', 1, 1, 2); + $library2 = $generator->create_library_record('Library2', 'Lib2', 1, 1, 2); + $library3 = $generator->create_library_record('Library3', 'Lib3', 1, 1, 2); + + // Create h5p content with library1 as a main library. + $h5pcontentid1 = $generator->create_h5p_record($library1->id); + // Create h5p content with library1 as a main library. + $h5pcontentid2 = $generator->create_h5p_record($library1->id); + // Create h5p content with library2 as a main library. + $h5pcontentid3 = $generator->create_h5p_record($library2->id); + // Create h5p content with library3 as a main library. + $h5pcontentid4 = $generator->create_h5p_record($library3->id); + + $h5pcontent1 = $DB->get_record('h5p', ['id' => $h5pcontentid1]); + $h5pcontent2 = $DB->get_record('h5p', ['id' => $h5pcontentid2]); + $h5pcontent3 = $DB->get_record('h5p', ['id' => $h5pcontentid3]); + $h5pcontent4 = $DB->get_record('h5p', ['id' => $h5pcontentid4]); + + // The filtered parameters should be present in each h5p content. + $this->assertNotEmpty($h5pcontent1->filtered); + $this->assertNotEmpty($h5pcontent2->filtered); + $this->assertNotEmpty($h5pcontent3->filtered); + $this->assertNotEmpty($h5pcontent4->filtered); + + // Clear the filtered parameters for contents that have library1 and library3 as + // their main library. + $this->framework->clearFilteredParameters([$library1->id, $library3->id]); + + $countnotfiltered = $this->framework->getNumNotFiltered(); + + // 3 contents don't have their parameters filtered. + $this->assertEquals(3, $countnotfiltered); + } + + /** + * Test the behaviour of getNumContent(). + */ + public function test_getNumContent() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $data = $generator->generate_h5p_data(); + + // The 'MainLibrary' library data. + $mainlibrary = $data->mainlib->data; + + // The 'Library1' library data. + $library1 = $data->lib1->data; + + // Create new h5p content with MainLibrary as a main library. + $generator->create_h5p_record($mainlibrary->id); + + // Get the number of h5p contents that are using 'MainLibrary' as their main library. + $countmainlib = $this->framework->getNumContent($mainlibrary->id); + + // Get the number of h5p contents that are using 'Library1' as their main library. + $countlib1 = $this->framework->getNumContent($library1->id); + + // Make sure that 2 contents are using MainLibrary as their main library. + $this->assertEquals(2, $countmainlib); + // Make sure that 0 contents are using Library1 as their main library. + $this->assertEquals(0, $countlib1); + } + + /** + * Test the behaviour of getNumContent() when certain contents are being skipped. + */ + public function test_getNumContent_skip_content() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $data = $generator->generate_h5p_data(); + + // The 'MainLibrary' library data. + $mainlibrary = $data->mainlib->data; + + // Create new h5p content with MainLibrary as a main library. + $h5pcontentid = $generator->create_h5p_record($mainlibrary->id); + + // Get the number of h5p contents that are using 'MainLibrary' as their main library. + // Skip the newly created content $h5pcontentid. + $countmainlib = $this->framework->getNumContent($mainlibrary->id, [$h5pcontentid]); + + // Make sure that 1 content is returned instead of 2 ($h5pcontentid being skipped). + $this->assertEquals(1, $countmainlib); + } + + /** + * Test the behaviour of isContentSlugAvailable(). + */ + public function test_isContentSlugAvailable() { + $this->resetAfterTest(); + + $slug = 'h5p-test-slug-1'; + + // Currently this returns always true. The slug is generated as a unique value for + // each h5p content and it is not stored in the h5p content table. + $isslugavailable = $this->framework->isContentSlugAvailable($slug); + + $this->assertTrue($isslugavailable); + } + + /** + * Test that a record is stored for cached assets. + */ + public function test_saveCachedAssets() { + global $DB; + + $this->resetAfterTest(); + + $libraries = array( + array( + 'machineName' => 'H5P.TestLib', + 'libraryId' => 405, + ), + array( + 'FontAwesome' => 'FontAwesome', + 'libraryId' => 406, + ), + array( + 'machineName' => 'H5P.SecondLib', + 'libraryId' => 407, + ), + ); + + $key = 'testhashkey'; + + $this->framework->saveCachedAssets($key, $libraries); + + $records = $DB->get_records('h5p_libraries_cachedassets'); + + $this->assertCount(3, $records); + } + + /** + * Test that the correct libraries are removed from the cached assets table + */ + public function test_deleteCachedAssets() { + global $DB; + + $this->resetAfterTest(); + + $libraries = array( + array( + 'machineName' => 'H5P.TestLib', + 'libraryId' => 405, + ), + array( + 'FontAwesome' => 'FontAwesome', + 'libraryId' => 406, + ), + array( + 'machineName' => 'H5P.SecondLib', + 'libraryId' => 407, + ), + ); + + $key1 = 'testhashkey'; + $this->framework->saveCachedAssets($key1, $libraries); + + $libraries = array( + array( + 'machineName' => 'H5P.DiffLib', + 'libraryId' => 408, + ), + array( + 'FontAwesome' => 'FontAwesome', + 'libraryId' => 406, + ), + array( + 'machineName' => 'H5P.ThirdLib', + 'libraryId' => 409, + ), + ); + + $key2 = 'secondhashkey'; + $this->framework->saveCachedAssets($key2, $libraries); + + $libraries = array( + array( + 'machineName' => 'H5P.AnotherDiffLib', + 'libraryId' => 410, + ), + array( + 'FontAwesome' => 'NotRelated', + 'libraryId' => 411, + ), + array( + 'machineName' => 'H5P.ForthLib', + 'libraryId' => 412, + ), + ); + + $key3 = 'threeforthewin'; + $this->framework->saveCachedAssets($key3, $libraries); + + $records = $DB->get_records('h5p_libraries_cachedassets'); + $this->assertCount(9, $records); + + // Selecting one library id will result in all related library entries also being deleted. + // Going to use the FontAwesome library id. The first two hashes should be returned. + $hashes = $this->framework->deleteCachedAssets(406); + $this->assertCount(2, $hashes); + $index = array_search($key1, $hashes); + $this->assertEquals($key1, $hashes[$index]); + $index = array_search($key2, $hashes); + $this->assertEquals($key2, $hashes[$index]); + $index = array_search($key3, $hashes); + $this->assertFalse($index); + + // Check that the records have been removed as well. + $records = $DB->get_records('h5p_libraries_cachedassets'); + $this->assertCount(3, $records); + } + + /** + * Test the behaviour of getLibraryContentCount(). + */ + public function test_getLibraryContentCount() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + // Generate h5p related data. + $data = $generator->generate_h5p_data(); + + // The 'MainLibrary' library data. + $mainlibrary = $data->mainlib->data; + + // The 'Library2' library data. + $library2 = $data->lib2->data; + + // Create new h5p content with Library2 as it's main library. + $generator->create_h5p_record($library2->id); + + // Create new h5p content with MainLibrary as it's main library. + $generator->create_h5p_record($mainlibrary->id); + + $countlibrarycontent = $this->framework->getLibraryContentCount(); + + $expected = array( + "{$mainlibrary->machinename} {$mainlibrary->majorversion}.{$mainlibrary->minorversion}" => 2, + "{$library2->machinename} {$library2->majorversion}.{$library2->minorversion}" => 1, + ); + + // MainLibrary and Library1 are currently main libraries to the existing h5p contents. + // Should return the number of cases where MainLibrary and Library1 are main libraries to an h5p content. + $this->assertEquals($expected, $countlibrarycontent); + } + + /** + * Test the behaviour of test_libraryHasUpgrade(). + * + * @dataProvider test_libraryHasUpgrade_provider + * @param array $libraryrecords Array containing data for the library creation + * @param array $testlibrary Array containing the test library data + * @param bool $expected The expectation whether the library is patched or not + **/ + public function test_libraryHasUpgrade(array $libraryrecords, array $testlibrary, bool $expected): void { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + foreach ($libraryrecords as $library) { + call_user_func_array([$generator, 'create_library_record'], $library); + } + + $this->assertEquals($expected, $this->framework->libraryHasUpgrade($testlibrary)); + } + + /** + * Data provider for test_libraryHasUpgrade(). + * + * @return array + */ + public function test_libraryHasUpgrade_provider(): array { + return [ + 'Lower major version; Identical lower version' => [ + [ + ['Library', 'Lib', 2, 2], + ], + [ + 'machineName' => 'Library', + 'majorVersion' => 1, + 'minorVersion' => 2 + ], + true, + ], + 'Major version identical; Lower minor version' => [ + [ + ['Library', 'Lib', 2, 2], + ], + [ + 'machineName' => 'Library', + 'majorVersion' => 2, + 'minorVersion' => 1 + ], + true, + ], + 'Major version identical; Minor version identical' => [ + [ + ['Library', 'Lib', 2, 2], + ], + [ + 'machineName' => 'Library', + 'majorVersion' => 2, + 'minorVersion' => 2 + ], + false, + ], + 'Major version higher; Minor version identical' => [ + [ + ['Library', 'Lib', 2, 2], + ], + [ + 'machineName' => 'Library', + 'majorVersion' => 3, + 'minorVersion' => 2 + ], + false, + ], + 'Major version identical; Minor version newer' => [ + [ + ['Library', 'Lib', 2, 2], + ], + [ + 'machineName' => 'Library', + 'majorVersion' => 2, + 'minorVersion' => 4 + ], + false, + ] + ]; + } +} diff --git a/h5p/tests/generator/lib.php b/h5p/tests/generator/lib.php index 6175e11aefb..22cdb54b80c 100644 --- a/h5p/tests/generator/lib.php +++ b/h5p/tests/generator/lib.php @@ -59,7 +59,7 @@ class core_h5p_generator extends \component_generator_base { * @param string $version Not really needed at the moment. */ protected function add_libfile_to_array(string $type, string $path, string $version, &$files): void { - $files[$type][] = (object) [ + $files[$type][] = (object)[ 'path' => $path, 'version' => "?ver=$version" ]; @@ -75,8 +75,8 @@ class core_h5p_generator extends \component_generator_base { * @param int $minorversion Minor version (any number will do). * @return array A list of library data and files that the core API will understand. */ - public function create_library(string $uploaddirectory, int $libraryid, string $machinename, int $majorversion, int -$minorversion): array { + public function create_library(string $uploaddirectory, int $libraryid, string $machinename, int $majorversion, + int $minorversion): array { /** @var array $files an array used in the cache tests. */ $files = ['scripts' => [], 'styles' => []]; @@ -121,4 +121,222 @@ $minorversion): array { return [$lib, $files]; } -} \ No newline at end of file + /** + * Save the library files on the filesystem. + * + * @param stdClss $lib The library data + */ + private function save_library(stdClass $lib) { + // Get a temp path. + $filestorage = new \core_h5p\file_storage(); + $temppath = $filestorage->getTmpPath(); + + // Create and save the library files on the filesystem. + $basedirectorymain = $temppath . '/' . $lib->machinename . '-' . + $lib->majorversion . '.' . $lib->minorversion; + + list($library, $libraryfiles) = $this->create_library($basedirectorymain, $lib->id, $lib->machinename, + $lib->majorversion, $lib->minorversion); + + $filestorage->saveLibrary($library); + } + + /** + * Populate H5P database tables with relevant data to simulate the process of adding H5P content. + * + * @param bool $createlibraryfiles Whether to create and store library files on the filesystem + * @return stdClass An object representing the added H5P records + */ + public function generate_h5p_data(bool $createlibraryfiles = false): stdClass { + // Create libraries. + $mainlib = $libraries[] = $this->create_library_record('MainLibrary', 'Main Lib', 1, 0); + $lib1 = $libraries[] = $this->create_library_record('Library1', 'Lib1', 2, 0); + $lib2 = $libraries[] = $this->create_library_record('Library2', 'Lib2', 2, 1); + $lib3 = $libraries[] = $this->create_library_record('Library3', 'Lib3', 3, 2); + $lib4 = $libraries[] = $this->create_library_record('Library4', 'Lib4', 1, 1); + $lib5 = $libraries[] = $this->create_library_record('Library5', 'Lib5', 1, 3); + + if ($createlibraryfiles) { + foreach ($libraries as $lib) { + // Create and save the library files on the filesystem. + $this->save_library($lib); + } + } + + // Create h5p content. + $h5p = $this->create_h5p_record($mainlib->id); + // Create h5p content library dependencies. + $this->create_contents_libraries_record($h5p, $mainlib->id); + $this->create_contents_libraries_record($h5p, $lib1->id); + $this->create_contents_libraries_record($h5p, $lib2->id); + $this->create_contents_libraries_record($h5p, $lib3->id); + $this->create_contents_libraries_record($h5p, $lib4->id); + // Create library dependencies for $mainlib. + $this->create_library_dependency_record($mainlib->id, $lib1->id); + $this->create_library_dependency_record($mainlib->id, $lib2->id); + $this->create_library_dependency_record($mainlib->id, $lib3->id); + // Create library dependencies for $lib1. + $this->create_library_dependency_record($lib1->id, $lib2->id); + $this->create_library_dependency_record($lib1->id, $lib3->id); + $this->create_library_dependency_record($lib1->id, $lib4->id); + // Create library dependencies for $lib3. + $this->create_library_dependency_record($lib3->id, $lib5->id); + + return (object) [ + 'h5pcontent' => (object) array( + 'h5pid' => $h5p, + 'contentdependencies' => array($mainlib, $lib1, $lib2, $lib3, $lib4) + ), + 'mainlib' => (object) array( + 'data' => $mainlib, + 'dependencies' => array($lib1, $lib2, $lib3) + ), + 'lib1' => (object) array( + 'data' => $lib1, + 'dependencies' => array($lib2, $lib3, $lib4) + ), + 'lib2' => (object) array( + 'data' => $lib2, + 'dependencies' => array() + ), + 'lib3' => (object) array( + 'data' => $lib3, + 'dependencies' => array($lib5) + ), + 'lib4' => (object) array( + 'data' => $lib4, + 'dependencies' => array() + ), + 'lib5' => (object) array( + 'data' => $lib5, + 'dependencies' => array() + ), + ]; + } + + /** + * Create a record in the h5p_libraries database table. + * + * @param string $machinename The library machine name + * @param string $title The library's name + * @param int $majorversion The library's major version + * @param int $minorversion The library's minor version + * @param int $patchversion The library's patch version + * @param string $semantics Json describing the content structure for the library + * @param string $addto The plugin configuration data + * @return stdClass An object representing the added library record + */ + public function create_library_record(string $machinename, string $title, int $majorversion = 1, + int $minorversion = 0, int $patchversion = 1, string $semantics = '', string $addto = null): stdClass { + global $DB; + + $content = array( + 'machinename' => $machinename, + 'title' => $title, + 'majorversion' => $majorversion, + 'minorversion' => $minorversion, + 'patchversion' => $patchversion, + 'runnable' => 1, + 'fullscreen' => 1, + 'preloadedjs' => 'js/example.js', + 'preloadedcss' => 'css/example.css', + 'droplibrarycss' => '', + 'semantics' => $semantics, + 'addto' => $addto + ); + + $libraryid = $DB->insert_record('h5p_libraries', $content); + + return $DB->get_record('h5p_libraries', ['id' => $libraryid]); + } + + /** + * Create a record in the h5p database table. + * + * @param int $mainlibid The ID of the content's main library + * @param string $jsoncontent The content in json format + * @param string $filtered The filtered content parameters + * @return int The ID of the added record + */ + public function create_h5p_record(int $mainlibid, string $jsoncontent = null, string $filtered = null): int { + global $DB; + + if (!$jsoncontent) { + $jsoncontent = json_encode( + array( + 'text' => '

      Dummy text<\/p>\n', + 'questions' => '

      Test question<\/p>\n' + ) + ); + } + + if (!$filtered) { + $filtered = json_encode( + array( + 'text' => 'Dummy text', + 'questions' => 'Test question' + ) + ); + } + + return $DB->insert_record( + 'h5p', + array( + 'jsoncontent' => $jsoncontent, + 'displayoptions' => 8, + 'mainlibraryid' => $mainlibid, + 'timecreated' => time(), + 'timemodified' => time(), + 'filtered' => $filtered, + 'pathnamehash' => sha1('pathname'), + 'contenthash' => sha1('content') + ) + ); + } + + /** + * Create a record in the h5p_contents_libraries database table. + * + * @param string $h5pid The ID of the H5P content + * @param int $libid The ID of the library + * @param string $dependencytype The dependency type + * @return int The ID of the added record + */ + public function create_contents_libraries_record(string $h5pid, int $libid, + string $dependencytype = 'preloaded'): int { + global $DB; + + return $DB->insert_record( + 'h5p_contents_libraries', + array( + 'h5pid' => $h5pid, + 'libraryid' => $libid, + 'dependencytype' => $dependencytype, + 'dropcss' => 0, + 'weight' => 1 + ) + ); + } + + /** + * Create a record in the h5p_library_dependencies database table. + * + * @param int $libid The ID of the library + * @param int $requiredlibid The ID of the required library + * @param string $dependencytype The dependency type + * @return int The ID of the added record + */ + public function create_library_dependency_record(int $libid, int $requiredlibid, + string $dependencytype = 'preloaded'): int { + global $DB; + + return $DB->insert_record( + 'h5p_library_dependencies', + array( + 'libraryid' => $libid, + 'requiredlibraryid' => $requiredlibid, + 'dependencytype' => $dependencytype + ) + ); + } +} diff --git a/h5p/tests/generator_test.php b/h5p/tests/generator_test.php new file mode 100644 index 00000000000..0ad41d4458d --- /dev/null +++ b/h5p/tests/generator_test.php @@ -0,0 +1,478 @@ +. + +/** +* Test class covering the h5p data generator class. +* +* @package core_h5p +* @category test +* @copyright 2019 Mihail Geshoski +* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later +*/ + +namespace core_h5p; + +defined('MOODLE_INTERNAL') || die(); + +/** +* Generator testcase for the core_grading generator. +* +* @package core_h5p +* @category test +* @copyright 2019 Mihail Geshoski +* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later +*/ +class generator_testcase extends \advanced_testcase { + + /** + * Test the returned data of generate_h5p_data() when the method is called without requesting + * creation of library files. + */ + public function test_generate_h5p_data_no_files_created_return_data() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + $data = $generator->generate_h5p_data(); + + $mainlib = $DB->get_record('h5p_libraries', ['machinename' => 'MainLibrary']); + $lib1 = $DB->get_record('h5p_libraries', ['machinename' => 'Library1']); + $lib2 = $DB->get_record('h5p_libraries', ['machinename' => 'Library2']); + $lib3 = $DB->get_record('h5p_libraries', ['machinename' => 'Library3']); + $lib4 = $DB->get_record('h5p_libraries', ['machinename' => 'Library4']); + $lib5 = $DB->get_record('h5p_libraries', ['machinename' => 'Library5']); + + $h5p = $DB->get_record('h5p', ['mainlibraryid' => $mainlib->id]); + + $expected = (object) [ + 'h5pcontent' => (object) array( + 'h5pid' => $h5p->id, + 'contentdependencies' => array($mainlib, $lib1, $lib2, $lib3, $lib4) + ), + 'mainlib' => (object) array( + 'data' => $mainlib, + 'dependencies' => array($lib1, $lib2, $lib3) + ), + 'lib1' => (object) array( + 'data' => $lib1, + 'dependencies' => array($lib2, $lib3, $lib4) + ), + 'lib2' => (object) array( + 'data' => $lib2, + 'dependencies' => array() + ), + 'lib3' => (object) array( + 'data' => $lib3, + 'dependencies' => array($lib5) + ), + 'lib4' => (object) array( + 'data' => $lib4, + 'dependencies' => array() + ), + 'lib5' => (object) array( + 'data' => $lib5, + 'dependencies' => array() + ), + ]; + + $this->assertEquals($expected, $data); + } + + /** + * Test the returned data of generate_h5p_data() when the method requests + * creation of library files. + */ + public function test_generate_h5p_data_files_created_return_data() { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + $data = $generator->generate_h5p_data(true); + + $mainlib = $DB->get_record('h5p_libraries', ['machinename' => 'MainLibrary']); + $lib1 = $DB->get_record('h5p_libraries', ['machinename' => 'Library1']); + $lib2 = $DB->get_record('h5p_libraries', ['machinename' => 'Library2']); + $lib3 = $DB->get_record('h5p_libraries', ['machinename' => 'Library3']); + $lib4 = $DB->get_record('h5p_libraries', ['machinename' => 'Library4']); + $lib5 = $DB->get_record('h5p_libraries', ['machinename' => 'Library5']); + + $h5p = $DB->get_record('h5p', ['mainlibraryid' => $mainlib->id]); + + $expected = (object) [ + 'h5pcontent' => (object) array( + 'h5pid' => $h5p->id, + 'contentdependencies' => array($mainlib, $lib1, $lib2, $lib3, $lib4) + ), + 'mainlib' => (object) array( + 'data' => $mainlib, + 'dependencies' => array($lib1, $lib2, $lib3) + ), + 'lib1' => (object) array( + 'data' => $lib1, + 'dependencies' => array($lib2, $lib3, $lib4) + ), + 'lib2' => (object) array( + 'data' => $lib2, + 'dependencies' => array() + ), + 'lib3' => (object) array( + 'data' => $lib3, + 'dependencies' => array($lib5) + ), + 'lib4' => (object) array( + 'data' => $lib4, + 'dependencies' => array() + ), + 'lib5' => (object) array( + 'data' => $lib5, + 'dependencies' => array() + ), + ]; + + $this->assertEquals($expected, $data); + } + + /** + * Test the behaviour of generate_h5p_data(). Test whether library files are created or not + * on filesystem depending what the method defines. + * + * @dataProvider test_generate_h5p_data_files_creation_provider + * @param bool $createlibraryfiles Whether to create library files on the filesystem + * @param bool $expected The expectation whether the files have been created or not + **/ + public function test_generate_h5p_data_files_creation(bool $createlibraryfiles, bool $expected) { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + $generator->generate_h5p_data($createlibraryfiles); + + $libraries[] = $DB->get_record('h5p_libraries', ['machinename' => 'MainLibrary']); + $libraries[] = $DB->get_record('h5p_libraries', ['machinename' => 'Library1']); + $libraries[] = $DB->get_record('h5p_libraries', ['machinename' => 'Library2']); + $libraries[] = $DB->get_record('h5p_libraries', ['machinename' => 'Library3']); + $libraries[] = $DB->get_record('h5p_libraries', ['machinename' => 'Library4']); + $libraries[] = $DB->get_record('h5p_libraries', ['machinename' => 'Library5']); + + foreach($libraries as $lib) { + // Return the created library files. + $libraryfiles = $DB->get_records('files', + array( + 'component' => \core_h5p\file_storage::COMPONENT, + 'filearea' => \core_h5p\file_storage::LIBRARY_FILEAREA, + 'itemid' => $lib->id + ) + ); + + $haslibraryfiles = !empty($libraryfiles); + + $this->assertEquals($expected, $haslibraryfiles); + } + } + + /** + * Data provider for test_generate_h5p_data_files_creation(). + * + * @return array + */ + public function test_generate_h5p_data_files_creation_provider(): array { + return [ + 'Do not create library related files on the filesystem' => [ + false, + false + ], + 'Create library related files on the filesystem' => [ + true, + true + ] + ]; + } + + /** + * Test the behaviour of create_library_record(). Test whether the library data is properly + * saved in the database. + */ + public function test_create_library_record() { + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + $data = $generator->create_library_record('Library', 'Lib', 1, 2, 3, 'Semantics example', '/regex11/'); + unset($data->id); + + $expected = (object) [ + 'machinename' => 'Library', + 'title' => 'Lib', + 'majorversion' => '1', + 'minorversion' => '2', + 'patchversion' => '3', + 'runnable' => '1', + 'fullscreen' => '1', + 'embedtypes' => '', + 'preloadedjs' => 'js/example.js', + 'preloadedcss' => 'css/example.css', + 'droplibrarycss' => '', + 'semantics' => 'Semantics example', + 'addto' => '/regex11/' + ]; + + $this->assertEquals($expected, $data); + } + + /** + * Test the behaviour of create_h5p_record(). Test whather the h5p content data is + * properly saved in the database. + * + * @dataProvider test_create_h5p_record_provider + * @param array $h5pdata The h5p content data + * @param \stdClass $expected The expected saved data + **/ + public function test_create_h5p_record(array $h5pdata, \stdClass $expected) { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + $h5pid = call_user_func_array([$generator, 'create_h5p_record'], $h5pdata); + + $data = $DB->get_record('h5p', ['id' => $h5pid]); + unset($data->id); + unset($data->timecreated); + unset($data->timemodified); + + $this->assertEquals($data, $expected); + } + + /** + * Data provider for test_create_h5p_record(). + * + * @return array + */ + public function test_create_h5p_record_provider(): array { + $createdjsoncontent = json_encode( + array( + 'text' => '

      Created dummy text<\/p>\n', + 'questions' => '

      Test created question<\/p>\n' + ) + ); + + $defaultjsoncontent = json_encode( + array( + 'text' => '

      Dummy text<\/p>\n', + 'questions' => '

      Test question<\/p>\n' + ) + ); + + $createdfilteredcontent = json_encode( + array( + 'text' => 'Created dummy text', + 'questions' => 'Test created question' + ) + ); + + $defaultfilteredcontent = json_encode( + array( + 'text' => 'Dummy text', + 'questions' => 'Test question' + ) + ); + + return [ + 'Create h5p content record with set json content and set filtered content' => [ + [ + 1, + $createdjsoncontent, + $createdfilteredcontent + ], + (object) array( + 'jsoncontent' => $createdjsoncontent, + 'mainlibraryid' => '1', + 'displayoptions' => '8', + 'pathnamehash' => sha1('pathname'), + 'contenthash' => sha1('content'), + 'filtered' => $createdfilteredcontent, + ) + ], + 'Create h5p content record with set json content and default filtered content' => [ + [ + 1, + $createdjsoncontent, + null + ], + (object) array( + 'jsoncontent' => $createdjsoncontent, + 'mainlibraryid' => '1', + 'displayoptions' => '8', + 'pathnamehash' => sha1('pathname'), + 'contenthash' => sha1('content'), + 'filtered' => $defaultfilteredcontent, + ) + ], + 'Create h5p content record with default json content and set filtered content' => [ + [ + 1, + null, + $createdfilteredcontent + ], + (object) array( + 'jsoncontent' => $defaultjsoncontent, + 'mainlibraryid' => '1', + 'displayoptions' => '8', + 'pathnamehash' => sha1('pathname'), + 'contenthash' => sha1('content'), + 'filtered' => $createdfilteredcontent, + ) + ], + 'Create h5p content record with default json content and default filtered content' => [ + [ + 1, + null, + null + ], + (object) array( + 'jsoncontent' => $defaultjsoncontent, + 'mainlibraryid' => '1', + 'displayoptions' => '8', + 'pathnamehash' => sha1('pathname'), + 'contenthash' => sha1('content'), + 'filtered' => $defaultfilteredcontent, + ) + ] + ]; + } + + /** + * Test the behaviour of create_contents_libraries_record(). Test whether the contents libraries + * are properly saved in the database. + * + * @dataProvider test_create_contents_libraries_record_provider + * @param array $contentslibrariestdata The h5p contents libraries data. + * @param \stdClass $expected The expected saved data. + **/ + public function test_create_contents_libraries_record(array $contentslibrariestdata, \stdClass $expected) { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + $contentlibid = call_user_func_array([$generator, 'create_contents_libraries_record'], $contentslibrariestdata); + + $data = $DB->get_record('h5p_contents_libraries', ['id' => $contentlibid]); + unset($data->id); + + $this->assertEquals($data, $expected); + } + + /** + * Data provider for test_create_contents_libraries_record(). + * + * @return array + */ + public function test_create_contents_libraries_record_provider(): array { + return [ + 'Create h5p content library with set dependency type' => [ + [ + 1, + 1, + 'dynamic' + ], + (object) array( + 'h5pid' => '1', + 'libraryid' => '1', + 'dependencytype' => 'dynamic', + 'dropcss' => '0', + 'weight' => '1' + ) + ], + 'Create h5p content library with a default dependency type' => [ + [ + 1, + 1 + ], + (object) array( + 'h5pid' => '1', + 'libraryid' => '1', + 'dependencytype' => 'preloaded', + 'dropcss' => '0', + 'weight' => '1' + ) + ] + ]; + } + + /** + * Test the behaviour of create_library_dependency_record(). Test whether the contents libraries + * are properly saved in the database. + * + * @dataProvider test_create_library_dependency_record_provider + * @param array $librarydependencydata The library dependency data. + * @param \stdClass $expected The expected saved data. + **/ + public function test_create_library_dependency_record(array $librarydependencydata, \stdClass $expected) { + global $DB; + + $this->resetAfterTest(); + + $generator = $this->getDataGenerator()->get_plugin_generator('core_h5p'); + + $contentlibid = call_user_func_array([$generator, 'create_library_dependency_record'], $librarydependencydata); + + $data = $DB->get_record('h5p_library_dependencies', ['id' => $contentlibid]); + unset($data->id); + + $this->assertEquals($data, $expected); + } + + /** + * Data provider for test_create_library_dependency_record(). + * + * @return array + */ + public function test_create_library_dependency_record_provider(): array { + return [ + 'Create h5p library dependency with set dependency type' => [ + [ + 1, + 1, + 'dynamic' + ], + (object) array( + 'libraryid' => '1', + 'requiredlibraryid' => '1', + 'dependencytype' => 'dynamic' + ) + ], + 'Create h5p library dependency with default dependency type' => [ + [ + 1, + 1 + ], + (object) array( + 'libraryid' => '1', + 'requiredlibraryid' => '1', + 'dependencytype' => 'preloaded' + ) + ] + ]; + } +} From b6fb5f036248980535791b626d1f7045118c2317 Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Fri, 27 Sep 2019 12:03:28 +0200 Subject: [PATCH 08/22] MDL-66609 core_h5p: Update the h5p-resizer.js reference in Atto --- .eslintignore | 1 - .stylelintignore | 1 - lib/editor/atto/plugins/h5p/js/h5p-resizer.js | 131 ------------------ .../atto/plugins/h5p/js/readme_moodle.txt | 9 -- lib/editor/atto/plugins/h5p/lib.php | 2 +- .../atto/plugins/h5p/thirdpartylibs.xml | 10 -- .../moodle-atto_h5p-button-debug.js | 2 +- .../moodle-atto_h5p-button-min.js | 2 +- .../moodle-atto_h5p-button.js | 2 +- .../plugins/h5p/yui/src/button/js/button.js | 2 +- 10 files changed, 5 insertions(+), 157 deletions(-) delete mode 100644 lib/editor/atto/plugins/h5p/js/h5p-resizer.js delete mode 100644 lib/editor/atto/plugins/h5p/js/readme_moodle.txt delete mode 100644 lib/editor/atto/plugins/h5p/thirdpartylibs.xml diff --git a/.eslintignore b/.eslintignore index 4992f80a9c9..b6ab7a7f7ee 100644 --- a/.eslintignore +++ b/.eslintignore @@ -9,7 +9,6 @@ cache/stores/mongodb/MongoDB/ enrol/lti/ims-blti/ filter/algebra/AlgParser.pm filter/tex/mimetex.* -lib/editor/atto/plugins/h5p/js/h5p-resizer.js lib/editor/atto/plugins/html/yui/src/codemirror/ lib/editor/atto/plugins/html/yui/src/beautify/ lib/editor/atto/yui/src/rangy/js/*.* diff --git a/.stylelintignore b/.stylelintignore index af419831a91..052248f388c 100644 --- a/.stylelintignore +++ b/.stylelintignore @@ -10,7 +10,6 @@ cache/stores/mongodb/MongoDB/ enrol/lti/ims-blti/ filter/algebra/AlgParser.pm filter/tex/mimetex.* -lib/editor/atto/plugins/h5p/js/h5p-resizer.js lib/editor/atto/plugins/html/yui/src/codemirror/ lib/editor/atto/plugins/html/yui/src/beautify/ lib/editor/atto/yui/src/rangy/js/*.* diff --git a/lib/editor/atto/plugins/h5p/js/h5p-resizer.js b/lib/editor/atto/plugins/h5p/js/h5p-resizer.js deleted file mode 100644 index ed78724ec1a..00000000000 --- a/lib/editor/atto/plugins/h5p/js/h5p-resizer.js +++ /dev/null @@ -1,131 +0,0 @@ -// H5P iframe Resizer -(function () { - if (!window.postMessage || !window.addEventListener || window.h5pResizerInitialized) { - return; // Not supported - } - window.h5pResizerInitialized = true; - - // Map actions to handlers - var actionHandlers = {}; - - /** - * Prepare iframe resize. - * - * @private - * @param {Object} iframe Element - * @param {Object} data Payload - * @param {Function} respond Send a response to the iframe - */ - actionHandlers.hello = function (iframe, data, respond) { - // Make iframe responsive - iframe.style.width = '100%'; - - // Bugfix for Chrome: Force update of iframe width. If this is not done the - // document size may not be updated before the content resizes. - iframe.getBoundingClientRect(); - - // Tell iframe that it needs to resize when our window resizes - var resize = function () { - if (iframe.contentWindow) { - // Limit resize calls to avoid flickering - respond('resize'); - } - else { - // Frame is gone, unregister. - window.removeEventListener('resize', resize); - } - }; - window.addEventListener('resize', resize, false); - - // Respond to let the iframe know we can resize it - respond('hello'); - }; - - /** - * Prepare iframe resize. - * - * @private - * @param {Object} iframe Element - * @param {Object} data Payload - * @param {Function} respond Send a response to the iframe - */ - actionHandlers.prepareResize = function (iframe, data, respond) { - // Do not resize unless page and scrolling differs - if (iframe.clientHeight !== data.scrollHeight || - data.scrollHeight !== data.clientHeight) { - - // Reset iframe height, in case content has shrinked. - iframe.style.height = data.clientHeight + 'px'; - respond('resizePrepared'); - } - }; - - /** - * Resize parent and iframe to desired height. - * - * @private - * @param {Object} iframe Element - * @param {Object} data Payload - * @param {Function} respond Send a response to the iframe - */ - actionHandlers.resize = function (iframe, data) { - // Resize iframe so all content is visible. Use scrollHeight to make sure we get everything - iframe.style.height = data.scrollHeight + 'px'; - }; - - /** - * Keyup event handler. Exits full screen on escape. - * - * @param {Event} event - */ - var escape = function (event) { - if (event.keyCode === 27) { - exitFullScreen(); - } - }; - - // Listen for messages from iframes - window.addEventListener('message', function receiveMessage(event) { - if (event.data.context !== 'h5p') { - return; // Only handle h5p requests. - } - - // Find out who sent the message - var iframe, iframes = document.getElementsByTagName('iframe'); - for (var i = 0; i < iframes.length; i++) { - if (iframes[i].contentWindow === event.source) { - iframe = iframes[i]; - break; - } - } - - if (!iframe) { - return; // Cannot find sender - } - - // Find action handler handler - if (actionHandlers[event.data.action]) { - actionHandlers[event.data.action](iframe, event.data, function respond(action, data) { - if (data === undefined) { - data = {}; - } - data.action = action; - data.context = 'h5p'; - event.source.postMessage(data, event.origin); - }); - } - }, false); - - // Let h5p iframes know we're ready! - var iframes = document.getElementsByTagName('iframe'); - var ready = { - context: 'h5p', - action: 'ready' - }; - for (var i = 0; i < iframes.length; i++) { - if (iframes[i].src.indexOf('h5p') !== -1) { - iframes[i].contentWindow.postMessage(ready, '*'); - } - } - -})(); diff --git a/lib/editor/atto/plugins/h5p/js/readme_moodle.txt b/lib/editor/atto/plugins/h5p/js/readme_moodle.txt deleted file mode 100644 index e403b440388..00000000000 --- a/lib/editor/atto/plugins/h5p/js/readme_moodle.txt +++ /dev/null @@ -1,9 +0,0 @@ -The H5P resizer JS. - -to update: - -Downloaded last release from: https://github.com/h5p/h5p-php-library/releases - -Import - -- In the downloaded h5p-php-library copy js/h5p-resizer.js into lib/editor/atto/plugins/h5p/js diff --git a/lib/editor/atto/plugins/h5p/lib.php b/lib/editor/atto/plugins/h5p/lib.php index d415bc0fc06..d07ad2a55c6 100644 --- a/lib/editor/atto/plugins/h5p/lib.php +++ b/lib/editor/atto/plugins/h5p/lib.php @@ -61,7 +61,7 @@ function atto_h5p_strings_for_js() { ); $PAGE->requires->strings_for_js($strings, 'atto_h5p'); - $PAGE->requires->js(new moodle_url('/lib/editor/atto/plugins/h5p/js/h5p-resizer.js')); + $PAGE->requires->js(new moodle_url('/lib/h5p/js/h5p-resizer.js')); } diff --git a/lib/editor/atto/plugins/h5p/thirdpartylibs.xml b/lib/editor/atto/plugins/h5p/thirdpartylibs.xml deleted file mode 100644 index e7f5237f06e..00000000000 --- a/lib/editor/atto/plugins/h5p/thirdpartylibs.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - js/h5p-resizer.js - H5P Resizer - GPL-3.0 - 1.23.1 - - - \ No newline at end of file diff --git a/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button-debug.js b/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button-debug.js index 7defc493b31..f95447189d7 100644 --- a/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button-debug.js +++ b/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button-debug.js @@ -68,7 +68,7 @@ var CSS = { 'width="100%" height="637" frameborder="0"' + 'allowfullscreen="{{allowfullscreen}}" allowmedia="{{allowmedia}}">' + '' + - '' + '' + '' + diff --git a/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button-min.js b/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button-min.js index ecb522176e3..56619758eda 100644 --- a/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button-min.js +++ b/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button-min.js @@ -1 +1 @@ -YUI.add("moodle-atto_h5p-button",function(e,t){var n={INPUTALT:"atto_h5p_altentry",INPUTSUBMIT:"atto_h5p_urlentrysubmit",INPUTH5PURL:"atto_h5p_url",URLWARNING:"atto_h5p_warning"},r={INPUTH5PURL:"."+n.INPUTH5PURL},i="atto_h5p",s='

      ',o='
      '+"
      "+""+"


      ";e.namespace("M.atto_h5p").Button=e.Base.create("button",e.M.editor_atto.EditorPlugin,[],{_currentSelection:null,_form:null,_placeholderH5P:null,initializer:function(){var e=this.get("allowedmethods");if(e!=="embed")return;this.addButton({icon:"icon",iconComponent:"atto_h5p",callback:this._displayDialogue,tags:".attoh5poverlay",tagMatchRequiresAll:!1}),this.editor.delegate("dblclick",this._handleDblClick,".attoh5poverlay",this),this.editor.delegate("click",this._handleClick,".attoh5poverlay",this)},_handleDblClick:function(){this._displayDialogue()},_handleClick:function(e){var t=e.target,n=this.get("host").getSelectionFromNode(t);this.get("host").getSelection()!==n&&this.get("host").setSelection(n)},_displayDialogue:function(){this._currentSelection=this.get("host").getSelection(),this._placeholderH5P=this._getH5PIframe();if(this._currentSelection===!1)return;var e=this.getDialogue({headerContent:M.util.get_string("h5pproperties",i),width:"auto",focusAfterHide:!0,focusOnShowSelector:r.INPUTH5PURL});e.set("bodyContent",this._getDialogueContent()).show()},_getH5PIframe:function(){var t=this.get("host").getSelectionParentNode();if(!t)return;return e.one(t).one("iframe.h5pcontent")},_getDialogueContent:function(){var t=e.Handlebars.compile(s),o=e.Node.create(t({elementid:this.get("host").get("elementid"),CSS:n,component:i}));this._form=o;if(this._placeholderH5P){var u=this._placeholderH5P.getAttribute("src");this._form.one(r.INPUTH5PURL).setAttribute("value",u)}return this._form.one("."+n.INPUTSUBMIT).on("click",this._setH5P,this),o},_setH5P:function(t){var n=this._form,i=n.one(r.INPUTH5PURL).get("value"),s,u=this.get("host");t.preventDefault();if(this._updateWarning())return;u.focus();if(this._placeholderH5P)this._placeholderH5P.setAttribute("src",i);else if(i!==""){u.setSelection(this._currentSelection);var a=e.Handlebars.compile(o);s=a({url:i,allowfullscreen:"allowfullscreen",allowmedia:"geolocation *; microphone *; camera *; midi *; encrypted-media *"}),this.get("host").insertContentAtFocusPoint(s),this.markUpdated()}this.getDialogue({focusAfterHide:null}).hide()},_validURL:function(e){var t=new RegExp("^(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*");return!!t.test(e)},_updateWarning:function(){var e=this._form,t=!0,r=e.one("."+n.INPUTH5PURL).get("value");return this._validURL(r)?(e.one("."+n.URLWARNING).setStyle("display","none"),t=!1):(e.one("."+n.URLWARNING).setStyle("display","block"),t=!0),t}},{ATTRS:{allowedmethods:{value:null}}})},"@VERSION@",{requires:["moodle-editor_atto-plugin"]}); +YUI.add("moodle-atto_h5p-button",function(e,t){var n={INPUTALT:"atto_h5p_altentry",INPUTSUBMIT:"atto_h5p_urlentrysubmit",INPUTH5PURL:"atto_h5p_url",URLWARNING:"atto_h5p_warning"},r={INPUTH5PURL:"."+n.INPUTH5PURL},i="atto_h5p",s='
      ',o='
      '+"
      "+""+"


      ";e.namespace("M.atto_h5p").Button=e.Base.create("button",e.M.editor_atto.EditorPlugin,[],{_currentSelection:null,_form:null,_placeholderH5P:null,initializer:function(){var e=this.get("allowedmethods");if(e!=="embed")return;this.addButton({icon:"icon",iconComponent:"atto_h5p",callback:this._displayDialogue,tags:".attoh5poverlay",tagMatchRequiresAll:!1}),this.editor.delegate("dblclick",this._handleDblClick,".attoh5poverlay",this),this.editor.delegate("click",this._handleClick,".attoh5poverlay",this)},_handleDblClick:function(){this._displayDialogue()},_handleClick:function(e){var t=e.target,n=this.get("host").getSelectionFromNode(t);this.get("host").getSelection()!==n&&this.get("host").setSelection(n)},_displayDialogue:function(){this._currentSelection=this.get("host").getSelection(),this._placeholderH5P=this._getH5PIframe();if(this._currentSelection===!1)return;var e=this.getDialogue({headerContent:M.util.get_string("h5pproperties",i),width:"auto",focusAfterHide:!0,focusOnShowSelector:r.INPUTH5PURL});e.set("bodyContent",this._getDialogueContent()).show()},_getH5PIframe:function(){var t=this.get("host").getSelectionParentNode();if(!t)return;return e.one(t).one("iframe.h5pcontent")},_getDialogueContent:function(){var t=e.Handlebars.compile(s),o=e.Node.create(t({elementid:this.get("host").get("elementid"),CSS:n,component:i}));this._form=o;if(this._placeholderH5P){var u=this._placeholderH5P.getAttribute("src");this._form.one(r.INPUTH5PURL).setAttribute("value",u)}return this._form.one("."+n.INPUTSUBMIT).on("click",this._setH5P,this),o},_setH5P:function(t){var n=this._form,i=n.one(r.INPUTH5PURL).get("value"),s,u=this.get("host");t.preventDefault();if(this._updateWarning())return;u.focus();if(this._placeholderH5P)this._placeholderH5P.setAttribute("src",i);else if(i!==""){u.setSelection(this._currentSelection);var a=e.Handlebars.compile(o);s=a({url:i,allowfullscreen:"allowfullscreen",allowmedia:"geolocation *; microphone *; camera *; midi *; encrypted-media *"}),this.get("host").insertContentAtFocusPoint(s),this.markUpdated()}this.getDialogue({focusAfterHide:null}).hide()},_validURL:function(e){var t=new RegExp("^(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*");return!!t.test(e)},_updateWarning:function(){var e=this._form,t=!0,r=e.one("."+n.INPUTH5PURL).get("value");return this._validURL(r)?(e.one("."+n.URLWARNING).setStyle("display","none"),t=!1):(e.one("."+n.URLWARNING).setStyle("display","block"),t=!0),t}},{ATTRS:{allowedmethods:{value:null}}})},"@VERSION@",{requires:["moodle-editor_atto-plugin"]}); diff --git a/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button.js b/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button.js index 7defc493b31..f95447189d7 100644 --- a/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button.js +++ b/lib/editor/atto/plugins/h5p/yui/build/moodle-atto_h5p-button/moodle-atto_h5p-button.js @@ -68,7 +68,7 @@ var CSS = { 'width="100%" height="637" frameborder="0"' + 'allowfullscreen="{{allowfullscreen}}" allowmedia="{{allowmedia}}">' + '' + - '' + '' + '' + diff --git a/lib/editor/atto/plugins/h5p/yui/src/button/js/button.js b/lib/editor/atto/plugins/h5p/yui/src/button/js/button.js index 8ba622575e4..d79e1907f6e 100644 --- a/lib/editor/atto/plugins/h5p/yui/src/button/js/button.js +++ b/lib/editor/atto/plugins/h5p/yui/src/button/js/button.js @@ -66,7 +66,7 @@ var CSS = { 'width="100%" height="637" frameborder="0"' + 'allowfullscreen="{{allowfullscreen}}" allowmedia="{{allowmedia}}">' + '' + - '' + '' + '' + From 60bd7a8021953754499613198690b8fb2a1b7410 Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Fri, 4 Oct 2019 10:07:48 +0200 Subject: [PATCH 09/22] MDL-66609 core_h5p: Update phpunit.xml.dist --- phpunit.xml.dist | 3 +++ 1 file changed, 3 insertions(+) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 1ba7628d72b..7a9610448d5 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -188,6 +188,9 @@ rss/tests + + h5p/tests + From 360755cc5635566e9d033fe3d6cdb9efbd7efb09 Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Wed, 2 Oct 2019 12:26:44 +0200 Subject: [PATCH 10/22] MDL-66609 core_h5p: New capability h5p:setdisplayoptions --- lang/en/role.php | 1 + lib/db/access.php | 9 +++++++++ version.php | 2 +- 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lang/en/role.php b/lang/en/role.php index 6946b6f6a80..5460e58b4c3 100644 --- a/lang/en/role.php +++ b/lang/en/role.php @@ -260,6 +260,7 @@ $string['grade:unlock'] = 'Unlock grades or items'; $string['grade:view'] = 'View own grades'; $string['grade:viewall'] = 'View grades of other users'; $string['grade:viewhidden'] = 'View hidden grades for owner'; +$string['h5p:setdisplayoptions'] = 'Set the display options to an H5P content'; $string['highlightedcellsshowdefault'] = 'The permissions highlighted in the table below are the defaults for the role archetype currently selected above.'; $string['highlightedcellsshowinherit'] = 'The highlighted cells in the table below show the permission (if any) that will be inherited. Apart from the capabilities whose permission you actually want to alter, you should leave everything set to Inherit.'; $string['checkglobalpermissions'] = 'Check system permissions'; diff --git a/lib/db/access.php b/lib/db/access.php index 47a039258aa..336cce64b1d 100644 --- a/lib/db/access.php +++ b/lib/db/access.php @@ -2430,4 +2430,13 @@ $capabilities = array( 'user' => CAP_ALLOW ) ), + + // Set display option buttons to an H5P content. + 'moodle/h5p:setdisplayoptions' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array( + 'editingteacher' => CAP_ALLOW, + ) + ), ); diff --git a/version.php b/version.php index b139b3d7324..5be1a36a072 100644 --- a/version.php +++ b/version.php @@ -29,7 +29,7 @@ defined('MOODLE_INTERNAL') || die(); -$version = 2019102500.01; // YYYYMMDD = weekly release date of this DEV branch. +$version = 2019102500.02; // YYYYMMDD = weekly release date of this DEV branch. // RR = release increments - 00 in DEV branches. // .XX = incremental changes. From 35221a2e158bb153e24774b9bbf9308b07d9baf9 Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Thu, 3 Oct 2019 21:50:38 +0200 Subject: [PATCH 11/22] MDL-66609 core_h5p: Add some H5P styles to themes --- theme/boost/scss/moodle/core.scss | 9 +++++++++ theme/boost/style/moodle.css | 6 ++++++ theme/classic/style/moodle.css | 6 ++++++ 3 files changed, 21 insertions(+) diff --git a/theme/boost/scss/moodle/core.scss b/theme/boost/scss/moodle/core.scss index d4f7f526a6c..b3c9917f46e 100644 --- a/theme/boost/scss/moodle/core.scss +++ b/theme/boost/scss/moodle/core.scss @@ -2254,6 +2254,15 @@ $switch-transition: .2s all !default; min-height: 3.125rem; } +body.h5p-embed { + #maincontent { + display: none; + } + .h5pmessages { + min-height: 230px; // This should be the same height as default core_h5p iframes. + } +} + .text-decoration-none { text-decoration: none !important; /* stylelint-disable-line declaration-no-important */ } diff --git a/theme/boost/style/moodle.css b/theme/boost/style/moodle.css index 741ae8f02cb..bd6625d7a13 100644 --- a/theme/boost/style/moodle.css +++ b/theme/boost/style/moodle.css @@ -11452,6 +11452,12 @@ div.editor_atto_toolbar button .icon { .paged-content-page-container { min-height: 3.125rem; } +body.h5p-embed #maincontent { + display: none; } + +body.h5p-embed .h5pmessages { + min-height: 230px; } + .text-decoration-none { text-decoration: none !important; /* stylelint-disable-line declaration-no-important */ } diff --git a/theme/classic/style/moodle.css b/theme/classic/style/moodle.css index 6620b423d23..b9030653c4f 100644 --- a/theme/classic/style/moodle.css +++ b/theme/classic/style/moodle.css @@ -11707,6 +11707,12 @@ div.editor_atto_toolbar button .icon { .paged-content-page-container { min-height: 3.125rem; } +body.h5p-embed #maincontent { + display: none; } + +body.h5p-embed .h5pmessages { + min-height: 230px; } + .text-decoration-none { text-decoration: none !important; /* stylelint-disable-line declaration-no-important */ } From 01923a07aa212ae55c385a31d92ac374fad6ce3e Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Wed, 25 Sep 2019 14:45:50 +0200 Subject: [PATCH 12/22] MDL-66609 core_h5p: Add new strings --- lang/en/h5p.php | 140 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 138 insertions(+), 2 deletions(-) diff --git a/lang/en/h5p.php b/lang/en/h5p.php index f0866ec170a..5d2c8f133ac 100644 --- a/lang/en/h5p.php +++ b/lang/en/h5p.php @@ -13,12 +13,148 @@ // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . + /** * Strings for component 'h5p', language 'en', branch 'master' * * @package core_h5p - * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} + * @copyright 2019 Moodle + * @author Sara Arjona * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ + +$string['addedandupdatedpp'] = 'Added {$a->%new} new H5P libraries and updated {$a->%old} old ones.'; +$string['addedandupdatedps'] = 'Added {$a->%new} new H5P libraries and updated {$a->%old} old one.'; +$string['addedandupdatedsp'] = 'Added {$a->%new} new H5P library and updated {$a->%old} old ones.'; +$string['addedandupdatedss'] = 'Added {$a->%new} new H5P library and updated {$a->%old} old one.'; +$string['addednewlibraries'] = 'Added {$a->%new} new H5P libraries.'; +$string['addednewlibrary'] = 'Added {$a->%new} new H5P library.'; +$string['additionallicenseinfo'] = 'Any additional information about the license'; +$string['author'] = 'Author'; +$string['authorcomments'] = 'Author comments'; +$string['authorcommentsdescription'] = 'Comments for the editor of the content (This text will not be published as a part of copyright info)'; +$string['authorname'] = 'Author\'s name'; +$string['authorrole'] = 'Author\'s role'; +$string['by'] = 'by'; +$string['cancellabel'] = 'Cancel'; +$string['ccattribution'] = 'Attribution (CC BY)'; +$string['ccattributionnc'] = 'Attribution-NonCommercial (CC BY-NC)'; +$string['ccattributionncnd'] = 'Attribution-NonCommercial-NoDerivs (CC BY-NC-ND)'; +$string['ccattributionncsa'] = 'Attribution-NonCommercial-ShareAlike (CC BY-NC-SA)'; +$string['ccattributionnd'] = 'Attribution-NoDerivs (CC BY-ND)'; +$string['ccattributionsa'] = 'Attribution-ShareAlike (CC BY-SA)'; +$string['ccpdd'] = 'Public Domain Dedication (CC0)'; +$string['changedby'] = 'Changed by'; +$string['changedescription'] = 'Description of change'; +$string['changelog'] = 'Changelog'; +$string['changeplaceholder'] = 'Photo cropped, text changed, etc.'; +$string['close'] = 'Close'; +$string['confirmdialogbody'] = 'Please confirm that you wish to proceed. This action is not reversible.'; +$string['confirmdialogheader'] = 'Confirm action'; +$string['confirmlabel'] = 'Confirm'; +$string['connectionLost'] = 'Connection lost. Results will be stored and sent when you regain connection.'; +$string['connectionReestablished'] = 'Connection reestablished.'; +$string['contentCopied'] = 'Content is copied to the clipboard'; +$string['contentchanged'] = 'This content has changed since you last used it.'; +$string['contenttype'] = 'Content Type'; +$string['copyright'] = 'Rights of use'; +$string['copyrightinfo'] = 'Copyright information'; +$string['copyrightstring'] = 'Copyright'; +$string['copyrighttitle'] = 'View copyright information for this content.'; +$string['couldNotParseJSONFromZip'] = 'Unable to parse JSON from the package: {$a->%fileName}'; +$string['couldNotReadFileFromZip'] = 'Unable to read file from the package: {$a->%fileName}'; +$string['creativecommons'] = 'Creative Commons'; +$string['date'] = 'Date'; +$string['disablefullscreen'] = 'Disable fullscreen'; +$string['download'] = 'Download'; +$string['downloadtitle'] = 'Download this content as a H5P file.'; +$string['editor'] = 'Editor'; +$string['embed'] = 'Embed'; +$string['embedtitle'] = 'View the embed code for this content.'; +$string['fileExceedsMaxSize'] = 'One of the files inside the package exceeds the maximum file size allowed. ({$a->%file} {$a->%used} > {$a->%max})'; +$string['fullscreen'] = 'Fullscreen'; +$string['gpl'] = 'General Public License v3'; +$string['h5p'] = 'H5P'; +$string['h5ptitle'] = 'Visit H5P.org to check out more cool content.'; +$string['h5pfilenotfound'] = 'H5P file not found'; +$string['h5pinvalidurl'] = 'Invalid H5P content URL.'; +$string['h5pprivatefile'] = 'This H5P content can\'t be displayed because you don\'t have access to the .h5p file.'; +$string['hideadvanced'] = 'Hide advanced'; +$string['invalidcontextid'] = 'H5P file not found (invalid contextid)'; +$string['invalidfile'] = 'File "{$a->%filename}" not allowed. Only files with the following extensions are allowed: {$a->%files-allowed}.'; +$string['invalidlanguagefile'] = 'Invalid language file {$a->%file} in library {$a->%library}'; +$string['invalidlanguagefile2'] = 'Invalid language file {$a->%languageFile} has been included in the library {$a->%name}'; +$string['invalidlibrarydata'] = 'Invalid data provided for {$a->%property} in {$a->%library}'; +$string['invalidlibrarydataboolean'] = 'Invalid data provided for {$a->%property} in {$a->%library}. Boolean expected.'; +$string['invalidlibraryname'] = 'Invalid library name: {$a->%name}'; +$string['invalidlibrarynamed'] = 'The H5P library {$a->%library} used in the content is not valid'; +$string['invalidlibraryoption'] = 'Illegal option {$a->%option} in {$a->%library}'; +$string['invalidlibraryproperty'] = 'Can\'t read the property {$a->%property} in {$a->%library}'; +$string['invalidmainjson'] = 'A valid main h5p.json file is missing'; +$string['invalidmultiselectoption'] = 'Invalid selected option in multi-select.'; +$string['invalidselectoption'] = 'Invalid selected option in select.'; +$string['invalidsemanticsjson'] = 'Invalid semantics.json file has been included in the library {$a->%name}'; +$string['invalidsemanticstype'] = 'H5P internal error: unknown content type "{$a->@type}" in semantics. Removing content!'; +$string['invalidstring'] = 'Provided string is not valid according to regexp in semantics. (value: "{$a->%value}", regexp: "{$a->%regexp}")'; +$string['librarydirectoryerror'] = 'Library directory name must match machineName or machineName-majorVersion.minorVersion (from library.json). (Directory: {$a->%directoryName} , machineName: {$a->%machineName}, majorVersion: {$a->%majorVersion}, minorVersion: {$a->%minorVersion})'; +$string['license'] = 'License'; +$string['licenseCC010'] = 'CC0 1.0 Universal (CC0 1.0) Public Domain Dedication'; +$string['licenseCC010U'] = 'CC0 1.0 Universal'; +$string['licenseCC10'] = '1.0 Generic'; +$string['licenseCC20'] = '2.0 Generic'; +$string['licenseCC25'] = '2.5 Generic'; +$string['licenseCC30'] = '3.0 Unported'; +$string['licenseCC40'] = '4.0 International'; +$string['licenseGPL'] = 'General Public License'; +$string['licenseV1'] = 'Version 1'; +$string['licenseV2'] = 'Version 2'; +$string['licenseV3'] = 'Version 3'; +$string['licensee'] = 'Licensee'; +$string['licenseextras'] = 'License Extras'; +$string['licenseversion'] = 'License Version'; +$string['missingcontentfolder'] = 'A valid content folder is missing'; +$string['missingcoreversion'] = 'The system was unable to install the {$a->%component} component from the package, it requires a newer version of the H5P plugin. This site is currently running version {$a->%current}, whereas the required version is {$a->%required} or higher. You should consider upgrading and then try again.'; +$string['missingdependency'] = 'Missing dependency {$a->@dep} required by {$a->@lib}.'; +$string['missinglibrary'] = 'Missing required library {$a->@library}'; +$string['missinglibraryfile'] = 'The file "{$a->%file}" is missing from library: "{$a->%name}"'; +$string['missinglibraryjson'] = 'Could not find library.json file with valid json format for library {$a->%name}'; +$string['missinglibraryproperty'] = 'The required property {$a->%property} is missing from {$a->%library}'; +$string['missingmbstring'] = 'The mbstring PHP extension is not loaded. H5P need this to function properly'; +$string['missinguploadpermissions'] = '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.'; +$string['nocopyright'] = 'No copyright information available for this content.'; +$string['noextension'] = 'The file you uploaded is not a valid HTML5 Package (It does not have the .h5p file extension)'; +$string['nojson'] = 'The main h5p.json file is not valid'; +$string['nounzip'] = 'The file you uploaded is not a valid HTML5 Package (We are unable to unzip it)'; +$string['offlineDialogBody'] = 'We were unable to send information about your completion of this task. Please check your internet connection.'; +$string['offlineDialogHeader'] = 'Your connection to the server was lost'; +$string['offlineDialogRetryButtonLabel'] = 'Retry now'; +$string['offlineDialogRetryMessage'] = 'Retrying in :num....'; +$string['offlineSuccessfulSubmit'] = 'Successfully submitted results.'; +$string['originator'] = 'Originator'; +$string['pd'] = 'Public Domain'; +$string['pddl'] = 'Public Domain Dedication and Licence'; +$string['pdm'] = 'Public Domain Mark (PDM)'; $string['privacy:metadata'] = 'H5P subsystem does not store any personal data.'; -$string['h5pfilenotfound'] = 'H5P file not found'; \ No newline at end of file +$string['resizescript'] = 'Include this script on your website if you want dynamic sizing of the embedded content:'; +$string['resubmitScores'] = 'Attempting to submit stored results.'; +$string['reuse'] = 'Reuse'; +$string['reuseContent'] = 'Reuse Content'; +$string['reuseDescription'] = 'Reuse this content.'; +$string['showadvanced'] = 'Show advanced'; +$string['showless'] = 'Show less'; +$string['showmore'] = 'Show more'; +$string['size'] = 'Size'; +$string['source'] = 'Source'; +$string['startingover'] = 'You\'ll be starting over.'; +$string['sublevel'] = 'Sublevel'; +$string['thumbnail'] = 'Thumbnail'; +$string['title'] = 'Title'; +$string['undisclosed'] = 'Undisclosed'; +$string['unpackedFilesExceedsMaxSize'] = 'The total size of the unpacked files exceeds the maximum size allowed. ({$a->%used} > {$a->%max})'; +$string['updatedlibraries'] = 'Updated {$a->%old} H5P libraries.'; +$string['updatedlibrary'] = 'Updated {$a->%old} H5P library.'; +$string['wrongversion'] = 'The version of the H5P library {$a->%machineName} used in this content is not valid. Content contains {$a->%contentLibrary}, but it should be {$a->%semanticsLibrary}.'; +$string['year'] = 'Year'; +$string['years'] = 'Year(s)'; +$string['yearsfrom'] = 'Years (from)'; +$string['yearsto'] = 'Years (to)'; \ No newline at end of file From f41a75f6f015e57654b2784bf515368cf7815184 Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Mon, 7 Oct 2019 12:59:14 +0200 Subject: [PATCH 13/22] MDL-66609 core_h5p: Update the h5p-resizer.js in the filter --- filter/displayh5p/filter.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/filter/displayh5p/filter.php b/filter/displayh5p/filter.php index e1b0cf74eaf..bd31b685ac5 100644 --- a/filter/displayh5p/filter.php +++ b/filter/displayh5p/filter.php @@ -111,7 +111,8 @@ class filter_displayh5p extends moodle_text_filter { // We want to request the resizing script only once. if (self::$loadresizerjs) { - $tagend .= ''; + $resizerurl = new moodle_url('/lib/h5p/js/h5p-resizer.js'); + $tagend .= ''; self::$loadresizerjs = false; } From e96569cc1e55b412ffa235458f0051d98eaa801e Mon Sep 17 00:00:00 2001 From: Amaia Anabitarte Date: Tue, 15 Oct 2019 15:01:08 +0200 Subject: [PATCH 14/22] MDL-66609 core_h5p: Unit test coverage --- h5p/tests/coverage.php | 48 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 h5p/tests/coverage.php diff --git a/h5p/tests/coverage.php b/h5p/tests/coverage.php new file mode 100644 index 00000000000..d5502cb8dbc --- /dev/null +++ b/h5p/tests/coverage.php @@ -0,0 +1,48 @@ +. + +defined('MOODLE_INTERNAL') || die(); + +/** + * Coverage information for the core_h5p subsystem. + * + * @package core_h5p + * @category phpunit + * @copyright 2019 Amaia Anabitarte + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * Coverage information for the core H5P subsystem. + * + * @copyright 2019 Amaia Anabitarte + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +return new class extends phpunit_coverage_info { + /** @var array The list of folders relative to the plugin root to whitelist in coverage generation. */ + protected $whitelistfolders = [ + 'classes', + ]; + + /** @var array The list of files relative to the plugin root to whitelist in coverage generation. */ + protected $whitelistfiles = []; + + /** @var array The list of folders relative to the plugin root to excludelist in coverage generation. */ + protected $excludelistfolders = []; + + /** @var array The list of files relative to the plugin root to excludelist in coverage generation. */ + protected $excludelistfiles = []; +}; From 6faafc0c8e4aab194858cbf9ab4d6919c46a9153 Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Fri, 11 Oct 2019 20:42:04 +0800 Subject: [PATCH 15/22] MDL-66609 core_h5p: Add getDependencyPath to H5P library --- lib/h5p/h5p.classes.php | 12 +++++++++++- lib/h5p/readme_moodle.txt | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/h5p/h5p.classes.php b/lib/h5p/h5p.classes.php index c127185e551..554f82030b2 100644 --- a/lib/h5p/h5p.classes.php +++ b/lib/h5p/h5p.classes.php @@ -2432,7 +2432,7 @@ class H5PCore { // Using content dependencies foreach ($dependencies as $dependency) { if (isset($dependency['path']) === FALSE) { - $dependency['path'] = 'libraries/' . H5PCore::libraryToString($dependency, TRUE); + $dependency['path'] = $this->getDependencyPath($dependency); $dependency['preloadedJs'] = explode(',', $dependency['preloadedJs']); $dependency['preloadedCss'] = explode(',', $dependency['preloadedCss']); } @@ -2452,6 +2452,16 @@ class H5PCore { return $files; } + /** + * Get the path to the dependency. + * + * @param stdClass $dependency + * @return string + */ + protected function getDependencyPath(array $dependency): string { + return H5PCore::libraryToString($dependency, TRUE); + } + private static function getDependenciesHash(&$dependencies) { // Build hash of dependencies $toHash = array(); diff --git a/lib/h5p/readme_moodle.txt b/lib/h5p/readme_moodle.txt index 1fa36a100a5..ed3ce037205 100644 --- a/lib/h5p/readme_moodle.txt +++ b/lib/h5p/readme_moodle.txt @@ -15,3 +15,17 @@ Added: * readme_moodle.txt Downloaded version: 1.23.1 release + +=== 3.8 === +* In order to allow the dependency path to be overridden by child H5PCore classes, a couple of minor changes have been added to the +h5p.classes.php file: + - Into the getDependenciesFiles method, the line 2435: + $dependency['path'] = 'libraries/' . H5PCore::libraryToString($dependency, TRUE); + + has been changed to: + $dependency['path'] = $this->getDependencyPath($dependency); + + - The method getDependencyPath has been added (line 2455). It might be rewritten by child classes. +A PR has been sent to the H5P library with these changes: +https://github.com/h5p/h5p-php-library/compare/master...andrewnicols:libraryPathSubclass +Hopefully, when upgrading, these patch won't be needed because it will be included in the H5P library by default. \ No newline at end of file From 9e67f5e3665959240b12287f015b64768db216ca Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Fri, 11 Oct 2019 20:41:43 +0800 Subject: [PATCH 16/22] MDL-66609 core_h5p: Make use of upstream change for getting itemid --- h5p/classes/core.php | 113 +++++++++++++++++++++++++++++++++++ h5p/classes/file_storage.php | 5 +- h5p/classes/framework.php | 3 +- h5p/classes/player.php | 29 ++++----- h5p/js/h5p_overrides.js | 9 +++ 5 files changed, 142 insertions(+), 17 deletions(-) create mode 100644 h5p/classes/core.php create mode 100644 h5p/js/h5p_overrides.js diff --git a/h5p/classes/core.php b/h5p/classes/core.php new file mode 100644 index 00000000000..c855c2f822a --- /dev/null +++ b/h5p/classes/core.php @@ -0,0 +1,113 @@ +. + +/** + * H5P player class. + * + * @package core_h5p + * @copyright 2019 Sara Arjona + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace core_h5p; + +use H5PCore; +use stdClass; +use moodle_url; + +defined('MOODLE_INTERNAL') || die(); + +/** + * H5P player class, for displaying any local H5P content. + * + * @package core_h5p + * @copyright 2019 Sara Arjona + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class core extends \H5PCore { + + protected $libraries; + + protected function getDependencyPath(array $dependency): string { + $library = $this->find_library($dependency); + + return "libraries/{$library->id}/{$library->machinename}-{$library->majorversion}.{$library->minorversion}"; + } + + public function get_dependency_roots(int $id): array { + $roots = []; + $dependencies = $this->h5pF->loadContentDependencies($id); + $context = \context_system::instance(); + foreach ($dependencies as $dependency) { + $library = $this->find_library($dependency); + $roots[self::libraryToString($dependency, true)] = (moodle_url::make_pluginfile_url( + $context->id, + 'core_h5p', + 'libraries', + $library->id, + "/" . self::libraryToString($dependency, true), + '' + ))->out(false); + } + + return $roots; + } + + protected function find_library($dependency): \stdClass { + global $DB; + if (null === $this->libraries) { + $this->libraries = $DB->get_records('h5p_libraries'); + } + + $major = $dependency['majorVersion']; + $minor = $dependency['minorVersion']; + $patch = $dependency['patchVersion']; + + foreach ($this->libraries as $library) { + if ($library->machinename !== $dependency['machineName']) { + continue; + } + + if ($library->majorversion != $major) { + continue; + } + if ($library->minorversion != $minor) { + continue; + } + if ($library->patchversion != $patch) { + continue; + } + + return $library; + } + + return null; + } + + public static function get_scripts(): array { + global $CFG; + $cachebuster = '?ver='.$CFG->jsrev; + $liburl = $CFG->wwwroot . '/lib/h5p/'; + $urls = []; + + foreach (self::$scripts as $script) { + $urls[] = new moodle_url($liburl . $script . $cachebuster); + } + $urls[] = new moodle_url("/h5p/js/h5p_overrides.js"); + + return $urls; + } +} diff --git a/h5p/classes/file_storage.php b/h5p/classes/file_storage.php index b26c5208b96..4af223480c0 100644 --- a/h5p/classes/file_storage.php +++ b/h5p/classes/file_storage.php @@ -600,11 +600,12 @@ class file_storage implements \H5PFileStorage { } // Get the filearea. $filearea = array_shift($sections); + $itemid = array_shift($sections); // Get the filepath. $filepath = implode('/', $sections); $filepath = '/' . $filepath . '/'; - return ['filearea' => $filearea, 'filepath' => $filepath, 'filename' => $filename]; + return ['filearea' => $filearea, 'filepath' => $filepath, 'filename' => $filename, 'itemid' => $itemid]; } /** @@ -620,4 +621,4 @@ class file_storage implements \H5PFileStorage { return $DB->get_field('files', 'itemid', ['component' => self::COMPONENT, 'filearea' => $filearea, 'filepath' => $filepath, 'filename' => $filename]); } -} \ No newline at end of file +} diff --git a/h5p/classes/framework.php b/h5p/classes/framework.php index 54d15ff1e27..4905ab28a0f 100644 --- a/h5p/classes/framework.php +++ b/h5p/classes/framework.php @@ -1536,7 +1536,8 @@ class framework implements \H5PFrameworkInterface { $context = \context_system::instance(); $url = "{$CFG->wwwroot}/pluginfile.php/{$context->id}/core_h5p"; - $core = new \H5PCore($interface, $fs, $url, $language, true); + require_once("{$CFG->libdir}/h5p/h5p.classes.php"); + $core = new core($interface, $fs, $url, $language, true); $core->aggregateAssets = !(isset($CFG->core_h5p_aggregate_assets) && $CFG->core_h5p_aggregate_assets === '0'); } diff --git a/h5p/classes/player.php b/h5p/classes/player.php index 4cdc495b13d..eee9bff4587 100644 --- a/h5p/classes/player.php +++ b/h5p/classes/player.php @@ -41,7 +41,7 @@ class player { private $url; /** - * @var \H5PCore The H5PCore object. + * @var core The H5PCore object. */ private $core; @@ -96,7 +96,7 @@ class player { $this->content = $this->core->loadContent($this->h5pid); // Get the embedtype to use for displaying the H5P content. - $this->embedtype = \H5PCore::determineEmbedType($this->content['embedType'], $this->content['library']['embedTypes']); + $this->embedtype = core::determineEmbedType($this->content['embedType'], $this->content['library']['embedTypes']); } } @@ -125,18 +125,18 @@ class player { $cid = $this->get_cid(); $systemcontext = \context_system::instance(); - $disable = array_key_exists('disable', $this->content) ? $this->content['disable'] : \H5PCore::DISABLE_NONE; + $disable = array_key_exists('disable', $this->content) ? $this->content['disable'] : core::DISABLE_NONE; $displayoptions = $this->core->getDisplayOptionsForView($disable, $this->h5pid); $contenturl = \moodle_url::make_pluginfile_url($systemcontext->id, \core_h5p\file_storage::COMPONENT, \core_h5p\file_storage::CONTENT_FILEAREA, $this->h5pid, null, null); $contentsettings = [ - 'library' => \H5PCore::libraryToString($this->content['library']), + 'library' => core::libraryToString($this->content['library']), 'fullScreen' => $this->content['library']['fullscreen'], - 'exportUrl' => $this->get_export_settings($displayoptions[ \H5PCore::DISPLAY_OPTION_DOWNLOAD ]), + 'exportUrl' => $this->get_export_settings($displayoptions[ core::DISPLAY_OPTION_DOWNLOAD ]), 'embedCode' => $this->get_embed_code($this->url->out(), - $displayoptions[ \H5PCore::DISPLAY_OPTION_EMBED ]), + $displayoptions[ core::DISPLAY_OPTION_EMBED ]), 'resizeCode' => $this->get_resize_code(), 'title' => $this->content['slug'], 'displayOptions' => $displayoptions, @@ -401,10 +401,10 @@ class player { } $disableoptions = [ - \H5PCore::DISPLAY_OPTION_FRAME => $frame, - \H5PCore::DISPLAY_OPTION_DOWNLOAD => $export, - \H5PCore::DISPLAY_OPTION_EMBED => $embed, - \H5PCore::DISPLAY_OPTION_COPYRIGHT => $copyright, + core::DISPLAY_OPTION_FRAME => $frame, + core::DISPLAY_OPTION_DOWNLOAD => $export, + core::DISPLAY_OPTION_EMBED => $embed, + core::DISPLAY_OPTION_COPYRIGHT => $copyright, ]; return $this->core->getStorableDisplayOptions($disableoptions, 0); @@ -496,14 +496,14 @@ class player { $relpath = '/' . preg_replace('/^[^:]+:\/\/[^\/]+\//', '', $liburl); // Add core stylesheets. - foreach (\H5PCore::$styles as $style) { + foreach (core::$styles as $style) { $settings['core']['styles'][] = $relpath . $style . $cachebuster; $this->cssrequires[] = new \moodle_url($liburl . $style . $cachebuster); } // Add core JavaScript. - foreach (\H5PCore::$scripts as $script) { - $settings['core']['scripts'][] = $relpath . $script . $cachebuster; - $this->jsrequires[] = new \moodle_url($liburl . $script . $cachebuster); + foreach (core::get_scripts() as $script) { + $settings['core']['scripts'][] = $script->out(false); + $this->jsrequires[] = $script; } $cid = $this->get_cid(); @@ -582,6 +582,7 @@ class player { 'libraryConfig' => $this->core->h5pF->getLibraryConfig(), 'pluginCacheBuster' => $this->get_cache_buster(), 'libraryUrl' => $basepath . 'lib/h5p/js', + 'moodleLibraryPaths' => $this->core->get_dependency_roots($this->h5pid), ); return $settings; diff --git a/h5p/js/h5p_overrides.js b/h5p/js/h5p_overrides.js new file mode 100644 index 00000000000..10679e0c61d --- /dev/null +++ b/h5p/js/h5p_overrides.js @@ -0,0 +1,9 @@ +H5P._getLibraryPath = H5P.getLibraryPath; +H5P.getLibraryPath = function (library) { + if (H5PIntegration.moodleLibraryPaths) { + if (H5PIntegration.moodleLibraryPaths[library]) { + return H5PIntegration.moodleLibraryPaths[library]; + } + } + return H5P._getLibraryPath(library); +}; From 810d7a3d2ea34afe543f1d2180689dd5d03831ad Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Thu, 17 Oct 2019 22:20:13 +0200 Subject: [PATCH 17/22] MDL-66609: core_h5p: Add _get_path_from_pluginfile method This method has been added to all the components having some exceptions with the way they treat the itemid in the pluginfile paths. --- blocks/html/lib.php | 24 ++++++++++++++++++++++++ lib/upgrade.txt | 4 ++++ mod/assign/lib.php | 24 ++++++++++++++++++++++++ mod/folder/lib.php | 24 ++++++++++++++++++++++++ mod/page/lib.php | 24 ++++++++++++++++++++++++ mod/resource/lib.php | 25 +++++++++++++++++++++++++ mod/scorm/lib.php | 24 ++++++++++++++++++++++++ mod/workshop/lib.php | 28 ++++++++++++++++++++++++++++ 8 files changed, 177 insertions(+) diff --git a/blocks/html/lib.php b/blocks/html/lib.php index 5fc988ceba8..89f5ec1894b 100644 --- a/blocks/html/lib.php +++ b/blocks/html/lib.php @@ -109,3 +109,27 @@ function block_html_global_db_replace($search, $replace) { } $instances->close(); } + +/** + * Given an array with a file path, it returns the itemid and the filepath for the defined filearea. + * + * @param string $filearea The filearea. + * @param array $args The path (the part after the filearea and before the filename). + * @return array The itemid and the filepath inside the $args path, for the defined filearea. + */ +function block_html_get_path_from_pluginfile(string $filearea, array $args) : array { + // This block never has an itemid (the number represents the revision but it's not stored in database). + array_shift($args); + + // Get the filepath. + if (empty($args)) { + $filepath = '/'; + } else { + $filepath = '/' . implode('/', $args) . '/'; + } + + return [ + 'itemid' => 0, + 'filepath' => $filepath, + ]; +} diff --git a/lib/upgrade.txt b/lib/upgrade.txt index a3e5e1de6ad..3075147d6ac 100644 --- a/lib/upgrade.txt +++ b/lib/upgrade.txt @@ -72,6 +72,10 @@ validation against and defaults to null (so, no user needed) if not provided. * Attempting to use xsendfile via the 3rd param of readstring_accel() is now ignored. * New H5P libraries have been added to Moodle core in /lib/h5p. * New H5P core subsystem have been added. +* Introduced new callback for plugin developers '_get_path_from_pluginfile($filearea, $args)': This will return +the itemid and filepath for the filearea and path defined in $args. It has been added in order to get the correct itemid and +filepath because some components, such as mod_page or mod_resource, add the revision to the URL where the itemid should be placed +(to prevent caching problems), but then they don't store it in database. === 3.7 === diff --git a/mod/assign/lib.php b/mod/assign/lib.php index af12729cfd9..5ca5031c0c7 100644 --- a/mod/assign/lib.php +++ b/mod/assign/lib.php @@ -1753,3 +1753,27 @@ function mod_assign_user_preferences() { return $preferences; } + +/** + * Given an array with a file path, it returns the itemid and the filepath for the defined filearea. + * + * @param string $filearea The filearea. + * @param array $args The path (the part after the filearea and before the filename). + * @return array The itemid and the filepath inside the $args path, for the defined filearea. + */ +function mod_assign_get_path_from_pluginfile(string $filearea, array $args) : array { + // Assign never has an itemid (the number represents the revision but it's not stored in database). + array_shift($args); + + // Get the filepath. + if (empty($args)) { + $filepath = '/'; + } else { + $filepath = '/' . implode('/', $args) . '/'; + } + + return [ + 'itemid' => 0, + 'filepath' => $filepath, + ]; +} diff --git a/mod/folder/lib.php b/mod/folder/lib.php index 3dd167eabf7..7b8b61268ec 100644 --- a/mod/folder/lib.php +++ b/mod/folder/lib.php @@ -818,3 +818,27 @@ function mod_folder_core_calendar_provide_event_action(calendar_event $event, true ); } + +/** + * Given an array with a file path, it returns the itemid and the filepath for the defined filearea. + * + * @param string $filearea The filearea. + * @param array $args The path (the part after the filearea and before the filename). + * @return array The itemid and the filepath inside the $args path, for the defined filearea. + */ +function mod_folder_get_path_from_pluginfile(string $filearea, array $args) : array { + // Folder never has an itemid (the number represents the revision but it's not stored in database). + array_shift($args); + + // Get the filepath. + if (empty($args)) { + $filepath = '/'; + } else { + $filepath = '/' . implode('/', $args) . '/'; + } + + return [ + 'itemid' => 0, + 'filepath' => $filepath, + ]; +} diff --git a/mod/page/lib.php b/mod/page/lib.php index 7b28d16e418..82d7725f542 100644 --- a/mod/page/lib.php +++ b/mod/page/lib.php @@ -571,3 +571,27 @@ function mod_page_core_calendar_provide_event_action(calendar_event $event, true ); } + +/** + * Given an array with a file path, it returns the itemid and the filepath for the defined filearea. + * + * @param string $filearea The filearea. + * @param array $args The path (the part after the filearea and before the filename). + * @return array The itemid and the filepath inside the $args path, for the defined filearea. + */ +function mod_page_get_path_from_pluginfile(string $filearea, array $args) : array { + // Page never has an itemid (the number represents the revision but it's not stored in database). + array_shift($args); + + // Get the filepath. + if (empty($args)) { + $filepath = '/'; + } else { + $filepath = '/' . implode('/', $args) . '/'; + } + + return [ + 'itemid' => 0, + 'filepath' => $filepath, + ]; +} diff --git a/mod/resource/lib.php b/mod/resource/lib.php index 8b593d3e0cf..ac53899a58c 100644 --- a/mod/resource/lib.php +++ b/mod/resource/lib.php @@ -584,3 +584,28 @@ function mod_resource_core_calendar_provide_event_action(calendar_event $event, true ); } + + +/** + * Given an array with a file path, it returns the itemid and the filepath for the defined filearea. + * + * @param string $filearea The filearea. + * @param array $args The path (the part after the filearea and before the filename). + * @return array The itemid and the filepath inside the $args path, for the defined filearea. + */ +function mod_resource_get_path_from_pluginfile(string $filearea, array $args) : array { + // Resource never has an itemid (the number represents the revision but it's not stored in database). + array_shift($args); + + // Get the filepath. + if (empty($args)) { + $filepath = '/'; + } else { + $filepath = '/' . implode('/', $args) . '/'; + } + + return [ + 'itemid' => 0, + 'filepath' => $filepath, + ]; +} diff --git a/mod/scorm/lib.php b/mod/scorm/lib.php index 4efe051a512..2b6160d5a98 100644 --- a/mod/scorm/lib.php +++ b/mod/scorm/lib.php @@ -1887,3 +1887,27 @@ function mod_scorm_core_calendar_get_valid_event_timestart_range(\calendar_event return [$mindate, $maxdate]; } + +/** + * Given an array with a file path, it returns the itemid and the filepath for the defined filearea. + * + * @param string $filearea The filearea. + * @param array $args The path (the part after the filearea and before the filename). + * @return array The itemid and the filepath inside the $args path, for the defined filearea. + */ +function mod_scorm_get_path_from_pluginfile(string $filearea, array $args) : array { + // SCORM never has an itemid (the number represents the revision but it's not stored in database). + array_shift($args); + + // Get the filepath. + if (empty($args)) { + $filepath = '/'; + } else { + $filepath = '/' . implode('/', $args) . '/'; + } + + return [ + 'itemid' => 0, + 'filepath' => $filepath, + ]; +} diff --git a/mod/workshop/lib.php b/mod/workshop/lib.php index cfe4922266e..b9dbf9a3521 100644 --- a/mod/workshop/lib.php +++ b/mod/workshop/lib.php @@ -2177,3 +2177,31 @@ function workshop_check_updates_since(cm_info $cm, $from, $filter = array()) { } return $updates; } + +/** + * Given an array with a file path, it returns the itemid and the filepath for the defined filearea. + * + * @param string $filearea The filearea. + * @param array $args The path (the part after the filearea and before the filename). + * @return array|null The itemid and the filepath inside the $args path, for the defined filearea. + */ +function mod_workshop_get_path_from_pluginfile(string $filearea, array $args) : ?array { + if ($filearea !== 'instructauthors' && $filearea !== 'instructreviewers' && $filearea !== 'conclusion') { + return null; + } + + // Workshop only has empty itemid for some of the fileareas. + array_shift($args); + + // Get the filepath. + if (empty($args)) { + $filepath = '/'; + } else { + $filepath = '/' . implode('/', $args) . '/'; + } + + return [ + 'itemid' => 0, + 'filepath' => $filepath, + ]; +} From 64153166461b26ad417e2d5950cd096302957751 Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Mon, 21 Oct 2019 15:12:48 +0200 Subject: [PATCH 18/22] MDL-66609 core_h5p: Upgrade H5P library to 1.24 --- lib/h5p/fonts/h5p-core-21.eot | Bin 7784 -> 0 bytes lib/h5p/fonts/h5p-core-21.svg | 56 --------------------- lib/h5p/fonts/h5p-core-21.ttf | Bin 7604 -> 0 bytes lib/h5p/fonts/h5p-core-21.woff | Bin 7680 -> 0 bytes lib/h5p/fonts/h5p-core-23.eot | Bin 0 -> 9224 bytes lib/h5p/fonts/h5p-core-23.svg | 62 +++++++++++++++++++++++ lib/h5p/fonts/h5p-core-23.ttf | Bin 0 -> 9044 bytes lib/h5p/fonts/h5p-core-23.woff | Bin 0 -> 9120 bytes lib/h5p/h5p-default-storage.class.php | 6 +-- lib/h5p/h5p.classes.php | 38 ++++++-------- lib/h5p/js/h5p-data-view.js | 68 +++++++++++++++++++++++++- lib/h5p/js/h5p-x-api-event.js | 12 +++++ lib/h5p/js/h5p.js | 20 ++++++-- lib/h5p/styles/h5p-admin.css | 14 ++++++ lib/h5p/styles/h5p.css | 14 ++++-- 15 files changed, 197 insertions(+), 93 deletions(-) delete mode 100644 lib/h5p/fonts/h5p-core-21.eot delete mode 100644 lib/h5p/fonts/h5p-core-21.svg delete mode 100644 lib/h5p/fonts/h5p-core-21.ttf delete mode 100644 lib/h5p/fonts/h5p-core-21.woff create mode 100644 lib/h5p/fonts/h5p-core-23.eot create mode 100644 lib/h5p/fonts/h5p-core-23.svg create mode 100644 lib/h5p/fonts/h5p-core-23.ttf create mode 100644 lib/h5p/fonts/h5p-core-23.woff diff --git a/lib/h5p/fonts/h5p-core-21.eot b/lib/h5p/fonts/h5p-core-21.eot deleted file mode 100644 index 3fe54449a159946d32dc7c12e800ae40ac38c4c7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 7784 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 - - - - - -{ - "fontFamily": "h5p-core-21", - "description": "Font generated by IcoMoon.", - "majorVersion": 1, - "minorVersion": 1, - "version": "Version 1.1", - "fontId": "h5p-core-21", - "psName": "h5p-core-21", - "subFamily": "Regular", - "fullName": "h5p-core-21" -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/lib/h5p/fonts/h5p-core-21.ttf b/lib/h5p/fonts/h5p-core-21.ttf deleted file mode 100644 index 9c767365b4e4e7defadca9be4dc13b569b61e937..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 7604 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 KR~K?|&Hn)_cUHFm diff --git a/lib/h5p/fonts/h5p-core-21.woff b/lib/h5p/fonts/h5p-core-21.woff deleted file mode 100644 index 32cc521e2a972a80fb3a5a9ff945c2c6a47173c0..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 7680 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 diff --git a/lib/h5p/fonts/h5p-core-23.eot b/lib/h5p/fonts/h5p-core-23.eot new file mode 100644 index 0000000000000000000000000000000000000000..f86828cffdda12bed59b2ad866f8df857a15fca1 GIT binary patch literal 9224 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 literal 0 HcmV?d00001 diff --git a/lib/h5p/fonts/h5p-core-23.svg b/lib/h5p/fonts/h5p-core-23.svg new file mode 100644 index 00000000000..b282ddd2c01 --- /dev/null +++ b/lib/h5p/fonts/h5p-core-23.svg @@ -0,0 +1,62 @@ + + + + + + +{ + "fontFamily": "h5p-core-21", + "description": "Font generated by IcoMoon.", + "majorVersion": 1, + "minorVersion": 1, + "version": "Version 1.1", + "fontId": "h5p-core-21", + "psName": "h5p-core-21", + "subFamily": "Regular", + "fullName": "h5p-core-21" +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/h5p/fonts/h5p-core-23.ttf b/lib/h5p/fonts/h5p-core-23.ttf new file mode 100644 index 0000000000000000000000000000000000000000..3a3348adf7f30f859ea69837ae25932cbd9d4c89 GIT binary patch literal 9044 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 literal 0 HcmV?d00001 diff --git a/lib/h5p/fonts/h5p-core-23.woff b/lib/h5p/fonts/h5p-core-23.woff new file mode 100644 index 0000000000000000000000000000000000000000..ff03f42489c69ff862254a487b6de5afb4b28998 GIT binary patch literal 9120 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 M3cCa)d%Nd<0Xg+y%K!iX literal 0 HcmV?d00001 diff --git a/lib/h5p/h5p-default-storage.class.php b/lib/h5p/h5p-default-storage.class.php index 951b72f11ec..c58e2fe3908 100644 --- a/lib/h5p/h5p-default-storage.class.php +++ b/lib/h5p/h5p-default-storage.class.php @@ -373,7 +373,7 @@ class H5PDefaultStorage implements \H5PFileStorage { $target = "{$this->path}/content/{$contentId}"; } - $contentSource = $source . DIRECTORY_SEPARATOR . 'content'; + $contentSource = $source . '/' . 'content'; $contentFiles = array_diff(scandir($contentSource), array('.','..', 'content.json')); foreach ($contentFiles as $file) { if (is_dir("{$contentSource}/{$file}")) { @@ -445,8 +445,8 @@ class H5PDefaultStorage implements \H5PFileStorage { * @return bool */ public function hasPresave($libraryFolder, $developmentPath = null) { - $path = is_null($developmentPath) ? 'libraries' . DIRECTORY_SEPARATOR . $libraryFolder : $developmentPath; - $filePath = realpath($this->path . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . 'presave.js'); + $path = is_null($developmentPath) ? 'libraries' . '/' . $libraryFolder : $developmentPath; + $filePath = realpath($this->path . '/' . $path . '/' . 'presave.js'); return file_exists($filePath); } diff --git a/lib/h5p/h5p.classes.php b/lib/h5p/h5p.classes.php index 554f82030b2..7176ad00431 100644 --- a/lib/h5p/h5p.classes.php +++ b/lib/h5p/h5p.classes.php @@ -933,7 +933,7 @@ class H5PValidator { // Process and validate libraries using the unpacked library folders $files = scandir($tmpDir); foreach ($files as $file) { - $filePath = $tmpDir . DIRECTORY_SEPARATOR . $file; + $filePath = $tmpDir . '/' . $file; if ($file === '.' || $file === '..' || $file === 'content' || !is_dir($filePath)) { continue; // Skip @@ -1102,14 +1102,14 @@ class H5PValidator { $this->h5pF->setErrorMessage($this->h5pF->t('Invalid library name: %name', array('%name' => $file)), 'invalid-library-name'); return FALSE; } - $h5pData = $this->getJsonData($filePath . DIRECTORY_SEPARATOR . 'library.json'); + $h5pData = $this->getJsonData($filePath . '/' . 'library.json'); if ($h5pData === FALSE) { $this->h5pF->setErrorMessage($this->h5pF->t('Could not find library.json file with valid json format for library %name', array('%name' => $file)), 'invalid-library-json-file'); return FALSE; } // validate json if a semantics file is provided - $semanticsPath = $filePath . DIRECTORY_SEPARATOR . 'semantics.json'; + $semanticsPath = $filePath . '/' . 'semantics.json'; if (file_exists($semanticsPath)) { $semantics = $this->getJsonData($semanticsPath, TRUE); if ($semantics === FALSE) { @@ -1122,7 +1122,7 @@ class H5PValidator { } // validate language folder if it exists - $languagePath = $filePath . DIRECTORY_SEPARATOR . 'language'; + $languagePath = $filePath . '/' . 'language'; if (is_dir($languagePath)) { $languageFiles = scandir($languagePath); foreach ($languageFiles as $languageFile) { @@ -1133,7 +1133,7 @@ class H5PValidator { $this->h5pF->setErrorMessage($this->h5pF->t('Invalid language file %file in library %library', array('%file' => $languageFile, '%library' => $file)), 'invalid-language-file'); return FALSE; } - $languageJson = $this->getJsonData($languagePath . DIRECTORY_SEPARATOR . $languageFile, TRUE); + $languageJson = $this->getJsonData($languagePath . '/' . $languageFile, TRUE); if ($languageJson === FALSE) { $this->h5pF->setErrorMessage($this->h5pF->t('Invalid language file %languageFile has been included in the library %name', array('%languageFile' => $languageFile, '%name' => $file)), 'invalid-language-file'); return FALSE; @@ -1144,7 +1144,7 @@ class H5PValidator { } // Check for icon: - $h5pData['hasIcon'] = file_exists($filePath . DIRECTORY_SEPARATOR . 'icon.svg'); + $h5pData['hasIcon'] = file_exists($filePath . '/' . 'icon.svg'); $validLibrary = $this->isValidH5pData($h5pData, $file, $this->libraryRequired, $this->libraryOptional); @@ -1228,8 +1228,8 @@ class H5PValidator { */ private function isExistingFiles($files, $tmpDir, $library) { foreach ($files as $file) { - $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $file['path']); - if (!file_exists($tmpDir . DIRECTORY_SEPARATOR . $library . DIRECTORY_SEPARATOR . $path)) { + $path = str_replace(array('/', '\\'), '/', $file['path']); + if (!file_exists($tmpDir . '/' . $library . '/' . $path)) { $this->h5pF->setErrorMessage($this->h5pF->t('The file "%file" is missing from library: "%name"', array('%file' => $path, '%name' => $library)), 'library-missing-file'); return FALSE; } @@ -1520,7 +1520,7 @@ class H5PStorage { if (!$skipContent) { $basePath = $this->h5pF->getUploadedH5pFolderPath(); - $current_path = $basePath . DIRECTORY_SEPARATOR . 'content'; + $current_path = $basePath . '/' . 'content'; // Save content if ($content === NULL) { @@ -1539,7 +1539,7 @@ class H5PStorage { } } - $content['params'] = file_get_contents($current_path . DIRECTORY_SEPARATOR . 'content.json'); + $content['params'] = file_get_contents($current_path . '/' . 'content.json'); if (isset($options['disable'])) { $content['disable'] = $options['disable']; @@ -1916,7 +1916,7 @@ Class H5PExport { */ private static function populateFileList($dir, &$files, $relative = '') { $strip = strlen($dir) + 1; - $contents = glob($dir . DIRECTORY_SEPARATOR . '*'); + $contents = glob($dir . '/' . '*'); if (!empty($contents)) { foreach ($contents as $file) { $rel = $relative . substr($file, $strip); @@ -1998,7 +1998,7 @@ class H5PCore { public static $coreApi = array( 'majorVersion' => 1, - 'minorVersion' => 23 + 'minorVersion' => 24 ); public static $styles = array( 'styles/h5p.css', @@ -2432,7 +2432,7 @@ class H5PCore { // Using content dependencies foreach ($dependencies as $dependency) { if (isset($dependency['path']) === FALSE) { - $dependency['path'] = $this->getDependencyPath($dependency); + $dependency['path'] = 'libraries/' . H5PCore::libraryToString($dependency, TRUE); $dependency['preloadedJs'] = explode(',', $dependency['preloadedJs']); $dependency['preloadedCss'] = explode(',', $dependency['preloadedCss']); } @@ -2452,16 +2452,6 @@ class H5PCore { return $files; } - /** - * Get the path to the dependency. - * - * @param stdClass $dependency - * @return string - */ - protected function getDependencyPath(array $dependency): string { - return H5PCore::libraryToString($dependency, TRUE); - } - private static function getDependenciesHash(&$dependencies) { // Build hash of dependencies $toHash = array(); @@ -3711,7 +3701,7 @@ class H5PContentValidator { $wl_regex = '/\.(' . preg_replace('/ +/i', '|', preg_quote($whitelist)) . ')$/i'; foreach ($files as $file) { - $filePath = $contentPath . DIRECTORY_SEPARATOR . $file; + $filePath = $contentPath . '/' . $file; if (is_dir($filePath)) { $valid = $this->validateContentFiles($filePath, $isLibrary) && $valid; } diff --git a/lib/h5p/js/h5p-data-view.js b/lib/h5p/js/h5p-data-view.js index 2f708f8fa96..3d628bb9d73 100644 --- a/lib/h5p/js/h5p-data-view.js +++ b/lib/h5p/js/h5p-data-view.js @@ -53,7 +53,17 @@ var H5PDataView = (function ($) { self.filterOn = []; self.facets = {}; - self.loadData(); + // Index of column with author name; could be made more general by passing database column names and checking for position + self.columnIdAuthor = 2; + + // Future option: Create more general solution for filter presets + if (H5PIntegration.user && parseInt(H5PIntegration.user.canToggleViewOthersH5PContents) === 1) { + self.updateTable([]); + self.filterByFacet(self.columnIdAuthor, H5PIntegration.user.id, H5PIntegration.user.name || ''); + } + else { + self.loadData(); + } } /** @@ -151,6 +161,12 @@ var H5PDataView = (function ($) { // Add filters self.addFilters(); + // Add toggler for others' content + if (H5PIntegration.user && parseInt(H5PIntegration.user.canToggleViewOthersH5PContents) > 0) { + // canToggleViewOthersH5PContents = 1 is setting for only showing current user's contents + self.addOthersContentToggler(parseInt(H5PIntegration.user.canToggleViewOthersH5PContents) === 1); + } + // Add facets self.$facets = $('
      ', { 'class': 'h5p-facet-wrapper', @@ -246,13 +262,17 @@ var H5PDataView = (function ($) { appendTo: self.$facets, }) }; - /** * Callback for removing filter. * * @private */ var remove = function () { + // Uncheck toggler for others' H5P contents + if ( self.$othersContentToggler && self.facets.hasOwnProperty( self.columnIdAuthor ) ) { + self.$othersContentToggler.prop('checked', false ); + } + self.facets[col].$tag.remove(); delete self.facets[col]; self.loadData(); @@ -374,5 +394,49 @@ var H5PDataView = (function ($) { }).appendTo(self.$container); }; + /** + * Add toggle for others' H5P content. + * @param {boolean} [checked=false] Initial check setting. + */ + H5PDataView.prototype.addOthersContentToggler = function (checked) { + var self = this; + + checked = (typeof checked === 'undefined') ? false : checked; + + // Checkbox + this.$othersContentToggler = $('', { + type: 'checkbox', + 'class': 'h5p-others-contents-toggler', + 'id': 'h5p-others-contents-toggler', + 'checked': checked, + 'click': function () { + if ( this.checked ) { + // Add filter on current user + self.filterByFacet( self.columnIdAuthor, H5PIntegration.user.id, H5PIntegration.user.name ); + } + else { + // Remove facet indicator and reload full data view + if ( self.facets.hasOwnProperty( self.columnIdAuthor ) && self.facets[self.columnIdAuthor].$tag ) { + self.facets[self.columnIdAuthor].$tag.remove(); + } + delete self.facets[self.columnIdAuthor]; + self.loadData(); + } + } + }); + + // Label + var $label = $('
      ') .insertAfter($element) - .click(function () { + .click(function (e) { + if (e && e.originalEvent && e.originalEvent.preventClosing) { + return; + } + self.close(); }) .children('.h5p-inner') - .click(function () { - return false; + .click(function (e) { + e.originalEvent.preventClosing = true; }) .find('.h5p-close') .click(function () { diff --git a/lib/h5p/styles/h5p-admin.css b/lib/h5p/styles/h5p-admin.css index 372da79b8a5..68306126fc0 100644 --- a/lib/h5p/styles/h5p-admin.css +++ b/lib/h5p/styles/h5p-admin.css @@ -266,6 +266,20 @@ button.h5p-admin.disabled:hover { display: none; } +.h5p-data-view .h5p-others-contents-toggler-wrapper { + float: right; + line-height: 2; + margin-right: 0.5em; +} + +.h5p-data-view .h5p-others-contents-toggler-label { + font-size: 14px; +} + +.h5p-data-view .h5p-others-contents-toggler { + margin-right: 0.5em; +} + .h5p-data-view th[role="button"] { cursor: pointer; } diff --git a/lib/h5p/styles/h5p.css b/lib/h5p/styles/h5p.css index 5a503267919..1f89e4ead7c 100644 --- a/lib/h5p/styles/h5p.css +++ b/lib/h5p/styles/h5p.css @@ -3,11 +3,11 @@ /* Custom H5P font to use for icons. */ @font-face { font-family: 'h5p'; - src: url('../fonts/h5p-core-21.eot?mz1lkp'); - src: url('../fonts/h5p-core-21.eot?mz1lkp#iefix') format('embedded-opentype'), - url('../fonts/h5p-core-21.ttf?mz1lkp') format('truetype'), - url('../fonts/h5p-core-21.woff?mz1lkp') format('woff'), - url('../fonts/h5p-core-21.svg?mz1lkp#h5p') format('svg'); + src: url('../fonts/h5p-core-23.eot?mz1lkp'); + src: url('../fonts/h5p-core-23.eot?mz1lkp#iefix') format('embedded-opentype'), + url('../fonts/h5p-core-23.ttf?mz1lkp') format('truetype'), + url('../fonts/h5p-core-23.woff?mz1lkp') format('woff'), + url('../fonts/h5p-core-23.svg?mz1lkp#h5p') format('svg'); font-weight: normal; font-style: normal; } @@ -560,3 +560,7 @@ iframe.h5peditor-semi-fullscreen { background: #fff; z-index: 100001; } + +.h5p-content.using-mouse *:not(textarea):focus { + outline: none !important; +} From 5da7a7fc31a8e6235330b8d34a3ecf9ce7e35b79 Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Mon, 21 Oct 2019 15:34:02 +0200 Subject: [PATCH 19/22] MDL-66609 core_h5p: Change core files when upgrading lib This commit contains the changes required when upgrading the H5P PHP library. --- lib/h5p/h5p-metadata.class.php | 2 +- lib/h5p/h5p.classes.php | 32 ++++++++++++++++++++++++++------ lib/h5p/readme_moodle.txt | 24 ++++++++++++++++++++---- lib/thirdpartylibs.xml | 2 +- 4 files changed, 48 insertions(+), 12 deletions(-) diff --git a/lib/h5p/h5p-metadata.class.php b/lib/h5p/h5p-metadata.class.php index 572cfd0324d..2154f27a71e 100644 --- a/lib/h5p/h5p-metadata.class.php +++ b/lib/h5p/h5p-metadata.class.php @@ -107,7 +107,7 @@ abstract class H5PMetadata { switch ($config['type']) { case 'text': if ($value !== null && strlen($value) > $config['maxLength']) { - $value = mb_substr($value, 0, $config['maxLength']); + $value = \core_text::substr($value, 0, $config['maxLength']); } $types[] = '%s'; break; diff --git a/lib/h5p/h5p.classes.php b/lib/h5p/h5p.classes.php index 7176ad00431..a624cf8c49a 100644 --- a/lib/h5p/h5p.classes.php +++ b/lib/h5p/h5p.classes.php @@ -758,11 +758,14 @@ class H5PValidator { unlink($tmpPath); return FALSE; } + // Moodle: the extension mbstring is optional. + /* if (!extension_loaded('mbstring')) { $this->h5pF->setErrorMessage($this->h5pF->t('The mbstring PHP extension is not loaded. H5P need this to function properly'), 'mbstring-unsupported'); unlink($tmpPath); return FALSE; } + */ // Create a temporary dir to extract package in. $tmpDir = $this->h5pF->getUploadedH5pFolderPath(); @@ -809,7 +812,7 @@ class H5PValidator { } $totalSize += $fileStat['size']; - $fileName = mb_strtolower($fileStat['name']); + $fileName = \core_text::strtolower($fileStat['name']); if (preg_match('/(^[\._]|\/[\._])/', $fileName) !== 0) { continue; // Skip any file or folder starting with a . or _ } @@ -2432,7 +2435,7 @@ class H5PCore { // Using content dependencies foreach ($dependencies as $dependency) { if (isset($dependency['path']) === FALSE) { - $dependency['path'] = 'libraries/' . H5PCore::libraryToString($dependency, TRUE); + $dependency['path'] = $this->getDependencyPath($dependency); $dependency['preloadedJs'] = explode(',', $dependency['preloadedJs']); $dependency['preloadedCss'] = explode(',', $dependency['preloadedCss']); } @@ -2452,6 +2455,16 @@ class H5PCore { return $files; } + /** + * Get the path to the dependency. + * + * @param stdClass $dependency + * @return string + */ + protected function getDependencyPath(array $dependency): string { + return H5PCore::libraryToString($dependency, TRUE); + } + private static function getDependenciesHash(&$dependencies) { // Build hash of dependencies $toHash = array(); @@ -3303,12 +3316,15 @@ class H5PCore { $setup->disable_hub = TRUE; } + // Moodle: the extension mbstring is optional. + /* if (!extension_loaded('mbstring')) { $setup->errors[] = $this->h5pF->t( 'The mbstring PHP extension is not loaded. H5P needs this to function properly' ); $setup->disable_hub = TRUE; } + */ // Check php version >= 5.2 $php_version = explode('.', phpversion()); @@ -3656,12 +3672,13 @@ class H5PContentValidator { // Check if string is within allowed length if (isset($semantics->maxLength)) { + // Moodle: the extension mbstring is optional. + /* if (!extension_loaded('mbstring')) { $this->h5pF->setErrorMessage($this->h5pF->t('The mbstring PHP extension is not loaded. H5P need this to function properly'), 'mbstring-unsupported'); } - else { - $text = mb_substr($text, 0, $semantics->maxLength); - } + */ + $text = \core_text::substr($text, 0, $semantics->maxLength); } // Check if string is according to optional regexp in semantics @@ -3711,11 +3728,14 @@ class H5PContentValidator { // file name, 2. testing against a returned error array that could // never be more than 1 element long anyway, 3. recreating the regex // for every file. + // Moodle: the extension mbstring is optional. + /* if (!extension_loaded('mbstring')) { $this->h5pF->setErrorMessage($this->h5pF->t('The mbstring PHP extension is not loaded. H5P need this to function properly'), 'mbstring-unsupported'); $valid = FALSE; } - else if (!preg_match($wl_regex, mb_strtolower($file))) { + */ + if (!preg_match($wl_regex, \core_text::strtolower($file))) { $this->h5pF->setErrorMessage($this->h5pF->t('File "%filename" not allowed. Only files with the following extensions are allowed: %files-allowed.', array('%filename' => $file, '%files-allowed' => $whitelist)), 'not-in-whitelist'); $valid = FALSE; } diff --git a/lib/h5p/readme_moodle.txt b/lib/h5p/readme_moodle.txt index ed3ce037205..2eb2896e40e 100644 --- a/lib/h5p/readme_moodle.txt +++ b/lib/h5p/readme_moodle.txt @@ -14,18 +14,34 @@ Removed: Added: * readme_moodle.txt -Downloaded version: 1.23.1 release +Downloaded version: 1.24 release + === 3.8 === -* In order to allow the dependency path to be overridden by child H5PCore classes, a couple of minor changes have been added to the +1. In order to allow the dependency path to be overridden by child H5PCore classes, a couple of minor changes have been added to the h5p.classes.php file: - Into the getDependenciesFiles method, the line 2435: $dependency['path'] = 'libraries/' . H5PCore::libraryToString($dependency, TRUE); has been changed to: - $dependency['path'] = $this->getDependencyPath($dependency); + $dependency['path'] = $this->getDependencyPath($dependency); - The method getDependencyPath has been added (line 2455). It might be rewritten by child classes. A PR has been sent to the H5P library with these changes: https://github.com/h5p/h5p-php-library/compare/master...andrewnicols:libraryPathSubclass -Hopefully, when upgrading, these patch won't be needed because it will be included in the H5P library by default. \ No newline at end of file +Hopefully, when upgrading, these patch won't be needed because it will be included in the H5P library by default. + + +2. As the mbstring extension is optional in Moodle, the following changes have been hardcoded to the library: +2.1. Comment the following methods in h5p.classes.php file where the extension_loaded('mbstring') is called: + * isValidPackage + * checkSetupErrorMessage + * validateText + * validateContentFiles + +2.2. Change all the mb_uses straight to the core_text() alternatives. Version 1.24 has 3 ocurrences in h5p.classes.php +and 1 ocurrence in h5p-metadata.class.php. + + +The point 2 from above won't be needed once the mbstring extension becomes mandatory in Moodle. A request has been +sent to MDL-65809. \ No newline at end of file diff --git a/lib/thirdpartylibs.xml b/lib/thirdpartylibs.xml index b901656ca51..89c1b67f1f4 100644 --- a/lib/thirdpartylibs.xml +++ b/lib/thirdpartylibs.xml @@ -318,6 +318,6 @@ h5p h5p-php-library GPL-3.0 - 1.23.1 + 1.24 From df74cd4aeae2aa1c5989c504386cd8818f785be4 Mon Sep 17 00:00:00 2001 From: Mihail Geshoski Date: Tue, 22 Oct 2019 21:37:17 +0800 Subject: [PATCH 20/22] MDL-66609 core_h5p: Use factory methods instead of framework::instance() --- h5p/classes/player.php | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/h5p/classes/player.php b/h5p/classes/player.php index eee9bff4587..93ecddc3e2c 100644 --- a/h5p/classes/player.php +++ b/h5p/classes/player.php @@ -75,6 +75,11 @@ class player { */ private $context; + /** + * @var context The \core_h5p\factory object. + */ + private $factory; + /** * Inits the H5P player for rendering the content. * @@ -87,8 +92,10 @@ class player { } $this->url = new \moodle_url($url); - // Create H5PFramework instance. - $this->core = \core_h5p\framework::instance(); + $this->factory = new \core_h5p\factory(); + + // Create \core_h5p\core instance. + $this->core = $this->factory->get_core(); // Get the H5P identifier linked to this URL. if ($this->h5pid = $this->get_h5p_id($url, $config)) { @@ -368,9 +375,9 @@ class player { $file->copy_content_to($path); // Check if the h5p file is valid before saving it. - $h5pvalidator = \core_h5p\framework::instance('validator'); + $h5pvalidator = $this->factory->get_validator(); if ($h5pvalidator->isValidPackage(false, false)) { - $h5pstorage = \core_h5p\framework::instance('storage'); + $h5pstorage = $this->factory->get_storage(); $options = ['disable' => $this->get_display_options($config)]; $content = [ @@ -416,7 +423,7 @@ class player { * @param stdClass $content The H5P package to delete. */ private function delete_h5p(\stdClass $content) { - $h5pstorage = \core_h5p\framework::instance('storage'); + $h5pstorage = $this->factory->get_storage(); // Add an empty slug to the content if it's not defined, because the H5P library requires this field exists. // It's not used when deleting a package, so the real slug value is not required at this point. $content->slug = $content->slug ?? ''; From a3cdaa8dd95f155b675a23601f775e07bdea4684 Mon Sep 17 00:00:00 2001 From: Amaia Anabitarte Date: Wed, 23 Oct 2019 18:58:58 +0200 Subject: [PATCH 21/22] MDL-66609 core_h5p: Autoload for H5P third party library classes --- h5p/classes/autoloader.php | 59 ++++++++++++++++++++++++++++++++++++++ h5p/classes/factory.php | 8 ++++++ h5p/lib.php | 3 ++ lib/classes/component.php | 8 ------ 4 files changed, 70 insertions(+), 8 deletions(-) create mode 100644 h5p/classes/autoloader.php diff --git a/h5p/classes/autoloader.php b/h5p/classes/autoloader.php new file mode 100644 index 00000000000..9088ac2b2fd --- /dev/null +++ b/h5p/classes/autoloader.php @@ -0,0 +1,59 @@ +. + +/** + * H5P Autoloader. + * + * @package core_h5p + * @copyright 2019 Mihail Geshoski + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace core_h5p; + +defined('MOODLE_INTERNAL') || die(); + +/** + * H5P Autoloader. + * + * @package core_h5p + * @copyright 2019 Mihail Geshoski + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class autoloader { + public static function register(): void { + spl_autoload_register([self::class, 'autoload']); + } + + public static function autoload($classname): void { + global $CFG; + + $classes = [ + 'H5PCore' => '/lib/h5p/h5p.classes.php', + 'H5PFrameworkInterface' => '/lib/h5p/h5p.classes.php', + 'H5PContentValidator' => 'lib/h5p/h5p.classes.php', + 'H5PValidator' => '/lib/h5p/h5p.classes.php', + 'H5PStorage' => '/lib/h5p/h5p.classes.php', + 'H5PDevelopment' => '/lib/h5p/h5p-development.class.php', + 'H5PFileStorage' => '/lib/h5p/h5p-file-storage.interface.php', + 'H5PMetadata' => '/lib/h5p/h5p-metadata.class.php', + ]; + + if (isset($classes[$classname])) { + require_once("{$CFG->dirroot}{$classes[$classname]}"); + } + } +} diff --git a/h5p/classes/factory.php b/h5p/classes/factory.php index f4edb4dd519..d63bfc2c502 100644 --- a/h5p/classes/factory.php +++ b/h5p/classes/factory.php @@ -58,6 +58,14 @@ class factory { /** @var content_validator The Moodle H5PContentValidator implementation */ protected $content_validator; + /** + * factory constructor. + */ + public function __construct() { + // Loading classes we need from H5P third party library. + autoloader::register(); + } + /** * Returns an instance of the \core_h5p\framework class. * diff --git a/h5p/lib.php b/h5p/lib.php index da4871a8bed..deccba44862 100644 --- a/h5p/lib.php +++ b/h5p/lib.php @@ -43,6 +43,9 @@ function core_h5p_pluginfile($course, $cm, $context, string $filearea, array $ar array $options = []) : bool { global $DB; + // Require classes from H5P third party library + \core_h5p\autoloader::register(); + $filesettingsset = false; switch ($filearea) { diff --git a/lib/classes/component.php b/lib/classes/component.php index 35bb9503a6d..22edb6ba780 100644 --- a/lib/classes/component.php +++ b/lib/classes/component.php @@ -90,14 +90,6 @@ class core_component { 'RedeyeVentures\\GeoPattern' => 'lib/geopattern-php/GeoPattern', 'MongoDB' => 'cache/stores/mongodb/MongoDB', 'Firebase\\JWT' => 'lib/php-jwt/src', - 'H5PCore' => '/lib/h5p/h5p.classes', - 'H5PFrameworkInterface' => '/lib/h5p/h5p.classes', - 'H5PContentValidator' => 'lib/h5p/h5p.classes', - 'H5PValidator' => '/lib/h5p/h5p.classes', - 'H5PStorage' => '/lib/h5p/h5p.classes', - 'H5PDevelopment' => '/lib/h5p/h5p-development.class', - 'H5PFileStorage' => '/lib/h5p/h5p-file-storage.interface', - 'H5PMetadata' => '/lib/h5p/h5p-metadata.class', ); /** From 8fda136dc832db89ae27ad1d7887fe44607fd990 Mon Sep 17 00:00:00 2001 From: Sara Arjona Date: Thu, 24 Oct 2019 21:48:30 +0200 Subject: [PATCH 22/22] MDL-66609 core_h5p: Add capability to deploy H5P content --- h5p/classes/player.php | 17 +++++++++++++---- lang/en/h5p.php | 1 + lang/en/role.php | 1 + lib/db/access.php | 11 +++++++++++ version.php | 2 +- 5 files changed, 27 insertions(+), 5 deletions(-) diff --git a/h5p/classes/player.php b/h5p/classes/player.php index 93ecddc3e2c..5605a972481 100644 --- a/h5p/classes/player.php +++ b/h5p/classes/player.php @@ -241,10 +241,7 @@ class player { $h5p = false; } - if (!$h5p) { - // The H5P content hasn't been deployed previously. It has to be validated and stored before displaying it. - return $this->save_h5p($file, $config); - } else { + if ($h5p) { // The H5P content has been deployed previously. $displayoptions = $this->get_display_options($config); // Check if the user can set the displayoptions. @@ -253,6 +250,18 @@ class player { $this->core->h5pF->updateContentFields($h5p->id, ['displayoptions' => $displayoptions]); } return $h5p->id; + } else { + // The H5P content hasn't been deployed previously. + + // Check if the user uploading the H5P content is "trustable". If the file hasn't been uploaded by a user with this + // capability, the content won't be deployed and an error message will be displayed. + if (!has_capability('moodle/h5p:deploy', $this->context, $file->get_userid())) { + $this->core->h5pF->setErrorMessage(get_string('nopermissiontodeploy', 'core_h5p')); + return false; + } + + // Validate and store the H5P content before displaying it. + return $this->save_h5p($file, $config); } } diff --git a/lang/en/h5p.php b/lang/en/h5p.php index 5d2c8f133ac..a65724f2e55 100644 --- a/lang/en/h5p.php +++ b/lang/en/h5p.php @@ -123,6 +123,7 @@ $string['missingmbstring'] = 'The mbstring PHP extension is not loaded. H5P need $string['missinguploadpermissions'] = '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.'; $string['nocopyright'] = 'No copyright information available for this content.'; $string['noextension'] = 'The file you uploaded is not a valid HTML5 Package (It does not have the .h5p file extension)'; +$string['nopermissiontodeploy'] = 'This file can\'t be displayed because it has been uploaded by a user without the required capability to deploy H5P content.'; $string['nojson'] = 'The main h5p.json file is not valid'; $string['nounzip'] = 'The file you uploaded is not a valid HTML5 Package (We are unable to unzip it)'; $string['offlineDialogBody'] = 'We were unable to send information about your completion of this task. Please check your internet connection.'; diff --git a/lang/en/role.php b/lang/en/role.php index 5460e58b4c3..07d94072b47 100644 --- a/lang/en/role.php +++ b/lang/en/role.php @@ -260,6 +260,7 @@ $string['grade:unlock'] = 'Unlock grades or items'; $string['grade:view'] = 'View own grades'; $string['grade:viewall'] = 'View grades of other users'; $string['grade:viewhidden'] = 'View hidden grades for owner'; +$string['h5p:deploy'] = 'Allow to deploy H5P content'; $string['h5p:setdisplayoptions'] = 'Set the display options to an H5P content'; $string['highlightedcellsshowdefault'] = 'The permissions highlighted in the table below are the defaults for the role archetype currently selected above.'; $string['highlightedcellsshowinherit'] = 'The highlighted cells in the table below show the permission (if any) that will be inherited. Apart from the capabilities whose permission you actually want to alter, you should leave everything set to Inherit.'; diff --git a/lib/db/access.php b/lib/db/access.php index 336cce64b1d..9b7668e7c8d 100644 --- a/lib/db/access.php +++ b/lib/db/access.php @@ -2439,4 +2439,15 @@ $capabilities = array( 'editingteacher' => CAP_ALLOW, ) ), + + // Allow to deploy H5P content. + 'moodle/h5p:deploy' => array( + 'riskbitmask' => RISK_XSS, + 'captype' => 'write', + 'contextlevel' => CONTEXT_MODULE, + 'archetypes' => array( + 'manager' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + ) + ), ); diff --git a/version.php b/version.php index 5be1a36a072..af1762447e4 100644 --- a/version.php +++ b/version.php @@ -29,7 +29,7 @@ defined('MOODLE_INTERNAL') || die(); -$version = 2019102500.02; // YYYYMMDD = weekly release date of this DEV branch. +$version = 2019102500.03; // YYYYMMDD = weekly release date of this DEV branch. // RR = release increments - 00 in DEV branches. // .XX = incremental changes.