diff --git a/admin/tool/brickfield/LICENSE_QUAIL.txt b/admin/tool/brickfield/LICENSE_QUAIL.txt new file mode 100644 index 0000000000000..0947f92adb9d7 --- /dev/null +++ b/admin/tool/brickfield/LICENSE_QUAIL.txt @@ -0,0 +1,219 @@ +PLEASE NOTE: + +There are included libraries in the directory quail/common/services which might have different (but compatible) licenses than the one covered in this file. Current licenses include: + *The current BSD: + *services/readability/php-text-statistics + *The MIT License: + *common/css.php The function parseSelector is from the PHPQuery project: + *http://code.google.com/p/phpquery + +GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. +TERMS AND CONDITIONS +0. Definitions. + +ÒThis LicenseÓ refers to version 3 of the GNU General Public License. + +ÒCopyrightÓ also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +ÒThe ProgramÓ refers to any copyrightable work licensed under this License. Each licensee is addressed as ÒyouÓ. ÒLicenseesÓ and ÒrecipientsÓ may be individuals or organizations. + +To ÒmodifyÓ a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a Òmodified versionÓ of the earlier work or a work Òbased onÓ the earlier work. + +A Òcovered workÓ means either the unmodified Program or a work based on the Program. + +To ÒpropagateÓ a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To ÒconveyÓ a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays ÒAppropriate Legal NoticesÓ to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. +1. Source Code. + +The Òsource codeÓ for a work means the preferred form of the work for making modifications to it. ÒObject codeÓ means any non-source form of a work. + +A ÒStandard InterfaceÓ means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The ÒSystem LibrariesÓ of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A ÒMajor ComponentÓ, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The ÒCorresponding SourceÓ for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. +2. Basic Permissions. + +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + * a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + * b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to Òkeep intact all noticesÓ. + * c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + * d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an ÒaggregateÓ if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + * a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + * b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + * c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + * d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + * e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A ÒUser ProductÓ is either (1) a Òconsumer productÓ, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, Ònormally usedÓ refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +ÒInstallation InformationÓ for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. +7. Additional Terms. + +ÒAdditional permissionsÓ are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + * a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + * b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + * c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + * d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + * e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + * f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered Òfurther restrictionsÓ within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An Òentity transactionÓ is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. +11. Patents. + +A ÒcontributorÓ is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's Òcontributor versionÓ. + +A contributor's Òessential patent claimsÓ are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, ÒcontrolÓ includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a Òpatent licenseÓ is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To ÒgrantÓ such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. ÒKnowingly relyingÓ means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is ÒdiscriminatoryÓ if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. +13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License Òor any later versionÓ applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM ÒAS ISÓ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS FOR QUAIL LIBRARY + + +THE FOLLOWING LICENSE COVERS PORTIONS OF THE FILE LOCATED AT common/css.php, NAMELY THE FUNCTION parseSelector: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/admin/tool/brickfield/README.md b/admin/tool/brickfield/README.md new file mode 100644 index 0000000000000..d95a3294bc979 --- /dev/null +++ b/admin/tool/brickfield/README.md @@ -0,0 +1,7 @@ +# Accessibility plugin # + +The Accessibility admin tool plugin provides a simple means of checking content for any accessibility issues. + +Portions of the htmlchecker files were derived from the ["Quail PHP Accessibility Library"](https://code.google.com/archive/p/quail-lib/). +The Quail library (Copyright (C) 2009 Kevin Miller) is licensed under [GNU GPL v3](http://www.gnu.org/licenses/gpl.html). +See the LICENSE_QUAIL.txt file in this directory for original Quail license information. diff --git a/admin/tool/brickfield/classes/accessibility.php b/admin/tool/brickfield/classes/accessibility.php new file mode 100644 index 0000000000000..98aa9b7878ef3 --- /dev/null +++ b/admin/tool/brickfield/classes/accessibility.php @@ -0,0 +1,618 @@ +. + +namespace tool_brickfield; + +use context_system; +use core\log\sql_reader; +use moodle_url; +use stdClass; +use tool_brickfield\event\plugin_installed; +use tool_brickfield\local\tool\filter; + +/** + * Provides the Brickfield Accessibility toolkit API. + * + * @package tool_brickfield + * @copyright 2020 onward Brickfield Education Labs Ltd, https://www.brickfield.ie + * @author Mike Churchward (mike@brickfieldlabs.ie) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class accessibility { + + /** @var string The component sub path */ + private static $pluginpath = 'tool/brickfield'; + + /** @var string Supported format of topics */ + const TOOL_BRICKFIELD_FORMAT_TOPIC = 'topics'; + + /** @var string Supported format of weeks */ + const TOOL_BRICKFIELD_FORMAT_WEEKLY = 'weeks'; + + /** + * Return the state of the site enable condition. + * @return bool + */ + public static function is_accessibility_enabled(): bool { + global $CFG; + + if (isset($CFG->enableaccessibilitytools)) { + return $CFG->enableaccessibilitytools; + } + + // Enabled by default. + return true; + } + + /** + * Throw an error if the toolkit is not enabled. + * @return bool + * @throws \moodle_exception + */ + public static function require_accessibility_enabled(): bool { + if (!static::is_accessibility_enabled()) { + print_error('accessibilitydisabled', manager::PLUGINNAME); + } + return true; + } + + /** + * Get a URL for a page within the plugin. + * + * This takes into account the value of the admin config value. + * + * @param string $url The URL within the plugin + * @return moodle_url + */ + public static function get_plugin_url(string $url = ''): moodle_url { + $url = ($url == '') ? 'index.php' : $url; + $pluginpath = self::$pluginpath; + return new moodle_url("/admin/{$pluginpath}/{$url}"); + } + + /** + * Get a file path for a file within the plugin. + * + * This takes into account the value of the admin config value. + * + * @param string $path The path within the plugin + * @return string + */ + public static function get_file_path(string $path): string { + global $CFG; + + return implode(DIRECTORY_SEPARATOR, [$CFG->dirroot, $CFG->admin, self::$pluginpath, $path, ]); + } + + /** + * Get the canonicalised name of a capability. + * + * @param string $capability + * @return string + */ + public static function get_capability_name(string $capability): string { + return self::$pluginpath . ':' . $capability; + } + + /** + * Get the relevant title with extra value concatenated on. + * @param local\tool\filter $filter + * @param int $countdata + * @param string $extra + * @return string + * @throws \coding_exception + * @throws \dml_exception + * @throws \moodle_exception + */ + public static function get_title(local\tool\filter $filter, int $countdata, string $extra = ''): string { + global $DB; + + if ($filter->courseid != 0) { + $thiscourse = get_fast_modinfo($filter->courseid)->get_course(); + return get_string('course') . ': ' . $thiscourse->fullname . $extra; + } else if ($filter->categoryid != 0) { + $category = $DB->get_record('course_categories', ['id' => $filter->categoryid]); + $tmp = new \stdClass(); + $tmp->catname = $category->name; + $tmp->count = $countdata; + return get_string('allcoursescat', manager::PLUGINNAME, $tmp) . $extra; + } else { + return get_string('allcourses', manager::PLUGINNAME, $countdata) . $extra; + } + } + + /** + * Function to be run periodically according to the scheduled task. + * Return true if a process was completed. False if no process executed. + * Finds all unprocessed courses for bulk batch processing and completes them. + * @param int $batch + * @return bool + * @throws \ReflectionException + * @throws \coding_exception + * @throws \ddl_exception + * @throws \ddl_table_missing_exception + * @throws \dml_exception + */ + public static function bulk_process_courses_cron(int $batch = 0): bool { + global $PAGE; + + // Run a registration check. + if (!(new registration())->validate()) { + return false; + } + + if (analysis::is_enabled()) { + $PAGE->set_context(context_system::instance()); + mtrace("Starting cron for bulk_process_courses"); + // Do regular processing. True if full deployment type isn't selected as well. + static::bulk_processing($batch); + mtrace("Ending cron for bulk_process_courses"); + return true; + } else { + mtrace('Content analysis is currently disabled in settings.'); + return false; + } + } + + /** + * Bulk processing. + * @param int $batch + * @return bool + */ + protected static function bulk_processing(int $batch = 0): bool { + manager::check_course_updates(); + mtrace("check_course_updates completed at " . time()); + $recordsprocessed = manager::check_scheduled_areas($batch); + mtrace("check_scheduled_areas completed at " . time()); + manager::check_scheduled_deletions(); + mtrace("check_scheduled_deletions completed at " . time()); + manager::delete_historical_data(); + mtrace("delete_historical_data completed at " . time()); + return $recordsprocessed; + } + + /** + * Function to be run periodically according to the scheduled task. + * Finds all unprocessed courses for cache processing and completes them. + */ + public static function bulk_process_caches_cron() { + global $DB; + + // Run a registration check. + if (!(new registration())->validate()) { + return; + } + + if (analysis::is_enabled()) { + mtrace("Starting cron for bulk_process_caches"); + // Monitor ongoing caching requests. + $fields = 'DISTINCT courseid'; + $reruns = $DB->get_records(manager::DB_PROCESS, ['item' => 'cache'], '', $fields); + foreach ($reruns as $rerun) { + mtrace("Running rerun caching for Courseid " . $rerun->courseid); + manager::store_result_summary($rerun->courseid); + mtrace("rerun cache completed at " . time()); + $DB->delete_records(manager::DB_PROCESS, ['courseid' => $rerun->courseid, 'item' => 'cache']); + } + mtrace("Ending cron for bulk_process_caches at " . time()); + } else { + mtrace('Content analysis is currently disabled in settings.'); + } + } + + /** + * This function runs the checks on the html item + * + * @param string $html The html string to be analysed; might be NULL. + * @param int $contentid The content area ID + * @param int $processingtime + * @param int $resultstime + * @throws \coding_exception + * @throws \dml_exception + */ + public static function run_check(string $html = '', int $contentid, int &$processingtime, int &$resultstime) { + global $DB; + + // Change the limit if 10,000 is not appropriate. + $bulkrecordlimit = manager::BULKRECORDLIMIT; + $bulkrecordcount = 0; + + $checkids = static::checkids(); + $checknameids = array_flip($checkids); + + $testname = 'brickfield'; + + $stime = time(); + + // Swapping in new library. + $htmlchecker = new local\htmlchecker\brickfield_accessibility($html, $testname, 'string'); + $htmlchecker->run_check(); + $tests = $htmlchecker->guideline->get_tests(); + $report = $htmlchecker->get_report(); + $processingtime += (time() - $stime); + + $records = []; + foreach ($tests as $test) { + $records[$test]['count'] = 0; + $records[$test]['errors'] = []; + } + + foreach ($report['report'] as $a) { + if (!isset($a['type'])) { + continue; + } + $type = $a['type']; + $records[$type]['errors'][] = $a; + if (!isset($records[$type]['count'])) { + $records[$type]['count'] = 0; + } + $records[$type]['count']++; + } + + $stime = time(); + $returnchecks = []; + $errors = []; + + // Build up records for inserting. + foreach ($records as $key => $rec) { + $recordres = new stdClass(); + // Handling if checkid is unknown. + $checkid = (isset($checknameids[$key])) ? $checknameids[$key] : 0; + $recordres->contentid = $contentid; + $recordres->checkid = $checkid; + $recordres->errorcount = $rec['count']; + + // Build error inserts if needed. + if ($rec['count'] > 0) { + foreach ($rec['errors'] as $tmp) { + $error = new stdClass(); + $error->resultid = 0; + $error->linenumber = $tmp['lineNo']; + $error->htmlcode = $tmp['html']; + $error->errordescription = $tmp['title']; + // Add contentid and checkid so that we can query for the results record id later. + $error->contentid = $contentid; + $error->checkid = $checkid; + $errors[] = $error; + } + } + $returnchecks[] = $recordres; + $bulkrecordcount++; + + // If we've hit the bulk limit, write the results records and reset. + if ($bulkrecordcount > $bulkrecordlimit) { + $DB->insert_records(manager::DB_RESULTS, $returnchecks); + $bulkrecordcount = 0; + $returnchecks = []; + // Get the results id value for each error record and write the errors. + foreach ($errors as $key2 => $error) { + $errors[$key2]->resultid = $DB->get_field(manager::DB_RESULTS, 'id', + ['contentid' => $error->contentid, 'checkid' => $error->checkid]); + unset($errors[$key2]->contentid); + unset($errors[$key2]->checkid); + } + $DB->insert_records(manager::DB_ERRORS, $errors); + $errors = []; + } + } + + // Write any leftover records. + if ($bulkrecordcount > 0) { + $DB->insert_records(manager::DB_RESULTS, $returnchecks); + // Get the results id value for each error record and write the errors. + foreach ($errors as $key => $error) { + $errors[$key]->resultid = $DB->get_field(manager::DB_RESULTS, 'id', + ['contentid' => $error->contentid, 'checkid' => $error->checkid]); + unset($errors[$key]->contentid); + unset($errors[$key]->checkid); + } + $DB->insert_records(manager::DB_ERRORS, $errors); + } + + $resultstime += (time() - $stime); + } + + /** + * This function runs one specified check on the html item + * + * @param string $html The html string to be analysed; might be NULL. + * @param int $contentid The content area ID + * @param int $errid The error ID + * @param string $check The check name to run + * @param int $processingtime + * @param int $resultstime + * @throws \coding_exception + * @throws \dml_exception + */ + public static function run_one_check( + string $html = null, + int $contentid, + int $errid, + string $check, + int &$processingtime, + int &$resultstime + ) { + global $DB; + + $stime = time(); + + $checkdata = $DB->get_record(manager::DB_CHECKS, ['shortname' => $check], 'id,shortname,severity'); + + $testname = 'brickfield'; + + // Swapping in new library. + $htmlchecker = new local\htmlchecker\brickfield_accessibility($html, $testname, 'string'); + $htmlchecker->run_check(); + $report = $htmlchecker->get_test($check); + $processingtime += (time() - $stime); + + $record = []; + $record['count'] = 0; + $record['errors'] = []; + + foreach ($report as $a) { + $a->html = $a->get_html(); + $record['errors'][] = $a; + $record['count']++; + } + + // Build up record for inserting. + $recordres = new stdClass(); + // Handling if checkid is unknown. + $checkid = (isset($checkdata->id)) ? $checkdata->id : 0; + $recordres->contentid = $contentid; + $recordres->checkid = $checkid; + $recordres->errorcount = $record['count']; + if ($exists = $DB->get_record(manager::DB_RESULTS, ['contentid' => $contentid, 'checkid' => $checkid])) { + $resultid = $exists->id; + $DB->set_field(manager::DB_RESULTS, 'errorcount', $record['count'], ['id' => $resultid]); + // Remove old error records for specific resultid, if existing. + $DB->delete_records(manager::DB_ERRORS, ['id' => $errid]); + } else { + $resultid = $DB->insert_record(manager::DB_RESULTS, $recordres); + } + $errors = []; + + // Build error inserts if needed. + if ($record['count'] > 0) { + // Reporting all found errors for this check, so need to ignore existing other error records. + foreach ($record['errors'] as $tmp) { + // Confirm if error is reported separately. + if ($DB->record_exists_select(manager::DB_ERRORS, + 'resultid = ? AND ' . $DB->sql_compare_text('htmlcode', 255) . ' = ' . $DB->sql_compare_text('?', 255), + [$resultid, html_entity_decode($tmp->html)])) { + continue; + } + $error = new stdClass(); + $error->resultid = $resultid; + $error->linenumber = $tmp->line; + $error->htmlcode = html_entity_decode($tmp->html); + $errors[] = $error; + } + + $DB->insert_records(manager::DB_ERRORS, $errors); + } + + $resultstime += (time() - $stime); + } + + /** + * Returns all of the id's and shortnames of all of the checks. + * @param int $status + * @return array + * @throws \dml_exception + */ + public static function checkids(int $status = 1): array { + global $DB; + + $checks = $DB->get_records_menu(manager::DB_CHECKS, ['status' => $status], 'id ASC', 'id,shortname'); + return $checks; + } + + /** + * Returns an array of translations from htmlchecker of all of the checks, and their descriptions. + * @return array + * @throws \dml_exception + */ + public static function get_translations(): array { + global $DB; + + $htmlchecker = new local\htmlchecker\brickfield_accessibility('test', 'brickfield', 'string'); + $htmlchecker->run_check(); + ksort($htmlchecker->guideline->translations); + + // Need to limit to active checks. + $activechecks = $DB->get_fieldset_select(manager::DB_CHECKS, 'shortname', 'status = :status', ['status' => 1]); + + $translations = []; + foreach ($htmlchecker->guideline->translations as $key => $trans) { + if (in_array($key, $activechecks)) { + $translations[$key] = $trans; + } + } + + return $translations; + } + + /** + * Returns an array of all of the course id's for a given category. + * @param int $categoryid + * @return array|null + * @throws \dml_exception + */ + public static function get_category_courseids(int $categoryid): ?array { + global $DB; + + if (!$DB->record_exists('course_categories', ['id' => $categoryid])) { + return null; + } + + $sql = "SELECT {course}.id + FROM {course}, {course_categories} + WHERE {course}.category = {course_categories}.id + AND ( + " . $DB->sql_like('path', ':categoryid1') . " + OR " . $DB->sql_like('path', ':categoryid2') . " + )"; + $params = ['categoryid1' => "%/$categoryid/%", 'categoryid2' => "%/$categoryid"]; + $courseids = $DB->get_fieldset_sql($sql, $params); + + return $courseids; + } + + /** + * Plugin installed. + * @throws coding_exception + * @throws dml_exception + */ + public static function plugin_installed() { + global $USER; + + $readers = get_log_manager()->get_readers(sql_reader::class); + $reader = reset($readers); + $select = 'eventname = :eventname AND action = :action AND target = :target'; + $params = [ + 'eventname' => '\\' . manager::PLUGINNAME . '\event\plugin_installed', + 'action' => 'installed', + 'target' => 'plugin' + ]; + $logplugininstalled = $reader->get_events_select($select, $params, 'timecreated ASC', 0, 1); + if (empty($logplugininstalled)) { + $context = context_system::instance(); + $pi = new stdClass(); + $pi->userid = empty($USER->id) ? 0 : $USER->id; + $pi->contextid = $context->id; + $pi->component = manager::PLUGINNAME; + $pi->modifierid = $pi->userid; + $pi->sortorder = 0; + $event = plugin_installed::create([ + 'context' => $context, + 'relateduserid' => $pi->userid, + 'other' => [ + 'plugin' => $pi->component, + 'installed' => 1 + ] + ]); + $event->trigger(); + } + } + + /** + * Get summary data for this site. + * @param int $id + * @return \stdClass + * @throws \dml_exception + */ + public static function get_summary_data(int $id): \stdClass { + global $CFG, $DB; + + $components = $DB->get_records(manager::DB_AREAS); + + $summarydata = new \stdClass(); + $summarydata->siteurl = (substr($CFG->wwwroot, -1) !== '/') ? $CFG->wwwroot . '/' : $CFG->wwwroot; + $summarydata->moodlerelease = (preg_match('/^(\d+\.\d.*?)[. ]/', $CFG->release, $matches)) ? $matches[1] : $CFG->release; + $summarydata->numcourses = $DB->count_records('course') - 1; + $summarydata->numusers = $DB->count_records('user', array('deleted' => 0)); + $summarydata->numfiles = $DB->count_records('files'); + $summarydata->numfactivities = $DB->count_records('course_modules'); + $summarydata->mobileservice = (int)$CFG->enablemobilewebservice === 1 ? true : false; + $summarydata->usersmobileregistered = $DB->count_records('user_devices'); + $summarydata->contenttyperesults = static::get_contenttyperesults($id, $components); + $summarydata->contenttypeerrors = static::get_contenttypeerrors(); + $summarydata->percheckerrors = static::get_percheckerrors(); + return $summarydata; + } + + /** + * Get content type results. + * @param int $id + * @param array $components + * @return \stdClass + */ + private static function get_contenttyperesults(int $id, array $components): \stdClass { + $contenttyperesults = new \stdClass(); + $contenttyperesults->id = $id; + $datacomponents = array(); + foreach ($components as $component) { + $datacomponents[$component->component][] = $component; + } + $contenttyperesults->contenttype = new \stdClass(); + foreach ($datacomponents as $key => $component) { + $contenttyperesults->contenttype->$key = count($component); + } + $contenttyperesults->summarydatastorage = static::get_summary_data_storage(); + $contenttyperesults->datachecked = time(); // Correct?? + return $contenttyperesults; + } + + + /** + * Get per check errors. + * @return stdClass + * @throws dml_exception + */ + private static function get_percheckerrors(): stdClass { + global $DB; + + $sql = 'SELECT ' . $DB->sql_concat_join("'_'", ['courseid', 'checkid']) . ' as tmpid, + ca.courseid, ca.status, ca.checkid, ch.shortname, ca.checkcount, ca.errorcount + FROM {' . manager::DB_CACHECHECK . '} ca + INNER JOIN {' . manager::DB_CHECKS . '} ch on ch.id = ca.checkid + ORDER BY courseid, checkid ASC'; + + $combo = $DB->get_records_sql($sql); + + return (object) [ + 'percheckerrors' => $combo, + ]; + } + + /** + * Get content type errors. + * @return stdClass + * @throws dml_exception + */ + private static function get_contenttypeerrors(): stdClass { + global $DB; + + $fields = 'courseid, status, activities, activitiespassed, activitiesfailed, + errorschecktype1, errorschecktype2, errorschecktype3, errorschecktype4, + errorschecktype5, errorschecktype6, errorschecktype7, + failedchecktype1, failedchecktype2, failedchecktype3, failedchecktype4, + failedchecktype5, failedchecktype6, failedchecktype7, + percentchecktype1, percentchecktype2, percentchecktype3, percentchecktype4, + percentchecktype5, percentchecktype6, percentchecktype7'; + $combo = $DB->get_records(manager::DB_SUMMARY, null, 'courseid ASC', $fields); + + return (object) [ + 'typeerrors' => $combo, + ]; + } + + /** + * Get summary data storage. + * @return array + * @throws dml_exception + */ + private static function get_summary_data_storage(): array { + global $DB; + + $fields = $DB->sql_concat_join("''", ['component', 'courseid']) . ' as tmpid, + courseid, component, errorcount, totalactivities, failedactivities, passedactivities'; + $combo = $DB->get_records(manager::DB_CACHEACTS, null, 'courseid, component ASC', $fields); + return $combo; + } +} diff --git a/admin/tool/brickfield/classes/analysis.php b/admin/tool/brickfield/classes/analysis.php new file mode 100644 index 0000000000000..67cb7139ddf38 --- /dev/null +++ b/admin/tool/brickfield/classes/analysis.php @@ -0,0 +1,95 @@ +. + +namespace tool_brickfield; + +use tool_brickfield\task\process_analysis_requests; + +/** + * Analysis and deployment class. + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class analysis { + + /** + * Indicates that analysis of content has been enabled. + */ + const ANALYSISDISABLED = '0'; + + /** + * Indicates that analysis is enabled and using request method. + */ + const ANALYSISBYREQUEST = '1'; + + /** + * Return the type of analysis being used (currently only request). + * + * @return false|mixed|object|string|null + * @throws \dml_exception + */ + public static function get_type() { + // Moodle caches these calls, so it's not expensive. + return get_config(manager::PLUGINNAME, 'analysistype'); + } + + /** + * Return true is analysis has been enabled. + * + * @return bool + * @throws \dml_exception + */ + public static function is_enabled(): bool { + $analysistype = static::get_type(); + return ($analysistype !== false) && ($analysistype !== self::ANALYSISDISABLED); + } + + /** + * Return true if analysis is by request method. + * + * @return bool + * @throws \dml_exception + */ + public static function type_is_byrequest(): bool { + return static::get_type() === self::ANALYSISBYREQUEST; + } + + /** + * Return true if the course has been analyzed. + * + * @param int $courseid + * @return bool + * @throws \dml_exception + */ + public static function is_course_analyzed(int $courseid): bool { + return scheduler::is_course_analyzed($courseid); + } + + /** + * Return a redirect message with the earliest time expected for analysis to complete. + * @return \lang_string|string + * @throws \coding_exception + */ + public static function redirect_message() { + $epoch = new process_analysis_requests; + $time = userdate($epoch->get_next_scheduled_time(), get_string('strftimetime', 'core_langconfig')); + $message = get_string('confirmationmessage', manager::PLUGINNAME, $time); + + return $message; + } +} diff --git a/admin/tool/brickfield/classes/area_base.php b/admin/tool/brickfield/classes/area_base.php new file mode 100644 index 0000000000000..75a8f5cf1f85f --- /dev/null +++ b/admin/tool/brickfield/classes/area_base.php @@ -0,0 +1,219 @@ +. + +namespace tool_brickfield; + +/** + * Area base class. + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + */ +abstract class area_base { + + /** + * Defines the unknown for the 'checkgroup' field in the tool_brickfield_checks table. + */ + const CHECKGROUP_UNKNOWN = 0; + + /** + * Defines the form for the 'checkgroup' field in the tool_brickfield_checks table. + */ + const CHECKGROUP_FORM = 1; + + /** + * Defines the image for the 'checkgroup' field in the tool_brickfield_checks table. + */ + const CHECKGROUP_IMAGE = 2; + + /** + * Defines the layout for the 'checkgroup' field in the tool_brickfield_checks table. + */ + const CHECKGROUP_LAYOUT = 3; + + /** + * Defines the link for the 'checkgroup' field in the tool_brickfield_checks table. + */ + const CHECKGROUP_LINK = 4; + + /** + * Defines the media for the 'checkgroup' field in the tool_brickfield_checks table. + */ + const CHECKGROUP_MEDIA = 5; + + /** + * Defines the table for the 'checkgroup' field in the tool_brickfield_checks table. + */ + const CHECKGROUP_TABLE = 6; + + /** + * Defines the text for the 'checkgroup' field in the tool_brickfield_checks table. + */ + const CHECKGROUP_TEXT = 7; + + /** @var string[] Array for quick access of string names for 'checkgroups'. */ + const CHECKGROUP_NAMES = [ + self::CHECKGROUP_UNKNOWN => 'unknown', + self::CHECKGROUP_FORM => 'form', + self::CHECKGROUP_IMAGE => 'image', + self::CHECKGROUP_LAYOUT => 'layout', + self::CHECKGROUP_LINK => 'link', + self::CHECKGROUP_MEDIA => 'media', + self::CHECKGROUP_TABLE => 'table', + self::CHECKGROUP_TEXT => 'text' + ]; + + /** + * Defines field value. + */ + const TYPE_FIELD = 0; + + /** + * Defines file value. + */ + const TYPE_FILE = 1; + + /** + * Return the name for the specified checkgroup value, or 'unknown' if no valid name for the value. Preferably, use this rather + * than direct access to CHECKGROUP_NAMES, since it checks value boundaries. + * @param int $checkgroupvalue + * @return string + */ + final public static function checkgroup_name(int $checkgroupvalue): string { + if (($checkgroupvalue < 0) || ($checkgroupvalue >= count(self::CHECKGROUP_NAMES))) { + return self::CHECKGROUP_NAMES[self::CHECKGROUP_UNKNOWN]; + } else { + return self::CHECKGROUP_NAMES[$checkgroupvalue]; + } + } + + /** + * Return the value for the specified checkgroup name, or the unknown value if no valid value for the name. + * @param string $checkgroupname + * @return int + */ + final public static function checkgroup_value(string $checkgroupname): int { + $value = array_search($checkgroupname, self::CHECKGROUP_NAMES); + return ($value !== false) ? $value : self::CHECKGROUP_UNKNOWN; + } + + /** + * Return the defined content type. + * @return int + */ + protected function get_type(): int { + return self::TYPE_FIELD; + } + + /** + * Return the component from the full class name. + * @return mixed|string + */ + public function get_component(): string { + $parts = preg_split('|\\\\|', get_class($this)); + return $parts[3]; + } + + /** + * Check if the system plugin is avaliable. + * @return bool + */ + public function is_available(): bool { + list($type, $plugin) = \core_component::normalize_component($this->get_component()); + if ($type === 'core') { + // We assume that all core components are defined corretly. + return true; + } + // Some contrib plugins may not be installed. + return ($dir = \core_component::get_component_directory($this->get_component())) + && file_exists($dir . '/version.php'); + } + + /** + * Return the name of the database table where information is stored + * @return string + */ + abstract public function get_tablename(): string; + + /** + * Return the name of the reference data table name. + * @return string + */ + public function get_ref_tablename(): string { + return ''; + } + + /** + * Return the name of the field in the table that has the content + * @return string + */ + abstract public function get_fieldname(): string; + + /** + * Return a recordset of the relevant areas for the component/module. + * @param \core\event\base $event + * @return \moodle_recordset|null + */ + abstract public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset; + + /** + * Return a recordset of the course areas for the course id. + * @param int $courseid + * @return \moodle_recordset|null + */ + abstract public function find_course_areas(int $courseid): ?\moodle_recordset; + + /** + * Return an array of area objects that contain content at the site and system levels only. Override this where necessary. + * @return \moodle_recordset|null + */ + public function find_system_areas(): ?\moodle_recordset { + return null; + } + + /** + * The standard Moodle parameter DML parameter substitution doesn't work on all versions of MySQL or Postgres, so we need to use + * inline function substitution to ensure that the left side is a string. + * @return string + */ + public function get_standard_area_fields_sql(): string { + return '\'' . $this->get_component() . '\' AS component, + \'' . $this->get_tablename() . '\' AS tablename, + \'' . $this->get_fieldname() . '\' AS fieldorarea, '; + } + + /** + * The standard Moodle parameter DML parameter substitution doesn't work on all versions of MySQL or Postgres, so we need to use + * inline function substitution to ensure that the left side is a string. + * @return string + */ + public function get_reftable_field_sql(): string { + return '\'' . $this->get_ref_tablename() . '\' AS reftable, '; + } + + /** + * Processes any sql filtering data. Implement in extensions. + * + * @return null + * @throws \coding_exception + * @throws \dml_exception + */ + public function get_courseid_filtering() { + $this->filter = ''; + $this->filterparams = []; + return null; + } +} diff --git a/admin/tool/brickfield/classes/brickfieldconnect.php b/admin/tool/brickfield/classes/brickfieldconnect.php new file mode 100644 index 0000000000000..4587dfe95cd9e --- /dev/null +++ b/admin/tool/brickfield/classes/brickfieldconnect.php @@ -0,0 +1,252 @@ +. + +namespace tool_brickfield; + +defined('MOODLE_INTERNAL') || die; + +// The curl class is in filelib. +global $CFG; +require_once("{$CFG->libdir}/filelib.php"); + +use curl; +use moodle_url; + +/** + * Class brickfieldconnect. Contains all function to connect to Brickfield external services. + * + * @package tool_brickfield + * @author 2020 Onwards Mike Churchward + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL + */ +class brickfieldconnect extends curl { + + /** @var string The base api uri. */ + private static $baseapiuri = 'https://api.mybrickfield.ie/moodle/'; + + /** @var array Endpoint details for setting and checking a site registration */ + const ACTION_CHECK_REGISTRATION = [ + 'endpoint' => 'checkRegister', + 'method' => 'get', + ]; + + /** @var array Endpoint details for sending site summary data */ + const ACTION_SEND_SUMMARY = [ + 'endpoint' => 'summary', + 'method' => 'post', + ]; + + /** + * Object method to test whether site is already registered. + * @return bool + */ + public function is_registered(): bool { + return !empty($this->get_registration_id_for_credentials()); + } + + /** + * Update registration of this site. + * @param string $apikey The API key to use for the registration attempt + * @param string $secretkey The secret key to use + * @return bool + */ + public function update_registration(string $apikey, string $secretkey): bool { + $registrationid = $this->get_registration_id_for_credentials($apikey, $secretkey); + if (empty($registrationid)) { + return false; + } + + (new registration())->set_siteid($registrationid); + return true; + } + + /** + * Send the summary data to Brickfield. + * @return bool + * @throws \dml_exception + */ + public function send_summary(): bool { + // Run a registration check. + if (!(new registration())->validate()) { + return false; + } + + $headers = $this->get_common_headers(); + $this->set_headers($headers); + $summary = accessibility::get_summary_data($headers['id']); + $body = json_encode($summary, JSON_UNESCAPED_SLASHES); + $result = json_decode($this->call(self::ACTION_SEND_SUMMARY, $body)); + if (is_object($result) && ((int)$result->statusCode === 200)) { + return true; + } else { + return false; + } + } + + /** + * Get the URL required for the command. + * + * @param array $command The command to call, for example see self::ACTION_REGISTER + * @return string The complete URL + */ + protected function get_url_for_command(array $command): string { + return $this->get_baseapiuri() . $command['endpoint']; + } + + /** + * Call the specified command. + * + * @param array $command The command to call, for example see self::ACTION_REGISTER + * @param array|string $params The params provided to the call + * @return string The response body + */ + protected function call(array $command, $params = ''): string { + $url = $this->get_url_for_command($command); + if ($command['method'] === 'get') { + return $this->get($url, $params); + } + + if ($command['method'] === 'post') { + return $this->post($url, $params); + } + + return ''; + } + + /** + * Get the common headers used for all calls to the Brickfields endpoints. + * + * @return array + */ + protected function get_common_headers(): array { + $headers = [ + 'Cache-Control' => 'no-cache', + 'Content-Type' => 'application/json', + 'siteurl' => static::get_siteurl(), + ]; + + if (static::has_registration_key()) { + $registration = new registration(); + $headers['secret'] = $registration->get_api_key(); + $headers['userhash'] = $registration->get_secret_key(); + $headers['id'] = $registration->get_siteid(); + } + + return $headers; + } + + /** + * Set headers on the request from the specified list of headers. + * + * @param array $headers An array of header name => value + */ + protected function set_headers(array $headers) { + foreach ($headers as $key => $value) { + $this->setHeader("{$key}: {$value}"); + } + } + + /** + * Whether the site currently has a registration key stored. + * + * @return bool + */ + protected function has_registration_key(): bool { + $registration = new registration(); + $localkey = $registration->get_api_key(); + $localhash = $registration->get_secret_key(); + $localid = $registration->get_siteid(); + + if (!$localhash || !$localkey || !$localid) { + return false; + } + + return true; + } + + /** + * Get a normalised URL for the site. + * + * @return string + */ + protected function get_siteurl(): string { + return (new moodle_url('/'))->out(false); + } + + /** + * Get the registration ID for the given set of credentials. + * @param null|string $apikey The API key to use for the registration attempt + * @param null|string $secretkey The secret key to use + * @return null|string The registration ID if registration was successful, or null if not + */ + protected function get_registration_id_for_credentials(string $apikey = null, string $secretkey = null): string { + $headers = $this->get_common_headers(); + if ($apikey || $secretkey) { + $headers['secret'] = $apikey; + $headers['userhash'] = $secretkey; + } else if (!$this->has_registration_key()) { + return ''; + } + + $this->set_headers($headers); + $response = $this->call(self::ACTION_CHECK_REGISTRATION); + + if ((int)$this->info['http_code'] !== 200) { + // The response was unsuccessful. + return ''; + } + + $result = json_decode($response); + if (!$result) { + // The response could not be decoded. + return ''; + } + + if ((int)$result->statusCode !== 200) { + // The data from the response suggests a failure. + return ''; + } + + // Decode the actual result. + $registrationdata = json_decode($result->body); + if (empty($registrationdata) || !is_array($registrationdata)) { + // Unable to decode the body of the response. + return ''; + } + + if (!property_exists($registrationdata[0], 'id') || !property_exists($registrationdata[0]->id, 'N')) { + // Unable to find a valid id in the response. + return ''; + } + + return $registrationdata[0]->id->N; + } + + /** + * Get the check registration API URI. + * @return string + * @throws dml_exception + */ + protected function get_baseapiuri(): string { + $baseapiuri = get_config(manager::PLUGINNAME, 'baseapiuri'); + if (!empty($baseapiuri)) { + return $baseapiuri; + } else { + set_config('baseapiuri', self::$baseapiuri, manager::PLUGINNAME); + return self::$baseapiuri; + } + } +} \ No newline at end of file diff --git a/admin/tool/brickfield/classes/event/analysis_requested.php b/admin/tool/brickfield/classes/event/analysis_requested.php new file mode 100644 index 0000000000000..4bf7f34963f4d --- /dev/null +++ b/admin/tool/brickfield/classes/event/analysis_requested.php @@ -0,0 +1,54 @@ +. + +namespace tool_brickfield\event; + +use tool_brickfield\manager; + +/** + * Class analysis_requested + * + * @package tool_brickfield + * @copyright 2020 onward Brickfield Education Labs, https://www.brickfield.ie + * @author Mike Churchward + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL + */ +class analysis_requested extends \core\event\base { + + /** + * Init function. + */ + protected function init() { + $this->data['crud'] = 'c'; + $this->data['edulevel'] = self::LEVEL_OTHER; + } + + /** + * Get name. + * @return \lang_string|string + */ + public static function get_name() { + return get_string('eventanalysis_requested', manager::PLUGINNAME); + } + + /** + * Get description. + * @return \lang_string|string|null + */ + public function get_description() { + return get_string('eventanalysis_requesteddesc', manager::PLUGINNAME, $this->other['course']); + } +} diff --git a/admin/tool/brickfield/classes/event/plugin_installed.php b/admin/tool/brickfield/classes/event/plugin_installed.php new file mode 100644 index 0000000000000..8ba590594e297 --- /dev/null +++ b/admin/tool/brickfield/classes/event/plugin_installed.php @@ -0,0 +1,54 @@ +. + +namespace tool_brickfield\event; +use coding_exception; +use core\event\base; +use tool_brickfield\manager; + +/** + * Class plugin_installed. + * + * @package tool_brickfield + * @author 2020 JM Tomas + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL + */ +class plugin_installed extends base { + + /** + * Init function. + */ + protected function init() { + $this->data['crud'] = 'u'; + $this->data['edulevel'] = self::LEVEL_OTHER; + } + + /** + * Get name. + * @return string + */ + public static function get_name(): string { + return get_string('installed', manager::PLUGINNAME); + } + + /** + * Get description. + * @return string + */ + public function get_description(): string { + return get_string('installeddescription', manager::PLUGINNAME); + } +} diff --git a/admin/tool/brickfield/classes/event/report_downloaded.php b/admin/tool/brickfield/classes/event/report_downloaded.php new file mode 100755 index 0000000000000..1067a9f4c2a6f --- /dev/null +++ b/admin/tool/brickfield/classes/event/report_downloaded.php @@ -0,0 +1,54 @@ +. + +namespace tool_brickfield\event; + +use tool_brickfield\manager; + +/** + * Class report_downloaded + * + * @package tool_brickfield + * @copyright 2020 onward Brickfield Education Labs, https://www.brickfield.ie + * @author Mike Churchward + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL + */ +class report_downloaded extends \core\event\base { + + /** + * Init function. + */ + protected function init() { + $this->data['crud'] = 'r'; + $this->data['edulevel'] = self::LEVEL_OTHER; + } + + /** + * Get name. + * @return \lang_string|string + */ + public static function get_name() { + return get_string('eventreport_downloaded', manager::PLUGINNAME); + } + + /** + * Get description. + * @return \lang_string|string|null + */ + public function get_description() { + return get_string('eventreport_downloadeddesc', manager::PLUGINNAME, $this->courseid); + } +} diff --git a/admin/tool/brickfield/classes/event/report_viewed.php b/admin/tool/brickfield/classes/event/report_viewed.php new file mode 100755 index 0000000000000..05b7acb665043 --- /dev/null +++ b/admin/tool/brickfield/classes/event/report_viewed.php @@ -0,0 +1,54 @@ +. + +namespace tool_brickfield\event; + +use tool_brickfield\manager; + +/** + * Class report_viewed + * + * @package tool_brickfield + * @copyright 2020 onward Brickfield Education Labs, https://www.brickfield.ie + * @author Mike Churchward + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL + */ +class report_viewed extends \core\event\base { + + /** + * Init function. + */ + protected function init() { + $this->data['crud'] = 'r'; + $this->data['edulevel'] = self::LEVEL_OTHER; + } + + /** + * Get name. + * @return \lang_string|string + */ + public static function get_name() { + return get_string('eventreport_viewed', manager::PLUGINNAME); + } + + /** + * Get description. + * @return \lang_string|string|null + */ + public function get_description() { + return get_string('eventreport_vieweddesc', manager::PLUGINNAME, (object)$this->other); + } +} diff --git a/admin/tool/brickfield/classes/eventobservers.php b/admin/tool/brickfield/classes/eventobservers.php new file mode 100644 index 0000000000000..0fcab252208b6 --- /dev/null +++ b/admin/tool/brickfield/classes/eventobservers.php @@ -0,0 +1,452 @@ +. + +namespace tool_brickfield; + +use core\event\base; +use tool_brickfield\event\plugin_installed; +use stdClass; + +/** + * Observer class containing methods monitoring various events. + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * + */ +class eventobservers { + + /** + * For course events to be handled, the accessibility tool needs to be enabled, and if a courseid is specified, the course + * has to have been added to the scheduler. + * @param int $courseid + * @return bool + * @throws \dml_exception + */ + protected static function course_event_should_be_handled(int $courseid): bool { + return accessibility::is_accessibility_enabled() && analysis::is_enabled() && + (empty($courseid) || (isset($courseid) && scheduler::is_course_in_schedule($courseid))); + } + + /** + * Content area altered event observer. + * @param base $event The area altered event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function area_altered(base $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + manager::find_new_or_updated_areas($event); + } + } + + /** + * Course event observers. + * These observer monitors course created / restored / updated events, + * then its HTML content is processed with accessibility checking. + */ + + /** + * Course created event observer. + * @param \core\event\course_created $event The course created event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function course_created(\core\event\course_created $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + // Need to trigger rerun check for automatically created forum... + $data = new stdClass(); + $data->courseid = $event->courseid; + $data->item = 'coursererun'; + static::observer_insert($data); + static::course_altered($event); + } + } + + /** + * Course deleted event observer. + * @param \core\event\course_deleted $event The course deleted event. + * @throws \dml_exception + */ + public static function course_deleted(\core\event\course_deleted $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + $data = new stdClass(); + $data->courseid = $event->courseid; + $data->contextid = -1; + $data->item = 'core_course'; + static::observer_insert($data); + } + } + + /** + * Course restored event observer. + * @param \core\event\course_restored $event The course restored event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function course_restored(\core\event\course_restored $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + $data = new stdClass(); + $data->courseid = $event->courseid; + $data->item = 'coursererun'; + static::observer_insert($data); + static::course_altered($event); + } + } + + /** + * Course update event observer. + * @param \core\event\course_updated $event The course updated event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function course_updated(\core\event\course_updated $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + static::course_altered($event); + } + } + + /** + * Course update event observer. This is called on both course_created and course_updated, so use the base class as a type hint. + * @param base $event The course updated event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function course_altered(base $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + // Need to rerun caching of allowed courseid, from category white/blacklist. + $data = new stdClass(); + $data->courseid = $data->contextid = $event->courseid; + $data->contextid = -1; + $data->item = 'category'; + static::observer_insert($data); + static::area_altered($event); + } + } + + /** + * Course section created event observer. + * @param \core\event\course_section_created $event The course section created event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function course_section_created(\core\event\course_section_created $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + static::area_altered($event); + } + } + + /** + * Course section deleted event observer. + * @param \core\event\course_section_deleted $event The course section deleted event. + * @throws \dml_exception + */ + public static function course_section_deleted(\core\event\course_section_deleted $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + $data = new stdClass(); + $data->courseid = $event->courseid; + $data->contextid = -1; + $data->innercontextid = $event->objectid; + $data->item = 'course_sections'; + static::observer_insert($data); + } + } + + /** + * Course section update event observer. + * @param \core\event\course_section_updated $event The course section updated event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function course_section_updated(\core\event\course_section_updated $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + static::area_altered($event); + } + } + + /** + * Course module event observers. + * These observer monitors course module created / restored / updated events, + * then its HTML content is processed with accessibility checking. + */ + + /** + * Course module created event observer. + * @param \core\event\course_module_created $event The course module created event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function course_module_created(\core\event\course_module_created $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + static::area_altered($event); + } + } + + /** + * Course module deleted event observer. + * @param \core\event\course_module_deleted $event The course module deleted event. + * @throws \dml_exception + */ + public static function course_module_deleted(\core\event\course_module_deleted $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + $data = new stdClass(); + $data->courseid = $event->courseid; + $data->contextid = -1; + $data->innercontextid = $event->other['instanceid']; + $data->item = 'mod_' . $event->other['modulename']; + static::observer_insert($data); + } + } + + /** + * Course module restored event observer. + * @param \core\event\course_module_restored $event The course module restored event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function course_module_restored(\core\event\course_module_restored $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + static::area_altered($event); + } + } + + /** + * Course module updated event observer. + * @param \core\event\course_module_updated $event The course module updated event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function course_module_updated(\core\event\course_module_updated $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + static::area_altered($event); + } + } + + /** + * course_category created event observer. + * @param \core\event\course_category_created $event The course_category created event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function course_category_created(\core\event\course_category_created $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + static::area_altered($event); + } + } + + /** + * course_category deleted event observer. + * @param \core\event\course_category_deleted $event The course_category deleted event. + * @throws \dml_exception + */ + public static function course_category_deleted(\core\event\course_category_deleted $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + $data = new stdClass(); + $data->contextid = $data->courseid = -1; + $data->innercontextid = $event->objectid; + $data->item = 'course_categories'; + static::observer_insert($data); + } + } + + /** + * course_category update event observer. + * @param \core\event\course_category_updated $event The course_category updated event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function course_category_updated(\core\event\course_category_updated $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + static::area_altered($event); + } + } + + /** + * mod_lesson_page created event observer. + * @param \mod_lesson\event\page_created $event The mod_lesson page created event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function mod_lesson_page_created(\mod_lesson\event\page_created $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + static::area_altered($event); + } + } + + /** + * mod_lesson_page deleted event observer. + * @param \mod_lesson\event\page_deleted $event The mod_lesson page deleted event. + * @throws \dml_exception + */ + public static function mod_lesson_page_deleted(\mod_lesson\event\page_deleted $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + $data = new stdClass(); + $data->courseid = $event->courseid; + $data->contextid = -1; + $data->innercontextid = $event->objectid; + $data->item = 'lesson_pages'; + static::observer_insert($data); + } + } + + /** + * mod_lesson_page updated event observer. + * @param \mod_lesson\event\page_updated $event The mod_lesson page updated event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function mod_lesson_page_updated(\mod_lesson\event\page_updated $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + static::area_altered($event); + } + } + + /** + * core_question created observer + * @param \core\event\question_created $event The core_question created event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function core_question_created(\core\event\question_created $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + manager::find_new_or_updated_areas($event); + } + } + + /** + * core_question updated observer + * @param \core\event\question_updated $event The core_question created event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function core_question_updated(\core\event\question_updated $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + manager::find_new_or_updated_areas($event); + } + } + + /** + * core_question deleted observer + * @param \core\event\question_deleted $event The core_question deleted event. + * @throws \dml_exception + */ + public static function core_question_deleted(\core\event\question_deleted $event) { + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($event->courseid)) { + $data = new stdClass(); + $data->courseid = $event->courseid; + $data->contextid = -1; + $data->innercontextid = $event->objectid; + $data->item = $event->objecttable; + static::observer_insert($data); + } + } + + /** + * Book chapter created event observer. + * @param \mod_book\event\chapter_created $event The book chapter created event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function book_chapter_created(\mod_book\event\chapter_created $event) { + // If this feature has been disabled, do nothing. + if (accessibility::is_accessibility_enabled()) { + static::area_altered($event); + } + } + + /** + * Book chapter deleted event observer. + * @param \mod_book\event\chapter_deleted $event The book chapter deleted event. + * @throws \dml_exception + */ + public static function book_chapter_deleted(\mod_book\event\chapter_deleted $event) { + // If this feature has been disabled, do nothing. + if (accessibility::is_accessibility_enabled()) { + $data = new stdClass(); + $data->courseid = $event->courseid; + $data->contextid = -1; + $data->innercontextid = $event->objectid; + $data->item = 'book_chapters'; + static::observer_insert($data); + } + } + + /** + * Book chapter update event observer. + * @param \mod_book\event\chapter_updated $event The book chapter updated event. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function book_chapter_updated(\mod_book\event\chapter_updated $event) { + // If this feature has been disabled, do nothing. + if (accessibility::is_accessibility_enabled()) { + static::area_altered($event); + } + } + + /** + * Look for a plugin installed event. + * @param plugin_installed $event + * @throws \moodle_exception + */ + public static function plugin_installed(plugin_installed $event) { + // If this feature has been disabled, do nothing. + if (accessibility::is_accessibility_enabled()) { + $urlregistration = manager::registration_url(); + redirect($urlregistration->out()); + } + } + + /** + * Add an observer record if appropriate. + * @param stdClass $data + * @throws \dml_exception + */ + public static function observer_insert(stdClass $data) { + global $DB; + + // Handle if this feature is enabled and this course is in the schedule. + if (static::course_event_should_be_handled($data->courseid)) { + $data->timecreated = time(); + $data->timecompleted = 0; + + $DB->insert_record(manager::DB_PROCESS, $data); + } + } +} diff --git a/admin/tool/brickfield/classes/form/registration_form.php b/admin/tool/brickfield/classes/form/registration_form.php new file mode 100644 index 0000000000000..8025374794729 --- /dev/null +++ b/admin/tool/brickfield/classes/form/registration_form.php @@ -0,0 +1,146 @@ +. + +/** + * Class registration_form + * + * @package tool_brickfield + * @copyright 2021 Brickfield Education Labs https://www.brickfield.ie + * @author 2020 JM Tomas + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL + */ + +namespace tool_brickfield\form; +defined('MOODLE_INTERNAL') || die(); + +use coding_exception; +use dml_exception; +use html_writer; +use moodle_exception; +use moodleform; +use stdClass; +use tool_brickfield\manager; +use tool_brickfield\registration; + +global $CFG; +require_once($CFG->libdir . '/formslib.php'); + +/** + * Class registration_form + * + * @package tool_brickfield + * @author 2020 JM Tomas + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL + */ +class registration_form extends moodleform { + + /** + * Form definition. + * @throws moodle_exception + */ + public function definition() { + $mform = & $this->_form; + $required = get_string('required'); + $info = $this->get_defaultinfo(); + $registration = new registration(); + $key = $registration->get_api_key(); + $hash = $registration->get_secret_key(); + + $mform->addElement('header', 'activationheader', get_string('activationheader', manager::PLUGINNAME)); + $mform->addElement('static', 'siteinfosummary', '', get_string('activationinfo', manager::PLUGINNAME, + '')); + + $mform->addElement('text', 'key', get_string('secretkey', manager::PLUGINNAME)); + $mform->setType('key', PARAM_TEXT); + $mform->setDefault('key', !empty($key) ? $key : ''); + $mform->addHelpButton('key', 'secretkey', manager::PLUGINNAME); + + $mform->addElement('text', 'hash', get_string('sitehash', manager::PLUGINNAME)); + $mform->setType('hash', PARAM_TEXT); + $mform->setDefault('hash', !empty($hash) ? $hash : ''); + $mform->addHelpButton('hash', 'sitehash', manager::PLUGINNAME); + + $mform->addElement('header', 'moreinfo', get_string('moreinfo', manager::PLUGINNAME)); + $mform->addElement('static', 'siteinfosummary', '', + get_string('sendfollowinginfo', manager::PLUGINNAME, $info->moreinfostring)); + + $mform->addElement('hidden', 'lang', $info->language); + $mform->setType('lang', PARAM_TEXT); + $mform->addElement('hidden', 'countrycode', $info->country); + $mform->setType('countrycode', PARAM_TEXT); + + $this->add_action_buttons(false, get_string('activate', manager::PLUGINNAME, '#')); + } + + /** + * Get default data for registration form + * + * @throws moodle_exception + * @return stdClass + */ + protected function get_defaultinfo(): stdClass { + global $CFG; + $admin = get_admin(); + $site = get_site(); + $data = new stdClass(); + $data->name = $site->fullname; + $data->url = $CFG->wwwroot; + $data->language = get_string('thislanguage', 'langconfig'); + $data->country = $admin->country ?: $CFG->country; + $data->email = $admin->email; + $data->moreinfo = self::get_moreinfo(); + $data->moreinfostring = self::get_moreinfostring($data->moreinfo); + return $data; + } + + /** + * Get more information. + * @return array + * @throws dml_exception + */ + private static function get_moreinfo(): array { + global $CFG, $DB; + $moreinfo = array(); + $moodlerelease = $CFG->release; + if (preg_match('/^(\d+\.\d.*?)[. ]/', $moodlerelease, $matches)) { + $moodlerelease = $matches[1]; + } + $moreinfo['release'] = $moodlerelease; + $moreinfo['numcourses'] = $DB->count_records('course') - 1; + $moreinfo['numusers'] = $DB->count_records('user', array('deleted' => 0)); + $moreinfo['numfiles'] = $DB->count_records('files'); + $moreinfo['numfactivities'] = $DB->count_records('course_modules'); + $moreinfo['mobileservice'] = empty($CFG->enablemobilewebservice) ? 0 : $CFG->enablemobilewebservice; + $moreinfo['usersmobileregistered'] = $DB->count_records('user_devices'); + return $moreinfo; + } + + /** + * Get HTML list for more information. + * + * @param array $moreinfo + * @return string + * @throws coding_exception + */ + private static function get_moreinfostring(array $moreinfo): string { + $html = html_writer::start_tag('ul'); + foreach ($moreinfo as $key => $value) { + $html .= html_writer::tag('li', get_string($key, manager::PLUGINNAME, $value)); + } + $html .= html_writer::end_tag('ul'); + return $html; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_course/base.php b/admin/tool/brickfield/classes/local/areas/core_course/base.php new file mode 100644 index 0000000000000..8367df6c369ca --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_course/base.php @@ -0,0 +1,118 @@ +. + +namespace tool_brickfield\local\areas\core_course; + +use core\event\course_created; +use core\event\course_updated; +use core\event\course_restored; +use tool_brickfield\area_base; + +/** + * Base class for various course-related areas + * + * This is an abstract class so it will be skipped by manager when it finds all areas + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class base extends area_base { + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + if ($event instanceof course_created) { + return $this->find_fields_in_course_table(['courseid' => $event->courseid]); + } else if ($event instanceof course_restored) { + return $this->find_fields_in_course_table(['courseid' => $event->courseid]); + } else if ($event instanceof course_updated) { + return $this->find_fields_in_course_table(['courseid' => $event->courseid]); + } + return null; + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + return $this->find_fields_in_course_table(['courseid' => $courseid]); + } + + /** + * Return an array of area objects that contain content at the site and system levels only. + * @return mixed + */ + public function find_system_areas(): ?\moodle_recordset { + return null; + } + + /** + * Helper method that can be used by the classes that define a field in the 'course' table + * + * @param array $params + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + protected function find_fields_in_course_table(array $params = []): \moodle_recordset { + global $DB; + $where = []; + + if (!empty($params['courseid'])) { + $where[] = 't.id = :courseid'; + } + + $rs = $DB->get_recordset_sql('SELECT + ' . $this->get_type() . ' AS type, + ctx.id AS contextid, + ' . $this->get_standard_area_fields_sql() . ' + t.id AS itemid, + t.id AS courseid, + t.'.$this->get_fieldname().' AS content + FROM {'.$this->get_tablename().'} t + JOIN {context} ctx ON ctx.instanceid = t.id AND ctx.contextlevel = :pctxlevelcourse '. + ($where ? 'WHERE ' . join(' AND ', $where) : '') . ' + ORDER BY t.id', + ['pctxlevelcourse' => CONTEXT_COURSE] + $params); + + return $rs; + } + + /** + * Returns the moodle_url of the page to edit the error. + * @param \stdClass $componentinfo + * @return \moodle_url + */ + public static function get_edit_url(\stdClass $componentinfo): \moodle_url { + if ($componentinfo->tablename == 'course_sections') { + return new \moodle_url('/course/editsection.php', ['id' => $componentinfo->itemid, 'sr' => '']); + } else if ($componentinfo->tablename == 'course_categories') { + return new \moodle_url('/course/editcategory.php', ['id' => $componentinfo->itemid]); + } else { + return new \moodle_url('/course/edit.php', ['id' => $componentinfo->courseid]); + } + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_course/category_base.php b/admin/tool/brickfield/classes/local/areas/core_course/category_base.php new file mode 100644 index 0000000000000..33741fea2e18b --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_course/category_base.php @@ -0,0 +1,92 @@ +. + +namespace tool_brickfield\local\areas\core_course; + +use core\event\course_category_created; +use core\event\course_category_updated; +use tool_brickfield\area_base; + +/** + * Base class for all areas that represent a field from the course_categories table (such as 'intro' or 'name') + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class category_base extends area_base { + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + if ($event instanceof course_category_updated || $event instanceof course_category_created) { + return $this->find_fields_in_course_categories_table(['itemid' => $event->objectid]); + } + return null; + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset|null + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + return null; + } + + /** + * Return an array of area objects that contain content at the site and system levels only. All category content is considered + * system level. + * @return mixed + */ + public function find_system_areas(): ?\moodle_recordset { + return $this->find_fields_in_course_categories_table(); + } + + /** + * Helper method that can be used by the classes that define a field in the respective module table + * + * @param array $params + * @return \moodle_recordset + * @throws \dml_exception + */ + protected function find_fields_in_course_categories_table(array $params = []): \moodle_recordset { + global $DB; + $where = []; + if (!empty($params['itemid'])) { + $where[] = 't.id = :itemid'; + } + + $rs = $DB->get_recordset_sql('SELECT + ' . $this->get_type() . ' AS type, + ctx.id AS contextid, + ' . $this->get_standard_area_fields_sql() . ' + t.id AS itemid, + t.id AS categoryid, + t.'.$this->get_fieldname().' AS content + FROM {'.$this->get_tablename().'} t + JOIN {context} ctx ON ctx.instanceid = t.id AND ctx.contextlevel = :pctxlevelcategory '. + ($where ? 'WHERE ' . join(' AND ', $where) : '') . ' + ORDER BY t.id', + ['pctxlevelcategory' => CONTEXT_COURSECAT] + $params); + + return $rs; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_course/category_description.php b/admin/tool/brickfield/classes/local/areas/core_course/category_description.php new file mode 100644 index 0000000000000..3c144e3b1ada4 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_course/category_description.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\core_course; + +/** + * Category description observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class category_description extends category_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'course_categories'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'description'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_course/category_name.php b/admin/tool/brickfield/classes/local/areas/core_course/category_name.php new file mode 100644 index 0000000000000..b0c3447a3742f --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_course/category_name.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\core_course; + +/** + * Category name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class category_name extends category_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'course_categories'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_course/fullname.php b/admin/tool/brickfield/classes/local/areas/core_course/fullname.php new file mode 100644 index 0000000000000..671061a60a33f --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_course/fullname.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\core_course; + +/** + * Course full name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class fullname extends base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'course'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'fullname'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_course/sectionname.php b/admin/tool/brickfield/classes/local/areas/core_course/sectionname.php new file mode 100644 index 0000000000000..f975a093f5aa6 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_course/sectionname.php @@ -0,0 +1,126 @@ +. + +namespace tool_brickfield\local\areas\core_course; + +use core\event\course_section_created; +use core\event\course_section_updated; +use tool_brickfield\area_base; + +/** + * Course section name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class sectionname extends area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'course_sections'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } + + /** + * Get table name reference. + * @return string + */ + public function get_ref_tablename(): string { + return 'course'; + } + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + if ($event instanceof course_section_created) { + return $this->find_fields_in_course_sections_table(['courseid' => $event->courseid, 'sectionid' => $event->objectid]); + } else if ($event instanceof course_section_updated) { + return $this->find_fields_in_course_sections_table(['courseid' => $event->courseid, 'sectionid' => $event->objectid]); + } + return null; + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + return $this->find_fields_in_course_sections_table(['courseid' => $courseid]); + } + + /** + * Helper method that can be used by the classes that define a field in the 'course_sections' table + * + * @param array $params + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + protected function find_fields_in_course_sections_table(array $params = []): \moodle_recordset { + global $DB; + $where = []; + if (!empty($params['courseid'])) { + $where[] = 't.course = :courseid'; + } + if (!empty($params['sectionid'])) { + $where[] = 't.id = :sectionid'; + } + + // Filter against approved / non-approved course category listings. + $this->filterfieldname = 'co.id'; + $this->get_courseid_filtering(); + if ($this->filter != '') { + $params = $params + $this->filterparams; + } + + $rs = $DB->get_recordset_sql('SELECT + ' . $this->get_type() . ' AS type, + ctx.id AS contextid, + ' . $this->get_standard_area_fields_sql() . ' + t.id AS itemid, + ' . $this->get_reftable_field_sql() . ' + t.course AS refid, + t.course AS courseid, + t.'.$this->get_fieldname().' AS content + FROM {'.$this->get_tablename().'} t + JOIN {course} co ON co.id = t.course + JOIN {context} ctx ON ctx.instanceid = co.id AND ctx.contextlevel = :pctxlevelcourse '. + ($where ? 'WHERE ' . join(' AND ', $where) : '') . $this->filter . ' + ORDER BY t.course', + ['pctxlevelcourse' => CONTEXT_COURSE] + $params); + + return $rs; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_course/sectionsummary.php b/admin/tool/brickfield/classes/local/areas/core_course/sectionsummary.php new file mode 100644 index 0000000000000..e8020d896d0cf --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_course/sectionsummary.php @@ -0,0 +1,126 @@ +. + +namespace tool_brickfield\local\areas\core_course; + +use core\event\course_section_created; +use core\event\course_section_updated; +use tool_brickfield\area_base; + +/** + * Course section summary observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class sectionsummary extends area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'course_sections'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'summary'; + } + + /** + * Get table name reference. + * @return string + */ + public function get_ref_tablename(): string { + return 'course'; + } + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + if ($event instanceof course_section_created) { + return $this->find_fields_in_course_sections_table(['courseid' => $event->courseid, 'sectionid' => $event->objectid]); + } else if ($event instanceof course_section_updated) { + return $this->find_fields_in_course_sections_table(['courseid' => $event->courseid, 'sectionid' => $event->objectid]); + } + return null; + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + return $this->find_fields_in_course_sections_table(['courseid' => $courseid]); + } + + /** + * Helper method that can be used by the classes that define a field in the 'course_sections' table + * + * @param array $params + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + protected function find_fields_in_course_sections_table(array $params = []): \moodle_recordset { + global $DB; + $where = []; + if (!empty($params['courseid'])) { + $where[] = 't.course = :courseid'; + } + if (!empty($params['sectionid'])) { + $where[] = 't.id = :sectionid'; + } + + // Filter against approved / non-approved course category listings. + $this->filterfieldname = 'co.id'; + $this->get_courseid_filtering(); + if ($this->filter != '') { + $params = $params + $this->filterparams; + } + + $rs = $DB->get_recordset_sql('SELECT + ' . $this->get_type() . ' AS type, + ctx.id AS contextid, + ' . $this->get_standard_area_fields_sql() . ' + t.id AS itemid, + ' . $this->get_reftable_field_sql() . ' + t.course AS refid, + t.course AS courseid, + t.'.$this->get_fieldname().' AS content + FROM {'.$this->get_tablename().'} t + JOIN {course} co ON co.id = t.course + JOIN {context} ctx ON ctx.instanceid = co.id AND ctx.contextlevel = :pctxlevelcourse '. + ($where ? 'WHERE ' . join(' AND ', $where) : '') . $this->filter . ' + ORDER BY t.section', + ['pctxlevelcourse' => CONTEXT_COURSE] + $params); + + return $rs; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_course/shortname.php b/admin/tool/brickfield/classes/local/areas/core_course/shortname.php new file mode 100644 index 0000000000000..e727eaf75216e --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_course/shortname.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\core_course; + +/** + * Course shortname observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class shortname extends base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'course'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'shortname'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_course/summary.php b/admin/tool/brickfield/classes/local/areas/core_course/summary.php new file mode 100644 index 0000000000000..fc8a4eec11ca2 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_course/summary.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\core_course; + +/** + * Course summary observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class summary extends base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'course'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'summary'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_question/answerbase.php b/admin/tool/brickfield/classes/local/areas/core_question/answerbase.php new file mode 100644 index 0000000000000..c01582646093e --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_question/answerbase.php @@ -0,0 +1,135 @@ +. + +namespace tool_brickfield\local\areas\core_question; + +use core\event\question_created; +use core\event\question_updated; + +/** + * Base class for various question-related areas + * + * This is an abstract class so it will be skipped by manager when it finds all areas + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class answerbase extends base { + + /** + * Get table name reference. + * @return string + */ + public function get_ref_tablename(): string { + return 'question'; + } + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + global $DB; + + if (($event instanceof question_created) || ($event instanceof question_updated)) { + $rs = $DB->get_recordset_sql( + "SELECT {$this->get_type()} AS type, + ctx.id AS contextid, + {$this->get_standard_area_fields_sql()} + a.id AS itemid, + {$this->get_reftable_field_sql()} + t.id AS refid, + {$this->get_course_and_cat_sql($event)} + a.{$this->get_fieldname()} AS content + FROM {question} t + INNER JOIN {question_answers} a ON a.question = t.id + INNER JOIN {question_categories} qc ON qc.id = t.category + INNER JOIN {context} ctx ON ctx.id = qc.contextid + WHERE (t.id = :refid) + ORDER BY a.id", + [ + 'refid' => $event->objectid, + ]); + return $rs; + } + return null; + } + + /** + * Return an array of area objects that contain content at the site and system levels only. This would be question content from + * question categories at the system context, or course category context. + * @return mixed + * @throws \dml_exception + */ + public function find_system_areas(): ?\moodle_recordset { + global $DB; + $select = 'SELECT ' . $this->get_type() . ' AS type, qc.contextid AS contextid, ' . $this->get_standard_area_fields_sql() . + ' a.id AS itemid, ' . $this->get_reftable_field_sql() . 't.id AS refid, '. + SITEID . ' as courseid, cc.id as categoryid, a.'.$this->get_fieldname().' AS content '; + $from = 'FROM {question} t ' . + 'INNER JOIN {question_answers} a ON a.question = t.id ' . + 'INNER JOIN {question_categories} qc ON qc.id = t.category ' . + 'INNER JOIN {context} ctx ON ctx.id = qc.contextid ' . + 'LEFT JOIN {course_categories} cc ON cc.id = ctx.instanceid AND ctx.contextlevel = :coursecat '; + $where = 'WHERE (ctx.contextlevel = :syscontext) OR (ctx.contextlevel = :coursecat2) '; + $order = 'ORDER BY a.id'; + $params = [ + 'syscontext' => CONTEXT_SYSTEM, + 'coursecat' => CONTEXT_COURSECAT, + 'coursecat2' => CONTEXT_COURSECAT, + ]; + + return $DB->get_recordset_sql($select . $from . $where . $order, $params); + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + global $DB; + + $coursecontext = \context_course::instance($courseid); + return $DB->get_recordset_sql( + "SELECT {$this->get_type()} AS type, + ctx.id AS contextid, + {$this->get_standard_area_fields_sql()} + a.id AS itemid, + {$this->get_reftable_field_sql()} + t.id AS refid, + {$courseid} AS courseid, + a.{$this->get_fieldname()} AS content + FROM {question} t + INNER JOIN {question_answers} a ON a.question = t.id + INNER JOIN {question_categories} qc ON qc.id = t.category + INNER JOIN {context} ctx ON ctx.id = qc.contextid + WHERE (ctx.contextlevel = :ctxcourse AND ctx.id = qc.contextid AND ctx.instanceid = :courseid) OR + (ctx.contextlevel = :module AND {$DB->sql_like('ctx.path', ':coursecontextpath')}) + ORDER BY a.id", + ['ctxcourse' => CONTEXT_COURSE, + 'courseid' => $courseid, + 'module' => CONTEXT_MODULE, + 'coursecontextpath' => $DB->sql_like_escape($coursecontext->path) . '/%', + ]); + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_question/base.php b/admin/tool/brickfield/classes/local/areas/core_question/base.php new file mode 100644 index 0000000000000..8887675f059bd --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_question/base.php @@ -0,0 +1,185 @@ +. + +namespace tool_brickfield\local\areas\core_question; + +use core\event\question_created; +use core\event\question_updated; +use tool_brickfield\area_base; + +/** + * Base class for various question-related areas + * + * This is an abstract class so it will be skipped by manager when it finds all areas + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class base extends area_base { + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + global $DB; + + if (($event instanceof question_created) || ($event instanceof question_updated)) { + $rs = $DB->get_recordset_sql( + "SELECT {$this->get_type()} AS type, + ctx.id AS contextid, + {$this->get_standard_area_fields_sql()} + t.id AS itemid, + {$this->get_course_and_cat_sql($event)} + t.{$this->get_fieldname()} AS content + FROM {question} t + INNER JOIN {question_categories} qc ON qc.id = t.category + INNER JOIN {context} ctx ON ctx.id = qc.contextid + WHERE (t.id = :refid) + ORDER BY t.id", + [ + 'refid' => $event->objectid, + ]); + return $rs; + } + return null; + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + global $DB; + + $coursecontext = \context_course::instance($courseid); + return $DB->get_recordset_sql( + "SELECT {$this->get_type()} AS type, + ctx.id AS contextid, + {$this->get_standard_area_fields_sql()} + t.id AS itemid, + {$courseid} AS courseid, + null AS categoryid, + t.{$this->get_fieldname()} AS content + FROM {question} t + INNER JOIN {question_categories} qc ON qc.id = t.category + INNER JOIN {context} ctx ON ctx.id = qc.contextid + WHERE (ctx.contextlevel = :ctxcourse AND ctx.id = qc.contextid AND ctx.instanceid = :courseid) OR + (ctx.contextlevel = :module AND {$DB->sql_like('ctx.path', ':coursecontextpath')}) + ORDER BY t.id ASC", + [ + 'ctxcourse' => CONTEXT_COURSE, + 'courseid' => $courseid, + 'module' => CONTEXT_MODULE, + 'coursecontextpath' => $DB->sql_like_escape($coursecontext->path) . '/%', + ]); + } + + /** + * Return an array of area objects that contain content at the site and system levels only. This would be question content from + * question categories at the system context only. + * @return \moodle_recordset + * @throws \dml_exception + */ + public function find_system_areas(): ?\moodle_recordset { + global $DB; + + $select = 'SELECT ' . $this->get_type() . ' AS type, qc.contextid AS contextid, ' . $this->get_standard_area_fields_sql() . + ' t.id AS itemid, ' . SITEID . ' as courseid, cc.id as categoryid,' . + ' t.'.$this->get_fieldname().' AS content '; + $from = 'FROM {question} t ' . + 'INNER JOIN {question_categories} qc ON qc.id = t.category ' . + 'INNER JOIN {context} ctx ON ctx.id = qc.contextid ' . + 'LEFT JOIN {course_categories} cc ON cc.id = ctx.instanceid AND ctx.contextlevel = :coursecat '; + $where = 'WHERE (ctx.contextlevel = :syscontext) OR (ctx.contextlevel = :coursecat2) '; + $order = 'ORDER BY t.id'; + $params = [ + 'syscontext' => CONTEXT_SYSTEM, + 'coursecat' => CONTEXT_COURSECAT, + 'coursecat2' => CONTEXT_COURSECAT, + ]; + + return $DB->get_recordset_sql($select . $from . $where . $order, $params); + } + + /** + * Returns the moodle_url of the page to edit the error. + * @param \stdClass $componentinfo + * @return \moodle_url + * @throws \moodle_exception + */ + public static function get_edit_url(\stdClass $componentinfo): \moodle_url { + $questionid = $componentinfo->itemid; + // Question answers are editable on main question page + // Hence, use refid for these links. + if ($componentinfo->tablename == 'question_answers') { + $questionid = $componentinfo->refid; + } + // Default to SITEID if courseid is null, i.e. system or category level questions. + $thiscourseid = ($componentinfo->courseid !== null) ? $componentinfo->courseid : SITEID; + return new \moodle_url('/question/question.php', ['courseid' => $thiscourseid, 'id' => $questionid]); + } + + /** + * Determine the course and category id SQL depending on the specific context associated with question data. + * @param \core\event\base $event + * @return string + * @throws \dml_exception + */ + protected function get_course_and_cat_sql(\core\event\base $event): string { + global $DB; + + $courseid = 'null'; + $catid = 'null'; + + $sql = " + SELECT ctx.instanceid, cm.course as courseid, ctx.contextlevel + FROM {question} q + INNER JOIN {question_categories} qc ON qc.id = q.category + INNER JOIN {context} ctx ON ctx.id = qc.contextid + LEFT JOIN {course_modules} cm ON cm.id = ctx.instanceid AND ctx.contextlevel = :coursemodule + WHERE q.id = :refid + "; + $params = [ + 'coursemodule' => CONTEXT_MODULE, + 'refid' => $event->objectid, + ]; + + if ($record = $DB->get_record_sql($sql, $params)) { + if ($record->contextlevel == CONTEXT_MODULE) { + $courseid = $record->courseid; + } else if ($record->contextlevel == CONTEXT_COURSE) { + $courseid = $record->instanceid; + } else if ($record->contextlevel == CONTEXT_COURSECAT) { + $catid = $record->instanceid; + } else if ($record->contextlevel == CONTEXT_SYSTEM) { + $courseid = 1; + } + } + + return " + {$courseid} AS courseid, + {$catid} AS categoryid, + "; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_question/generalfeedback.php b/admin/tool/brickfield/classes/local/areas/core_question/generalfeedback.php new file mode 100644 index 0000000000000..bf6c33861867b --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_question/generalfeedback.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\core_question; + +/** + * Question generalfeedback observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class generalfeedback extends base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'question'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'generalfeedback'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_question/questionanswers.php b/admin/tool/brickfield/classes/local/areas/core_question/questionanswers.php new file mode 100644 index 0000000000000..6a7c0f95124c4 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_question/questionanswers.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\core_question; + +/** + * Question answers observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class questionanswers extends answerbase { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'question_answers'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'answer'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_question/questionfeedback.php b/admin/tool/brickfield/classes/local/areas/core_question/questionfeedback.php new file mode 100644 index 0000000000000..fb0a58bb5340e --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_question/questionfeedback.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\core_question; + +/** + * Question feedback observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class questionfeedback extends answerbase { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'question_answers'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'feedback'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_question/questionname.php b/admin/tool/brickfield/classes/local/areas/core_question/questionname.php new file mode 100644 index 0000000000000..cc5b2f3d82f46 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_question/questionname.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\core_question; + +/** + * Question name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class questionname extends base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'question'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/core_question/questiontext.php b/admin/tool/brickfield/classes/local/areas/core_question/questiontext.php new file mode 100644 index 0000000000000..6d9181459f404 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/core_question/questiontext.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\core_question; + +/** + * Question text observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class questiontext extends base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'question'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'questiontext'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_assign/intro.php b/admin/tool/brickfield/classes/local/areas/mod_assign/intro.php new file mode 100644 index 0000000000000..6eb31d18d837f --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_assign/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_assign; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Assignment intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'assign'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_assign/name.php b/admin/tool/brickfield/classes/local/areas/mod_assign/name.php new file mode 100644 index 0000000000000..bfa1e48a8ff34 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_assign/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_assign; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Assignment name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'assign'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_book/base.php b/admin/tool/brickfield/classes/local/areas/mod_book/base.php new file mode 100644 index 0000000000000..8c4b715d027f5 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_book/base.php @@ -0,0 +1,42 @@ +. + +namespace tool_brickfield\local\areas\mod_book; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Book base observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class base extends module_area_base { + /** + * Returns the moodle_url of the page to edit the error. + * @param \stdClass $componentinfo + * @return \moodle_url + */ + public static function get_edit_url(\stdClass $componentinfo): \moodle_url { + if (!empty($componentinfo->refid)) { + return new \moodle_url('/mod/book/edit.php', + ['cmid' => $componentinfo->cmid, 'id' => $componentinfo->itemid, 'sesskey' => sesskey()]); + } else { + return parent::get_edit_url($componentinfo); + } + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_book/chaptercontent.php b/admin/tool/brickfield/classes/local/areas/mod_book/chaptercontent.php new file mode 100644 index 0000000000000..5ad2dd4a36203 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_book/chaptercontent.php @@ -0,0 +1,128 @@ +. + +namespace tool_brickfield\local\areas\mod_book; + +use tool_brickfield\area_base; + +/** + * Book chapter content observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class chaptercontent extends area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'book_chapters'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'content'; + } + + /** + * Get table name reference. + * @return string + */ + public function get_ref_tablename(): string { + return 'book'; + } + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + if ($event->eventname == '\mod_book\event\chapter_updated' || $event->eventname == '\mod_book\event\chapter_created') { + return $this->find_areas(['contextid' => $event->contextid, 'objectid' => $event->objectid]); + } + return null; + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + return $this->find_areas(['courseid' => $courseid]); + } + + /** + * Find recordset of areas. + * @param array $params + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + protected function find_areas(array $params = []): \moodle_recordset { + global $DB; + + $where = []; + if (!empty($params['contextid'])) { + $where[] = 'ctx.id = :contextid'; + $where[] = 'co.id = :objectid'; + } + if (!empty($params['courseid'])) { + $where[] = 'cm.course = :courseid'; + } + + // Filter against approved / non-approved course category listings. + $this->filterfieldname = 'cm.course'; + $this->get_courseid_filtering(); + if ($this->filter != '') { + $params = $params + $this->filterparams; + } + + $rs = $DB->get_recordset_sql('SELECT + ' . $this->get_type() . ' AS type, + ctx.id AS contextid, + ' . $this->get_standard_area_fields_sql() . ' + co.id AS itemid, + ' . $this->get_reftable_field_sql() . ' + t.id AS refid, + cm.id AS cmid, + cm.course AS courseid, + co.'.$this->get_fieldname().' AS content + FROM {book} t + JOIN {course_modules} cm ON cm.instance = t.id + JOIN {modules} m ON m.id = cm.module AND m.name = :preftablename2 + JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :pctxlevelmodule + JOIN {'.$this->get_tablename().'} co ON co.bookid = t.id ' . + ($where ? 'WHERE ' . join(' AND ', $where) : '') . $this->filter . ' + ORDER BY t.id, co.id', + ['pctxlevelmodule' => CONTEXT_MODULE, + 'preftablename2' => $this->get_ref_tablename(), + ] + $params); + + return $rs; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_book/chaptertitle.php b/admin/tool/brickfield/classes/local/areas/mod_book/chaptertitle.php new file mode 100644 index 0000000000000..fcc7e7afca981 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_book/chaptertitle.php @@ -0,0 +1,128 @@ +. + +namespace tool_brickfield\local\areas\mod_book; + +use tool_brickfield\area_base; + +/** + * Book chapter title observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class chaptertitle extends area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'book_chapters'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'title'; + } + + /** + * Get table name reference. + * @return string + */ + public function get_ref_tablename(): string { + return 'book'; + } + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + if ($event->eventname == '\mod_book\event\chapter_updated' || $event->eventname == '\mod_book\event\chapter_created') { + return $this->find_areas(['contextid' => $event->contextid, 'objectid' => $event->objectid]); + } + return null; + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + return $this->find_areas(['courseid' => $courseid]); + } + + /** + * Find recordset of areas. + * @param array $params + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + protected function find_areas(array $params = []): \moodle_recordset { + global $DB; + + $where = []; + if (!empty($params['contextid'])) { + $where[] = 'ctx.id = :contextid'; + $where[] = 'co.id = :objectid'; + } + if (!empty($params['courseid'])) { + $where[] = 'cm.course = :courseid'; + } + + // Filter against approved / non-approved course category listings. + $this->filterfieldname = 'cm.course'; + $this->get_courseid_filtering(); + if ($this->filter != '') { + $params = $params + $this->filterparams; + } + + $rs = $DB->get_recordset_sql('SELECT + ' . $this->get_type() . ' AS type, + ctx.id AS contextid, + ' . $this->get_standard_area_fields_sql() . ' + co.id AS itemid, + ' . $this->get_reftable_field_sql() . ' + t.id AS refid, + cm.id AS cmid, + cm.course AS courseid, + co.'.$this->get_fieldname().' AS content + FROM {book} t + JOIN {course_modules} cm ON cm.instance = t.id + JOIN {modules} m ON m.id = cm.module AND m.name = :preftablename2 + JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :pctxlevelmodule + JOIN {'.$this->get_tablename().'} co ON co.bookid = t.id ' . + ($where ? 'WHERE ' . join(' AND ', $where) : '') . $this->filter . ' + ORDER BY t.id, co.id', + ['pctxlevelmodule' => CONTEXT_MODULE, + 'preftablename2' => $this->get_ref_tablename(), + ] + $params); + + return $rs; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_book/intro.php b/admin/tool/brickfield/classes/local/areas/mod_book/intro.php new file mode 100644 index 0000000000000..f21f913a3badb --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_book/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_book; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Book intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'book'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_book/name.php b/admin/tool/brickfield/classes/local/areas/mod_book/name.php new file mode 100644 index 0000000000000..bd8b8b1acc0d3 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_book/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_book; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Book name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'book'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_chat/intro.php b/admin/tool/brickfield/classes/local/areas/mod_chat/intro.php new file mode 100644 index 0000000000000..5f3d42ddef4ef --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_chat/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_chat; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Chat intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'chat'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_chat/name.php b/admin/tool/brickfield/classes/local/areas/mod_chat/name.php new file mode 100644 index 0000000000000..11e37271f76df --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_chat/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_chat; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Chat name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'chat'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_choice/intro.php b/admin/tool/brickfield/classes/local/areas/mod_choice/intro.php new file mode 100644 index 0000000000000..8f3ae45adfd88 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_choice/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_choice; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Chat intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'choice'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_choice/name.php b/admin/tool/brickfield/classes/local/areas/mod_choice/name.php new file mode 100644 index 0000000000000..235782d47aee6 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_choice/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_choice; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Choice name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'choice'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_choice/option.php b/admin/tool/brickfield/classes/local/areas/mod_choice/option.php new file mode 100644 index 0000000000000..23e804c692e15 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_choice/option.php @@ -0,0 +1,131 @@ +. + +namespace tool_brickfield\local\areas\mod_choice; + +use core\event\course_module_created; +use core\event\course_module_updated; +use tool_brickfield\area_base; + +/** + * Choice option observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class option extends area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'choice_options'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'text'; + } + + /** + * Get table name reference. + * @return string + */ + public function get_ref_tablename(): string { + return 'choice'; + } + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + if ($event instanceof course_module_updated || $event instanceof course_module_created) { + if ($event->other['modulename'] === 'choice') { + return $this->find_areas(['refid' => $event->other['instanceid']]); + } + } + return null; + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + return $this->find_areas(['courseid' => $courseid]); + } + + /** + * Find recordset of areas. + * @param array $params + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + protected function find_areas(array $params = []): \moodle_recordset { + global $DB; + + $where = []; + if (!empty($params['refid'])) { + $where[] = 't.id = :refid'; + } + if (!empty($params['courseid'])) { + $where[] = 'cm.course = :courseid'; + } + + // Filter against approved / non-approved course category listings. + $this->filterfieldname = 'cm.course'; + $this->get_courseid_filtering(); + if ($this->filter != '') { + $params = $params + $this->filterparams; + } + + $rs = $DB->get_recordset_sql('SELECT + ' . $this->get_type() . ' AS type, + ctx.id AS contextid, + ' . $this->get_standard_area_fields_sql() . ' + co.id AS itemid, + ' . $this->get_reftable_field_sql() . ' + t.id AS refid, + cm.id AS cmid, + cm.course AS courseid, + co.'.$this->get_fieldname().' AS content + FROM {choice} t + JOIN {course_modules} cm ON cm.instance = t.id + JOIN {modules} m ON m.id = cm.module AND m.name = :preftablename2 + JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :pctxlevelmodule + JOIN {'.$this->get_tablename().'} co ON co.choiceid = t.id ' . + ($where ? 'WHERE ' . join(' AND ', $where) : '') . $this->filter . ' + ORDER BY t.id, co.id', + ['pctxlevelmodule' => CONTEXT_MODULE, + 'preftablename2' => $this->get_ref_tablename(), + ] + $params); + + return $rs; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_data/intro.php b/admin/tool/brickfield/classes/local/areas/mod_data/intro.php new file mode 100644 index 0000000000000..7b2a04bad1dce --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_data/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_data; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Data activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'data'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_data/name.php b/admin/tool/brickfield/classes/local/areas/mod_data/name.php new file mode 100644 index 0000000000000..c4f4f98dbd27c --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_data/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_data; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Data activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'data'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_feedback/intro.php b/admin/tool/brickfield/classes/local/areas/mod_feedback/intro.php new file mode 100644 index 0000000000000..c44d113dc2be7 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_feedback/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_feedback; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Feedback activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'feedback'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_feedback/name.php b/admin/tool/brickfield/classes/local/areas/mod_feedback/name.php new file mode 100644 index 0000000000000..24f2e6234952f --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_feedback/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_feedback; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Feedback activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'feedback'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_folder/intro.php b/admin/tool/brickfield/classes/local/areas/mod_folder/intro.php new file mode 100644 index 0000000000000..c659eb4e3a373 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_folder/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_folder; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Folder activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'folder'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_folder/name.php b/admin/tool/brickfield/classes/local/areas/mod_folder/name.php new file mode 100644 index 0000000000000..3336eef1f55cb --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_folder/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_folder; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Folder activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'folder'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_forum/intro.php b/admin/tool/brickfield/classes/local/areas/mod_forum/intro.php new file mode 100644 index 0000000000000..afe5ef9befeeb --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_forum/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_forum; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Forum activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'forum'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_forum/name.php b/admin/tool/brickfield/classes/local/areas/mod_forum/name.php new file mode 100644 index 0000000000000..aea1827c2af74 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_forum/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_forum; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Forum activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'forum'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_glossary/intro.php b/admin/tool/brickfield/classes/local/areas/mod_glossary/intro.php new file mode 100644 index 0000000000000..652e4c0ce7be9 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_glossary/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_glossary; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Glossary activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'glossary'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_glossary/name.php b/admin/tool/brickfield/classes/local/areas/mod_glossary/name.php new file mode 100644 index 0000000000000..6d43ff870c4b5 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_glossary/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_glossary; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Glossary activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'glossary'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_imscp/intro.php b/admin/tool/brickfield/classes/local/areas/mod_imscp/intro.php new file mode 100644 index 0000000000000..815a59f7d1c58 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_imscp/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_imscp; + +use tool_brickfield\local\areas\module_area_base; + +/** + * IMSCP activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'imscp'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_imscp/name.php b/admin/tool/brickfield/classes/local/areas/mod_imscp/name.php new file mode 100644 index 0000000000000..3ec9e4d92ba39 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_imscp/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_imscp; + +use tool_brickfield\local\areas\module_area_base; + +/** + * IMSCP activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'imscp'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_label/intro.php b/admin/tool/brickfield/classes/local/areas/mod_label/intro.php new file mode 100644 index 0000000000000..c5b3d68ec9465 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_label/intro.php @@ -0,0 +1,48 @@ +. + +namespace tool_brickfield\local\areas\mod_label; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Label activity intro observer. + * + * Although {label} has two fields, name and intro, name is a duplication of + * the intro content, therefore it is removed as an area location, to avoid duplicating errors. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'label'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_lesson/answer_answer.php b/admin/tool/brickfield/classes/local/areas/mod_lesson/answer_answer.php new file mode 100644 index 0000000000000..32398798f132a --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_lesson/answer_answer.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\mod_lesson; + +/** + * Lesson answer observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class answer_answer extends answer_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'lesson_answers'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'answer'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_lesson/answer_base.php b/admin/tool/brickfield/classes/local/areas/mod_lesson/answer_base.php new file mode 100644 index 0000000000000..d439de1114fb5 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_lesson/answer_base.php @@ -0,0 +1,114 @@ +. + +namespace tool_brickfield\local\areas\mod_lesson; + +use tool_brickfield\area_base; + +/** + * Lesson answer base. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class answer_base extends area_base { + + /** + * Get table name reference. + * @return string + */ + public function get_ref_tablename(): string { + return 'lesson_pages'; + } + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + if ($event->eventname == '\mod_lesson\event\page_created' || $event->eventname == '\mod_lesson\event\page_updated') { + if ($event->component === 'mod_lesson') { + return $this->find_areas(['itemid' => $event->objectid]); + } + } + return null; + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + return $this->find_areas(['courseid' => $courseid]); + } + + /** + * Find recordset of areas. + * @param array $params + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + protected function find_areas(array $params = []): \moodle_recordset { + global $DB; + + $where = []; + if (!empty($params['itemid'])) { + $where[] = 'pa.id = :itemid'; + } + if (!empty($params['courseid'])) { + $where[] = 'cm.course = :courseid'; + } + + // Filter against approved / non-approved course category listings. + $this->filterfieldname = 'cm.course'; + $this->get_courseid_filtering(); + if ($this->filter != '') { + $params = $params + $this->filterparams; + } + + $rs = $DB->get_recordset_sql('SELECT + ' . $this->get_type() . ' AS type, + ctx.id AS contextid, + ' . $this->get_standard_area_fields_sql() . ' + co.id AS itemid, + ' . $this->get_reftable_field_sql() . ' + pa.id AS refid, + cm.id AS cmid, + cm.course AS courseid, + co.'.$this->get_fieldname().' AS content + FROM {lesson} t + JOIN {course_modules} cm ON cm.instance = t.id + JOIN {modules} m ON m.id = cm.module AND m.name = :preftablename2 + JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :pctxlevelmodule + JOIN {lesson_pages} pa ON pa.lessonid = t.id + JOIN {'.$this->get_tablename().'} co ON co.lessonid = t.id AND co.pageid = pa.id ' . + ($where ? 'WHERE ' . join(' AND ', $where) : '') . $this->filter . ' + ORDER BY t.id, co.id', + ['pctxlevelmodule' => CONTEXT_MODULE, + 'preftablename2' => 'lesson', + ] + $params); + + return $rs; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_lesson/answer_response.php b/admin/tool/brickfield/classes/local/areas/mod_lesson/answer_response.php new file mode 100644 index 0000000000000..747934e76e7fa --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_lesson/answer_response.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\mod_lesson; + +/** + * Lesson answer response observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class answer_response extends answer_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'lesson_answers'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'response'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_lesson/base.php b/admin/tool/brickfield/classes/local/areas/mod_lesson/base.php new file mode 100644 index 0000000000000..3a4a0cd5c1b4d --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_lesson/base.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\mod_lesson; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Lesson answer base. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class base extends module_area_base { + /** + * Returns the moodle_url of the page to edit the error. + * @param \stdClass $componentinfo + * @return \moodle_url + */ + public static function get_edit_url(\stdClass $componentinfo): \moodle_url { + if (!empty($componentinfo->refid)) { + $pageid = ($componentinfo->tablename == "lesson_answers") ? $componentinfo->refid : $componentinfo->itemid; + return new \moodle_url('/mod/lesson/editpage.php', + ['id' => $componentinfo->cmid, 'pageid' => $pageid, 'edit' => 1, 'sesskey' => sesskey()]); + } else { + return parent::get_edit_url($componentinfo); + } + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_lesson/intro.php b/admin/tool/brickfield/classes/local/areas/mod_lesson/intro.php new file mode 100644 index 0000000000000..4e840623a232e --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_lesson/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_lesson; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Lesson intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'lesson'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_lesson/name.php b/admin/tool/brickfield/classes/local/areas/mod_lesson/name.php new file mode 100644 index 0000000000000..a2c9781fa0a76 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_lesson/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_lesson; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Lesson name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'lesson'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_lesson/page_base.php b/admin/tool/brickfield/classes/local/areas/mod_lesson/page_base.php new file mode 100644 index 0000000000000..2a26d6a6fdd3d --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_lesson/page_base.php @@ -0,0 +1,113 @@ +. + +namespace tool_brickfield\local\areas\mod_lesson; + +use tool_brickfield\area_base; + +/** + * Lesson page base. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class page_base extends area_base { + + /** + * Get table name reference. + * @return string + */ + public function get_ref_tablename(): string { + return 'lesson'; + } + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + if ($event->eventname == '\mod_lesson\event\page_created' || $event->eventname == '\mod_lesson\event\page_updated') { + if ($event->component === 'mod_lesson') { + return $this->find_areas(['itemid' => $event->objectid]); + } + } + return null; + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + return $this->find_areas(['courseid' => $courseid]); + } + + /** + * Find recordset of areas. + * @param array $params + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + protected function find_areas(array $params = []): \moodle_recordset { + global $DB; + + $where = []; + if (!empty($params['itemid'])) { + $where[] = 'co.id = :itemid'; + } + if (!empty($params['courseid'])) { + $where[] = 'cm.course = :courseid'; + } + + // Filter against approved / non-approved course category listings. + $this->filterfieldname = 'cm.course'; + $this->get_courseid_filtering(); + if ($this->filter != '') { + $params = $params + $this->filterparams; + } + + $rs = $DB->get_recordset_sql('SELECT + ' . $this->get_type() . ' AS type, + ctx.id AS contextid, + ' . $this->get_standard_area_fields_sql() . ' + co.id AS itemid, + ' . $this->get_reftable_field_sql() . ' + t.id AS refid, + cm.id AS cmid, + cm.course AS courseid, + co.'.$this->get_fieldname().' AS content + FROM {lesson} t + JOIN {course_modules} cm ON cm.instance = t.id + JOIN {modules} m ON m.id = cm.module AND m.name = :preftablename2 + JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :pctxlevelmodule + JOIN {'.$this->get_tablename().'} co ON co.lessonid = t.id ' . + (!empty($where) ? 'WHERE ' . join(' AND ', $where) : '') . $this->filter . ' + ORDER BY t.id, co.id', + ['pctxlevelmodule' => CONTEXT_MODULE, + 'preftablename2' => $this->get_ref_tablename(), + ] + $params); + + return $rs; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_lesson/pagecontent.php b/admin/tool/brickfield/classes/local/areas/mod_lesson/pagecontent.php new file mode 100644 index 0000000000000..20563378a48de --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_lesson/pagecontent.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\mod_lesson; + +/** + * Lesson page content observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class pagecontent extends page_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'lesson_pages'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'contents'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_lesson/pagetitle.php b/admin/tool/brickfield/classes/local/areas/mod_lesson/pagetitle.php new file mode 100644 index 0000000000000..a0dfb83238fb5 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_lesson/pagetitle.php @@ -0,0 +1,43 @@ +. + +namespace tool_brickfield\local\areas\mod_lesson; + +/** + * Lesson page title observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class pagetitle extends page_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'lesson_pages'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'title'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_lti/intro.php b/admin/tool/brickfield/classes/local/areas/mod_lti/intro.php new file mode 100644 index 0000000000000..dcca33e6f509b --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_lti/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_lti; + +use tool_brickfield\local\areas\module_area_base; + +/** + * LTI activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'lti'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_lti/name.php b/admin/tool/brickfield/classes/local/areas/mod_lti/name.php new file mode 100644 index 0000000000000..0536854621517 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_lti/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_lti; + +use tool_brickfield\local\areas\module_area_base; + +/** + * LTI activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'lti'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_page/content.php b/admin/tool/brickfield/classes/local/areas/mod_page/content.php new file mode 100644 index 0000000000000..e985ec773af14 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_page/content.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_page; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Page activity content observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class content extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'page'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'content'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_page/intro.php b/admin/tool/brickfield/classes/local/areas/mod_page/intro.php new file mode 100644 index 0000000000000..843c2b84a4777 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_page/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_page; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Page activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'page'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_page/name.php b/admin/tool/brickfield/classes/local/areas/mod_page/name.php new file mode 100644 index 0000000000000..a65e6aef8f395 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_page/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_page; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Page activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'page'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_quiz/intro.php b/admin/tool/brickfield/classes/local/areas/mod_quiz/intro.php new file mode 100644 index 0000000000000..4717be806e545 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_quiz/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_quiz; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Quiz activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'quiz'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_quiz/name.php b/admin/tool/brickfield/classes/local/areas/mod_quiz/name.php new file mode 100644 index 0000000000000..d3ce50991f5cb --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_quiz/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_quiz; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Quiz activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'quiz'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_resource/intro.php b/admin/tool/brickfield/classes/local/areas/mod_resource/intro.php new file mode 100644 index 0000000000000..fbdeef32108f1 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_resource/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_resource; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Resource activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'resource'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_resource/name.php b/admin/tool/brickfield/classes/local/areas/mod_resource/name.php new file mode 100644 index 0000000000000..2771c9c39e759 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_resource/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_resource; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Resource activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'resource'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_scorm/intro.php b/admin/tool/brickfield/classes/local/areas/mod_scorm/intro.php new file mode 100644 index 0000000000000..aa76eb54db5b4 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_scorm/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_scorm; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Scorm activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'scorm'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_scorm/name.php b/admin/tool/brickfield/classes/local/areas/mod_scorm/name.php new file mode 100644 index 0000000000000..a21ac03a4275c --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_scorm/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_scorm; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Scorm activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'scorm'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_survey/intro.php b/admin/tool/brickfield/classes/local/areas/mod_survey/intro.php new file mode 100644 index 0000000000000..6f4f983a18b61 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_survey/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_survey; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Survey activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'survey'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_survey/name.php b/admin/tool/brickfield/classes/local/areas/mod_survey/name.php new file mode 100644 index 0000000000000..ef980950dd8e6 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_survey/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_survey; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Survey activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'survey'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_url/intro.php b/admin/tool/brickfield/classes/local/areas/mod_url/intro.php new file mode 100644 index 0000000000000..55c3f26c3ef60 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_url/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_url; + +use tool_brickfield\local\areas\module_area_base; + +/** + * URL activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'url'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_url/name.php b/admin/tool/brickfield/classes/local/areas/mod_url/name.php new file mode 100644 index 0000000000000..77f91f6bf985f --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_url/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_url; + +use tool_brickfield\local\areas\module_area_base; + +/** + * URL activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'url'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_wiki/intro.php b/admin/tool/brickfield/classes/local/areas/mod_wiki/intro.php new file mode 100644 index 0000000000000..797a803e6befe --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_wiki/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_wiki; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Wiki activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'wiki'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_wiki/name.php b/admin/tool/brickfield/classes/local/areas/mod_wiki/name.php new file mode 100644 index 0000000000000..37f988fa82141 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_wiki/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_wiki; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Wiki activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'wiki'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_workshop/intro.php b/admin/tool/brickfield/classes/local/areas/mod_workshop/intro.php new file mode 100644 index 0000000000000..34a8836c0a84f --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_workshop/intro.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_workshop; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Workshop activity intro observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class intro extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'workshop'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'intro'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/mod_workshop/name.php b/admin/tool/brickfield/classes/local/areas/mod_workshop/name.php new file mode 100644 index 0000000000000..b738f5a22567d --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/mod_workshop/name.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\areas\mod_workshop; + +use tool_brickfield\local\areas\module_area_base; + +/** + * Workshop activity name observer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class name extends module_area_base { + + /** + * Get table name. + * @return string + */ + public function get_tablename(): string { + return 'workshop'; + } + + /** + * Get field name. + * @return string + */ + public function get_fieldname(): string { + return 'name'; + } +} diff --git a/admin/tool/brickfield/classes/local/areas/module_area_base.php b/admin/tool/brickfield/classes/local/areas/module_area_base.php new file mode 100644 index 0000000000000..71673d16aca38 --- /dev/null +++ b/admin/tool/brickfield/classes/local/areas/module_area_base.php @@ -0,0 +1,113 @@ +. + +namespace tool_brickfield\local\areas; + +use core\event\course_module_created; +use core\event\course_module_updated; +use tool_brickfield\area_base; + +/** + * Base class for all areas that represent a field from the module table (such as 'intro' or 'name') + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class module_area_base extends area_base { + + /** + * Find recordset of the relevant areas. + * @param \core\event\base $event + * @return \moodle_recordset|null + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_relevant_areas(\core\event\base $event): ?\moodle_recordset { + if ($event instanceof course_module_updated || $event instanceof course_module_created) { + if ($event->other['modulename'] === $this->get_tablename()) { + return $this->find_fields_in_module_table(['itemid' => $event->other['instanceid']]); + } + } + return null; + } + + /** + * Find recordset of the course areas. + * @param int $courseid + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + public function find_course_areas(int $courseid): ?\moodle_recordset { + return $this->find_fields_in_module_table(['courseid' => $courseid]); + } + + /** + * Helper method that can be used by the classes that define a field in the respective module table + * + * @param array $params + * @return \moodle_recordset + * @throws \coding_exception + * @throws \dml_exception + */ + protected function find_fields_in_module_table(array $params = []): \moodle_recordset { + global $DB; + $where = []; + if (!empty($params['itemid'])) { + $where[] = 't.id = :itemid'; + } + if (!empty($params['courseid'])) { + $where[] = 'cm.course = :courseid'; + } + + // Filter against approved / non-approved course category listings. + $this->filterfieldname = 'cm.course'; + $this->get_courseid_filtering(); + if ($this->filter != '') { + $params = $params + $this->filterparams; + } + + $rs = $DB->get_recordset_sql('SELECT + ' . $this->get_type() . ' AS type, + ctx.id AS contextid, + ' . $this->get_standard_area_fields_sql() . ' + t.id AS itemid, + cm.id AS cmid, + cm.course AS courseid, + t.'.$this->get_fieldname().' AS content + FROM {'.$this->get_tablename().'} t + JOIN {course_modules} cm ON cm.instance = t.id + JOIN {modules} m ON m.id = cm.module AND m.name = :ptablename2 + JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :pctxlevelmodule '. + ($where ? 'WHERE ' . join(' AND ', $where) : '') . $this->filter . ' + ORDER BY t.id', + ['pctxlevelmodule' => CONTEXT_MODULE, + 'ptablename2' => $this->get_tablename(), + ] + $params); + + return $rs; + } + + /** + * Returns the moodle_url of the page to edit the error. + * @param \stdClass $componentinfo + * @return \moodle_url + */ + public static function get_edit_url(\stdClass $componentinfo): \moodle_url { + return new \moodle_url('/course/mod.php', ['update' => $componentinfo->cmid, 'sr' => 0, 'sesskey' => sesskey()]); + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility.php b/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility.php new file mode 100644 index 0000000000000..aab9ff57d1fa2 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility.php @@ -0,0 +1,436 @@ +. + +namespace tool_brickfield\local\htmlchecker; + +use DOMDocument; +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_css; + +/** + * Brickfield accessibility HTML checker library. + * + * The main interface class for brickfield_accessibility. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_accessibility { + + /** @var int Failure level severe. */ + const BA_TEST_SEVERE = 1; + + /** @var int Failure level moderate. */ + const BA_TEST_MODERATE = 2; + + /** @var int Failure level seggestion. */ + const BA_TEST_SUGGESTION = 3; + + /** @var string Tag identifier to enclose all error HTML fragments in. */ + const BA_ERROR_TAG = 'bferror'; + + /** @var object The central DOMDocument object */ + public $dom; + + /** @var string The type of request this is (either 'string', 'file', or 'uri' */ + public $type; + + /** @var string The value of the request. Either HTML, a URI, or the path to a file */ + public $value; + + /** @var string The base URI of the current request (used to rebuild page if necessary) */ + public $uri = ''; + + /** @var string The translation domain of the current library */ + public $domain; + + /** @var string The name of the guideline */ + public $guidelinename = 'wcag'; + + /** @var string The name of the reporter to use */ + public $reportername = 'static'; + + /** @var object A reporting object */ + public $reporter; + + /** @var object The central guideline object */ + public $guideline; + + /** @var string The base URL for any request of type URI */ + public $baseurl; + + /** @var array An array of the current file or URI path */ + public $path = []; + + /** @var array An array of additional CSS files to load (useful for CMS content) */ + public $cssfiles = []; + + /** @var object The brickfieldCSS object */ + public $css; + + /** @var array An array of additional options */ + public $options = [ + 'cms_mode' => false, + 'start_element' => 0, + 'end_element' => 0, + 'cms_template' => [] + ]; + + /** @var bool An indicator if the DOMDocument loaded. If not, this means that the + * HTML given to it was so munged it wouldn't even load. + */ + public $isvalid = true; + + /** + * The class constructor + * @param string $value Either the HTML string to check or the file/uri of the request + * @param string $guideline The name of the guideline + * @param string $type The type of the request (either file, uri, or string) + * @param string $reporter The name of the reporter to use + * @param string $domain The domain of the translation language to use + */ + public function __construct(string $value = '', string $guideline = 'wcag2aaa', string $type = 'string', + string $reporter = 'static', string $domain = 'en') { + $this->dom = new DOMDocument(); + $this->type = $type; + if ($type == 'uri' || $type == 'file') { + $this->uri = $value; + } + $this->domain = $domain; + $this->guidelinename = $guideline; + $this->reportername = $reporter; + $this->value = $value; + } + + /** + * Prepares the DOMDocument object for brickfield_accessibility. It loads based on the file type + * declaration and first scrubs the value using prepareValue(). + */ + public function prepare_dom() { + $this->prepare_value(); + $this->isvalid = @$this->dom->loadHTML('' . $this->value); + $this->prepare_base_url($this->value, $this->type); + } + + /** + * If the CMS mode options are set, then we remove some items front the + * HTML value before sending it back. + */ + public function prepare_value() { + // We ignore the 'string' type because it would mean the value already contains HTML. + if ($this->type == 'file' || $this->type == 'uri') { + $this->value = @file_get_contents($this->value); + } + + // If there are no surrounding tags, add self::BA_ERROR_TAG to prevent the DOM from adding a

tag. + if (strpos(trim($this->value), '<') !== 0) { + $this->value = '<' . self::BA_ERROR_TAG . '>' . $this->value . ''; + } + } + + /** + * Set global predefined options for brickfield_accessibility. First we check that the + * array key has been defined. + * @param mixed $variable Either an array of values, or a variable name of the option + * @param mixed $value If this is a single option, the value of the option + */ + public function set_option($variable, $value = null) { + if (!is_array($variable)) { + $variable = [$variable => $value]; + } + foreach ($variable as $k => $value) { + if (isset($this->options[$k])) { + $this->options[$k] = $value; + } + } + } + + /** + * Returns an absolute path from a relative one. + * @param string $absolute The absolute URL + * @param string $relative The relative path + * @return string A new path + */ + public function get_absolute_path(string $absolute, string $relative): string { + if (substr($relative, 0, 2) == '//') { + if ($this->uri) { + $current = parse_url($this->uri); + } else { + $current = ['scheme' => 'http']; + } + return $current['scheme'] .':'. $relative; + } + + $relativeurl = parse_url($relative); + + if (isset($relativeurl['scheme'])) { + return $relative; + } + + $absoluteurl = parse_url($absolute); + + if (isset($absoluteurl['path'])) { + $path = dirname($absoluteurl['path']); + } + + if ($relative[0] == '/') { + $cparts = array_filter(explode('/', $relative)); + } else { + $aparts = array_filter(explode('/', $path)); + $rparts = array_filter(explode('/', $relative)); + $cparts = array_merge($aparts, $rparts); + + foreach ($cparts as $i => $part) { + if ($part == '.') { + $cparts[$i] = null; + } + + if ($part == '..') { + $cparts[$i - 1] = null; + $cparts[$i] = null; + } + } + + $cparts = array_filter($cparts); + } + + $path = implode('/', $cparts); + $url = ""; + + if (isset($absoluteurl['scheme'])) { + $url = $absoluteurl['scheme'] .'://'; + } + + if (isset($absoluteurl['user'])) { + $url .= $absoluteurl['user']; + + if ($absoluteurl['pass']) { + $url .= ':'. $absoluteurl['user']; + } + + $url .= '@'; + } + + if (isset($absoluteurl['host'])) { + $url .= $absoluteurl['host']; + + if (isset($absoluteurl['port'])) { + $url .= ':'. $absoluteurl['port']; + } + + $url .= '/'; + } + + $url .= $path; + + return $url; + } + + /** + * Sets the URI if this is for a string or to change where + * Will look for resources like CSS files + * @param string $uri The URI to set + */ + public function set_uri(string $uri) { + if (parse_url($uri)) { + $this->uri = $uri; + } + } + + /** + * Formats the base URL for either a file or uri request. We are essentially + * formatting a base url for future reporters to use to find CSS files or + * for tests that use external resources (images, objects, etc) to run tests on them. + * @param string $value The path value + * @param string $type The type of request + */ + public function prepare_base_url(string $value, string $type) { + if ($type == 'file') { + $path = explode('/', $this->uri); + array_pop($path); + $this->path = $path; + } else if ($type == 'uri' || $this->uri) { + $parts = explode('://', $this->uri); + $this->path[] = $parts[0] .':/'; + + if (is_array($parts[1])) { + foreach (explode('/', $this->get_base_from_file($parts[1])) as $part) { + $this->path[] = $part; + } + } else { + $this->path[] = $parts[1] .'/'; + } + } + } + + /** + * Retrieves the absolute path to a file + * @param string $file The path to a file + * @return string The absolute path to a file + */ + public function get_base_from_file(string $file): string { + $find = '/'; + $afterfind = substr(strrchr($file, $find), 1); + $strlenstr = strlen($afterfind); + $result = substr($file, 0, -$strlenstr); + + return $result; + } + + /** + * Helper method to add an additional CSS file + * @param string $css The URI or file path to a CSS file + */ + public function add_css(string $css) { + if (is_array($css)) { + $this->cssfiles = $css; + } else { + $this->cssfiles[] = $css; + } + } + + /** + * Retrives a single error from the current reporter + * @param string $error The error key + * @return object A ReportItem object + */ + public function get_error(string $error) { + return $this->reporter->get_error($error); + } + + /** + * A local method to load the required file for a reporter and set it for the current object + * @param array $options An array of options for the reporter + */ + public function load_reporter(array $options = []) { + $classname = '\\tool_brickfield\\local\\htmlchecker\\reporters\\'.'report_'.$this->reportername; + + $this->reporter = new $classname($this->dom, $this->css, $this->guideline, $this->path); + + if (count($options)) { + $this->reporter->set_options($options); + } + } + + /** + * Checks that the DOM object is valid or not + * @return bool Whether the DOMDocument is valid + */ + public function is_valid(): bool { + return $this->isvalid; + } + + /** + * Starts running automated checks. Loads the CSS file parser + * and the guideline object. + * @param null $options + * @return bool + */ + public function run_check($options = null) { + $this->prepare_dom(); + + if (!$this->is_valid()) { + return false; + } + + $this->get_css_object(); + $classname = 'tool_brickfield\\local\\htmlchecker\\guidelines\\'.strtolower($this->guidelinename).'_guideline'; + + $this->guideline = new $classname($this->dom, $this->css, $this->path, $options, $this->domain, $this->options['cms_mode']); + } + + /** + * Loads the brickfield_accessibility_css object + */ + public function get_css_object() { + $this->css = new brickfield_accessibility_css($this->dom, $this->uri, $this->type, $this->path, false, $this->cssfiles); + } + + /** + * Returns a formatted report from the current reporter. + * @param array $options An array of all the options + * @return mixed See the documentation on your reporter's getReport method. + */ + public function get_report(array $options = []) { + if (!$this->reporter) { + $this->load_reporter($options); + } + if ($options) { + $this->reporter->set_options($options); + } + $report = $this->reporter->get_report(); + $path = $this->path; + return ['report' => $report, 'path' => $path]; + } + + /** + * Runs one test on the current DOMDocument + * @param string $test The name of the test to run + * @return bool|array The ReportItem returned from the test + */ + public function get_test(string $test) { + $test = 'tool_brickfield\local\htmlchecker\common\checks\\' . $test; + + if (!class_exists($test)) { + return false; + } + + $testclass = new $test($this->dom, $this->css, $this->path); + + return $testclass->report; + } + + /** + * Retrieves the default severity of a test + * @param string $test The name of the test to run + * @return object The severity level of the test + */ + public function get_test_severity(string $test) { + $testclass = new $test($this->dom, $this->css, $this->path); + + return $testclass->get_severity(); + } + + /** + * A general cleanup function which just does some memory + * cleanup by unsetting the particularly large local vars. + */ + public function cleanup() { + unset($this->dom); + unset($this->css); + unset($this->guideline); + unset($this->reporter); + } + + /** + * Determines if the link text is the same as the link URL, without necessarily being an exact match. + * For example, 'www.google.com' matches 'https://www.google.com'. + * @param string $text + * @param string $href + * @return bool + */ + public static function match_urls(string $text, string $href): bool { + $parsetext = parse_url($text); + $parsehref = parse_url($href); + $parsetextfull = (isset($parsetext['host'])) ? $parsetext['host'] : ''; + $parsetextfull .= (isset($parsetext['path'])) ? $parsetext['path'] : ''; + $parsehreffull = (isset($parsehref['host'])) ? $parsehref['host'] : ''; + $parsehreffull .= (isset($parsehref['path'])) ? $parsehref['path'] : ''; + + // Remove any last '/' character before comparing. + return (rtrim($parsetextfull, '/') === rtrim($parsehreffull, '/')); + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility_guideline.php b/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility_guideline.php new file mode 100644 index 0000000000000..4e97ac19be3e8 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility_guideline.php @@ -0,0 +1,156 @@ +. + +namespace tool_brickfield\local\htmlchecker; + +/** + * The base class for a guideline + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_accessibility_guideline { + /** @var object The current document's DOMDocument */ + public $dom; + + /** @var object The current brickfield CSS object */ + public $css; + + /** @var array The path to the current document */ + public $path; + + /** @var array An array of report objects */ + public $report; + + /** @var array An array of translations for all this guideline's tests */ + public $translations; + + /** @var bool Whether we are running in CMS mode */ + public $cmsmode = false; + + /** @var array An array of all the severity levels for every test */ + public $severity = []; + + /** + * The class constructor. + * @param object $dom The current DOMDocument object + * @param object $css The current brickfieldCSS object + * @param array $path The current path + * @param null $arg + * @param string $domain + * @param bool $cmsmode + */ + public function __construct(&$dom, &$css, array &$path, + $arg = null, string $domain = 'en', bool $cmsmode = false) { + $this->dom = &$dom; + $this->css = &$css; + $this->path = &$path; + $this->cmsmode = $cmsmode; + $this->load_translations($domain); + $this->run($arg, $domain); + } + + /** + * Returns an array of all the tests associated with the current guideline + * @return array + */ + public function get_tests(): array { + return $this->tests; + } + + /** + * Loads translations from a file. This can be overriden, just as long as the + * local variable 'translations' is an associative array with test function names + * as the key + * @param string $domain + */ + public function load_translations(string $domain) { + $csv = fopen(dirname(__FILE__) .'/guidelines/translations/'. $domain .'.txt', 'r'); + + if ($csv) { + while ($translation = fgetcsv($csv)) { + if (count($translation) == 4) { + $this->translations[$translation[0]] = [ + 'title' => $translation[1], + 'description' => $translation[2], + ]; + } + } + } + } + + /** + * Returns the translation for a test name. + * @param string $testname The function name of the test + * @return mixed + */ + public function get_translation(string $testname) { + return (isset($this->translations[$testname])) + ? $this->translations[$testname] + : $testname; + } + + /** + * Iterates through each test string, makes a new test object, and runs it against the current DOM + * @param null $arg + * @param string $language + */ + public function run($arg = null, string $language = 'en') { + foreach ($this->tests as $testname => $options) { + if (is_numeric($testname) && !is_array($options)) { + $testname = $options; + } + $name = $testname; + $testname = 'tool_brickfield\local\htmlchecker\common\\checks\\'.$testname; + if (class_exists($testname) && $this->dom) { + $testname = new $testname($this->dom, $this->css, $this->path, $language, $arg); + if (!$this->cmsmode || ($testname->cms && $this->cmsmode)) { + $this->report[$name] = $testname->get_report(); + } + $this->severity[$name] = $testname->defaultseverity; + unset($testname); + } else { + $this->report[$name] = false; + } + } + } + + /** + * Returns all the Report variable + * @return mixed Look to your report to see what it returns + */ + public function get_report() { + return $this->report; + } + + /** + * Returns the severity level of a given test + * @param string $testname The name of the test + * @return int The severity level + */ + public function get_severity(string $testname): int { + if (isset($this->tests[$testname]['severity'])) { + return $this->tests[$testname]['severity']; + } + + if (isset($this->severity[$testname])) { + return $this->severity[$testname]; + } + + return brickfield_accessibility::BA_TEST_MODERATE; + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility_report_item.php b/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility_report_item.php new file mode 100644 index 0000000000000..7f67912ee308d --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility_report_item.php @@ -0,0 +1,90 @@ +. + +namespace tool_brickfield\local\htmlchecker; + +use DOMDocument; + +/** + * A report item. There is one per issue with the report + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_accessibility_report_item { + + /** @var object The DOMElement that the report item refers to (if any) */ + public $element; + + /** @var string The error message */ + public $message; + + /** @var bool Whether the check needs to be manually verified */ + public $manual; + + /** @var bool For document-level tests, this says whether the test passed or not */ + public $pass; + + /** @var object For issues with more than two possible states, this contains information about the state */ + public $state; + + /** + * Returns the line number of the report item. Unfortunately we can't use getLineNo + * if we are before PHP 5.3, so if not we try to get the line number through a more + * circuitous way. + */ + public function get_line() { + if (is_object($this->element) && method_exists($this->element, 'getLineNo')) { + return $this->element->getLineNo(); + } + return 0; + } + + /** + * Returns the current element in plain HTML form + * @param array $extraattributes An array of extra attributes to add to the element + * @return string An HTML string version of the provided DOMElement object + */ + public function get_html(array $extraattributes = []): string { + if (!$this->element) { + return ''; + } + + $resultdom = new DOMDocument(); + $resultdom->formatOutput = true; + $resultdom->preserveWhiteSpace = false; + + try { + $resultelement = $resultdom->importNode($this->element, true); + } catch (Exception $e) { + return false; + } + + foreach ($this->element->attributes as $attribute) { + if ($attribute->name != 'brickfield_accessibility_style_index') { + $resultelement->setAttribute($attribute->name, $attribute->value); + } + } + + foreach ($extraattributes as $name => $value) { + $resultelement->setAttribute($name, $value); + } + + @$resultdom->appendChild($resultelement); + return @$resultdom->saveHTML(); + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility_reporter.php b/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility_reporter.php new file mode 100644 index 0000000000000..f977a410b5f23 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/brickfield_accessibility_reporter.php @@ -0,0 +1,96 @@ +. + +namespace tool_brickfield\local\htmlchecker; + +use stdClass; + +/** + * The base class for a reporter + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_accessibility_reporter { + /** @var object The current document's DOMDocument */ + public $dom; + + /** @var object The current brickfieldaccessibilitycss object */ + public $css; + + /** @var array An array of test names and the translation for the problems with it */ + public $translation; + + /** @var array A collection of ReportItem objects */ + public $report; + + /** @var array The path to the current document */ + public $path; + + /** @var object Additional options for this reporter */ + public $options; + + /** @var array An array of attributes to search for to turn into absolute paths rather than relative paths */ + public $absoluteattributes = ['src', 'href']; + + /** + * The class constructor + * @param object $dom The current DOMDocument object + * @param object $css The current brickfield CSS object + * @param object $guideline The current guideline object + * @param string $path The current path + */ + public function __construct(&$dom, &$css, &$guideline, $path = '') { + $this->dom = &$dom; + $this->css = &$css; + $this->path = $path; + $this->options = new stdClass; + $this->guideline = &$guideline; + } + + /** + * Sets options for the reporter + * @param array $options an array of options + */ + public function set_options(array $options) { + foreach ($options as $key => $value) { + $this->options->$key = $value; + } + } + + /** + * Sets the absolute path for an element + * @param object $element A DOMElement object to turn into an absolute path + */ + public function set_absolute_path(&$element) { + $attr = false; + foreach ($this->absoluteattributes as $attribute) { + if ($element->hasAttribute($attribute)) { + $attr = $attribute; + } + } + + if ($attr) { + $item = $element->getAttribute($attr); + // We are ignoring items with absolute URLs. + if (strpos($item, '://') === false) { + $item = implode('/', $this->path) . ltrim($item, '/'); + $element->setAttribute($attr, $item); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/body_color_contrast.php b/admin/tool/brickfield/classes/local/htmlchecker/common/body_color_contrast.php new file mode 100644 index 0000000000000..c9f09426cd6b5 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/body_color_contrast.php @@ -0,0 +1,48 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +/** + * Helper function to support checking the varous color attributes of the tag against WCAG standards + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class body_color_contrast extends brickfield_accessibility_color_test { + /** @var string The attribute to check for the background color of the tag */ + public $background = 'bgcolor'; + + /** @var string The attribute to check for the foreground color of the tag */ + public $foreground = 'text'; + + /** + * Compares the WCAG contrast on the given color attributes of the tag + */ + public function check() { + $body = $this->get_all_elements('body'); + if (!$body) { + return false; + } + $body = $body[0]; + if ($body->hasAttribute($this->foreground) && $body->hasAttribute($this->background)) { + if ($this->get_luminosity($body->getAttribute($this->foreground), $body->getAttribute($this->background)) < 5) { + $this->add_report(null, null, false); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/body_wai_ert_color_contrast.php b/admin/tool/brickfield/classes/local/htmlchecker/common/body_wai_ert_color_contrast.php new file mode 100644 index 0000000000000..5f4058902dcc0 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/body_wai_ert_color_contrast.php @@ -0,0 +1,53 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +/** + * Base class for test dealing with WAI ERT color contrast for the document + * + * Because a lot of the tests deal with text, vlink, alink, etc. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class body_wai_ert_color_contrast extends brickfield_accessibility_color_test { + /** @var string The attribute to check for the background color of the tag */ + public $background = 'bgcolor'; + + /** @var string The attribute to check for the foreground color of the tag */ + public $foreground = 'text'; + + /** + * Compares the WAI ERT contrast on the given color attributes of the tag + */ + public function check() { + $body = $this->get_all_elements('body'); + if (!$body) { + return false; + } + $body = $body[0]; + if ($body->hasAttribute($this->foreground) && $body->hasAttribute($this->background)) { + if ($this->get_wai_ert_contrast($body->getAttribute($this->foreground), $body->getAttribute($this->background)) < 500) { + $this->add_report(null, null, false); + } else if ($this->get_wai_ert_brightness($body->getAttribute($this->foreground), + $body->getAttribute($this->background)) < 125) { + $this->add_report(null, null, false); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_color_test.php b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_color_test.php new file mode 100644 index 0000000000000..82f6e01396829 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_color_test.php @@ -0,0 +1,347 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +/** + * Helper test base for tests dealing with color difference and luminosity. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_accessibility_color_test extends brickfield_accessibility_test { + + /** @var string[] Mapping of colours to hex codes. */ + public $colornames = [ + 'aliceblue' => 'f0f8ff', + 'antiquewhite' => 'faebd7', + 'aqua' => '00ffff', + 'aquamarine' => '7fffd4', + 'azure' => 'f0ffff', + 'beige' => 'f5f5dc', + 'bisque' => 'ffe4c4', + 'black' => '000000', + 'blanchedalmond' => 'ffebcd', + 'blue' => '0000ff', + 'blueviolet' => '8a2be2', + 'brown' => 'a52a2a', + 'burlywood' => 'deb887', + 'cadetblue' => '5f9ea0', + 'chartreuse' => '7fff00', + 'chocolate' => 'd2691e', + 'coral' => 'ff7f50', + 'cornflowerblue' => '6495ed', + 'cornsilk' => 'fff8dc', + 'crimson' => 'dc143c', + 'cyan' => '00ffff', + 'darkblue' => '00008b', + 'darkcyan' => '008b8b', + 'darkgoldenrod' => 'b8860b', + 'darkgray' => 'a9a9a9', + 'darkgreen' => '006400', + 'darkkhaki' => 'bdb76b', + 'darkmagenta' => '8b008b', + 'darkolivegreen' => '556b2f', + 'darkorange' => 'ff8c00', + 'darkorchid' => '9932cc', + 'darkred' => '8b0000', + 'darksalmon' => 'e9967a', + 'darkseagreen' => '8fbc8f', + 'darkslateblue' => '483d8b', + 'darkslategray' => '2f4f4f', + 'darkturquoise' => '00ced1', + 'darkviolet' => '9400d3', + 'deeppink' => 'ff1493', + 'deepskyblue' => '00bfff', + 'dimgray' => '696969', + 'dodgerblue' => '1e90ff', + 'firebrick' => 'b22222', + 'floralwhite' => 'fffaf0', + 'forestgreen' => '228b22', + 'fuchsia' => 'ff00ff', + 'gainsboro' => 'dcdcdc', + 'ghostwhite' => 'f8f8ff', + 'gold' => 'ffd700', + 'goldenrod' => 'daa520', + 'gray' => '808080', + 'green' => '008000', + 'greenyellow' => 'adff2f', + 'grey' => '808080', + 'honeydew' => 'f0fff0', + 'hotpink' => 'ff69b4', + 'indianred' => 'cd5c5c', + 'indigo' => '4b0082', + 'ivory' => 'fffff0', + 'khaki' => 'f0e68c', + 'lavender' => 'e6e6fa', + 'lavenderblush' => 'fff0f5', + 'lawngreen' => '7cfc00', + 'lemonchiffon' => 'fffacd', + 'lightblue' => 'add8e6', + 'lightcoral' => 'f08080', + 'lightcyan' => 'e0ffff', + 'lightgoldenrodyellow' => 'fafad2', + 'lightgrey' => 'd3d3d3', + 'lightgreen' => '90ee90', + 'lightpink' => 'ffb6c1', + 'lightsalmon' => 'ffa07a', + 'lightseagreen' => '20b2aa', + 'lightskyblue' => '87cefa', + 'lightslategray' => '778899', + 'lightsteelblue' => 'b0c4de', + 'lightyellow' => 'ffffe0', + 'lime' => '00ff00', + 'limegreen' => '32cd32', + 'linen' => 'faf0e6', + 'magenta' => 'ff00ff', + 'maroon' => '800000', + 'mediumaquamarine' => '66cdaa', + 'mediumblue' => '0000cd', + 'mediumorchid' => 'ba55d3', + 'mediumpurple' => '9370d8', + 'mediumseagreen' => '3cb371', + 'mediumslateblue' => '7b68ee', + 'mediumspringgreen' => '00fa9a', + 'mediumturquoise' => '48d1cc', + 'mediumvioletred' => 'c71585', + 'midnightblue' => '191970', + 'mintcream' => 'f5fffa', + 'mistyrose' => 'ffe4e1', + 'moccasin' => 'ffe4b5', + 'navajowhite' => 'ffdead', + 'navy' => '000080', + 'oldlace' => 'fdf5e6', + 'olive' => '808000', + 'olivedrab' => '6b8e23', + 'orange' => 'ffa500', + 'orangered' => 'ff4500', + 'orchid' => 'da70d6', + 'palegoldenrod' => 'eee8aa', + 'palegreen' => '98fb98', + 'paleturquoise' => 'afeeee', + 'palevioletred' => 'd87093', + 'papayawhip' => 'ffefd5', + 'peachpuff' => 'ffdab9', + 'peru' => 'cd853f', + 'pink' => 'ffc0cb', + 'plum' => 'dda0dd', + 'powderblue' => 'b0e0e6', + 'purple' => '800080', + 'red' => 'ff0000', + 'rosybrown' => 'bc8f8f', + 'royalblue' => '4169e1', + 'saddlebrown' => '8b4513', + 'salmon' => 'fa8072', + 'sandybrown' => 'f4a460', + 'seagreen' => '2e8b57', + 'seashell' => 'fff5ee', + 'sienna' => 'a0522d', + 'silver' => 'c0c0c0', + 'skyblue' => '87ceeb', + 'slateblue' => '6a5acd', + 'slategray' => '708090', + 'snow' => 'fffafa', + 'springgreen' => '00ff7f', + 'steelblue' => '4682b4', + 'tan' => 'd2b48c', + 'teal' => '008080', + 'thistle' => 'd8bfd8', + 'tomato' => 'ff6347', + 'turquoise' => '40e0d0', + 'violet' => 'ee82ee', + 'wheat' => 'f5deb3', + 'white' => 'ffffff', + 'whitesmoke' => 'f5f5f5', + 'yellow' => 'ffff00', + 'yellowgreen' => '9acd32' + ]; + + /** + * Helper method that finds the luminosity between the provided + * foreground and background parameters. + * @param string $foreground The HEX value of the foreground color + * @param string $background The HEX value of the background color + * @return float The luminosity contrast ratio between the colors + */ + public function get_luminosity(string $foreground, string $background): float { + if ($foreground == $background) { + return 0; + } + $forergb = $this->get_rgb($foreground); + $backrgb = $this->get_rgb($background); + return $this->luminosity($forergb['r'], $backrgb['r'], + $forergb['g'], $backrgb['g'], + $forergb['b'], $backrgb['b']); + } + + /** + * Returns the luminosity between two colors + * @param string $r The first Red value + * @param string $r2 The second Red value + * @param string $g The first Green value + * @param string $g2 The second Green value + * @param string $b The first Blue value + * @param string $b2 The second Blue value + * @return float The luminosity contrast ratio between the colors + */ + public function luminosity(string $r, string $r2, string $g, string $g2, string $b, string $b2): float { + $rsrgb = $r / 255; + $gsrgb = $g / 255; + $bsrgb = $b / 255; + $r3 = ($rsrgb <= 0.03928) ? $rsrgb / 12.92 : pow(($rsrgb + 0.055) / 1.055, 2.4); + $g3 = ($gsrgb <= 0.03928) ? $gsrgb / 12.92 : pow(($gsrgb + 0.055) / 1.055, 2.4); + $b3 = ($bsrgb <= 0.03928) ? $bsrgb / 12.92 : pow(($bsrgb + 0.055) / 1.055, 2.4); + + $rsrgb2 = $r2 / 255; + $gsrgb2 = $g2 / 255; + $bsrgb2 = $b2 / 255; + $r4 = ($rsrgb2 <= 0.03928) ? $rsrgb2 / 12.92 : pow(($rsrgb2 + 0.055) / 1.055, 2.4); + $g4 = ($gsrgb2 <= 0.03928) ? $gsrgb2 / 12.92 : pow(($gsrgb2 + 0.055) / 1.055, 2.4); + $b4 = ($bsrgb2 <= 0.03928) ? $bsrgb2 / 12.92 : pow(($bsrgb2 + 0.055) / 1.055, 2.4); + + if ($r + $g + $b <= $r2 + $g2 + $b2) { + $l2 = (.2126 * $r3 + 0.7152 * $g3 + 0.0722 * $b3); + $l1 = (.2126 * $r4 + 0.7152 * $g4 + 0.0722 * $b4); + } else { + $l1 = (.2126 * $r3 + 0.7152 * $g3 + 0.0722 * $b3); + $l2 = (.2126 * $r4 + 0.7152 * $g4 + 0.0722 * $b4); + } + + $luminosity = round(($l1 + 0.05) / ($l2 + 0.05), 2); + return $luminosity; + } + + + /** + * Returns the decimal equivalents for a HEX color + * @param string $color The hex color value + * @return array An array where 'r' is the Red value, 'g' is Green, and 'b' is Blue + */ + public function get_rgb(string $color) { + $color = $this->convert_color($color); + $c = str_split($color, 2); + if (count($c) != 3) { + return false; + } + $results = ['r' => hexdec($c[0]), 'g' => hexdec($c[1]), 'b' => hexdec($c[2])]; + return $results; + } + + /** + * Converts multiple color or background styles into a simple hex string + * @param string $color The color attribute to convert (this can also be a multi-value css background value) + * @return string A standard CSS hex value for the color + */ + public function convert_color(string $color): string { + $color = trim($color); + if (strpos($color, ' ') !== false) { + $colors = explode(' ', $color); + foreach ($colors as $backgroundpart) { + if (substr(trim($backgroundpart), 0, 1) == '#' || + in_array(trim($backgroundpart), array_keys($this->colornames)) || + strtolower(substr(trim($backgroundpart), 0, 3)) == 'rgb') { + $color = $backgroundpart; + } + } + } + // Normal hex color. + if (substr($color, 0, 1) == '#') { + if (strlen($color) == 7) { + return str_replace('#', '', $color); + } else if (strlen($color) == 4) { + return substr($color, 1, 1) . substr($color, 1, 1) . + substr($color, 2, 1) . substr($color, 2, 1) . + substr($color, 3, 1) . substr($color, 3, 1); + } else { + return "000000"; + } + } + // Named Color. + if (in_array($color, array_keys($this->colornames))) { + return $this->colornames[$color]; + } + // RGB values. + if (strtolower(substr($color, 0, 3)) == 'rgb') { + $colors = explode(',', trim(str_replace('rgb(', '', $color), '()')); + if (count($colors) != 3) { + return false; + } + $r = intval($colors[0]); + $g = intval($colors[1]); + $b = intval($colors[2]); + + $r = dechex($r < 0 ? 0 : ($r > 255 ? 255 : $r)); + $g = dechex($g < 0 ? 0 : ($g > 255 ? 255 : $g)); + $b = dechex($b < 0 ? 0 : ($b > 255 ? 255 : $b)); + + $color = (strlen($r) < 2 ? '0' : '') . $r; + $color .= (strlen($g) < 2 ? '0' : '') . $g; + $color .= (strlen($b) < 2 ? '0' : '') . $b; + return $color; + } + + return ''; + } + + /** + * Returns the WAIERT contrast between two colors + * @param string $foreground + * @param string $background + * @return array + * @see get_luminosity + */ + public function get_wai_ert_contrast(string $foreground, string $background): array { + $forergb = $this->get_rgb($foreground); + $backrgb = $this->get_rgb($background); + $diffs = $this->get_wai_diffs($forergb, $backrgb); + + return $diffs['red'] + $diffs['green'] + $diffs['blue']; + } + + /** + * Returns the WAI ERT Brightness between two colors + * @param string $foreground + * @param string $background + * @return float|int + */ + public function get_wai_ert_brightness(string $foreground, string $background): float { + $forergb = $this->get_rgb($foreground); + $backrgb = $this->get_rgb($background); + $color = $this->get_wai_diffs($forergb, $backrgb); + return (($color['red'] * 299) + ($color['green'] * 587) + ($color['blue'] * 114)) / 1000; + } + + /** + * Get wai diffs. + * @param array $forergb + * @param array $backrgb + * @return array + */ + public function get_wai_diffs(array $forergb, array $backrgb): array { + $reddiff = ($forergb['r'] > $backrgb['r']) + ? $forergb['r'] - $backrgb['r'] + : $backrgb['r'] - $forergb['r']; + $greendiff = ($forergb['g'] > $backrgb['g']) + ? $forergb['g'] - $backrgb['g'] + : $backrgb['g'] - $forergb['g']; + + $bluediff = ($forergb['b'] > $backrgb['b']) + ? $forergb['b'] - $backrgb['b'] + : $backrgb['b'] - $forergb['b']; + return ['red' => $reddiff, 'green' => $greendiff, 'blue' => $bluediff]; + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_css.php b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_css.php new file mode 100644 index 0000000000000..3af93874352c9 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_css.php @@ -0,0 +1,541 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +/** + * Parse content to check CSS validity. + * + * This class first parses all the CSS in the document and prepares an index of CSS styles to be used by accessibility tests + * to determine color and positioning. + * + * First, in loadCSS we get all the inline and linked style sheet information and merge it into a large CSS file string. + * + * Second, in setStyles we use XPath queries to find all the DOM elements which are effected by CSS styles and then + * build up an index in style_index of all the CSS styles keyed by an attriute we attach to all DOM objects to lookup + * the style quickly. + * + * Most of the second step is to get around the problem where XPath DOMNodeList objects are only marginally referential + * to the original elements and cannot be altered directly. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_accessibility_css { + + /** @var object The DOMDocument object of the current document */ + public $dom; + + /** @var string The URI of the current document */ + public $uri; + + /** @var string The type of request (inherited from the main htmlchecker object) */ + public $type; + + /** @var array An array of all the CSS elements and attributes */ + public $css; + + /** @var string Additional CSS information (usually for CMS mode requests) */ + public $cssstring; + + /** @var bool Whether or not we are running in CMS mode */ + public $cmsmode; + + /** @var array An array of all the strings which means the current style inherts from above */ + public $inheritancestrings = ['inherit', 'currentColor']; + + /** @var array An array of all the styles keyed by the new attribute brickfield_accessibility_style_index */ + public $styleindex = []; + + /** @var int The next index ID to be applied to a node to lookup later in style_index */ + public $nextindex = 0; + + /** @var array A list of all the elements which support deprecated styles such as 'background' or 'bgcolor' */ + public $deprecatedstyleelements = ['body', 'table', 'tr', 'td', 'th']; + + /** + * Class constructor. We are just building and importing variables here and then loading the CSS + * @param \DOMDocument $dom The DOMDocument object + * @param string $uri The URI of the request + * @param string $type The type of request + * @param array $path + * @param bool $cmsmode Whether we are running in CMS mode + * @param array $cssfiles An array of additional CSS files to load + */ + public function __construct(\DOMDocument &$dom, string $uri, string $type, array $path, bool $cmsmode = false, + array $cssfiles = []) { + $this->dom =& $dom; + $this->type = $type; + $this->uri = $uri; + $this->path = $path; + $this->cmsmode = $cmsmode; + $this->css_files = $cssfiles; + } + + /** + * Loads all the CSS files from the document using LINK elements or @import commands + */ + private function load_css() { + if (count($this->css_files) > 0) { + $css = $this->css_files; + } else { + $css = []; + $headerstyles = $this->dom->getElementsByTagName('style'); + foreach ($headerstyles as $headerstyle) { + if ($headerstyle->nodeValue) { + $this->cssstring .= $headerstyle->nodeValue; + } + } + $stylesheets = $this->dom->getElementsByTagName('link'); + + foreach ($stylesheets as $style) { + if ($style->hasAttribute('rel') && + (strtolower($style->getAttribute('rel')) == 'stylesheet') && + ($style->getAttribute('media') != 'print')) { + $css[] = $style->getAttribute('href'); + } + } + } + foreach ($css as $sheet) { + $this->load_uri($sheet); + } + $this->load_imported_files(); + $this->cssstring = str_replace(':link', '', $this->cssstring); + $this->format_css(); + } + + /** + * Imports files from the CSS file using @import commands + */ + private function load_imported_files() { + $matches = []; + preg_match_all('/@import (.*?);/i', $this->cssstring, $matches); + if (count($matches[1]) == 0) { + return null; + } + foreach ($matches[1] as $match) { + $this->load_uri(trim(str_replace('url', '', $match), '"\')(')); + } + preg_replace('/@import (.*?);/i', '', $this->cssstring); + } + + /** + * Returns a specificity count to the given selector. + * Higher specificity means it overrides other styles. + * @param string $selector The CSS Selector + * @return int $specifity + */ + public function get_specificity(string $selector): int { + $selector = $this->parse_selector($selector); + if ($selector[0][0] == ' ') { + unset($selector[0][0]); + } + $selector = $selector[0]; + $specificity = 0; + foreach ($selector as $part) { + switch(substr(str_replace('*', '', $part), 0, 1)) { + case '.': + $specificity += 10; + case '#': + $specificity += 100; + case ':': + $specificity++; + default: + $specificity++; + } + if (strpos($part, '[id=') != false) { + $specificity += 100; + } + } + return $specificity; + } + + /** + * Interface method for tests to call to lookup the style information for a given DOMNode + * @param \stdClass $element A DOMElement/DOMNode object + * @return array An array of style information (can be empty) + */ + public function get_style($element): array { + // To prevent having to parse CSS unless the info is needed, + // we check here if CSS has been set, and if not, run off the parsing now. + if (!is_a($element, 'DOMElement')) { + return []; + } + $style = $this->get_node_style($element); + if (isset($style['background-color']) || isset($style['color'])) { + $style = $this->walkup_tree_for_inheritance($element, $style); + } + if ($element->hasAttribute('style')) { + $inlinestyles = explode(';', $element->getAttribute('style')); + foreach ($inlinestyles as $inlinestyle) { + $s = explode(':', $inlinestyle); + + if (isset($s[1])) { // Edit: Make sure the style attribute doesn't have a trailing. + $style[trim($s[0])] = trim(strtolower($s[1])); + } + } + } + if ($element->tagName === 'strong') { + $style['font-weight'] = 'bold'; + } + if ($element->tagName === 'em') { + $style['font-style'] = 'italic'; + } + if (!is_array($style)) { + return []; + } + return $style; + } + + /** + * Adds a selector to the CSS index + * @param string $key The CSS selector + * @param string $codestr The CSS Style code string + * @return null + */ + private function add_selector(string $key, string $codestr) { + if (strpos($key, '@import') !== false) { + return null; + } + $key = strtolower($key); + $codestr = strtolower($codestr); + if (!isset($this->css[$key])) { + $this->css[$key] = array(); + } + $codes = explode(';', $codestr); + if (count($codes) > 0) { + foreach ($codes as $code) { + $code = trim($code); + $explode = explode(':', $code, 2); + if (count($explode) > 1) { + list($codekey, $codevalue) = $explode; + if (strlen($codekey) > 0) { + $this->css[$key][trim($codekey)] = trim($codevalue); + } + } + } + } + } + + /** + * Returns the style from the CSS index for a given element by first + * looking into its tag bucket then iterating over every item for an + * element that matches + * @param \stdClass $element + * @return array An array of all the style elements that _directly_ apply to that element (ignoring inheritance) + */ + private function get_node_style($element): array { + $style = []; + + if ($element->hasAttribute('brickfield_accessibility_style_index')) { + $style = $this->styleindex[$element->getAttribute('brickfield_accessibility_style_index')]; + } + // To support the deprecated 'bgcolor' attribute. + if ($element->hasAttribute('bgcolor') && in_array($element->tagName, $this->deprecatedstyleelements)) { + $style['background-color'] = $element->getAttribute('bgcolor'); + } + if ($element->hasAttribute('style')) { + $inlinestyles = explode(';', $element->getAttribute('style')); + foreach ($inlinestyles as $inlinestyle) { + $s = explode(':', $inlinestyle); + if (isset($s[1])) { // Edit: Make sure the style attribute doesn't have a trailing. + $style[trim($s[0])] = trim(strtolower($s[1])); + } + } + } + + return $style; + } + + /** + * A helper function to walk up the DOM tree to the end to build an array of styles. + * @param \stdClass $element The DOMNode object to walk up from + * @param array $style The current style built for the node + * @return array The array of the DOM element, altered if it was overruled through css inheritance + */ + private function walkup_tree_for_inheritance($element, array $style): array { + while (property_exists($element->parentNode, 'tagName')) { + $parentstyle = $this->get_node_style($element->parentNode); + if (is_array($parentstyle)) { + foreach ($parentstyle as $k => $v) { + if (!isset($style[$k])) { + $style[$k] = $v; + } + + if ((!isset($style['background-color'])) || strtolower($style['background-color']) == strtolower("#FFFFFF")) { + if ($k == 'background-color') { + $style['background-color'] = $v; + } + } + + if ((!isset($style['color'])) || strtolower($style['color']) == strtolower("#000000")) { + if ($k == 'color') { + $style['color'] = $v; + } + } + } + } + $element = $element->parentNode; + } + return $style; + } + + /** + * Loads a CSS file from a URI + * @param string $rel The URI of the CSS file + */ + private function load_uri(string $rel) { + if ($this->type == 'file') { + $uri = substr($this->uri, 0, strrpos($this->uri, '/')) .'/'.$rel; + } else { + $bfao = new \tool_brickfield\local\htmlchecker\brickfield_accessibility(); + $uri = $bfao->get_absolute_path($this->uri, $rel); + } + $this->cssstring .= @file_get_contents($uri); + + } + + /** + * Formats the CSS to be ready to import into an array of styles + * @return bool Whether there were elements imported or not + */ + private function format_css(): bool { + // Remove comments. + $str = preg_replace("/\/\*(.*)?\*\//Usi", "", $this->cssstring); + // Parse this csscode. + $parts = explode("}", $str); + if (count($parts) > 0) { + foreach ($parts as $part) { + if (strpos($part, '{') !== false) { + list($keystr, $codestr) = explode("{", $part); + $keys = explode(", ", trim($keystr)); + if (count($keys) > 0) { + foreach ($keys as $key) { + if (strlen($key) > 0) { + $key = str_replace("\n", "", $key); + $key = str_replace("\\", "", $key); + $this->add_selector($key, trim($codestr)); + } + } + } + } + } + } + return (count($this->css) > 0); + } + + /** + * Converts a CSS selector to an Xpath query + * @param string $selector The selector to convert + * @return string An Xpath query string + */ + private function get_xpath(string $selector): string { + $query = $this->parse_selector($selector); + + $xpath = '//'; + foreach ($query[0] as $k => $q) { + if ($q == ' ' && $k) { + $xpath .= '//'; + } else if ($q == '>' && $k) { + $xpath .= '/'; + } else if (substr($q, 0, 1) == '#') { + $xpath .= '[ @id = "' . str_replace('#', '', $q) . '" ]'; + } else if (substr($q, 0, 1) == '.') { + $xpath .= '[ @class = "' . str_replace('.', '', $q) . '" ]'; + } else if (substr($q, 0, 1) == '[') { + $xpath .= str_replace('[id', '[ @ id', $q); + } else { + $xpath .= trim($q); + } + } + return str_replace('//[', '//*[', str_replace('//[ @', '//*[ @', $xpath)); + } + + /** + * Checks that a string is really a regular character + * @param string $char The character + * @return bool Whether the string is a character + */ + private function is_char(string $char): bool { + return extension_loaded('mbstring') ? mb_eregi('\w', $char) : preg_match('@\w@', $char); + } + + /** + * Parses a CSS selector into an array of rules. + * @param string $query The CSS Selector query + * @return array An array of the CSS Selector parsed into rule segments + */ + private function parse_selector(string $query): array { + // Clean spaces. + $query = trim(preg_replace('@\s+@', ' ', preg_replace('@\s*(>|\\+|~)\s*@', '\\1', $query))); + $queries = [[]]; + if (!$query) { + return $queries; + } + $return =& $queries[0]; + $specialchars = ['>', ' ']; + $specialcharsmapping = []; + $strlen = mb_strlen($query); + $classchars = ['.', '-']; + $pseudochars = ['-']; + $tagchars = ['*', '|', '-']; + // Split multibyte string + // http://code.google.com/p/phpquery/issues/detail?id=76. + $newquery = []; + for ($i = 0; $i < $strlen; $i++) { + $newquery[] = mb_substr($query, $i, 1); + } + $query = $newquery; + // It works, but i dont like it... + $i = 0; + while ($i < $strlen) { + $c = $query[$i]; + $tmp = ''; + // TAG. + if ($this->is_char($c) || in_array($c, $tagchars)) { + while (isset($query[$i]) && ($this->is_char($query[$i]) || in_array($query[$i], $tagchars))) { + $tmp .= $query[$i]; + $i++; + } + $return[] = $tmp; + // IDs. + } else if ( $c == '#') { + $i++; + while (isset($query[$i]) && ($this->is_char($query[$i]) || $query[$i] == '-')) { + $tmp .= $query[$i]; + $i++; + } + $return[] = '#'.$tmp; + // SPECIAL CHARS. + } else if (in_array($c, $specialchars)) { + $return[] = $c; + $i++; + // MAPPED SPECIAL CHARS. + } else if ( isset($specialcharsmapping[$c])) { + $return[] = $specialcharsmapping[$c]; + $i++; + // COMMA. + } else if ( $c == ',') { + $queries[] = []; + $return =& $queries[count($queries) - 1]; + $i++; + while (isset($query[$i]) && $query[$i] == ' ') { + $i++; + } + // CLASSES. + } else if ($c == '.') { + while (isset($query[$i]) && ($this->is_char($query[$i]) || in_array($query[$i], $classchars))) { + $tmp .= $query[$i]; + $i++; + } + $return[] = $tmp; + // General Sibling Selector. + } else if ($c == '~') { + $spaceallowed = true; + $tmp .= $query[$i++]; + while (isset($query[$i]) + && ($this->is_char($query[$i]) + || in_array($query[$i], $classchars) + || $query[$i] == '*' + || ($query[$i] == ' ' && $spaceallowed) + )) { + if ($query[$i] != ' ') { + $spaceallowed = false; + } + $tmp .= $query[$i]; + $i++; + } + $return[] = $tmp; + // Adjacent sibling selectors. + } else if ($c == '+') { + $spaceallowed = true; + $tmp .= $query[$i++]; + while (isset($query[$i]) + && ($this->is_char($query[$i]) + || in_array($query[$i], $classchars) + || $query[$i] == '*' + || ($spaceallowed && $query[$i] == ' ') + )) { + if ($query[$i] != ' ') { + $spaceallowed = false; + } + $tmp .= $query[$i]; + $i++; + } + $return[] = $tmp; + // ATTRS. + } else if ($c == '[') { + $stack = 1; + $tmp .= $c; + while (isset($query[++$i])) { + $tmp .= $query[$i]; + if ( $query[$i] == '[') { + $stack++; + } else if ( $query[$i] == ']') { + $stack--; + if (!$stack) { + break; + } + } + } + $return[] = $tmp; + $i++; + // PSEUDO CLASSES. + } else if ($c == ':') { + $stack = 1; + $tmp .= $query[$i++]; + while (isset($query[$i]) && ($this->is_char($query[$i]) || in_array($query[$i], $pseudochars))) { + $tmp .= $query[$i]; + $i++; + } + // With arguments? + if (isset($query[$i]) && $query[$i] == '(') { + $tmp .= $query[$i]; + $stack = 1; + while (isset($query[++$i])) { + $tmp .= $query[$i]; + if ( $query[$i] == '(') { + $stack++; + } else if ( $query[$i] == ')') { + $stack--; + if (!$stack) { + break; + } + } + } + $return[] = $tmp; + $i++; + } else { + $return[] = $tmp; + } + } else { + $i++; + } + } + foreach ($queries as $k => $q) { + if (isset($q[0])) { + if (isset($q[0][0]) && $q[0][0] == ':') { + array_unshift($queries[$k], '*'); + } + if ($q[0] != '>') { + array_unshift($queries[$k], ' '); + } + } + } + return $queries; + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_dom_element.php b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_dom_element.php new file mode 100644 index 0000000000000..9059bc3238608 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_dom_element.php @@ -0,0 +1,59 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +use DOMElement; + +/** + * Brickfield accessibility HTML checker library. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * An older attempt at using dom element extensions to introducefinding the styling of an element. + * @package tool_brickfield + * @deprecated + */ +class brickfield_accessibility_dom_element extends DOMElement { + + /** @var mixed Css style */ + public $cssstyle; + + /** + * Set css. + * @param mixed $css + */ + public function set_css($css) { + $this->cssstyle = $css; + } + + /** + * Get style. + * @param bool $style + * @return mixed + */ + public function get_style(bool $style = false) { + if (!$style) { + return $this->cssstyle; + } else { + return $this->cssstyle[$style]; + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_header_test.php b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_header_test.php new file mode 100644 index 0000000000000..95b33171e41ef --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_header_test.php @@ -0,0 +1,54 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +/** + * Special base test class that deals with tests concerning the logical heirarchy of headers. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_accessibility_header_test extends brickfield_accessibility_test { + /** @var string The header tag this test applies to. */ + public $tag = ''; + + /** @var array An array of all the header tags */ + public $headers = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']; + + /** + * The check method gathers all the headers together and walks through them, making sure that + * the logical display of headers makes sense. + */ + public function check() { + $firstheader = $this->dom->getElementsByTagName($this->tag); + if ($firstheader->item(0)) { + $current = $firstheader->item(0); + $previousnumber = intval(substr($current->tagName, -1, 1)); + while ($current) { + if (property_exists($current, 'tagName') && in_array($current->tagName, $this->headers)) { + $currentnumber = intval(substr($current->tagName, -1, 1)); + if ($currentnumber > ($previousnumber + 1)) { + $this->add_report($current); + } + $previousnumber = intval(substr($current->tagName, -1, 1)); + } + $current = $current->nextSibling; + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_table_test.php b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_table_test.php new file mode 100644 index 0000000000000..b8a996da367d2 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_table_test.php @@ -0,0 +1,82 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +/** + * Special base class which provides helper methods for tables. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_accessibility_table_test extends brickfield_accessibility_test { + /** + * Takes the element object of a main table and returns the number of rows and columns in it. + * @param \stdClass $table + * @return array An array with the 'rows' value showing the number of rows, and column showing the number of columns + */ + public function get_table(\stdClass $table): array { + $rows = 0; + $columns = 0; + $firstrow = true; + if ($table->tagName != 'table') { + return false; + } + foreach ($table->childNodes as $child) { + if (property_exists($child, 'tagName') && $child->tagName == 'tr') { + $rows++; + if ($firstrow) { + foreach ($child->childNodes as $columnchild) { + if ($columnchild->tagName == 'th' || $columnchild->tagName == 'td') { + $columns++; + } + } + $firstrow = false; + } + } + } + + return ['rows' => $rows, 'columns' => $columns]; + } + + /** + * Finds whether or not the table is a data table. Checks that the + * table has a logical order and uses 'th' or 'thead' tags to illustrate + * the page author thought it was a data table. + * @param object $table The DOMElement object of the table tag + * @return bool TRUE if the element is a data table, otherwise false + */ + public function is_data($table): bool { + if ($table->tagName != 'table') { + return false; + } + + foreach ($table->childNodes as $child) { + if (property_exists($child, 'tagName') && $child->tagName == 'tr') { + foreach ($child->childNodes as $rowchild) { + if (property_exists($rowchild, 'tagName') && $rowchild->tagName == 'th') { + return true; + } + } + } + if (property_exists($child, 'tagName') && $child->tagName == 'thead') { + return true; + } + } + return false; + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_tag_test.php b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_tag_test.php new file mode 100644 index 0000000000000..8d5115507376f --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_tag_test.php @@ -0,0 +1,41 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +/** + * Special class test thats only for file a report whenever it hits the specified tag regardless of anything about the element. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_accessibility_tag_test extends brickfield_accessibility_test { + /** + * @var string The tag name of this test + */ + public $tag = ''; + + /** + * Shouldn't need to be overridden. We just file one report item for every + * element we find with this class's $tag var. + */ + public function check() { + foreach ($this->get_all_elements($this->tag) as $element) { + $this->add_report($element); + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_test.php b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_test.php new file mode 100644 index 0000000000000..1b2738cf6b355 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/brickfield_accessibility_test.php @@ -0,0 +1,394 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +use tool_brickfield\local\htmlchecker\brickfield_accessibility_report_item; +use tool_brickfield\manager; + +/** + * This handles importing DOM objects, adding items to the report and provides a few DOM-traversing methods + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_accessibility_test { + /** @var object The DOMDocument object */ + public $dom; + + /** @var object The brickfieldCSS object */ + public $css; + + /** @var array The path for the request */ + public $path; + + /** @var bool Whether the test can be used in a CMS (content without HTML head) */ + public $cms = true; + + /** @var string The base path for this request */ + public $basepath; + + /** @var array An array of ReportItem objects */ + public $report = array(); + + /** @var int The fallback severity level for all tests */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SUGGESTION; + + /** @var array An array of all the extensions that are images */ + public $imageextensions = array('gif', 'jpg', 'png', 'jpeg', 'tiff', 'svn'); + + /** @var string The language domain */ + public $lang = 'en'; + + /** @var array An array of translatable strings */ + public $strings = array('en' => ''); + + /** + * The class constructor. We pass items by reference so we can alter the DOM if necessary + * @param object $dom The DOMDocument object + * @param object $css The brickfieldCSS object + * @param array $path The path of this request + * @param string $languagedomain The langauge domain to user + * @param mixed $options Any additional options passed by htmlchecker. + */ + public function __construct(&$dom, &$css, &$path, $languagedomain = 'en', $options = null) { + $this->dom = $dom; + $this->css = $css; + $this->path = $path; + $this->lang = $languagedomain; + $this->options = $options; + $this->report = array(); + $this->check(); + } + + /** + * Helper method to collect the report from this test. Some + * tests do additional cleanup by overriding this method + * @return array An array of ReportItem objects + */ + public function get_report(): array { + $this->report['severity'] = $this->defaultseverity; + return $this->report; + } + + /** + * Returns the default severity of the test + * @return int The severity level + */ + public function get_severity(): int { + return $this->defaultseverity; + } + + /** + * Adds a new ReportItem to this current tests collection of reports. + * Most reports pertain to a particular element (like an IMG with no Alt attribute); + * however, some are document-level and just either pass or don't pass + * @param object $element The DOMElement object that pertains to this report + * @param string $message An additional message to add to the report + * @param bool $pass Whether or not this report passed + * @param object $state Extra information about the error state + * @param bool $manual Whether the report needs a manual check + */ + public function add_report($element = null, $message = null, $pass = null, $state = null, $manual = null) { + $report = new brickfield_accessibility_report_item(); + $report->element = $element; + $report->message = $message; + $report->pass = $pass; + $report->state = $state; + $report->manual = $manual; + $report->line = $report->get_line(); + $this->report[] = $report; + } + + /** + * Retrieves the full path for a file. + * @param string $file The path to a file + * @return string The absolute path to the file. + */ + public function get_path($file): string { + if ((substr($file, 0, 7) == 'http://') || (substr($file, 0, 8) == 'https://')) { + return $file; + } + $file = explode('/', $file); + if (count($file) == 1) { + return implode('/', $this->path) . '/' . $file[0]; + } + + $path = $this->path; + foreach ($file as $directory) { + if ($directory == '..') { + array_pop($path); + } else { + $filepath[] = $directory; + } + } + return implode('/', $path) .'/'. implode('/', $filepath); + } + + /** + * Returns a translated variable. If the translation is unavailable, English is returned + * Because tests only really have one string array, we can get all of this info locally + * @return mixed The translation for the object + */ + public function translation() { + if (isset($this->strings[$this->lang])) { + return $this->strings[$this->lang]; + } + if (isset($this->strings['en'])) { + return $this->strings['en']; + } + return false; + } + + /** + * Helper method to find all the elements that fit a particular query + * in the document (either by tag name, or by attributes from the htmlElements object) + * @param mixed $tags Either a single tag name in a string, or an array of tag names + * @param string $options The kind of option to select an element by (see htmlElements) + * @param bool $value The value of the above option + * @return array An array of elements that fit the description + */ + public function get_all_elements($tags = null, string $options = '', bool $value = true): array { + if (!is_array($tags)) { + $tags = [$tags]; + } + if ($options !== '') { + $temp = new html_elements(); + $tags = $temp->get_elements_by_option($options, $value); + } + $result = []; + + if (!is_array($tags)) { + return []; + } + foreach ($tags as $tag) { + $elements = $this->dom->getElementsByTagName($tag); + if ($elements) { + foreach ($elements as $element) { + $result[] = $element; + } + } + } + if (count($result) == 0) { + return []; + } + return $result; + } + + /** + * Returns true if an element has a child with a given tag name + * @param object $element A DOMElement object + * @param string $childtag The tag name of the child to find + * @return bool TRUE if the element does have a child with + * the given tag name, otherwise FALSE + */ + public function element_has_child($element, string $childtag): bool { + foreach ($element->childNodes as $child) { + if (property_exists($child, 'tagName') && $child->tagName == $childtag) { + return true; + } + } + return false; + } + + /** + * Returns the first ancestor reached of a tag, or false if it hits + * the document root or a given tag. + * @param object $element A DOMElement object + * @param string $ancestortag The name of the tag we are looking for + * @param string $limittag Where to stop searching + * @return bool + */ + public function get_element_ancestor($element, string $ancestortag, string $limittag = 'body') { + while (property_exists($element, 'parentNode')) { + if ($element->parentNode->tagName == $ancestortag) { + return $element->parentNode; + } + if ($element->parentNode->tagName == $limittag) { + return false; + } + $element = $element->parentNode; + } + return false; + } + + /** + * Finds all the elements with a given tag name that has + * an attribute + * @param string $tag The tag name to search for + * @param string $attribute The attribute to search on + * @param bool $unique Whether we only want one result per attribute + * @return array An array of DOMElements with the attribute + * value as the key. + */ + public function get_elements_by_attribute(string $tag, string $attribute, bool $unique = false): array { + $results = array(); + foreach ($this->get_all_elements($tag) as $element) { + if ($element->hasAttribute($attribute)) { + if ($unique) { + $results[$element->getAttribute($attribute)] = $element; + } else { + $results[$element->getAttribute($attribute)][] = $element; + } + } + } + return $results; + } + + /** + * Returns the next element after the current one. + * @param object $element A DOMElement object + * @return mixed FALSE if there is no other element, or a DOMElement object + */ + public function get_next_element($element) { + $parent = $element->parentNode; + $next = false; + foreach ($parent->childNodes as $child) { + if ($next) { + return $child; + } + if ($child->isSameNode($element)) { + $next = true; + } + } + return false; + } + + /** + * To minimize notices, this compares an object's property to the valus + * and returns true or false. False will also be returned if the object is + * not really an object, or if the property doesn't exist at all + * @param object $object The object too look at + * @param string $property The name of the property + * @param mixed $value The value to check against + * @param bool $trim Whether the property value should be trimmed + * @param bool $lower Whether the property value should be compared on lower case + * + * @return bool + */ + public function property_is_equal($object, string $property, $value, bool $trim = false, bool $lower = false) { + if (!is_object($object)) { + return false; + } + if (!property_exists($object, $property)) { + return false; + } + $propertyvalue = $object->$property; + if ($trim) { + $propertyvalue = trim($propertyvalue); + $value = trim($value); + } + if ($lower) { + $propertyvalue = strtolower($propertyvalue); + $value = strtolower($value); + } + return ($propertyvalue == $value); + } + + /** + * Returns the parent of an elment that has a given tag Name, but + * stops the search if it hits the $limiter tag + * @param object $element The DOMElement object to search on + * @param string $tagname The name of the tag of the parent to find + * @param string $limiter The tag name of the element to stop searching on + * regardless of the results (like search for a parent "P" tag + * of this node but stop if you reach "body") + * @return mixed FALSE if no parent is found, or the DOMElement object of the found parent + */ + public function get_parent($element, string $tagname, string $limiter) { + while ($element) { + if ($element->tagName == $tagname) { + return $element; + } + if ($element->tagName == $limiter) { + return false; + } + $element = $element->parentNode; + } + return false; + } + + /** + * Returns if a GIF files is animated or not http://us.php.net/manual/en/function.imagecreatefromgif.php#88005 + * @param string $filename + * @return int + */ + public function image_is_animated($filename): int { + if (!($fh = @fopen($filename, 'rb'))) { + return false; + } + $count = 0; + // An animated gif contains multiple "frames", with each frame having a + // header made up of: + // * a static 4-byte sequence (\x00\x21\xF9\x04) + // * 4 variable bytes + // * a static 2-byte sequence (\x00\x2C). + + // We read through the file til we reach the end of the file, or we've found + // at least 2 frame headers. + while (!feof($fh) && $count < 2) { + $chunk = fread($fh, 1024 * 100); // Read 100kb at a time. + $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches); + } + + fclose($fh); + return $count > 1; + } + + /** + * Returns if there are any printable/readable characters within an element. + * This finds both node values or images with alt text. + * @param object $element The given element to look at + * @return bool TRUE if contains readable text, FALSE if otherwise + */ + public function element_contains_readable_text($element): bool { + if (is_a($element, 'DOMText')) { + if (trim($element->wholeText) != '') { + return true; + } + } else { + if (trim($element->nodeValue) != '' || + ($element->hasAttribute('alt') && trim($element->getAttribute('alt')) != '')) { + return true; + } + if (method_exists($element, 'hasChildNodes') && $element->hasChildNodes()) { + foreach ($element->childNodes as $child) { + if ($this->element_contains_readable_text($child)) { + return true; + } + } + } + } + return false; + } + + /** + * Returns an array of the invalidlinkphrases for all enabled language packs. + * @return array of the invalidlinkphrases for all enabled language packs. + */ + public static function get_all_invalidlinkphrases(): array { + // Need to process all enabled lang versions of invalidlinkphrases. + $allstrings = []; + $enabledlangs = get_string_manager()->get_list_of_translations(); + foreach ($enabledlangs as $lang => $value) { + $tmpstring = (string)new \lang_string('invalidlinkphrases', manager::PLUGINNAME, null, $lang); + $tmplangarray = explode('|', $tmpstring); + $allstrings = array_merge($allstrings, $tmplangarray); + } + return $allstrings; + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/a_links_dont_open_new_window.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/a_links_dont_open_new_window.php new file mode 100644 index 0000000000000..87a263e37d366 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/a_links_dont_open_new_window.php @@ -0,0 +1,48 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Anchor should not open new window without warning. + * a (anchor) element must not contain a target attribute unless the target attribute value is either _self, _top, or _parent. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class a_links_dont_open_new_window extends brickfield_accessibility_test { + /** @var int $defaultseverity The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** @var string[] A list of targets allowed that don't open a new window. */ + public $allowedtargets = array('_self', '_parent', '_top', ''); + + /** + * The main check function. This is called by the parent class to actually check content. + */ + public function check(): void { + foreach ($this->get_all_elements('a') as $a) { + if ($a->hasAttribute('target') && !in_array($a->getAttribute('target'), $this->allowedtargets)) { + $this->add_report($a); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/a_must_contain_text.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/a_must_contain_text.php new file mode 100644 index 0000000000000..f7a1d8cfe9dce --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/a_must_contain_text.php @@ -0,0 +1,56 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Each source anchor contains text. + * a (anchor) element must contain text. The text may occur in the anchor text or in the title attribute of the anchor + * or in the Alt text of an image used within the anchor. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class a_must_contain_text extends brickfield_accessibility_test { + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content. + */ + public function check(): void { + foreach ($this->get_all_elements('a') as $a) { + if (!$this->element_contains_readable_text($a) && ($a->hasAttribute('href'))) { + $this->add_report($a); + } + } + } + + /** + * Returns if a link is not a candidate to be an anchor (which does + * not need text). + * @param \DOMElement $a + * @return bool Whether is is a link (TRUE) or an anchor (FALSE) + */ + public function is_not_anchor(\DOMElement $a): bool { + return (!($a->hasAttribute('name') && !$a->hasAttribute('href'))); + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/a_suspicious_link_text.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/a_suspicious_link_text.php new file mode 100644 index 0000000000000..b1708d07f7237 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/a_suspicious_link_text.php @@ -0,0 +1,70 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\brickfield_accessibility; +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; +use tool_brickfield\manager; + +/** + * Brickfield accessibility HTML checker library. + * + * Suspicious link text. + * 'a' (anchor) element cannot contain any of the following text, such as (English): "click here". + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class a_suspicious_link_text extends brickfield_accessibility_test { + /** + * @var int The default severity code for this test. + */ + public $defaultseverity = brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + // Need to process all enabled lang versions of invalidlinkphrases. + $badtext = brickfield_accessibility_test::get_all_invalidlinkphrases(); + + foreach ($this->get_all_elements('a') as $a) { + if (in_array(strtolower(trim($a->nodeValue)), $badtext) || $a->nodeValue == $a->getAttribute('href')) { + // If the link text matches invalid phrases. + $this->add_report($a); + } else if (brickfield_accessibility::match_urls($a->nodeValue, $a->getAttribute('href'))) { + // If the link text is the same as the link URL. + $this->add_report($a); + } + } + } + + /** + * Return all 'a' elements. + * + * @return array + */ + public function search(): array { + $data = []; + foreach ($this->get_all_elements('a') as $a) { + $data[] = $a; + } + + return $data; + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/area_dont_open_new_window.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/area_dont_open_new_window.php new file mode 100644 index 0000000000000..8fa55250bc55a --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/area_dont_open_new_window.php @@ -0,0 +1,48 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Area should not open new window without warning. + * Area element, target attribute values must contain any one of (case insensitive) _self, _top, _parent. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class area_dont_open_new_window extends brickfield_accessibility_test { + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** @var string[] A list of targets which are allowed. */ + public $allowedtargets = array('_self', '_parent', '_top'); + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements('area') as $area) { + if ($area->hasAttribute('target') && !in_array($area->getAttribute('target'), $this->allowedtargets)) { + $this->add_report($area); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/area_has_alt_value.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/area_has_alt_value.php new file mode 100644 index 0000000000000..054e4684f3a11 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/area_has_alt_value.php @@ -0,0 +1,47 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * All area elements have an alt attribute. + * Area elements must contain a alt attribute. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class area_has_alt_value extends brickfield_accessibility_test { + /** + * @var int The default severity code for this test. + */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements('area') as $area) { + if (!$area->hasAttribute('alt')) { + $this->add_report($area); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/basefont_is_not_used.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/basefont_is_not_used.php new file mode 100644 index 0000000000000..f610d3502966d --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/basefont_is_not_used.php @@ -0,0 +1,37 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_tag_test; + +/** + * Brickfield accessibility HTML checker library. + * + * 'basefont' must not be used. + * This error is generated for all basefont elements. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class basefont_is_not_used extends brickfield_accessibility_tag_test { + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** @var string The tag this test will fire on. */ + public $tag = 'basefont'; +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/blink_is_not_used.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/blink_is_not_used.php new file mode 100644 index 0000000000000..d26cf5f7667ca --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/blink_is_not_used.php @@ -0,0 +1,37 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_tag_test; + +/** + * Brickfield accessibility HTML checker library. + * + * 'blink' element is not used. + * This error is generated for all blink elements. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class blink_is_not_used extends brickfield_accessibility_tag_test { + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** @var string The tag this test will fire on. */ + public $tag = 'blink'; +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/bold_is_not_used.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/bold_is_not_used.php new file mode 100644 index 0000000000000..76460fdb04482 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/bold_is_not_used.php @@ -0,0 +1,37 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_tag_test; + +/** + * Brickfield accessibility HTML checker library. + * + * 'b' (bold) element is not used. + * This error will be generated for all B elements. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class bold_is_not_used extends brickfield_accessibility_tag_test { + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** @var string The tag this test will fire on. */ + public $tag = 'b'; +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/content_too_long.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/content_too_long.php new file mode 100644 index 0000000000000..f05ac7b304c22 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/content_too_long.php @@ -0,0 +1,55 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Test counts words for all text elements on page and suggests content chunking for pages longer than 3000 words. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class content_too_long extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SUGGESTION; + + /** + * The main check function. This is called by the parent class to actually check content. + */ + public function check(): void { + global $contentlengthlimit; + + $contentlengthlimit = 500; + $pagetext = ''; + foreach ($this->get_all_elements(null, 'text') as $element) { + $text = $element->nodeValue; + if ($text != null) { + $pagetext = $pagetext . $text; + } + } + + $wordcount = str_word_count($pagetext); + if ($wordcount > $contentlengthlimit) { + $this->add_report(null, "

Word Count: " . $wordcount . "

", false); + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/css_text_has_contrast.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/css_text_has_contrast.php new file mode 100644 index 0000000000000..1ae273c3180e0 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/css_text_has_contrast.php @@ -0,0 +1,148 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use DOMXPath; +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_color_test; + +/** + * Brickfield accessibility HTML checker library. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class css_text_has_contrast extends brickfield_accessibility_color_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** @var string The default background color. */ + public $defaultbackground = '#ffffff'; + + /** @var string The default color. */ + public $defaultcolor = '#000000'; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + if (isset($this->options['css_background'])) { + $this->defaultbackground = $this->options['css_background']; + } + + if (isset($this->options['css_foreground'])) { + $this->defaultcolor = $this->options['css_foreground']; + } + + $xpath = new DOMXPath($this->dom); + + // Selects all nodes that have a style attribute OR 'strong' OR 'em' elements that: + // Contain only the text in their text nodes + // OR Have text nodes AND text nodes that are not equal to the string-value of the context node + // OR Have a text node descendant that equals the string-value of the context node and has no style attributes. + + $entries = $xpath->query('//*[(text() = . or ( ./*[text() != .]) or (.//*[text() = . and not(@style)])) + and ((@style) or (name() = "strong") or (name() = "em"))]'); + + foreach ($entries as $element) { + $style = $this->css->get_style($element); + + if (isset($style['background-color']) || isset($style['color'])) { + if (!isset($style['background-color'])) { + $style['background-color'] = $this->defaultbackground; + } + + if (!isset($style['color'])) { + $style['color'] = $this->defaultcolor; + } + + if ((isset($style['background']) || isset($style['background-color'])) && isset($style['color']) && + $element->nodeValue) { + + $background = (isset($style['background-color'])) ? $style['background-color'] : $style['background']; + if (!$background || !empty($this->options['css_only_use_default'])) { + $background = $this->defaultbackground; + } + + $style['color'] = '#' . $this->convert_color($style['color']); + $style['background-color'] = '#' . $this->convert_color($background); + + if (substr($background, 0, 3) == "rgb") { + $background = '#' . $this->convert_color($background); + } + + $luminosity = $this->get_luminosity($style['color'], $background); + $fontsize = 0; + $bold = false; + $italic = false; + + if (isset($style['font-size'])) { + preg_match_all('!\d+!', $style['font-size'], $matches); + $fontsize = $matches[0][0]; + } + + if (isset($style['font-weight'])) { + preg_match_all('!\d+!', $style['font-weight'], $matches); + + if (count($matches) > 0) { + if ($matches >= 700) { + $bold = true; + } else { + if ($style['font-weight'] === 'bold' || $style['font-weight'] === 'bolder') { + $bold = true; + } + } + } + } else if ($element->tagName === "strong") { + $bold = true; + $style['font-weight'] = "bold"; + } else { + $style['font-weight'] = "normal"; + } + + if (isset($style['font-style'])) { + if ($style['font-style'] === "italic") { + $italic = true; + } + } else if ($element->tagName === "em") { + $italic = true; + $style['font-style'] = "italic"; + } else { + $style['font-style'] = "normal"; + } + + if ($element->tagName === 'h1' || $element->tagName === 'h2' || $element->tagName === 'h3' || + $element->tagName === 'h4' || $element->tagName === 'h5' || $element->tagName === 'h6' || + $fontsize >= 18 || $fontsize >= 14 && $bold) { + if ($luminosity < 3) { + $message = 'heading: background-color: ' . $background . '; color:' . $style["color"] . + '; font-style: ' . $style['font-style'] . '; font-weight: ' . $style['font-weight'] . '; '; + $this->add_report($element, $message); + } + } else { + if ($luminosity < 4.5) { + $message = 'text: background-color: ' . $background . '; color:' . $style["color"] . '; font-style: ' . + $style['font-style'] . '; font-weight: ' . $style['font-weight'] . '; '; + $this->add_report($element, $message); + } + } + } + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/embed_has_associated_no_embed.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/embed_has_associated_no_embed.php new file mode 100644 index 0000000000000..8f58cca0ac7b6 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/embed_has_associated_no_embed.php @@ -0,0 +1,53 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * All embed elements have an associated noembed element that contains a text equivalent to the embed element. + * Provide a text equivalent for the embed element. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class embed_has_associated_no_embed extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements('embed') as $embed) { + // If one of the child nodes is a 'noembed', then content is fine. + foreach ($embed->childNodes as $child) { + if ($child->nodeName == 'noembed') { + return; + } + } + // There were no 'noembed' child nodes. If the next sibling isn't, then the content is flawed. + if (!$this->property_is_equal($embed->nextSibling, 'tagName', 'noembed')) { + $this->add_report($embed); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/header_h3.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/header_h3.php new file mode 100644 index 0000000000000..4af96f349d341 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/header_h3.php @@ -0,0 +1,35 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_header_test; + +/** + * Brickfield accessibility HTML checker library. + * + * The header following an h3 is h1, h2, h3 or h4. + * The following header must be equal, one level greater or any level less. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class header_h3 extends brickfield_accessibility_header_test { + + /** @var string The tag this test will fire on. */ + public $tag = 'h3'; +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/headers_have_text.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/headers_have_text.php new file mode 100644 index 0000000000000..6fe8e22e535d6 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/headers_have_text.php @@ -0,0 +1,45 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Headers should have text content so as not to confuse screen-reader users. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class headers_have_text extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements(null, 'header', true) as $header) { + if (!$this->element_contains_readable_text($header)) { + $this->add_report($header); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/i_is_not_used.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/i_is_not_used.php new file mode 100644 index 0000000000000..a9a7799b32a06 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/i_is_not_used.php @@ -0,0 +1,38 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_tag_test; + +/** + * Brickfield accessibility HTML checker library. + * + * 'i' (italic) element is not used. + * This error will be generated for all i elements. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class i_is_not_used extends brickfield_accessibility_tag_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** @var string The tag this test will fire on. */ + public $tag = 'i'; +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_is_different.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_is_different.php new file mode 100644 index 0000000000000..f6b943ce49ff6 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_is_different.php @@ -0,0 +1,48 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Alt text is not the same as the filename unless author has confirmed it is correct. + * 'img' element cannot have alt attribute value that is the same as its src attribute. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class img_alt_is_different extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements('img') as $img) { + if (trim($img->getAttribute('src')) == trim($img->getAttribute('alt'))) { + $this->add_report($img); + } else if (preg_match("/.jpg|.JPG|.png|.PNG|.gif|.GIF|.jpeg|.JPEG$/", trim($img->getAttribute('alt')))) { + $this->add_report($img); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_is_too_long.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_is_too_long.php new file mode 100644 index 0000000000000..e19812c33c5db --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_is_too_long.php @@ -0,0 +1,49 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Image Alt text is long. + * Image Alt text is long or user must confirm that Alt text is as short as possible. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class img_alt_is_too_long extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content. + */ + public function check(): void { + global $alttextlengthlimit; + + foreach ($this->get_all_elements('img') as $img) { + $alttextlengthlimit = 125; + if ($img->hasAttribute('alt') && strlen($img->getAttribute('alt')) > $alttextlengthlimit) { + $this->add_report($img); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_not_empty_in_anchor.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_not_empty_in_anchor.php new file mode 100644 index 0000000000000..461649773b79c --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_not_empty_in_anchor.php @@ -0,0 +1,52 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Alt text for all img elements used as source anchors is not empty when there is no other text in the anchor. + * img element cannot have alt attribute value of null or whitespace if the img element is contained by an + * a element and there is no other link text. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class img_alt_not_empty_in_anchor extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements('a') as $a) { + if (!$a->nodeValue && $a->childNodes) { + foreach ($a->childNodes as $child) { + if ($this->property_is_equal($child, 'tagName', 'img') + && trim($child->getAttribute('alt')) == '') { + $this->add_report($child); + } + } + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_not_place_holder.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_not_place_holder.php new file mode 100644 index 0000000000000..b1c6c4becfe5b --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_alt_not_place_holder.php @@ -0,0 +1,60 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Alt text for all img elements is not placeholder text unless author has confirmed it is correct. + * 'img' element cannot have alt attribute value of "nbsp" or "spacer". + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class img_alt_not_place_holder extends brickfield_accessibility_test { + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** @var \string[][] An array of strings, broken up by language domain. */ + public $strings = + [ + 'en' => array('nbsp', ' ', 'spacer', 'image', 'img', 'photo'), + 'es' => array('nbsp', ' ', 'spacer', 'espacio', 'imagen', 'img', 'foto'), + ]; + + /** + * The main check function. This is called by the parent class to actually check content. + */ + public function check(): void { + foreach ($this->get_all_elements('img') as $img) { + if ($img->hasAttribute('alt')) { + if (strlen($img->getAttribute('alt')) > 0) { + if (in_array($img->getAttribute('alt'), $this->translation()) + || ord($img->getAttribute('alt')) == 194) { + $this->add_report($img); + } else if (preg_match("/^([0-9]*)(k|kb|mb|k bytes|k byte)?$/", + strtolower($img->getAttribute('alt')))) { + $this->add_report($img); + } + } + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_has_alt.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_has_alt.php new file mode 100644 index 0000000000000..8339560ffc7d5 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_has_alt.php @@ -0,0 +1,47 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * All img elements must have an alt attribute. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class img_has_alt extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content. + */ + public function check(): void { + foreach ($this->get_all_elements('img') as $img) { + if (!$img->hasAttribute('alt') || ($img->getAttribute('alt') == '') || ($img->getAttribute('alt') == ' ')) { + if (!($img->hasAttribute('role') && ($img->getAttribute('role') == 'presentation'))) { + $this->add_report($img); + } + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_with_map_has_use_map.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_with_map_has_use_map.php new file mode 100644 index 0000000000000..7f17fbb4b22ac --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/img_with_map_has_use_map.php @@ -0,0 +1,56 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * All img elements with a valid usemap attribute has a matching element. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class img_with_map_has_use_map extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + $maps = $this->get_all_elements('map'); + + foreach ($this->get_all_elements('img') as $img) { + if ($img->hasAttribute('usemap')) { + $usemap = $img->getAttribute('usemap'); + $mapfound = false; + foreach ($maps as $map) { + if (('#'.$map->getAttribute('id') == $usemap) || ('#'.$map->getAttribute('name') == $usemap)) { + $mapfound = true; + } + } + if (!$mapfound) { + $this->add_report($img); + } + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/legend_text_not_empty.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/legend_text_not_empty.php new file mode 100644 index 0000000000000..bf712d6bd1460 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/legend_text_not_empty.php @@ -0,0 +1,46 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * legend text is not empty or whitespace. + * The legend must describe the group of choices. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class legend_text_not_empty extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements('legend') as $legend) { + if (!$legend->nodeValue || trim($legend->nodeValue) == '') { + $this->add_report($legend); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/marquee_is_not_used.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/marquee_is_not_used.php new file mode 100644 index 0000000000000..ee5f02260f66e --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/marquee_is_not_used.php @@ -0,0 +1,37 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_tag_test; + +/** + * Brickfield accessibility HTML checker library. + * + * 'marquee' element is not used. + * This error will be generated for each marquee element. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class marquee_is_not_used extends brickfield_accessibility_tag_test { + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** @var string The tag this test will fire on. */ + public $tag = 'marquee'; +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/no_headings.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/no_headings.php new file mode 100644 index 0000000000000..9159dc3df21a1 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/no_headings.php @@ -0,0 +1,67 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Custom test. + * Checks if content uses heading elements (h1 - h6) at all. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class no_headings extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SUGGESTION; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + global $doclength; + + $doclength = '1800'; + $elements = $this->get_all_elements('p'); + $documentstring = ""; + + foreach ($elements as $element) { + $documentstring .= $element->textContent; + } + + if (strlen($documentstring) > $doclength) { + if (!$this->get_all_elements('h1') + && !$this->get_all_elements('h2') + && !$this->get_all_elements('h3') + && !$this->get_all_elements('h4') + && !$this->get_all_elements('h5') + && !$this->get_all_elements('h6')) { + $noheadings = true; + } else { + $noheadings = false; + } + + if ($noheadings) { + $this->add_report(null, null, false); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/object_must_have_embed.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/object_must_have_embed.php new file mode 100644 index 0000000000000..2301e85970a0a --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/object_must_have_embed.php @@ -0,0 +1,46 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Use the embed element within the object element. + * Each object element must contain an embed element. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class object_must_have_embed extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements('object') as $object) { + if (!$this->element_has_child($object, 'embed')) { + $this->add_report($object); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/object_must_have_title.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/object_must_have_title.php new file mode 100644 index 0000000000000..ac89b7828080e --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/object_must_have_title.php @@ -0,0 +1,46 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * 'object' must have a title. + * 'object' element must contain a title attribute. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class object_must_have_title extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements('object') as $object) { + if (!$object->hasAttribute('title')) { + $this->add_report($object); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/object_must_have_valid_title.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/object_must_have_valid_title.php new file mode 100644 index 0000000000000..ff36dcecdda1e --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/object_must_have_valid_title.php @@ -0,0 +1,57 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * 'object' must have a valid title. + * 'object' element must not have a title attribute with value of null or whitespace. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class object_must_have_valid_title extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** @var \string[][] An array of strings, broken up by language domain. */ + public $strings = + [ + 'en' => ['nbsp', ' ', 'object', 'an object', 'spacer', 'image', 'img', 'photo', ' '], + 'es' => ['nbsp', ' ', 'objeto', 'un objeto', 'espacio', 'imagen', 'img', 'foto', ' '], + ]; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements('object') as $object) { + if ($object->hasAttribute('title')) { + if (trim($object->getAttribute('title')) == '') { + $this->add_report($object); + } else if (!in_array(trim(strtolower($object->getAttribute('title'))), $this->translation())) { + $this->add_report($object); + } + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/strike_is_not_used.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/strike_is_not_used.php new file mode 100644 index 0000000000000..12bbcdacf45c1 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/strike_is_not_used.php @@ -0,0 +1,38 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_tag_test; + +/** + * Brickfield accessibility HTML checker library. + * + * strike element is not used. + * This error will be generated for all strike elements. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class strike_is_not_used extends brickfield_accessibility_tag_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** @var string The tag this test will fire on. */ + public $tag = 'strike'; +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_data_should_have_th.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_data_should_have_th.php new file mode 100644 index 0000000000000..4d77cb3d42391 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_data_should_have_th.php @@ -0,0 +1,69 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_table_test; + +/** + * Brickfield accessibility HTML checker library. + * + * All data tables contain th elements. + * Data tables must have th elements while layout tables can not have th elements. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class table_data_should_have_th extends brickfield_accessibility_table_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + // Remember: We only need to check the first tr in a table and only if there's a single th in there. + foreach ($this->get_all_elements('table') as $table) { + foreach ($table->childNodes as $child) { + if ($this->property_is_equal($child, 'tagName', 'tbody') || $this->property_is_equal($child, 'tagName', 'thead')) { + foreach ($child->childNodes as $tr) { + if (!is_null($tr->childNodes)) { + foreach ($tr->childNodes as $th) { + if ($this->property_is_equal($th, 'tagName', 'th')) { + break 3; + } else { + $this->add_report($table); + break 3; + } + } + } + } + } else if ($this->property_is_equal($child, 'tagName', 'tr')) { + foreach ($child->childNodes as $th) { + if ($this->property_is_equal($th, 'tagName', 'th')) { + break 2; + } else { + $this->add_report($table); + break 2; + } + } + } + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_summary_does_not_duplicate_caption.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_summary_does_not_duplicate_caption.php new file mode 100644 index 0000000000000..c40dc36291ec7 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_summary_does_not_duplicate_caption.php @@ -0,0 +1,54 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * Table summaries do not duplicate the table captions. + * The summary and the caption must be different. Caption identifies the table. Summary describes the table contents. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class table_summary_does_not_duplicate_caption extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements('table') as $table) { + if ($this->element_has_child($table, 'caption') && $table->hasAttribute('summary')) { + foreach ($table->childNodes as $child) { + if ($this->property_is_equal($child, 'tagName', 'caption')) { + $caption = $child; + } + } + if (strtolower(trim($caption->nodeValue)) == + strtolower(trim($table->getAttribute('summary')))) { + $this->add_report($table); + } + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_td_should_not_merge.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_td_should_not_merge.php new file mode 100644 index 0000000000000..6a3867d6fbd24 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_td_should_not_merge.php @@ -0,0 +1,58 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_table_test; + +/** + * Brickfield accessibility HTML checker library. + * + * All table cells should not be merged. + * The table element, for all table cells should contain no colspans or rowspans. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class table_td_should_not_merge extends brickfield_accessibility_table_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content + */ + public function check(): void { + foreach ($this->get_all_elements('table') as $table) { + foreach ($table->childNodes as $child) { + if ($this->property_is_equal($child, 'tagName', 'tbody')) { + foreach ($child->childNodes as $tr) { + if (!is_null($tr->childNodes)) { + foreach ($tr->childNodes as $td) { + if (isset($td->tagName) + && ($td->tagName == 'td' || $td->tagName == 'th') + && ($td->hasAttribute('colspan') || $td->hasAttribute('rowspan'))) { + $this->add_report($td); + } + } + } + } + } + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_th_should_have_scope.php b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_th_should_have_scope.php new file mode 100644 index 0000000000000..4ef0d2237f714 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/checks/table_th_should_have_scope.php @@ -0,0 +1,47 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\common\brickfield_accessibility_test; + +/** + * Brickfield accessibility HTML checker library. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class table_th_should_have_scope extends brickfield_accessibility_test { + + /** @var int The default severity code for this test. */ + public $defaultseverity = \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE; + + /** + * The main check function. This is called by the parent class to actually check content. + */ + public function check() { + foreach ($this->get_all_elements('th') as $th) { + if ($th->hasAttribute('scope')) { + if ($th->getAttribute('scope') != 'col' && $th->getAttribute('scope') != 'row') { + $this->add_report($th); + } + } else { + $this->add_report($th); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/html_elements.php b/admin/tool/brickfield/classes/local/htmlchecker/common/html_elements.php new file mode 100644 index 0000000000000..33c96463567d8 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/html_elements.php @@ -0,0 +1,79 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +use tool_brickfield\local\htmlchecker\brickfield_accessibility; + +/** + * This is a helper class which organizes all the HTML tags into groups for finding. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class html_elements { + /** + * @var array An array of HTML tag names and their attributes + */ + public static $htmlelements = [ + 'img' => ['text' => false], + 'p' => ['text' => true], + 'pre' => ['text' => true], + 'span' => ['text' => true], + 'div' => ['text' => true], + 'applet' => ['text' => false], + 'embed' => ['text' => false, 'media' => true], + 'object' => ['text' => false, 'media' => true], + 'area' => ['imagemap' => true], + 'b' => ['text' => true, 'non-emphasis' => true], + 'i' => ['text' => true, 'non-emphasis' => true], + 'font' => ['text' => true, 'font' => true], + 'h1' => ['text' => true, 'header' => true], + 'h2' => ['text' => true, 'header' => true], + 'h3' => ['text' => true, 'header' => true], + 'h4' => ['text' => true, 'header' => true], + 'h5' => ['text' => true, 'header' => true], + 'h6' => ['text' => true, 'header' => true], + 'ul' => ['text' => true, 'list' => true], + 'dl' => ['text' => true, 'list' => true], + 'ol' => ['text' => true, 'list' => true], + 'blockquote' => ['text' => true, 'quote' => true], + 'q' => ['text' => true, 'quote' => true], + 'acronym' => ['acronym' => true, 'text' => true], + 'abbr' => ['acronym' => true, 'text' => true], + 'input' => ['form' => true], + 'select' => ['form' => true], + 'textarea' => ['form' => true], + brickfield_accessibility::BA_ERROR_TAG => ['text' => true], + ]; + + /** + * Retrieves elements by an option. + * @param string $option The option to search fore + * @param bool $value Whether the option should be true or false + * @return array An array of HTML tag names + */ + public static function get_elements_by_option(string $option, bool $value = true): array { + $results = []; + foreach (self::$htmlelements as $k => $element) { + if (isset($element[$option]) && ($element[$option] == $value)) { + $results[] = $k; + } + } + return $results; + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/input_has_label.php b/admin/tool/brickfield/classes/local/htmlchecker/common/input_has_label.php new file mode 100644 index 0000000000000..17861d26b7412 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/input_has_label.php @@ -0,0 +1,70 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +/** + * Base test class for tests which checks that the given input tag has an associated lable tag. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class input_has_label extends brickfield_accessibility_test { + + // To override, just override the tag and type variables, and use $no_type = true if it is a special form tag like textarea. + + /** @var string The tag name that this test applies to */ + public $tag = 'input'; + + /** @var string The type of input tag this is */ + public $type = 'text'; + + /** @var bool Wehether or not we should check the type attribute of the input tags */ + public $notype = false; + + /** + * Iterate through all the elemetns using the $tag tagname and the $type attribute (if appropriate) + * and then check it against a list of all LABEL tags. + */ + public function check() { + foreach ($this->get_all_elements('label') as $label) { + if ($label->hasAttribute('for')) { + $labels[$label->getAttribute('for')] = $label; + } else { + foreach ($label->childNodes as $child) { + if (property_exists($child, 'tagName') && + ($child->tagName == $this->tag) && + (($child->getAttribute('type') == $this->type) || $this->notype)) { + $inputinlabel[$child->getAttribute('name')] = $child; + } + } + } + } + foreach ($this->get_all_elements($this->tag) as $input) { + if ($input->getAttribute('type') == $this->type || $this->notype) { + if (!$input->hasAttribute('title')) { + if (!isset($inputinlabel[$input->getAttribute('name')])) { + if (!isset($labels[$input->getAttribute('id')]) || + (trim($labels[$input->getAttribute('id')]->nodeValue) == '')) { + $this->add_report($input); + } + } + } + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/input_tab_index.php b/admin/tool/brickfield/classes/local/htmlchecker/common/input_tab_index.php new file mode 100644 index 0000000000000..cdeeca1ad25f9 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/input_tab_index.php @@ -0,0 +1,46 @@ +. + +namespace tool_brickfield\local\htmlchecker\common; + +/** + * Helper base class to check that input tags have an appropriate tab order + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class input_tab_index extends brickfield_accessibility_test { + /** @var string The tag name that this test applies to */ + public $tag; + + /** @var string The type of input tag this is */ + public $type; + + /** @var bool Wehether or not we should check the type attribute of the input tags */ + public $notype = false; + + /** Iterate through all the input items and make sure the tabindex exists and is numeric. */ + public function check() { + foreach ($this->get_all_elements($this->tag) as $element) { + if (($element->getAttribute('type') == $this->type) + && (!($element->hasAttribute('tabindex')) + || !is_numeric($element->getAttribute('tabindex')))) { + $this->add_report($element); + } + } + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/resources/emoticons.txt b/admin/tool/brickfield/classes/local/htmlchecker/common/resources/emoticons.txt new file mode 100644 index 0000000000000..b9e7deb15e903 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/resources/emoticons.txt @@ -0,0 +1,137 @@ +:) +:-) +:^) +=) +B) +8) +c8 +cB +=] +:] +x] +:o) +:-D +:D +=D +:-( +:( +=( +D: +D= +38* +]:8) +:(] +:@ +=@ +;-) +;) +*) +X( +(|) +(_|_) +(_:_) +8c +Bc +B( +|8c +|8C +:[ +=[ +=C +:P +:p +:Þ +:b +|D +:O +=O +:/ +:-/ +:-\ +:\ +8/ +8\ +>/ +>\ +=/ +:| +:l +=| +xP +XP +xD +XD +:S +:s +^o) +=S +:3 +>:3 +>=3or=3 +:E +=E +:F +=F +:X +:# +:-{) +:-* +>:O +XO +:-(o) +>:@ +>=O +D=< +>:( +>[ +D< +>:) +}:) +0:) +O=) +O=] +<3 +x3♥ +-- +X3 +%-) +%-( +8-) +8-0 +80 +X-( +X[ +:-& +=& +;^) +:-} +=} +=\ +o____0 +<:} +>:L +>=L +:9 +=9 +>:D +>=D +:0->-<|: +o->-<}: +})i({ +(=C +V.v.V +_/\___\o/__ +_/\_*\o/*__ +@=:-) +<:D-|< +^_^ +=^_^= +\m/(>_<)\m/ \ No newline at end of file diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/resources/iso639.txt b/admin/tool/brickfield/classes/local/htmlchecker/common/resources/iso639.txt new file mode 100644 index 0000000000000..d024ed67dd993 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/resources/iso639.txt @@ -0,0 +1,200 @@ +bh +bi +nb +bs +br +bg +my +es +ca +km +ch +ce +ny +ny +zh +za +cu +cu +cv +kw +co +cr +hr +cs +da +dv +dv +nl +dz +en +eo +et +ee +fo +fj +fi +nl +fr +ff +gd +gl +lg +ka +de +ki +el +kl +gn +gu +ht +ht +ha +he +hz +hi +ho +hu +is +io +ig +id +ia +ie +iu +ik +ga +it +ja +jv +kl +kn +kr +ks +kk +ki +rw +ky +kv +kg +ko +kj +ku +kj +ky +lo +la +lv +lb +li +li +li +ln +lt +lu +lb +mk +mg +ms +ml +dv +mt +gv +mi +mr +mh +ro +ro +mn +na +nv +nv +nd +nr +ng +ne +nd +se +no +nb +nn +ii +ny +nn +ie +oc +oj +cu +cu +cu +or +om +os +os +pi +pa +ps +fa +pl +pt +pa +ps +qu +ro +rm +rn +ru +sm +sg +sa +sc +gd +sr +sn +ii +sd +si +si +sk +sl +so +st +nr +es +su +sw +ss +sv +tl +ty +tg +ta +tt +te +th +bo +ti +to +ts +tn +tr +tk +tw +ug +uk +ur +ug +uz +ca +ve +vi +vo +wa +cy +fy +wo +xh +yi +yo +za +zu diff --git a/admin/tool/brickfield/classes/local/htmlchecker/common/resources/placeholder.txt b/admin/tool/brickfield/classes/local/htmlchecker/common/resources/placeholder.txt new file mode 100644 index 0000000000000..263517fa0a0db --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/common/resources/placeholder.txt @@ -0,0 +1,9 @@ +title +untitled +untitled document +this is the title +the title +  + +new page +new \ No newline at end of file diff --git a/admin/tool/brickfield/classes/local/htmlchecker/guidelines/brickfield_guideline.php b/admin/tool/brickfield/classes/local/htmlchecker/guidelines/brickfield_guideline.php new file mode 100644 index 0000000000000..b390caf0897ee --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/guidelines/brickfield_guideline.php @@ -0,0 +1,53 @@ +. + +namespace tool_brickfield\local\htmlchecker\guidelines; + +use tool_brickfield\local\htmlchecker\brickfield_accessibility_guideline; +use tool_brickfield\manager; + +/** + * Brickfield Guideline + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_guideline extends brickfield_accessibility_guideline { + + /** + * @var array An array of test class names which will be called for this guideline + */ + public $tests = []; + + /** + * brickfield_guideline constructor. + * @param \DOMDocument $dom + * @param \brickfield_accessibility_css $css + * @param array $path + * @param null $arg + * @param string $domain + * @param bool $cmsmode + * @throws \dml_exception + */ + public function __construct(&$dom, &$css, array &$path, $arg = null, string $domain = 'en', bool $cmsmode = false) { + global $DB; + + $this->tests = array_values($DB->get_records_menu(manager::DB_CHECKS, null, '', 'id,shortname')); + + parent::__construct($dom, $css, $path, $arg, $domain, $cmsmode); + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/guidelines/brickfield_textonly_guideline.php b/admin/tool/brickfield/classes/local/htmlchecker/guidelines/brickfield_textonly_guideline.php new file mode 100644 index 0000000000000..57936bdf71d9e --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/guidelines/brickfield_textonly_guideline.php @@ -0,0 +1,47 @@ +. + +namespace tool_brickfield\local\htmlchecker\guidelines; + +use tool_brickfield\local\htmlchecker\brickfield_accessibility_guideline; + +/** + * Brickfield Education Labs Guideline + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class brickfield_textonly_guideline extends brickfield_accessibility_guideline { + + /** + * @var array An array of test class names which will be called for this guideline + */ + public $tests = array( + 'aSuspiciousLinkText', + 'cssTextHasContrast', + 'contentTooLong', + 'imgAltIsDifferent', + 'imgAltIsTooLong', + 'imgAltNotPlaceHolder', + 'imgAltNotEmptyInAnchor', + 'imgHasAlt', + 'imgWithMapHasUseMap', + 'tableDataShouldHaveTh', + 'tableThShouldHaveScope', + 'tableTdShouldNotMerge', + ); +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/guidelines/translations/en.txt b/admin/tool/brickfield/classes/local/htmlchecker/guidelines/translations/en.txt new file mode 100644 index 0000000000000..42deb1761d197 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/guidelines/translations/en.txt @@ -0,0 +1,31 @@ +"a_links_dont_open_new_window","Links should not open a new window without warning","

Links which open a new window using the ""target"" attribute should warn users.

Example

Wrong

<a href=""webpage.html"">View this page</a>

Right

<a href=""webpage.html"">View this page (opens in new window)</a>

","1" +"a_must_contain_text","Links should contain text","

Because many users of screen readers use links to navigate the page, providing links with no text (or with images that have empty 'alt' attributes and no other readable text) hinders these users.

","1" +"area_dont_open_new_window","No ""area"" elements should open a new window without warning","

No area elements should open a new window without warning.

Example

Wrong

<map name=""anatomymap""> <area shape=""rect"" coords=""0,0,82,126"" href=""skull.htm"" target=""_blank"" alt=""Human skull""/> </map>

Right

<map name=""anatomymap""> <area shape=""rect"" coords=""0,0,82,126"" href=""skull.htm"" target=""_blank"" alt=""Human skull (opens in new window)""/> </map>

","1" +"area_has_alt_value","All ""area"" elements should have an ""alt"" attribute","

All area elements within a map should have an ""alt"" attribute.

Example

Wrong

<map name=""anatomymap""> <area shape=""rect"" coords=""0,0,82,126"" href=""skull.htm""/> </map>

Right

<map name=""anatomymap""> <area shape=""rect"" coords=""0,0,82,126"" href=""skull.htm"" alt=""Human skull""/> </map>

","1" +"a_suspicious_link_text","Link text should be descriptive","

Links should be descriptive of the content they're linking to, such as 'Project guidelines' rather than 'guidelines.html' or 'Click here'.

Example

Wrong

<a href=""webpage.html"">Click here</a>

Right

<a href=""webpage.html"">View Project guidelines here</a>

","1" +"basefont_is_not_used","The ""Basefont"" tag should not be used","

The basefont tag is deprecated and should not be used. CSS properties should be used instead.

","1" +"blink_is_not_used","The ""blink"" tag should not be used","

The blink tag should not be used, as it can hinder some users with cognitive disabilities or photosensitive epilepsy or eyesight issues.

Example

Wrong

<blink>Important text</blink>

Right

<strong>Important text</strong>

","1" +"bold_is_not_used","The ""b"" (bold) element should not be used","

The b (bold) element provides no emphasis for non-sighted readers. Use the strong tag instead.

Example

Wrong

<p>This is <b>really important text</b>.</p>

Right

<p>This is <strong>really important text</strong>.</p>

","1" +"content_too_long","Content length should not exceed 3000 words.","

For content longer than 3000 words, consider splitting it up into multiple documents. This makes it easier for students to navigate, process and retain the information, especially those with memory, concentration, reading or mental health issues.

","3" +"css_text_has_contrast","Insufficient text color contrast with the background","

Text color should be easily viewable and should not be the only indicator of meaning or function. Color contrast should have at least a 4.5:1 ratio for small text and 3:1 ratio for large text.

","1" +"embed_has_associated_no_embed","All ""embed"" elements have an associated ""noembed"" element","

Because some users cannot use the embed element, provide alternative content in a noembed element.

Example

Wrong

<embed src=""multimedia.mov""/>

Right

<embed src=""multimedia.mov""/><noembed>Multimedia with <a href=""multimedia.html"">an available transcript</a>.</noembed>

","1" +"header_h3","The header following an h3 should be h1, h2, h3 or h4","

Well-structured documents are easier for all users to navigate. The title of a page should have a heading level of H2, each section should have a heading level of H3, each sub-section should be H4, etc.

","3" +"headers_have_text","Headings should contain text","

Sighted and screen reader users depend on headings to organize and navigate the content on the page. Headings should not be empty and should represent an accurate outline of the relevant content

","1" +"i_is_not_used","The ""i"" (italic) element is not used","

The i (italic) element provides no emphasis for non-sighted readers. Use the em tag instead.

Impact

The i (italic) element only conveys appearance, wheras the em element conveys meaning.

Example

Wrong

<p>This is <i>really important text</i>.</p>

Right

<p>This is <em>really important text</em>.</p>

","1" +"img_alt_is_different","Alternative Text should not be the image filename","

Alternative Text (Alt Text) is an alternative (non-visual) way to describe the meaning of an image. Please provide a brief description of the image for a screen reader user. Note: It should not be the image file name.

","1" +"img_alt_is_too_long","Alternative Text is more than the maximum allowed characters","

Alternative Text (Alt Text) is an alternative (non-visual) way to describe the meaning of an image. It should be concise, relevant, meaningful, and no longer than 125 characters ideally.

","1" +"img_alt_not_empty_in_anchor","Alt text for all img elements used as source anchors should not be empty","

Alternative Text (Alt Text) is an alternative (non-visual) way to describe the destination of an image within an anchor link. Please provide a brief description of the image link destination for a screen reader user.

","1" +"img_alt_not_place_holder","Images should not have a simple placeholder text as an ""alt"" attribute","

Any image that is not used for decorativon or which is purely for layout purposes cannot have an ""alt"" attribute that consists solely of placeholders. Placeholders include:

  • nbsp
  • &nbsp;
  • spacer
  • image
  • img
  • photo

Example

Wrong

<img src=""dog.jpg"" alt=""image"">

Right

<img src=""dog.jpg"" alt=""A photograph of a dog"">

","1" +"img_has_alt","Image elements should have an ""alt"" attribute","

Alternative Text (Alt Text) is an alternative (non-visual) way to describe the meaning of an image. Please provide a brief description of the image for a screen reader user. Note: It should not be the image file name.

","1" +"img_with_map_has_use_map","Any image with an ""ismap"" attribute have a valid ""usemap"" attribute","

If an image has an ""ismap"" attribute, it should also have a ""usemap"" attribute.

","1" +"legend_text_not_empty","""Legend"" text should not contain just whitespace","

If a legend element is used in a fieldset, the legend should not contain empty text.

Example

Wrong

<fieldset> <legend> </legend> <label for=""name"">Name:</label> <input type=""text"" size=""30"" id=""name""/><br /> <label for=""email"">Email:</label> <input type=""text"" size=""30"" id=""email""/><br /></fieldset>

Right

<fieldset> <legend>Personal Information:</legend> <label for=""name"">Name:</label> <input type=""text"" size=""30"" id=""name""/><br /> <label for=""email"">Email:</label> <input type=""text"" size=""30"" id=""email""/><br /></fieldset>

","1" +"marquee_is_not_used","The ""marquee"" tag should not be used","

The marquee element is difficult for users to read and is not a standard HTML element. Try to find another way to convey the importance of this text.

Example

Wrong

<marquee>This is really hard to read</marquee>

Right

<strong>This is much easier to read</strong>

","1" +"no_headings","Consider adding headings to your document to create more structure","

If appropriate, add headings to the page to organize the content for sighted and screen reader users. The headings should represent an accurate outline of the content

","3" +"object_must_have_embed","Every object should contain an ""embed"" element","

Every object element should also contain an embed element.

Example

Wrong

<object data=""movie.mov""></object>

Right

<object data=""movie.mov""><embed src=""movie.mov""></embed></object>

","1" +"object_must_have_title","Objects should have a title attribute","

All object elements should contain a ""title"" attribute.

Example

Wrong

<object src=""widget.html""></object>

Right

<object src=""widget.html"" title=""A small web widget""></object>

","1" +"object_must_have_valid_title","Objects should not have an empty title attribute","

All object elements should have a ""title"" attribute which is not empty.

Example

Wrong

<object src=""widget.html"" title=""""></object>

Right

<object src=""widget.html"" title=""A small web widget""></object>

","1" +"strike_is_not_used","The ""strike"" (strike-through) element should not be used","

The strike element is deprecated and should not be used. It provides no text meaning for non-sighted readers. Use the del (deleted) tag instead.

Example

Wrong

<p><strike>(10 remaining)</strike> All sold out!</p>

Right

<p><del>(10 remaining)</del> All sold out!</p>

","1" +"table_data_should_have_th","No table headers found","

Add a table header because it provides a description of the table structure for sighted and screen reader users.

","1" +"table_summary_does_not_duplicate_caption","Table ""summary"" elements should not duplicate the ""caption"" element","

The summary and the caption should be different, as both provide different information. A caption","1" +"table_td_should_not_merge","Tables should have no merged cells","

Tables which contain merged cells are more problematic for accessibility tools such as screen readers to read correctly.

","1" +"table_th_should_have_scope", "No row or column scopes declarations found in headers of the table", "

Scope declarations in headers organize and define table data by row/column for sighted and screen reader users.

", "1" diff --git a/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_array.php b/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_array.php new file mode 100644 index 0000000000000..5dacefdfd5450 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_array.php @@ -0,0 +1,57 @@ +. + +namespace tool_brickfield\local\htmlchecker\reporters; + +use tool_brickfield\local\htmlchecker\brickfield_accessibility_reporter; + +/** + * An array reporter that simply returns an unformatted and nested PHP array of tests and report objects + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class report_array extends brickfield_accessibility_reporter { + + /** + * Generates a static list of errors within a div. + * @return array|null A nested array of tests and problems with Report Item objects + */ + public function get_report() { + $results = $this->guideline->get_report(); + if (!is_array($results)) { + return null; + } + foreach ($results as $testname => $test) { + $translation = $this->guideline->get_translation($testname); + $output[$testname]['severity'] = $this->guideline->get_severity($testname); + $output[$testname]['title'] = $translation['title']; + $output[$testname]['body'] = $translation['description']; + foreach ($test as $k => $problem) { + if (is_object($problem)) { + $output[$testname]['problems'][$k]['element'] = htmlentities($problem->get_html()); + $output[$testname]['problems'][$k]['line'] = $problem->get_line(); + if ($problem->message) { + $output[$testname]['problems']['message'] = $problem->message; + } + $output[$testname]['problems']['pass'] = $problem->pass; + } + } + } + return $output; + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_codehighlight.php b/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_codehighlight.php new file mode 100644 index 0000000000000..60f33b6c67696 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_codehighlight.php @@ -0,0 +1,78 @@ +. + +namespace tool_brickfield\local\htmlchecker\reporters; + +use tool_brickfield\local\htmlchecker\brickfield_accessibility; + +/** + * Returns a formatted HTML view of the problems + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class report_codehighlight extends \tool_brickfield\local\htmlchecker\brickfield_accessibility_reporter { + + /** + * @var array An array of the classnames to be associated with items + */ + public $classnames = [brickfield_accessibility::BA_TEST_SEVERE => 'testlevel_severe', + brickfield_accessibility::BA_TEST_MODERATE => 'testlevel_moderate', + brickfield_accessibility::BA_TEST_SUGGESTION => 'testlevel_suggestion', + ]; + + /** + * The getReport method - we iterate through every test item and + * add additional attributes to build the report UI. + * @return string A fully-formed HTML document. + */ + public function get_report(): string { + $problems = $this->guideline->get_report(); + if (is_array($problems)) { + foreach ($problems as $testname => $test) { + if (!isset($this->options->display_level) || + ($this->options->display_level >= $test['severity'] && is_array($test))) { + foreach ($test as $problem) { + if (is_object($problem) + && property_exists($problem, 'element') + && is_object($problem->element)) { + // Wrap each error with a "wrapper" node who's tag name is the severity + // level class. We'll fix this later and change them back to 'span' elements + // after we have converted the HTML code to entities. + $severitywrapper = $this->dom->createElement($this->classnames[$test['severity']]); + $severitywrapper->setAttribute('class', $this->classnames[$test['severity']] .' '. $testname); + $severitywrapper->setAttribute('test', $testname); + $severitywrapper->appendChild($problem->element->cloneNode(true)); + $parent = $problem->element->parentNode; + if (is_object($parent)) { + $parent->replaceChild($severitywrapper, $problem->element); + } + } + } + } + } + } + $this->dom->formatOutput = true; + $html = htmlspecialchars($this->dom->saveHTML()); + $html = str_replace('"', '"', $html); + foreach ($this->classnames as $name) { + $html = preg_replace('/<'. $name .'([^&]+)+\>/', '', $html); + $html = str_replace('</'. $name .'>', '', $html); + } + return $html; + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_demo.php b/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_demo.php new file mode 100644 index 0000000000000..cc6db6868ad1e --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_demo.php @@ -0,0 +1,163 @@ +. + +namespace tool_brickfield\local\htmlchecker\reporters; + +use tool_brickfield\local\htmlchecker\brickfield_accessibility; +use tool_brickfield\local\htmlchecker\brickfield_accessibility_reporter; + +/** + * Returns the entire document marked-up to highlight problems. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class report_demo extends brickfield_accessibility_reporter { + + /** + * @var array An array of the classnames to be associated with items + */ + public $classnames = [ + brickfield_accessibility::BA_TEST_SEVERE => 'testlevel_severe', + brickfield_accessibility::BA_TEST_MODERATE => 'testlevel_moderate', + brickfield_accessibility::BA_TEST_SUGGESTION => 'testlevel_suggestion', + ]; + + /** + * The get_report method - we iterate through every test item and + * add additional attributes to build the report UI. + * @return string A fully-formed HTML document. + */ + public function get_report(): string { + $problems = $this->guideline->get_report(); + if (is_array($problems)) { + foreach ($problems as $testname => $test) { + if (!isset($this->options->display_level) || + ($this->options->display_level >= $test['severity'] && is_array($test))) { + foreach ($test as $problem) { + if (is_object($problem) && property_exists($problem, 'element') && is_object($problem->element)) { + $existing = $problem->element->getAttribute('style'); + $problem->element->setAttribute('style', + $existing .'; border: 2px solid red;'); + if (isset($this->options->image_url)) { + $image = $this->dom->createElement('img'); + $image = $problem->element->parentNode->insertBefore($image, $problem->element); + $image->setAttribute('alt', $testname); + if ($problem->message) { + $image->setAttribute('title', $problem->message); + } + $image->setAttribute('src', $this->options->image_url[$test['severity']]); + } + } + } + } + } + } + return $this->complete_urls($this->dom->saveHTML(), implode('/', $this->path)); + } + + + /** + * Finds the final postion of a needle in the haystack. + * + * @param mixed $haystack + * @param mixed $needle + * @param mixed $occurance + * @param int $pos + * @return false|int + */ + public function strnpos($haystack, $needle, $occurance, int $pos = 0) { + for ($i = 1; $i <= $occurance; $i++) { + $pos = strpos($haystack, $needle, $pos) + 1; + } + return $pos - 1; + } + + /** + * A helper function for completeURLs. Parses a URL into an the scheme, host, and path + * @param string $url The URL to parse + * @return array An array that includes the scheme, host, and path of the URL + */ + public function parse_url(string $url): array { + $pattern = "/^(?:(http[s]?):\/\/(?:(.*):(.*)@)?([^\/]+))?((?:[\/])?(?:[^\.]*?)?(?:[\/])?)?(?:([^\/^\.]+)\." . + "([^\?]+))?(?:\?(.+))?$/i"; + preg_match($pattern, $url, $matches); + + $uriparts["scheme"] = $matches[1]; + $uriparts["host"] = $matches[4]; + $uriparts["path"] = $matches[5]; + + return $uriparts; + } + + /** + * Turns all relative links to absolute links so that the page can be rendered correctly. + * @param string $html A complete HTML document + * @param string $url The absolute URL to the document + * @return string A HTML document with all the relative links converted to absolute links + */ + public function complete_urls(string $html, string $url) { + $uriparts = $this->parse_url($url); + $path = trim($uriparts["path"], "/"); + $hosturl = trim($uriparts["host"], "/"); + + $host = $uriparts["scheme"]."://".$hosturl."/".$path."/"; + $hostnopath = $uriparts["scheme"]."://".$hosturl."/"; + + // Proxifies local META redirects. + $html = preg_replace('@\s"\']+)\\1[^>]*>/i', + "
", $html); + + // Matches '/[any assortment of chars or nums]/../'. + $html = preg_replace("#\/(\w*?)\/\.\.\/(.*?)>#ims", "/\$2>", $html); + + // Matches '/./'. + $html = preg_replace("#\/\.\/(.*?)>#ims", "/\$1>", $html); + + // Handles CSS2 imports. + if (strpos($html, "import url(\"http") == false && (strpos($html, "import \"http") == false) + && strpos($html, "import url(\"www") == false && (strpos($html, "import \"www") == false)) { + $pattern = "#import .(.*?).;#ims"; + $mainurl = substr($host, 0, $this->strnpos($host, "/", 3)); + $replace = "import '".$mainurl."\$1';"; + $html = preg_replace($pattern, $replace, $html); + } + return $html; + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_static.php b/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_static.php new file mode 100644 index 0000000000000..c247338020bc9 --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_static.php @@ -0,0 +1,140 @@ +. + +namespace tool_brickfield\local\htmlchecker\reporters; + +use tool_brickfield\local\htmlchecker\brickfield_accessibility_reporter; + +/** + * A static reporter. + * + * Generates a list of errors which do not pass and their severity. + * + * This is just a demonstration of what you can do with a reporter. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class report_static extends brickfield_accessibility_reporter { + /** + * Generates a static list of errors within a div. + * @return array A fully-formatted report + */ + public function get_report(): array { + $output = []; + foreach ($this->guideline->get_report() as $testname => $test) { + $severity = $this->guideline->get_severity($testname); + $translation = $this->guideline->get_translation($testname); + + if (isset($translation['title'])) { + $title = $translation['title']; + } else { + $title = null; + } + if (isset($translation['description'])) { + $description = $translation['description']; + } else { + $description = null; + } + + switch ($severity) { + case \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SEVERE: + $severitylevel = 'Error'; + $severitynumber = 1; + break; + case \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_MODERATE: + $severitylevel = 'Warning'; + $severitynumber = 2; + break; + case \tool_brickfield\local\htmlchecker\brickfield_accessibility::BA_TEST_SUGGESTION: + $severitylevel = 'Suggestion'; + $severitynumber = 3; + break; + } + + if (is_array($test)) { + $testcount = 0; + foreach ($test as $problem) { + $testresult = []; + if (is_object($problem)) { + $testresult['text_type'] = $problem->message; + if ($testname === "cssTextHasContrast" || $testname === "cssTextStyleEmphasize") { + $stylevalue = $problem->message; + $hexcolors = []; + $stylematches = []; + $weightmatches = []; + + preg_match_all("/(#[0-9a-f]{6}|#[0-9a-f]{3})/", $stylevalue, $hexcolors); + preg_match("/font-style:\s([a-z]*);/", $stylevalue, $stylematches); + preg_match("/font-weight:\s([a-z]*);/", $stylevalue, $weightmatches); + $hexcolors = array_unique($hexcolors[0]); + + $testresult['colors'] = $hexcolors; + $testresult['back_color'] = $hexcolors[0]; + $testresult['fore_color'] = $hexcolors[1]; + $testresult['font_style'] = $stylematches[1]; + $testresult['font_weight'] = $weightmatches[1]; + if ($testresult['font_weight'] === "bolder") { + $testresult['font_weight'] = "bold"; + } + $testresult['text_type'] = preg_replace('/(?=:).+/', '', $problem->message); + + } + + $testresult['type'] = $testname; + $testresult['lineNo'] = $problem->line; + + if (isset($testresult['element'])) { + $testresult['element'] = $problem->element->tagName; + } + + // Edit description for certain cases. + switch($testname) { + case 'videosEmbeddedOrLinkedNeedCaptions': + if ($problem->manual == true || $testcount > 0) { + if ($problem->manual == true) { + $testcount++; + } + $testresult['description'] = $description."

⚠️ ".$testcount. + ' items require manual verification because unable to detect captions.' . + ' This is most likely due to the video being unlisted, private, or deleted.

'; + } else { + $testresult['description'] = $description; + } + break; + + default: + $testresult['description'] = $description; + break; + } + + $testresult['severity'] = $severitylevel; + $testresult['severity_num'] = $severitynumber; + $testresult['title'] = $title; + $testresult['path'] = count($this->path) > 1 ? $this->path[1] : "None"; + $testresult['html'] = $problem->get_html(); + $testresult['state'] = $problem->state; + $testresult['manual'] = $problem->manual; + } + + $output[] = $testresult; + } + } + } + return $output; + } +} diff --git a/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_xml.php b/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_xml.php new file mode 100644 index 0000000000000..58562eda5591d --- /dev/null +++ b/admin/tool/brickfield/classes/local/htmlchecker/reporters/report_xml.php @@ -0,0 +1,67 @@ +. + +namespace tool_brickfield\local\htmlchecker\reporters; + +use tool_brickfield\local\htmlchecker\brickfield_accessibility_reporter; + +/** + * Returns an ATOM feed of all the issues - useful to run this as a web service + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class report_xml extends brickfield_accessibility_reporter { + + /** + * Generates an ATOM feed of accessibility problems + * @return string|null A nested array of tests and problems with Report Item objects + */ + public function get_report() { + $output = " + "; + $results = $this->guideline->getReport(); + if (!is_array($results)) { + return null; + } + foreach ($results as $testname => $test) { + $translation = $this->guideline->get_translation($testname); + $output .= "\n\t + ". date('c') .""; + $output .= "\n\t". $translation['title'] .""; + $output .= "\n\t"; + $output .= "\n\t"; + foreach ($test as $problem) { + if (is_object($problem)) { + $output .= "\n\tget_html()) . + "]]>"; + $output .= "\n\t". $problem->get_line() .""; + if ($problem->message) { + $output .= "\n\t$problem->message"; + } + $output .= "\n\t$problem->pass"; + } + } + $output .= "\n\t"; + $output .= ""; + } + $output .= ""; + return $output; + } +} diff --git a/admin/tool/brickfield/classes/local/tool/activityresults.php b/admin/tool/brickfield/classes/local/tool/activityresults.php new file mode 100644 index 0000000000000..9c03391c4cd69 --- /dev/null +++ b/admin/tool/brickfield/classes/local/tool/activityresults.php @@ -0,0 +1,85 @@ +. + +namespace tool_brickfield\local\tool; + +use tool_brickfield\sitedata; + +/** + * Class activityresults. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class activityresults extends tool { + + /** + * Provide a name for this tool, suitable for display on pages. + * @return mixed|string + * @throws \coding_exception + */ + public static function toolname(): string { + return get_string('activityresults:toolname', 'tool_brickfield'); + } + + /** + * Provide a short name for this tool, suitable for menus and selectors. + * @return mixed|string + * @throws \coding_exception + */ + public static function toolshortname(): string { + return get_string('activityresults:toolshortname', 'tool_brickfield'); + } + + /** + * Provide a lowercase name identifying this plugin. Should really be the same as the directory name. + * @return string + */ + public function pluginname(): string { + return 'activityresults'; + } + + /** + * Return the data for renderer / template display. + * @return \stdClass + * @throws \coding_exception + * @throws \dml_exception + */ + protected function fetch_data(): \stdClass { + $filter = $this->get_filter(); + if (!$filter->validate_filters()) { + return (object)[ + 'valid' => false, + 'error' => $filter->get_errormessage(), + ]; + } + + $data = (object)[ + 'valid' => true, + 'error' => '', + 'data' => (new sitedata())->get_component_data($filter), + ]; + + if ($filter->categoryid != 0) { + $data->countdata = count($filter->courseids); + } else { + $data->countdata = sitedata::get_total_courses_checked(); + } + + return $data; + } +} diff --git a/admin/tool/brickfield/classes/local/tool/advanced.php b/admin/tool/brickfield/classes/local/tool/advanced.php new file mode 100644 index 0000000000000..7d6a43fb907f6 --- /dev/null +++ b/admin/tool/brickfield/classes/local/tool/advanced.php @@ -0,0 +1,66 @@ +. + +namespace tool_brickfield\local\tool; + +/** + * Class advanced. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class advanced extends tool { + + /** + * Provide a name for this tool, suitable for display on pages. + * @return mixed|string + * @throws \coding_exception + */ + public static function toolname() { + return get_string('advanced:toolname', 'tool_brickfield'); + } + + /** + * Provide a short name for this tool, suitable for menus and selectors. + * @return mixed|string + * @throws \coding_exception + */ + public static function toolshortname() { + return get_string('advanced:toolshortname', 'tool_brickfield'); + } + + /** + * Provide a lowercase name identifying this plugin. Should really be the same as the directory name. + * @return string + */ + public function pluginname() { + return 'advanced'; + } + + /** + * Return the data for renderer / template display. + * @return \stdClass + */ + protected function fetch_data(): \stdClass { + $data = (object)[ + 'valid' => true, + 'error' => '', + ]; + + return $data; + } +} diff --git a/admin/tool/brickfield/classes/local/tool/bfpdf.php b/admin/tool/brickfield/classes/local/tool/bfpdf.php new file mode 100644 index 0000000000000..0f040094bc712 --- /dev/null +++ b/admin/tool/brickfield/classes/local/tool/bfpdf.php @@ -0,0 +1,53 @@ +. + +/** + * tool_brickfield bfpdf + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs, https://brickfield.ie + * @author Max Larkin + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\tool; + +use tool_brickfield\accessibility; + +defined('MOODLE_INTERNAL') || die; +require_once($CFG->libdir . '/pdflib.php'); + +/** + * tool_brickfield bfpdf + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs, https://brickfield.ie + * @author Max Larkin + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class bfpdf extends \pdf { + /** + * Overriding the footer function in TCPDF. + */ + public function Footer() { + $this->SetY(-25); + $this->SetFont('helvetica', 'I', 10); + + $this->write(10, 'Powered by ', '', 0, 'C', true, 0, false, false, 0); + $this->image(accessibility::get_file_path('/pix/pdf/logo-black.png'), + '', '', 34, '', 'PNG', '', '', false, 300, 'C'); + } +} diff --git a/admin/tool/brickfield/classes/local/tool/checktyperesults.php b/admin/tool/brickfield/classes/local/tool/checktyperesults.php new file mode 100644 index 0000000000000..cb00ebacc818a --- /dev/null +++ b/admin/tool/brickfield/classes/local/tool/checktyperesults.php @@ -0,0 +1,84 @@ +. + +namespace tool_brickfield\local\tool; + +use tool_brickfield\sitedata; + +/** + * Class checktyperesults. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class checktyperesults extends tool { + + /** + * Provide a name for this tool, suitable for display on pages. + * @return mixed|string + * @throws \coding_exception + */ + public static function toolname(): string { + return get_string('checktyperesults:toolname', 'tool_brickfield'); + } + + /** + * Provide a short name for this tool, suitable for menus and selectors. + * @return mixed|string + * @throws \coding_exception + */ + public static function toolshortname(): string { + return get_string('checktyperesults:toolshortname', 'tool_brickfield'); + } + + /** + * Provide a lowercase name identifying this plugin. Should really be the same as the directory name. + * @return string + */ + public function pluginname(): string { + return 'checktyperesults'; + } + + /** + * Return the data for renderer / template display. + * @return \stdClass + * @throws \coding_exception + * @throws \dml_exception + */ + protected function fetch_data(): \stdClass { + $filter = $this->get_filter(); + if (!$filter->validate_filters()) { + return (object)[ + 'valid' => false, + 'error' => $filter->get_errormessage(), + ]; + + } + $data = (object)[ + 'valid' => true, + 'error' => '', + 'data' => (new sitedata())->get_checkgroup_data($filter), + ]; + if ($filter->categoryid != 0) { + $data->countdata = count($filter->courseids); + } else { + $data->countdata = sitedata::get_total_courses_checked(); + } + + return $data; + } +} diff --git a/admin/tool/brickfield/classes/local/tool/errors.php b/admin/tool/brickfield/classes/local/tool/errors.php new file mode 100644 index 0000000000000..511017c646801 --- /dev/null +++ b/admin/tool/brickfield/classes/local/tool/errors.php @@ -0,0 +1,145 @@ +. + +namespace tool_brickfield\local\tool; + +use tool_brickfield\manager; + +/** + * Class errors. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class errors extends tool { + + /** + * Provide a name for this tool, suitable for display on pages. + * @return mixed|string + * @throws \coding_exception + */ + public static function toolname(): string { + return get_string('errors:toolname', 'tool_brickfield'); + } + + /** + * Provide a short name for this tool, suitable for menus and selectors. + * @return mixed|string + * @throws \coding_exception + */ + public static function toolshortname(): string { + return get_string('errors:toolshortname', 'tool_brickfield'); + } + + /** + * Provide a lowercase name identifying this plugin. Should really be the same as the directory name. + * @return string + */ + public function pluginname(): string { + return 'errors'; + } + + /** + * Return the data for renderer / template display. + * @return \stdClass + * @throws \coding_exception + * @throws \dml_exception + */ + protected function fetch_data(): \stdClass { + global $DB; + + $filter = $this->get_filter(); + if (!$filter->validate_filters()) { + return (object)[ + 'valid' => false, + 'error' => $filter->get_errormessage(), + ]; + + } + + $data = (object)[ + 'valid' => true, + 'error' => '', + ]; + + list($wheresql, $params) = $filter->get_course_sql(); + $sql = 'SELECT err.id as errid, res.id as resid, area.*, + res.checkid, err.linenumber as errline, err.htmlcode + FROM {' . manager::DB_AREAS . '} area + INNER JOIN {' . manager::DB_CONTENT . '} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + INNER JOIN {' . manager::DB_RESULTS . '} res ON res.contentid = ch.id + INNER JOIN {' . manager::DB_ERRORS . '} err ON res.id = err.resultid + WHERE 1=1 ' . $wheresql .' + ORDER BY area.courseid, area.component ASC'; + + $errordata = $DB->get_records_sql($sql, $params, ($filter->page * $filter->perpage), $filter->perpage); + + // Adding check displaynames and component names from language strings. + $checks = $DB->get_records_menu(manager::DB_CHECKS, ['status' => 1], '', 'id, shortname'); + foreach ($errordata as $value) { + $value->shortname = $checks[$value->checkid]; + $value->checkdesc = self::get_check_description($value->shortname); + // Truncating HTML with base64 image data, to avoid page overstretching. + $base64detected = parent::base64_img_detected($value->htmlcode); + if ($base64detected) { + $value->htmlcode = parent::truncate_base64($value->htmlcode); + } + } + + $countsql = 'SELECT COUNT(err.id) + FROM {' . manager::DB_AREAS . '} area + INNER JOIN {' . manager::DB_CONTENT . '} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + INNER JOIN {' . manager::DB_RESULTS . '} res ON res.contentid = ch.id + INNER JOIN {' . manager::DB_ERRORS . '} err ON res.id = err.resultid + WHERE 1=1 ' . $wheresql; + + if (($filter->courseid == 0) + && ($filter->categoryid == 0)) { + $countsql = 'SELECT COUNT(err.id) + FROM {' . manager::DB_CONTENT . '} ch + INNER JOIN {' . manager::DB_RESULTS . '} res ON res.contentid = ch.id AND ch.iscurrent = 1 + INNER JOIN {' . manager::DB_ERRORS . '} err ON res.id = err.resultid + WHERE 1=1 ' . $wheresql; + } + + $errortotal = $DB->count_records_sql($countsql, $params); + + $data->errordata = $errordata; + $data->errortotal = $errortotal; + + if ($filter->categoryid != 0) { + $data->countdata = count($filter->courseids); + } else { + $countsql = 'select count(distinct courseid) from {' . manager::DB_AREAS . '}'; + $countdata = $DB->count_records_sql($countsql, []); + $data->countdata = $countdata; + } + + return $data; + } + + /** + * Errors needs to use perpage for pages. + * + * @param int $perpage + * @return int + */ + public function perpage_limits(int $perpage): int { + $config = get_config(manager::PLUGINNAME); + return $config->perpage; + } +} diff --git a/admin/tool/brickfield/classes/local/tool/filter.php b/admin/tool/brickfield/classes/local/tool/filter.php new file mode 100644 index 0000000000000..e308464ace466 --- /dev/null +++ b/admin/tool/brickfield/classes/local/tool/filter.php @@ -0,0 +1,204 @@ +. + +namespace tool_brickfield\local\tool; + +use tool_brickfield\accessibility; +use tool_brickfield\manager; + +/** + * Class filter. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class filter { + + /** @var int Possible course id being filtered. */ + public $courseid; + + /** @var int Possible category id being filtered. */ + public $categoryid; + + /** @var string The tab (page) being accessed. */ + public $tab; + + /** @var int The page number if multiple pages. */ + public $page; + + /** @var int Number of items per page for multiple pages. */ + public $perpage; + + /** @var array Array of filtered course ids if more than one. */ + public $courseids; + + /** @var string The url of the page being accessed. */ + public $url; + + /** @var string The output target. */ + public $target; + + /** @var string Any error message if present. */ + protected $errormessage; + + /** + * filter constructor. + * @param int $courseid + * @param int $categoryid + * @param string $tab + * @param int $page + * @param int $perpage + * @param string $url + * @param string $target + */ + public function __construct(int $courseid = 0, int $categoryid = 0, string $tab = '', + int $page = 0, int $perpage = 0, string $url = '', string $target = '') { + $this->courseid = $courseid; + $this->categoryid = $categoryid; + $this->tab = $tab; + $this->page = $page; + $this->perpage = $perpage; + $this->url = $url; + $this->target = $target; + } + + /** + * Get any course and category sql fragment and parameters and return as an array for this filter. Return false if course + * filters are invalid. + * @param string $alias Optional field alias to prefix on the where condition. + * @param bool $onlycondition Set to true if this is the only condition to be used in the SQL statement. + * @return array|bool + * @throws \coding_exception + * @throws \dml_exception + */ + public function get_course_sql(string $alias = '', bool $onlycondition = false) { + global $DB; + + $params = []; + if ($alias != '') { + $alias .= '.'; + } + if (!$onlycondition) { + $sql = ' AND ('; + } else { + $sql = '('; + } + if ($this->courseid != 0) { + $sql .= $alias . 'courseid = ?)'; + $params[] = $this->courseid; + } else if (($this->categoryid != 0) || !empty($this->courseids)) { + if ($this->validate_filters()) { + list($coursesql, $params) = $DB->get_in_or_equal($this->courseids); + $sql .= $alias . 'courseid '.$coursesql . ')'; + } else { + $sql = ''; + } + } else { + $sql = ''; + } + return [$sql, $params]; + } + + /** + * Validate the filters. Set an errormessage if invalid. No filters is also valid - in that case using entire system. + * @return bool + * @throws \coding_exception + * @throws \dml_exception + */ + public function validate_filters(): bool { + if (!empty($this->courseid)) { + return true; + } else if (!empty($this->categoryid) && empty($this->courseids)) { + $this->courseids = accessibility::get_category_courseids($this->categoryid); + if ($this->courseids === null) { + $this->errormessage = get_string('invalidcategoryid', manager::PLUGINNAME); + return false; + } else if (count($this->courseids) == 0) { + $this->errormessage = get_string('emptycategory', manager::PLUGINNAME, $this->categoryid); + return false; + } + } + return true; + } + + /** + * Return true if filter has course filter data, and the data is valid. Note that the site uses courseid 1. + * @return bool + * @throws \coding_exception + * @throws \dml_exception + */ + public function has_course_filters(): bool { + if ((!empty($this->courseid) && ($this->courseid > 1)) || !empty($this->categoryid) || !empty($this->courseids)) { + return $this->validate_filters(); + } + return false; + } + + /** + * Check whether the user has appropriate permissions on the supplied context. Determine the capability to check by the filters + * that are set. + * @param \context|null $context The context being viewed (e.g. system, course category, course). + * @param string $capability An optional capability to check. + * @return bool + * @throws \coding_exception + * @throws \dml_exception + */ + public function can_access(\context $context = null, string $capability = ''): bool { + if ($capability == '') { + if ($this->has_course_filters()) { + $capability = accessibility::get_capability_name('viewcoursetools'); + } else { + $capability = accessibility::get_capability_name('viewsystemtools'); + } + } + return $this->has_capability_in_context($capability, $context); + } + + /** + * Check the specified capability against the filter's context, or the specified context with the filter's information. + * @param string $capability + * @param null $context + * @return bool + * @throws \coding_exception + * @throws \dml_exception + */ + public function has_capability_in_context(string $capability, \context $context = null): bool { + $coursefiltersvalid = $this->has_course_filters(); + if ($context === null) { + // If the filter is using a list of courses ($this->>courseids), use the system context. + if ($coursefiltersvalid && !empty($this->courseid)) { + if (!empty($this->categoryid)) { + $context = \context_coursecat::instance($this->categoryid); + } else { + $context = \context_course::instance($this->courseid); + } + } else { + $context = \context_system::instance(); + } + } + + return has_capability($capability, $context); + } + + /** + * Return the error message data. + * @return mixed + */ + public function get_errormessage() { + return $this->errormessage; + } +} diff --git a/admin/tool/brickfield/classes/local/tool/printable.php b/admin/tool/brickfield/classes/local/tool/printable.php new file mode 100644 index 0000000000000..99a1347f6148d --- /dev/null +++ b/admin/tool/brickfield/classes/local/tool/printable.php @@ -0,0 +1,236 @@ +. + +namespace tool_brickfield\local\tool; + +use tool_brickfield\manager; + +/** + * Class printable. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class printable extends tool { + + /** + * Provide a name for this tool, suitable for display on pages. + * @return mixed|string + * @throws \coding_exception + */ + public static function toolname(): string { + return get_string('printable:toolname', 'tool_brickfield'); + } + + /** + * Provide a short name for this tool, suitable for menus and selectors. + * @return mixed|string + * @throws \coding_exception + */ + public static function toolshortname(): string { + return get_string('printable:toolshortname', 'tool_brickfield'); + } + + /** + * Provide a lowercase name identifying this plugin. Should really be the same as the directory name. + * @return string + */ + public function pluginname(): string { + return 'printable'; + } + + /** + * Return the data for renderer / template display. + * @return \stdClass + * @throws \coding_exception + * @throws \dml_exception + */ + protected function fetch_data(): \stdClass { + global $DB; + + $filter = $this->get_filter(); + if (!$filter->has_course_filters()) { + return (object)[ + 'valid' => false, + 'error' => get_string('error:nocoursespecified', 'tool_brickfield'), + ]; + } else if (!$filter->validate_filters()) { + return (object)[ + 'valid' => false, + 'error' => $filter->get_errormessage(), + ]; + } + + $data = (object)[ + 'valid' => true, + 'error' => '', + ]; + + $config = get_config(manager::PLUGINNAME); + $perpage = isset($config->perpagefix) ? $config->perpagefix : $config->perpage; + + list($wheresql, $params) = $filter->get_course_sql(); + + $combo = []; + $sqlcombo = 'SELECT distinct '.$DB->sql_concat_join("''", ['area.component', 'area.contextid']).' as tmpid, + sum(res.errorcount) + FROM {' . manager::DB_AREAS . '} area + INNER JOIN {' . manager::DB_CONTENT . '} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + INNER JOIN {' . manager::DB_RESULTS . '} res ON res.contentid = ch.id + WHERE 1=1 ' . $wheresql . ' + group by area.component, area.contextid'; + $combodata = $DB->get_records_sql_menu($sqlcombo, $params); + + $combo['total'] = count($combodata); + $combo['failed'] = 0; + foreach ($combodata as $count) { + if ($count != 0) { + $combo['failed']++; + } + } + $combo['passed'] = ($combo['total'] - $combo['failed']); + + $data->combodata = $combo; + + $sql = 'SELECT che.checkgroup, SUM(res.errorcount) as errorinstances + FROM {' . manager::DB_AREAS . '} area + INNER JOIN {' . manager::DB_CONTENT . '} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + INNER JOIN {' . manager::DB_RESULTS . '} res ON res.contentid = ch.id + INNER JOIN {' . manager::DB_CHECKS . '} che ON che.id = res.checkid + WHERE 1=1 ' . $wheresql . ' GROUP BY che.checkgroup + ORDER BY che.checkgroup'; + + $groupdata = $DB->get_records_sql($sql, $params); + + $data->groupdata = $groupdata; + + // Adding check displaynames from language strings. + + $wheresql = ' and area.courseid = ?'; + $params = [$filter->courseid]; + + $sql4 = 'SELECT area.component, sum(res.errorcount) as errorsum + FROM {' . manager::DB_AREAS . '} area + INNER JOIN {' . manager::DB_CONTENT . '} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + INNER JOIN {' . manager::DB_RESULTS . '} res ON res.contentid = ch.id + WHERE 1=1 ' . $wheresql . ' GROUP BY area.component + ORDER BY errorsum DESC'; + $toptargetdataraw = $DB->get_records_sql($sql4, $params, 0, 5); + $toptargetdata = []; + foreach ($toptargetdataraw as $top) { + $top->component = tool::get_module_label($top->component); + if ($top->errorsum != 0) { + $toptargetdata[] = $top; + } + } + $data->toptargetdata = $toptargetdata; + + $sql3 = 'SELECT che.shortname, sum(res.errorcount) as checkcount + FROM {' . manager::DB_AREAS . '} area + INNER JOIN {' . manager::DB_CONTENT . '} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + INNER JOIN {' . manager::DB_RESULTS . '} res ON res.contentid = ch.id + INNER JOIN {' . manager::DB_CHECKS . '} che ON che.id = res.checkid + WHERE 1=1 ' . $wheresql . ' AND res.errorcount >= ? GROUP BY che.shortname + ORDER BY checkcount DESC'; + $params[] = 1; + $checkcountdata = $DB->get_records_sql($sql3, $params, 0, 5); + foreach ($checkcountdata as $key => &$cdata) { + $cdata->checkname = self::get_check_description($key); + } + $data->checkcountdata = $checkcountdata; + + $sqltar = 'SELECT distinct '.$DB->sql_concat_join("''", ['area.component', 'area.contextid']).' as tmpid, + component, SUM(errorcount) as errorsum + FROM {' . manager::DB_AREAS . '} area + INNER JOIN {' . manager::DB_CONTENT . '} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + INNER JOIN {' . manager::DB_RESULTS . '} res ON res.contentid = ch.id + WHERE 1=1 '.$wheresql.' + GROUP BY area.component, area.contextid'; + $targetdata = $DB->get_records_sql($sqltar, $params); + + $tarlabels = []; + $combotar = []; + foreach ($targetdata as $tar) { + if (!array_key_exists($tar->component, $combotar)) { + $combotar[$tar->component] = []; + $combotar[$tar->component]['total'] = 0; + $combotar[$tar->component]['failed'] = 0; + $tarlabels[$tar->component] = tool::get_module_label($tar->component); + } + $combotar[$tar->component]['total']++; + if ($tar->errorsum > 0) { + $combotar[$tar->component]['failed']++; + } + } + ksort($combotar); + $data->combotardata = $combotar; + $data->tarlabels = $tarlabels; + + $errorsql = 'SELECT err.id as errid, res.id as resid, area.component, area.itemid, area.cmid, + che.shortname, err.linenumber as errline, err.htmlcode + FROM {' . manager::DB_AREAS . '} area + INNER JOIN {' . manager::DB_CONTENT . '} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + INNER JOIN {' . manager::DB_RESULTS . '} res ON res.contentid = ch.id + INNER JOIN {' . manager::DB_CHECKS . '} che ON che.id = res.checkid + INNER JOIN {' . manager::DB_ERRORS . '} err ON res.id = err.resultid WHERE 1=1 ' . $wheresql; + $errordata = $DB->get_records_sql($errorsql, $params, 0, $perpage); + + foreach ($errordata as $err) { + $err->shortname = self::get_check_description($err->shortname); + // Truncating HTML with base64 image data, to avoid page overstretching. + $base64detected = parent::base64_img_detected($err->htmlcode); + if ($base64detected) { + $err->htmlcode = parent::truncate_base64($err->htmlcode); + } + } + + $data->errordata = $errordata; + $data->errordetailscount = $perpage; + + if ($filter->categoryid != 0) { + $data->countdata = count($filter->courseids); + } else { + $countsql = 'select count(distinct courseid) from {' . manager::DB_AREAS . '}'; + $countdata = $DB->count_records_sql($countsql, []); + $data->countdata = $countdata; + } + + return $data; + } + + /** + * Get the HTML output for display. + * @return mixed + */ + public function get_output() { + global $PAGE; + + $data = $this->get_data(); + $filter = $this->get_filter(); + + $renderer = $PAGE->get_renderer('tool_brickfield', 'printable'); + if ($filter->target == 'pdf') { + $renderer->pdf_renderer($data, $filter); + return ''; + } else if ($filter->target == 'html') { + $output = $renderer->header(); + return $output . $renderer->display($data, $filter); + } else { + return $renderer->display($data, $filter); + } + } +} diff --git a/admin/tool/brickfield/classes/local/tool/tool.php b/admin/tool/brickfield/classes/local/tool/tool.php new file mode 100644 index 0000000000000..829871ee12cdf --- /dev/null +++ b/admin/tool/brickfield/classes/local/tool/tool.php @@ -0,0 +1,357 @@ +. + +namespace tool_brickfield\local\tool; + +use tool_brickfield\manager; + +/** + * Brickfield accessibility tool base class. + * + * All common properties and methods for all tool types. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class tool { + + /** @var string[] All of the tools provided. */ + const TOOLNAMES = ['errors', 'activityresults', 'checktyperesults', 'printable', 'advanced']; + + /** @var string base64 bitmap image type */ + const BASE64_BMP = 'data:image/bmp;base64'; + + /** @var string base64 gif image type */ + const BASE64_GIF = 'data:image/gif;base64'; + + /** @var string base64 jpg image type */ + const BASE64_JPG = 'data:image/jpeg;base64'; + + /** @var string base64 png image type */ + const BASE64_PNG = 'data:image/png;base64'; + + /** @var string base64 svg image type */ + const BASE64_SVG = 'data:image/svg+xml;base64'; + + /** @var string base64 webp image type */ + const BASE64_WEBP = 'data:image/webp;base64'; + + /** @var string base64 ico image type */ + const BASE64_ICO = 'data:image/x-icon;base64'; + + /** @var null Generic object for data used in tool renderers/templates. */ + private $data = null; + + /** @var filter Any filter being used for tool display. */ + private $filter; + + /** @var string Error message if there is one. */ + private $errormessage = ''; + + /** + * Get a mapping of tool shortname => class name. + * + * @return string[] + */ + protected static function get_tool_classnames(): array { + $tools = []; + + foreach (self::TOOLNAMES as $toolname) { + $tools[$toolname] = "tool_brickfield\\local\\tool\\{$toolname}"; + } + + return $tools; + } + + /** + * Return an array with one of each tool instance. + * + * @return tool[] + */ + public static function build_all_accessibilitytools(): array { + return array_map(function($classname) { + return new $classname(); + }, self::get_tool_classnames()); + } + + /** + * Get a list of formal tool names for each tool. + * + * @return string[] + */ + public static function get_tool_names(): array { + return array_map(function($classname) { + return $classname::toolname(); + }, self::get_tool_classnames()); + } + + /** + * Provide a lowercase name identifying this plugin. Should really be the same as the directory name. + * @return string + */ + abstract public function pluginname(); + + /** + * Provide a name for this tool, suitable for display on pages. + * @return mixed + */ + abstract public static function toolname(); + + /** + * Provide a short name for this tool, suitable for menus and selectors. + * @return mixed + */ + abstract public static function toolshortname(); + + /** + * Fetch the data for renderer / template display. Classes must implement this. + * @return \stdClass + */ + abstract protected function fetch_data(): \stdClass; + + /** + * Return the data needed for the renderer. + * @return \stdClass + * @throws \coding_exception + */ + public function get_data(): \stdClass { + if (!$this->filter) { + throw new \coding_exception('Filter has not been set.'); + } + + if (empty($this->data)) { + $this->data = $this->fetch_data(); + } + + return $this->data; + } + + /** + * Implementing class should set the 'valid' property when get_data is called. + * @return bool + */ + public function data_is_valid(): bool { + $data = $this->get_data(); + return (!empty($data->valid)); + } + + /** + * Implementing class should set an error string if data is invalidated in 'get_data'; + * @return string + */ + public function data_error(): string { + if (!$this->data_is_valid()) { + return $this->data->error; + } else { + return ''; + } + } + + /** + * Setter for filter property. + * @param filter $filter + * @throws \coding_exception + */ + public function set_filter(filter $filter): void { + if ($this->filter) { + throw new \coding_exception('Filter can only be set once.'); + } + + $this->filter = $filter; + } + + /** + * Getter for filter property. + * @return filter|null + */ + public function get_filter(): ?filter { + return $this->filter; + } + + /** + * Returns the output target for this tool's filter. + * + * @return string + * @throws \coding_exception + */ + public function get_output_target() { + $filter = $this->get_filter(); + if (!$filter) { + throw new \coding_exception('Filter has not been set.'); + } + return $filter->target; + } + + /** + * Get the HTML output for display. + * + * @return mixed + */ + public function get_output() { + global $PAGE; + + $data = $this->get_data(); + $filter = $this->get_filter(); + $renderer = $PAGE->get_renderer('tool_brickfield', $this->pluginname()); + return $renderer->display($data, $filter); + } + + /** + * Return the defined toolname. + * + * @return mixed + */ + public function get_toolname(): string { + return static::toolname(); + } + + /** + * Return the defined toolshortname. + * + * @return mixed + */ + public function get_toolshortname(): string { + return static::toolshortname(); + } + + /** + * Verify that accessibility tools can be accessed in the provided context. + * @param filter $filter + * @param \context $context + * @return bool + * @throws \coding_exception + * @throws \dml_exception + */ + public function can_access(filter $filter, \context $context = null): bool { + return $filter->can_access($context); + } + + /** + * Return any defined error message. + * + * @return string + */ + public function get_error_message(): string { + return $this->errormessage; + } + + /** + * Get module label for display + * @param string $modulename + * @return string + * @throws \coding_exception + */ + public static function get_module_label(string $modulename): string { + if (get_string_manager()->string_exists('pluginname', $modulename)) { + $modulename = get_string('pluginname', $modulename); + } else { + $modulename = get_string($modulename, manager::PLUGINNAME); + } + return($modulename); + } + + /** + * Provide arguments required for the toplevel page, using any provided filter. + * @param filter|null $filter + * @return array + */ + public static function toplevel_arguments(filter $filter = null): array { + if ($filter !== null) { + return ['courseid' => $filter->courseid, 'categoryid' => $filter->categoryid]; + } else { + return []; + } + } + + /** + * Override this to return any tool specific perpage limits. + * @param int $perpage + * @return int + */ + public function perpage_limits(int $perpage): int { + return $perpage; + } + + /** + * Return array of base64 image formats. + * @return array + */ + public static function base64_img_array(): array { + $base64 = []; + $base64[] = self::BASE64_BMP; + $base64[] = self::BASE64_GIF; + $base64[] = self::BASE64_JPG; + $base64[] = self::BASE64_PNG; + $base64[] = self::BASE64_SVG; + $base64[] = self::BASE64_WEBP; + $base64[] = self::BASE64_ICO; + return $base64; + } + + /** + * Detects if htmlcode contains base64 img data, for HTML display, such as errors page. + * @param string $htmlcode + * @return boolean + */ + public static function base64_img_detected(string $htmlcode): bool { + $detected = false; + + // Grab defined base64 img array. + $base64 = self::base64_img_array(); + foreach ($base64 as $type) { + // Need to detect this within an img tag. + $pos = stripos($htmlcode, '. + +namespace tool_brickfield; + +/** + * Class manager + * @package tool_brickfield + * @copyright 2021 Brickfield Education Labs https://www.brickfield.ie + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class manager { + + /** + * Defines the waiting for analysis status. + */ + const STATUS_WAITING = 0; + + /** + * Defined the analysis in progress status. + */ + const STATUS_INPROGRESS = -1; + + /** + * Defines the analysis has completed status. + */ + const STATUS_CHECKED = 1; + + /** + * Defines summary error value. + */ + const SUMMARY_ERROR = 0; + + /** + * Defines summary failed value. + */ + const SUMMARY_FAILED = 1; + + /** + * Defines summary percent value. + */ + const SUMMARY_PERCENT = 2; + + /** + * Default bulk record limit. + */ + const BULKRECORDLIMIT = 1000; + + /** + * Name of this plugin. + */ + const PLUGINNAME = 'tool_brickfield'; + + /** + * Areas table name. + */ + const DB_AREAS = self::PLUGINNAME . '_areas'; + + /** + * Cacheacts table name. + */ + const DB_CACHEACTS = self::PLUGINNAME . '_cache_acts'; + + /** + * Cachecheck table name. + */ + const DB_CACHECHECK = self::PLUGINNAME . '_cache_check'; + + /** + * Checks table name. + */ + const DB_CHECKS = self::PLUGINNAME . '_checks'; + + /** + * Content table name. + */ + const DB_CONTENT = self::PLUGINNAME . '_content'; + + /** + * Errors table name. + */ + const DB_ERRORS = self::PLUGINNAME . '_errors'; + + /** + * Process table name. + */ + const DB_PROCESS = self::PLUGINNAME . '_process'; + + /** + * Results table name. + */ + const DB_RESULTS = self::PLUGINNAME . '_results'; + + /** + * Schedule table name. + */ + const DB_SCHEDULE = self::PLUGINNAME . '_schedule'; + + /** + * Summary table name. + */ + const DB_SUMMARY = self::PLUGINNAME . '_summary'; + + /** @var string The URL to find help at. */ + private static $helpurl = 'https://www.brickfield.ie/moodle-help-311'; + + + /** @var array Statically stores the database checks records. */ + static protected $checks; + + /** + * Returns the URL used for registration. + * + * @return \moodle_url + */ + public static function registration_url(): \moodle_url { + return accessibility::get_plugin_url('registration.php'); + } + + /** + * Returns an appropriate message about the current registration state. + * + * @return string + * @throws \coding_exception + * @throws \dml_exception + * @throws \moodle_exception + */ + public static function registration_message(): string { + $firstline = get_string('notregistered', self::PLUGINNAME); + if (has_capability('moodle/site:config', \context_system::instance())) { + $secondline = \html_writer::link(self::registration_url(), get_string('registernow', self::PLUGINNAME)); + } else { + $secondline = get_string('contactadmin', self::PLUGINNAME); + } + return $firstline . '
' . $secondline; + } + + /** + * Get the help page URL. + * @return string + * @throws dml_exception + */ + public static function get_helpurl(): string { + return self::$helpurl; + } + + /** + * Return an array of system checks available, and store them statically. + * + * @return array + * @throws \dml_exception + */ + public static function get_checks(): array { + global $DB; + if (self::$checks === null) { + self::$checks = $DB->get_records(self::DB_CHECKS, [] , 'id'); + } + return self::$checks; + } + + /** + * Find all available areas. + * + * @return area_base[] + * @throws \ReflectionException + */ + public static function get_all_areas(): array { + return array_filter( + array_map( + function($classname) { + $reflectionclass = new \ReflectionClass($classname); + if ($reflectionclass->isAbstract()) { + return false; + } + $instance = new $classname(); + + if ($instance->is_available()) { + return $instance; + } else { + return null; + } + }, + array_keys(\core_component::get_component_classes_in_namespace('tool_brickfield', 'local\areas')) + ) + ); + } + + /** + * Calculate contenthash of a given content string + * + * @param string|null $content + * @return string + */ + public static function get_contenthash(?string $content = null): string { + return sha1($content); + } + + /** + * Does the current area content need to be scheduled for check? + * + * It does not need to be scheduled if: + * - it is the current content + * OR + * - there is already schedule + * + * @param int $areaid + * @param string $contenthash + * @return bool + * @throws \dml_exception + */ + protected static function content_needs_scheduling(int $areaid, string $contenthash): bool { + global $DB; + return ! $DB->get_field_sql('SELECT 1 FROM {' . self::DB_CONTENT . '} '. + 'WHERE areaid = ? + AND (status = 0 OR (iscurrent = 1 AND contenthash = ?))', + [$areaid, $contenthash], IGNORE_MULTIPLE); + } + + /** + * Schedule an area for analysis if there has been changes. + * + * @param \stdClass $arearecord record with the fields from the {tool_brickfield_areas} table + * as returned by area_base::find_relevant_areas(). + * It also contains the 'content' property with the current area content + * @throws \dml_exception + */ + protected static function schedule_area_if_necessary(\stdClass $arearecord) { + global $DB; + + $contenthash = static::get_contenthash($arearecord->content); + $searchparams = array_diff_key((array)$arearecord, ['content' => 1, 'reftable' => 1, 'refid' => 1]); + if ($dbrecord = $DB->get_record(self::DB_AREAS, $searchparams)) { + if ( ! static::content_needs_scheduling($dbrecord->id, $contenthash)) { + // This is already the latest content record or there is already scheduled record, nothing to do. + return; + } + } else { + $dbrecord = (object)array_diff_key((array)$arearecord, ['content' => 1]); + $dbrecord->id = $DB->insert_record(self::DB_AREAS, $dbrecord); + } + // Schedule the area for the check. Note that we do not record the contenthash, we will calculate it again + // during the actual check. + $DB->insert_record(self::DB_CONTENT, + (object)['areaid' => $dbrecord->id, 'contenthash' => '', 'timecreated' => time(), + 'status' => self::STATUS_WAITING]); + } + + /** + * Asks all area providers if they have any areas that might have changed as a result of an event and schedules them + * + * @param \core\event\base $event + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function find_new_or_updated_areas(\core\event\base $event) { + foreach (static::get_all_areas() as $area) { + if ($records = $area->find_relevant_areas($event)) { + foreach ($records as $record) { + static::schedule_area_if_necessary($record); + } + $records->close(); + } + } + } + + /** + * Returns the current content of the area. + * + * @param \stdClass $arearecord record from the tool_brickfield_areas table + * @return array|null array where the first element is the value of the field and the second element + * is the 'format' for this field if it is present. If the record was not found null is returned. + * @throws \ddl_exception + * @throws \ddl_table_missing_exception + * @throws \dml_exception + */ + protected static function get_area_content(\stdClass $arearecord): array { + global $DB; + if ($arearecord->type == area_base::TYPE_FIELD) { + $tablename = $arearecord->tablename; + $fieldname = $arearecord->fieldorarea; + $itemid = $arearecord->itemid; + + if (!$DB->get_manager()->table_exists($tablename)) { + return []; + } + if (!$DB->get_manager()->field_exists($tablename, $fieldname)) { + return []; + } + $fields = $fieldname; + if ($DB->get_manager()->field_exists($tablename, $fieldname . 'format')) { + $fields .= ',' . $fieldname . 'format'; + } + if ($record = $DB->get_record($tablename, ['id' => $itemid], $fields)) { + return array_values((array)$record); + } + } + return []; + } + + /** + * Asks all area providers if they have any areas that might have changed per courseid and schedules them. + * + * @param int $courseid + * @throws \ReflectionException + * @throws \coding_exception + * @throws \ddl_exception + * @throws \ddl_table_missing_exception + * @throws \dml_exception + */ + public static function find_new_or_updated_areas_per_course(int $courseid) { + $totalcount = 0; + foreach (static::get_all_areas() as $area) { + if ($records = $area->find_course_areas($courseid)) { + foreach ($records as $record) { + $totalcount++; + static::schedule_area_if_necessary($record); + } + $records->close(); + } + // For a site course request, also process the site level areas. + if (($courseid == SITEID) && ($records = $area->find_system_areas())) { + foreach ($records as $record) { + $totalcount++; + // Currently, the courseid in the area table is null if there is a category id. + if (!empty($record->categoryid)) { + $record->courseid = null; + } + static::schedule_area_if_necessary($record); + } + $records->close(); + } + } + // Need to run for total count of areas. + static::check_scheduled_areas($totalcount); + } + + /** + * Finds all areas that are waiting to be checked, performs checks. Returns true if there were records processed, false if not. + * To be called from scheduled task + * + * @param int $batch + * @return bool + * @throws \coding_exception + * @throws \ddl_exception + * @throws \ddl_table_missing_exception + * @throws \dml_exception + */ + public static function check_scheduled_areas(int $batch = 0): bool { + global $DB; + + $processingtime = 0; + $resultstime = 0; + + $config = get_config(self::PLUGINNAME); + if ($batch == 0) { + $batch = $config->batch; + } + // Creating insert array for courseid cache reruns. + $recordsfound = false; + $batchinserts = []; + echo("Batch amount is ".$batch.", starttime ".time()."\n"); + $rs = $DB->get_recordset_sql('SELECT a.*, ch.id AS contentid + FROM {' . self::DB_AREAS. '} a + JOIN {' . self::DB_CONTENT . '} ch ON ch.areaid = a.id + WHERE ch.status = ? + ORDER BY a.id, ch.timecreated, ch.id', + [self::STATUS_WAITING], 0, $batch); + + foreach ($rs as $arearecord) { + $recordsfound = true; + $DB->set_field(self::DB_CONTENT, 'status', self::STATUS_INPROGRESS, ['id' => $arearecord->contentid]); + $content = static::get_area_content($arearecord); + if ($content[0] == null) { + $content[0] = ''; + } + accessibility::run_check($content[0], $arearecord->contentid, $processingtime, $resultstime); + + // Set all content 'iscurrent' fields for this areaid to 0. + $DB->set_field(self::DB_CONTENT, 'iscurrent', 0, ['areaid' => $arearecord->id]); + // Update this content record to be the current record. + $DB->update_record(self::DB_CONTENT, + (object)['id' => $arearecord->contentid, 'status' => self::STATUS_CHECKED, 'timechecked' => time(), + 'contenthash' => static::get_contenthash($content[0]), 'iscurrent' => 1]); + + // If full caching has been run, then queue, if not in queue already. + if (($arearecord->courseid != null) && static::is_okay_to_cache() && + !isset($batchinserts[$arearecord->courseid])) { + $batchinserts[$arearecord->courseid] = ['courseid' => $arearecord->courseid, 'item' => 'cache']; + } + } + + if (count($batchinserts) > 0) { + $DB->insert_records(self::DB_PROCESS, $batchinserts); + } + + mtrace('Total time in htmlchecker: ' . $processingtime . ' secs.'); + mtrace('Total time in results: ' . $resultstime . ' secs.'); + return $recordsfound; + } + + /** + * Return true if analysis hasn't been disabled. + * @return bool + * @throws \dml_exception + */ + public static function is_okay_to_cache(): bool { + return (analysis::type_is_byrequest()); + } + + /** + * Finds all areas that are waiting to be deleted, performs deletions. + * + * @param int $batch limit, can be called from runcli.php + * To be called from scheduled task + * @throws \coding_exception + * @throws \dml_exception + */ + public static function check_scheduled_deletions(int $batch = 0) { + global $DB; + + $config = get_config(self::PLUGINNAME); + if ($batch == 0) { + $batch = $config->batch; + } + + // Creating insert array for courseid cache reruns. + $batchinserts = []; + + $rs = $DB->get_recordset(self::DB_PROCESS, ['contextid' => -1, 'timecompleted' => 0], '', '*', 0, $batch); + + foreach ($rs as $record) { + + if ($record->item == "core_course") { + $tidyparams = ['courseid' => $record->courseid]; + static::delete_summary_data($record->courseid); // Delete cache too. + } else if ($record->item == "course_categories") { + $tidyparams = ['component' => 'core_course', 'categoryid' => $record->innercontextid]; + } else if ($record->item == "course_sections") { + // Locate course sections, using innercontextid, contextid set to -1 for delete. + $tidyparams = ['courseid' => $record->courseid, 'component' => 'core_course', + 'tablename' => $record->item, 'itemid' => $record->innercontextid]; + } else if ($record->item == "lesson_pages") { + // Locate lesson pages, using innercontextid, contextid set to -1 for delete. + $tidyparams = ['courseid' => $record->courseid, 'component' => 'mod_lesson', + 'tablename' => $record->item, 'itemid' => $record->innercontextid]; + } else if ($record->item == "book_chapters") { + // Locate book chapters, using innercontextid, contextid set to -1 for delete. + $tidyparams = ['courseid' => $record->courseid, 'component' => 'mod_book', + 'tablename' => $record->item, 'itemid' => $record->innercontextid]; + } else if ($record->item == "question") { + // Locate question areas, using innercontextid, contextid set to -1 for delete. + $tidyparams = [ + 'courseid' => $record->courseid, 'component' => 'core_question', + 'tablename' => $record->item, 'itemid' => $record->innercontextid + ]; + } else { + // Locate specific module instance, using innercontextid, contextid set to -1 for delete. + $tidyparams = ['courseid' => $record->courseid, 'component' => $record->item, + 'itemid' => $record->innercontextid]; + } + + $areas = $DB->get_records(self::DB_AREAS, $tidyparams); + foreach ($areas as $area) { + static::delete_area_tree($area); + } + + $DB->delete_records(self::DB_PROCESS, ['id' => $record->id]); + + // If full caching has been run, then queue, if not in queue already. + if ($record->courseid != null && static::is_okay_to_cache() && !isset($batchinserts[$record->courseid])) { + $batchinserts[$record->courseid] = ['courseid' => $record->courseid, 'item' => 'cache']; + } + } + $rs->close(); + + if (count($batchinserts) > 0) { + $DB->insert_records(self::DB_PROCESS, $batchinserts); + } + } + + /** + * Checks all queued course updates, and finds all relevant areas. + * + * @param int $batch limit + * To be called from scheduled task + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function check_course_updates(int $batch = 0) { + global $DB; + + if ($batch == 0) { + $config = get_config(self::PLUGINNAME); + $batch = $config->batch; + } + + $recs = $DB->get_records(self::DB_PROCESS, ['item' => 'coursererun'], '', 'DISTINCT courseid', 0, $batch); + + foreach ($recs as $record) { + static::find_new_or_updated_areas_per_course($record->courseid); + $DB->delete_records(self::DB_PROCESS, ['courseid' => $record->courseid, 'item' => 'coursererun']); + static::store_result_summary($record->courseid); + } + } + + /** + * Finds all records for a given content area and performs deletions. + * + * To be called from scheduled task + * @param \stdClass $area + * @throws \dml_exception + */ + public static function delete_area_tree(\stdClass $area) { + global $DB; + + $contents = $DB->get_records(self::DB_CONTENT, ['areaid' => $area->id]); + foreach ($contents as $content) { + $results = $DB->get_records(self::DB_RESULTS, ['contentid' => $content->id]); + foreach ($results as $result) { + $DB->delete_records(self::DB_ERRORS, ['resultid' => $result->id]); + } + $DB->delete_records(self::DB_RESULTS, ['contentid' => $content->id]); + } + + // Also, delete all child areas, if existing. + $childparams = ['type' => $area->type, 'reftable' => $area->tablename, + 'refid' => $area->itemid]; + $childareas = $DB->get_records(self::DB_AREAS, $childparams); + foreach ($childareas as $childarea) { + static::delete_area_tree($childarea); + } + + $DB->delete_records(self::DB_CONTENT, ['areaid' => $area->id]); + $DB->delete_records(self::DB_AREAS, ['id' => $area->id]); + } + + /** + * Finds all records which are no longer current and performs deletions. + * + * To be called from scheduled task. + */ + public static function delete_historical_data() { + global $DB; + + $config = get_config(self::PLUGINNAME); + + if ($config->deletehistoricaldata) { + $contents = $DB->get_records(self::DB_CONTENT, ['iscurrent' => 0, 'status' => self::STATUS_CHECKED]); + foreach ($contents as $content) { + $results = $DB->get_records(self::DB_RESULTS, ['contentid' => $content->id]); + foreach ($results as $result) { + $DB->delete_records(self::DB_ERRORS, ['resultid' => $result->id]); + } + $DB->delete_records(self::DB_RESULTS, ['contentid' => $content->id]); + $DB->delete_records(self::DB_CONTENT, ['id' => $content->id]); + } + } + } + + /** + * Finds all summary cache records for a given courseid and performs deletions. + * To be called from scheduled task. + * + * @param int $courseid + * @throws \dml_exception + */ + public static function delete_summary_data(int $courseid) { + global $DB; + + if ($courseid == null) { + mtrace('Attempting to run delete_summary_data with no courseid, returning'); + return; + } + + $DB->delete_records(self::DB_SUMMARY, ['courseid' => $courseid]); + $DB->delete_records(self::DB_CACHECHECK, ['courseid' => $courseid]); + $DB->delete_records(self::DB_CACHEACTS, ['courseid' => $courseid]); + } + + /** + * Finds all results required to display accessibility report and stores them in the database. + * + * To be called from scheduled task. + * @param int|null $courseid + * @throws \coding_exception + * @throws \dml_exception + */ + public static function store_result_summary(int $courseid = null) { + global $DB; + + if (static::is_okay_to_cache() && ($courseid == null)) { + mtrace('Attempting to run update cache with no courseid, returning'); + return; + } + + $extrasql = !$courseid ? "" : "AND courseid = ?"; + $coursesqlval = !$courseid ? [] : [$courseid]; + + // Count of failed activities and count of errors by check. + $errorsql = "SELECT areas.courseid, chx.checkgroup, + COUNT(DISTINCT (".$DB->sql_concat('areas.contextid', 'areas.component').")) AS failed, + SUM(res.errorcount) AS errors + FROM {" . self::DB_AREAS . "} areas + INNER JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = areas.id + INNER JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id + INNER JOIN {" . self::DB_CHECKS . "} chx ON chx.id = res.checkid + WHERE res.errorcount > ? AND ch.iscurrent = ? ". $extrasql ." GROUP BY courseid, chx.checkgroup"; + + $recordserrored = $DB->get_recordset_sql($errorsql, array_merge([0, 1], $coursesqlval)); + + // Count of failed activities by course. + $failsql = "SELECT areas.courseid, + COUNT(DISTINCT (".$DB->sql_concat('areas.contextid', 'areas.component').")) AS failed, + SUM(res.errorcount) AS errors + FROM {" . self::DB_AREAS . "} areas + INNER JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = areas.id + INNER JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id + WHERE res.errorcount > ? AND ch.iscurrent = ? ". $extrasql ." GROUP BY courseid"; + + $recordsfailed = $DB->get_recordset_sql($failsql, array_merge([0, 1], $coursesqlval)); + + $extrasql = !$courseid ? "" : "WHERE courseid = ?"; + // Count of activities per course. + $countsql = "SELECT courseid, COUNT(DISTINCT (".$DB->sql_concat('areas.contextid', 'areas.component').")) AS activities + FROM {" . self::DB_AREAS . "} areas ". $extrasql ."GROUP BY areas.courseid"; + + $recordscount = $DB->get_records_sql($countsql, $coursesqlval); + + $final = []; + $values = []; + + foreach ($recordscount as $countrecord) { + $final[$countrecord->courseid] = array_pad(array(), 8, + [self::SUMMARY_ERROR => 0, self::SUMMARY_FAILED => 0, self::SUMMARY_PERCENT => 100] + ) + [ + "activitiespassed" => $countrecord->activities, + "activitiesfailed" => 0, + "activities" => $countrecord->activities + ]; + } + + foreach ($recordsfailed as $failedrecord) { + $final[$failedrecord->courseid]["activitiespassed"] -= $failedrecord->failed; + $final[$failedrecord->courseid]["activitiesfailed"] += $failedrecord->failed; + } + + foreach ($recordserrored as $errorrecord) { + $final[$errorrecord->courseid][$errorrecord->checkgroup][self::SUMMARY_ERROR] = $errorrecord->errors; + $final[$errorrecord->courseid][$errorrecord->checkgroup][self::SUMMARY_FAILED] = $errorrecord->failed; + $final[$errorrecord->courseid][$errorrecord->checkgroup][self::SUMMARY_PERCENT] = round(100 * (1 - + ($final[$errorrecord->courseid][$errorrecord->checkgroup][self::SUMMARY_FAILED] + / $final[$errorrecord->courseid]["activities"]))); + } + + foreach ($recordscount as $course) { + if (!$course->courseid) { + continue; + } + $element = [ + 'courseid' => $course->courseid, + 'status' => self::STATUS_CHECKED, + 'activities' => $final[$course->courseid]["activities"], + 'activitiespassed' => $final[$course->courseid]["activitiespassed"], + 'activitiesfailed' => $final[$course->courseid]["activitiesfailed"], + 'errorschecktype1' => $final[$course->courseid][area_base::CHECKGROUP_FORM][self::SUMMARY_ERROR], + 'errorschecktype2' => $final[$course->courseid][area_base::CHECKGROUP_IMAGE][self::SUMMARY_ERROR], + 'errorschecktype3' => $final[$course->courseid][area_base::CHECKGROUP_LAYOUT][self::SUMMARY_ERROR], + 'errorschecktype4' => $final[$course->courseid][area_base::CHECKGROUP_LINK][self::SUMMARY_ERROR], + 'errorschecktype5' => $final[$course->courseid][area_base::CHECKGROUP_MEDIA][self::SUMMARY_ERROR], + 'errorschecktype6' => $final[$course->courseid][area_base::CHECKGROUP_TABLE][self::SUMMARY_ERROR], + 'errorschecktype7' => $final[$course->courseid][area_base::CHECKGROUP_TEXT][self::SUMMARY_ERROR], + 'failedchecktype1' => $final[$course->courseid][area_base::CHECKGROUP_FORM][self::SUMMARY_FAILED], + 'failedchecktype2' => $final[$course->courseid][area_base::CHECKGROUP_IMAGE][self::SUMMARY_FAILED], + 'failedchecktype3' => $final[$course->courseid][area_base::CHECKGROUP_LAYOUT][self::SUMMARY_FAILED], + 'failedchecktype4' => $final[$course->courseid][area_base::CHECKGROUP_LINK][self::SUMMARY_FAILED], + 'failedchecktype5' => $final[$course->courseid][area_base::CHECKGROUP_MEDIA][self::SUMMARY_FAILED], + 'failedchecktype6' => $final[$course->courseid][area_base::CHECKGROUP_TABLE][self::SUMMARY_FAILED], + 'failedchecktype7' => $final[$course->courseid][area_base::CHECKGROUP_TEXT][self::SUMMARY_FAILED], + 'percentchecktype1' => $final[$course->courseid][area_base::CHECKGROUP_FORM][self::SUMMARY_PERCENT], + 'percentchecktype2' => $final[$course->courseid][area_base::CHECKGROUP_IMAGE][self::SUMMARY_PERCENT], + 'percentchecktype3' => $final[$course->courseid][area_base::CHECKGROUP_LAYOUT][self::SUMMARY_PERCENT], + 'percentchecktype4' => $final[$course->courseid][area_base::CHECKGROUP_LINK][self::SUMMARY_PERCENT], + 'percentchecktype5' => $final[$course->courseid][area_base::CHECKGROUP_MEDIA][self::SUMMARY_PERCENT], + 'percentchecktype6' => $final[$course->courseid][area_base::CHECKGROUP_TABLE][self::SUMMARY_PERCENT], + 'percentchecktype7' => $final[$course->courseid][area_base::CHECKGROUP_TEXT][self::SUMMARY_PERCENT] + ]; + $resultid = $DB->get_field(self::DB_SUMMARY, 'id', ['courseid' => $course->courseid]); + if ($resultid) { + $element['id'] = $resultid; + $DB->update_record(self::DB_SUMMARY, (object)$element); + continue; + } + array_push($values, $element); + } + + $DB->insert_records(self::DB_SUMMARY, $values); + + $extrasql = !$courseid ? "WHERE courseid != ?" : "WHERE courseid = ?"; + $coursesqlval = !$courseid ? [0] : [$courseid]; + // Count of failed errors per check. + $checkssql = "SELECT area.courseid, ".self::STATUS_CHECKED." AS status, res.checkid, + COUNT(res.errorcount) as checkcount, SUM(res.errorcount) AS errorcount + FROM {" . self::DB_AREAS . "} area + INNER JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + INNER JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id + ".$extrasql." GROUP BY area.courseid, res.checkid"; + + $checksresult = $DB->get_recordset_sql($checkssql, $coursesqlval); + + $checkvalues = []; + foreach ($checksresult as $check) { + if ($result = $DB->get_record(self::DB_CACHECHECK, ['courseid' => $check->courseid, 'checkid' => $check->checkid])) { + $check->id = $result->id; + $DB->update_record(self::DB_CACHECHECK, $check); + } else { + array_push($checkvalues, (array)$check); + } + } + $DB->insert_records(self::DB_CACHECHECK, $checkvalues); + + // Count of failed or passed rate per activity. + $activitysql = "SELECT courseid, ".self::STATUS_CHECKED." AS status, area.component, + COUNT(DISTINCT area.contextid) AS totalactivities, 0 AS failedactivities, + COUNT(DISTINCT area.contextid) AS passedactivities, 0 AS errorcount + FROM {" . self::DB_AREAS . "} area + ".$extrasql." + GROUP BY area.courseid, area.component"; + + $activityresults = $DB->get_recordset_sql($activitysql, $coursesqlval); + + $activityvalues = []; + + // Count of failed errors per courseid per activity. + $activityfailedsql = "SELECT area.courseid, area.component, area.contextid, SUM(res.errorcount) AS errorcount + FROM {" . self::DB_AREAS . "} area + INNER JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + INNER JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id + ".$extrasql." AND res.errorcount != 0 + GROUP BY area.courseid, area.component, area.contextid"; + + $activityfailedresults = $DB->get_recordset_sql($activityfailedsql, $coursesqlval); + + foreach ($activityresults as $activity) { + $tmpkey = $activity->courseid.$activity->component; + $activityvalues[$tmpkey] = $activity; + } + + foreach ($activityfailedresults as $failed) { + $tmpkey = $failed->courseid.$failed->component; + $activityvalues[$tmpkey]->failedactivities ++; + $activityvalues[$tmpkey]->passedactivities --; + $activityvalues[$tmpkey]->errorcount += $failed->errorcount; + } + + $activityvaluespush = []; + foreach ($activityvalues as $value) { + if ($result = $DB->get_record(self::DB_CACHEACTS, ['courseid' => $value->courseid, 'component' => $value->component])) { + $value->id = $result->id; + $DB->update_record(self::DB_CACHEACTS, $value); + } else { + array_push($activityvaluespush, (array)$value); + } + } + + $DB->insert_records(self::DB_CACHEACTS, $activityvaluespush); + + $recordserrored->close(); + $recordsfailed->close(); + $checksresult->close(); + $activityresults->close(); + $activityfailedresults->close(); + } + + /** + * Get course module summary information for a course. + * + * @param int $courseid + * @return stdClass[] + */ + public static function get_cm_summary_for_course(int $courseid): array { + global $DB; + + $sql = " + SELECT + area.cmid, + sum(errorcount) as numerrors, + count(errorcount) as numchecks + FROM {" . self::DB_AREAS . "} area + JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id + WHERE area.courseid = :courseid AND component != :component + GROUP BY cmid"; + + $params = [ + 'courseid' => $courseid, + 'component' => 'core_course', + ]; + + return $DB->get_records_sql($sql, $params); + } + + /** + * Get section summary information for a course. + * + * @param int $courseid + * @return stdClass[] + */ + public static function get_section_summary_for_course(int $courseid): array { + global $DB; + + $sql = " + SELECT + sec.section, + sum(errorcount) AS numerrors, + count(errorcount) as numchecks + FROM {" . self::DB_AREAS . "} area + JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = area.id AND ch.iscurrent = 1 + JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id + JOIN {course_sections} sec ON area.itemid = sec.id + WHERE area.tablename = :tablename AND area.courseid = :courseid + GROUP BY sec.id"; + + $params = [ + 'courseid' => $courseid, + 'tablename' => 'course_sections' + ]; + + return $DB->get_records_sql($sql, $params); + } +} diff --git a/admin/tool/brickfield/classes/output/activityresults/renderer.php b/admin/tool/brickfield/classes/output/activityresults/renderer.php new file mode 100644 index 0000000000000..895234e5b1235 --- /dev/null +++ b/admin/tool/brickfield/classes/output/activityresults/renderer.php @@ -0,0 +1,75 @@ +. + +namespace tool_brickfield\output\activityresults; + +use core\chart_bar as chart_bar; +use core\chart_series as chart_series; +use tool_brickfield\accessibility; +use tool_brickfield\local\tool\filter; +use tool_brickfield\manager; + +/** + * tool_brickfield/activityresults renderer + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @author Mike Churchward + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class renderer extends \tool_brickfield\output\renderer { + /** + * Render the page containing the activity results report. + * + * @param \stdClass $data Report data. + * @param filter $filter Display filters. + * @return String HTML showing charts. + * @throws \coding_exception + * @throws \dml_exception + * @throws \moodle_exception + */ + public function display(\stdClass $data, filter $filter): string { + $templatedata = new \stdClass(); + + // Set up the page information for the template. + $templatedata->title = get_string('titlepertarget', manager::PLUGINNAME) . ' : ' . + accessibility::get_title($filter, $data->countdata); + $templatedata->chartdesc = get_string('pagedesc:pertarget', manager::PLUGINNAME); + $templatedata->chartdesctitle = get_string('pagedesctitle:pertarget', manager::PLUGINNAME); + + // Set up a table of data for the external renderer. + $labels = []; + $failed = []; + $passed = []; + foreach ($data->data as $rowdata) { + $labels[] = $rowdata->componentlabel; + $passed[] = $rowdata->total - $rowdata->failed; + $failed[] = $rowdata->failed; + } + + $chart = new chart_bar(); + $chart->set_stacked(true); + $series1 = new chart_series(get_string('passed', manager::PLUGINNAME), $passed); + $series2 = new chart_series(get_string('failed', manager::PLUGINNAME), $failed); + $chart->add_series($series1); + $chart->add_series($series2); + $chart->set_labels($labels); + $chart->set_title(get_string('targetratio', manager::PLUGINNAME)); + + $templatedata->chart = $this->render($chart); + return $this->render_from_template(manager::PLUGINNAME . '/chartsingle', $templatedata); + } +} diff --git a/admin/tool/brickfield/classes/output/advanced/renderer.php b/admin/tool/brickfield/classes/output/advanced/renderer.php new file mode 100644 index 0000000000000..7be722b07047c --- /dev/null +++ b/admin/tool/brickfield/classes/output/advanced/renderer.php @@ -0,0 +1,42 @@ +. + +namespace tool_brickfield\output\advanced; + +use tool_brickfield\local\tool\filter; +use tool_brickfield\manager; + +/** + * tool_brickfield/advanced renderer + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @author Mike Churchward + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class renderer extends \tool_brickfield\output\renderer { + /** + * Render the page containing the Advanced report. + * + * @param \stdClass $data Report data. + * @param filter $filter Display filters. + * @return String HTML showing charts. + * @throws \moodle_exception + */ + public function display(\stdClass $data, filter $filter): string { + return $this->render_from_template(manager::PLUGINNAME . '/advanced', $data); + } +} diff --git a/admin/tool/brickfield/classes/output/checktyperesults/renderer.php b/admin/tool/brickfield/classes/output/checktyperesults/renderer.php new file mode 100644 index 0000000000000..60d62a266e2bc --- /dev/null +++ b/admin/tool/brickfield/classes/output/checktyperesults/renderer.php @@ -0,0 +1,84 @@ +. + +namespace tool_brickfield\output\checktyperesults; + +use core\chart_pie as chart_pie; +use core\chart_series as chart_series; +use tool_brickfield\accessibility; +use tool_brickfield\local\tool\filter; +use tool_brickfield\manager; + +/** + * tool_brickfield/checktyperesults renderer + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @author Mike Churchward + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class renderer extends \tool_brickfield\output\renderer { + /** + * Render the page containing the Checktype results report. + * @param \stdClass $data + * @param filter $filter + * @return bool|string + * @throws \coding_exception + * @throws \dml_exception + * @throws \moodle_exception + */ + public function display(\stdClass $data, filter $filter): string { + $templatedata = new \stdClass(); + + // Set up the page information for the external renderer. + $templatedata->title = get_string('titlepertype', manager::PLUGINNAME) . ' : ' . + accessibility::get_title($filter, $data->countdata); + $templatedata->chartdesc = get_string('pagedesc:checktype', manager::PLUGINNAME); + $templatedata->chartdesctitle = get_string('pagedesctitle:checktype', manager::PLUGINNAME); + + // Set up a table of data for the template. + $noerrorsfound = true; + $grouperrors = []; + $labels = []; + $count = 0; + for ($i = 1; (($count < $data->data[0]->groupcount) && ($i < 10)); $i++) { + if (isset($data->data[0]->{'componentlabel' . $i})) { + $grouperrors[] = $data->data[0]->{'errorsvalue' . $i}; + if ($data->data[0]->{'errorsvalue' . $i} > 0) { + $noerrorsfound = false; + } + $labels[] = $data->data[0]->{'componentlabel' . $i}; + $count++; + } + } + + if ($noerrorsfound) { + $templatedata->pagetitle = $templatedata->title; + $templatedata->noerrorsfound = get_string('noerrorsfound', manager::PLUGINNAME); + return $this->render_from_template(manager::PLUGINNAME . '/norecords', $templatedata); + } + + $chart = new chart_pie(); + $chart->set_doughnut(true); + $series1 = new chart_series(get_string('totalerrors', manager::PLUGINNAME), $grouperrors); + $chart->add_series($series1); + $chart->set_labels($labels); + $chart->set_title(get_string('totalgrouperrors', manager::PLUGINNAME)); + + $templatedata->chart = $this->render($chart); + return $this->render_from_template(manager::PLUGINNAME . '/chartsingle', $templatedata); + } +} diff --git a/admin/tool/brickfield/classes/output/errors/renderer.php b/admin/tool/brickfield/classes/output/errors/renderer.php new file mode 100644 index 0000000000000..fb1bcf360c15b --- /dev/null +++ b/admin/tool/brickfield/classes/output/errors/renderer.php @@ -0,0 +1,117 @@ +. + +namespace tool_brickfield\output\errors; + +use tool_brickfield\accessibility; +use tool_brickfield\local\areas\module_area_base; +use tool_brickfield\local\tool\filter; +use tool_brickfield\local\tool\tool; +use tool_brickfield\manager; + +/** + * tool_brickfield/errors renderer + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @author Mike Churchward + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class renderer extends \tool_brickfield\output\renderer { + /** + * Render the page containing the errors tool. + * + * @param \stdClass $data Report data. + * @param filter $filter Display filters. + * @return String HTML showing charts. + * @throws \coding_exception + * @throws \dml_exception + * @throws \moodle_exception + */ + public function display(\stdClass $data, filter $filter): string { + $templatedata = new \stdClass(); + + // Need a URL for the paging bar. + $pageurl = new \moodle_url( + accessibility::get_plugin_url(), + [ + 'courseid' => $filter->courseid, + 'categoryid' => $filter->categoryid, + 'tab' => $filter->tab, + 'perpage' => $filter->perpage, + ] + ); + + // Set up a table of data for the template. + $templatedata->pagetitle = get_string('titleerrors', manager::PLUGINNAME) . ' : ' . + accessibility::get_title($filter, $data->countdata); + + if (count($data->errordata) == 0) { + $templatedata->noerrorsfound = get_string('noerrorsfound', manager::PLUGINNAME); + return $this->render_from_template(manager::PLUGINNAME . '/norecords', $templatedata); + } + + $templatedata->tableheading1 = get_string('tbltarget', manager::PLUGINNAME); + $templatedata->tableheading2 = get_string('tblcheck', manager::PLUGINNAME); + $templatedata->tableheading3 = get_string('tbledit', manager::PLUGINNAME); + $templatedata->tableheading4 = get_string('tblline', manager::PLUGINNAME); + $templatedata->tableheading5 = get_string('tblhtmlcode', manager::PLUGINNAME); + + $templatedata->tabledata = []; + foreach ($data->errordata as $err) { + $row = new \stdClass(); + $row->activity = ucfirst(tool::get_module_label($err->component)); + $row->check = $err->checkdesc; + $row->edit = $this->get_link($err); + $row->line = $err->errline; + $row->html = $err->htmlcode; + $templatedata->tabledata[] = $row; + } + + $bar = new \paging_bar($data->errortotal, $filter->page, $filter->perpage, $pageurl->out()); + $templatedata->pagenavigation = $this->render($bar); + + return $this->render_from_template(manager::PLUGINNAME . '/errors', $templatedata); + } + + /** + * Return a link to edit the appropriate content for the error. + * + * @param \stdClass $err + * @return string + * @throws \coding_exception + */ + public function get_link(\stdClass $err): string { + $out = ''; + + $areaclass = '\tool_brickfield\local\areas\\' . $err->component . '\base'; + if (class_exists($areaclass)) { + $link = $areaclass::get_edit_url($err); + } else { + $link = module_area_base::get_edit_url($err); + } + + $titlestr = ucfirst($err->component) . ' ' . ucfirst($err->shortname) . ' (ID ' . $err->resid . ')'; + $title = get_string('errorlink', manager::PLUGINNAME, $titlestr); + + if (!isset($link)) { + debugging($err->component . ' ' . $err->tablename); + } + $out .= \html_writer::link($link, get_string('edit'), ['title' => $title]); + + return $out; + } +} diff --git a/admin/tool/brickfield/classes/output/printable/renderer.php b/admin/tool/brickfield/classes/output/printable/renderer.php new file mode 100644 index 0000000000000..a829a0f426c59 --- /dev/null +++ b/admin/tool/brickfield/classes/output/printable/renderer.php @@ -0,0 +1,453 @@ +. + +namespace tool_brickfield\output\printable; + +use tool_brickfield\local\tool\bfpdf; +use core\chart_bar; +use core\chart_pie; +use core\chart_series; +use tool_brickfield\accessibility; +use tool_brickfield\area_base; +use tool_brickfield\local\tool\filter; +use tool_brickfield\manager; + +/** + * tool_brickfield/printable renderer + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @author Mike Churchward + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class renderer extends \tool_brickfield\output\renderer { + /** + * Render the page containing the Printable report. + * + * @param \stdClass $data Report data. + * @param filter $filter Display filters. + * @return String HTML showing charts. + * @throws \coding_exception + * @throws \dml_exception + * @throws \moodle_exception + */ + public function display(\stdClass $data, filter $filter): string { + $css = ''; + + // Page data. + $out = ''; + + if (empty($filter->target)) { + $linkname = get_string('printable:downloadpdf', 'tool_brickfield'); + $link = new \moodle_url( + accessibility::get_plugin_url(), + [ + 'tab' => 'printable', + 'courseid' => $filter->courseid, + 'target' => 'pdf', + ] + ); + $htmlicon = new \pix_icon('t/print', $linkname); + $class = 'tool_brickfield_floatprinticon'; + $printlink = $this->action_link($link, $linkname, null, ['class' => $class, 'title' => $linkname], $htmlicon); + } + + $out .= \html_writer::tag('h3', accessibility::get_title($filter, $data->countdata)); + $out .= !empty($printlink) ? $printlink : ''; + + $div1 = \html_writer::div($this->pix_icon('f/award', + get_string('totalactivities', manager::PLUGINNAME), manager::PLUGINNAME). + get_string('totalactivities', manager::PLUGINNAME) . ': ' . $data->combodata['total'], '', + ['class' => 'col-sm-3'.$css]); + $div2 = \html_writer::div($this->pix_icon('f/done2', + get_string('passed', manager::PLUGINNAME), manager::PLUGINNAME). + get_string('passed', manager::PLUGINNAME) . ': ' . $data->combodata['passed'], '', + ['class' => 'col-sm-3'.$css]); + $div3 = \html_writer::div($this->pix_icon('f/error', + get_string('failed', manager::PLUGINNAME), manager::PLUGINNAME). + get_string('failed', manager::PLUGINNAME) . ': ' . $data->combodata['failed'], '', + ['class' => 'col-sm-3'.$css]); + $out .= \html_writer::div($div1.$div2.$div3, '', ['id' => 'rowa', 'class' => 'row h4']); + + $out .= \html_writer::div(' '); // Padding row. + $str1 = \html_writer::tag('h4', get_string('toperrors', manager::PLUGINNAME)); + + $table = new \html_table(); + $table->head = [ + get_string('tblcheck', manager::PLUGINNAME), + get_string('count', manager::PLUGINNAME), + ]; + $table->size = ['80%', '20%']; + $table->align = ['left', 'center']; + $data->checkcountdata = !empty($data->checkcountdata) ? $data->checkcountdata : []; + foreach ($data->checkcountdata as $key => $value) { + if ($value->checkcount > 0) { + $table->data[] = [$value->checkname, $value->checkcount]; + } + } + + if (count($data->checkcountdata) > 0) { + $str1 .= \html_writer::table($table, true); + } else { + $str1 .= \html_writer::tag('p', get_string('noerrorsfound', manager::PLUGINNAME)); + } + $out .= \html_writer::start_div('row', ['id' => 'row2']); + $out .= \html_writer::div($str1, '', ['class' => 'col-sm-4']); + + $str2 = \html_writer::tag('h4', get_string('toptargets', manager::PLUGINNAME)); + $table = new \html_table(); + $table->head = [ + get_string('tbltarget', manager::PLUGINNAME), + get_string('count', manager::PLUGINNAME), + ]; + $table->size = ['80%', '20%']; + $table->align = ['left', 'center']; + $data->toptargetdata = !empty($data->toptargetdata) ? $data->toptargetdata : []; + $table->data = $data->toptargetdata; + if (count($data->toptargetdata) > 0) { + $str2 .= \html_writer::table($table, true); + } else { + $str2 .= \html_writer::tag('p', get_string('noerrorsfound', manager::PLUGINNAME)); + } + $out .= \html_writer::div($str2, '', ['class' => 'col-sm-4']); + + $str3 = \html_writer::tag('h4', get_string('taberrors', manager::PLUGINNAME)); + $table = new \html_table(); + $table->head = [ + get_string('checktype', manager::PLUGINNAME), + get_string('count', manager::PLUGINNAME), + ]; + $table->size = ['80%', '20%']; + $table->align = ['left', 'center']; + foreach ($data->groupdata as $key => $group) { + $checkgroup = area_base::checkgroup_name($key); + $tmplabel = get_string('checktype:' . $checkgroup, manager::PLUGINNAME); + $icon = $this->pix_icon('f/' . $checkgroup, $tmplabel, manager::PLUGINNAME); + $table->data[] = [get_string('checktype:' . $checkgroup, manager::PLUGINNAME), $group->errorinstances]; + } + $str3 .= \html_writer::table($table, true); + $out .= \html_writer::div($str3, '', ['class' => 'col-sm-4']); + + $out .= \html_writer::end_div(); // End row2. + + $out .= \html_writer::start_div('row', ['id' => 'row3']); + + foreach ($data->combotardata as $key => &$combotar) { + $combotar['passed'] = $combotar['total'] - $combotar['failed']; + $combos[] = $combotar['total'] - $combotar['failed']; + $combosf[] = $combotar['failed']; + } + + $str4 = \html_writer::tag('h4', get_string('targetratio', manager::PLUGINNAME)); + $table = new \html_table(); + $table->head = [ + get_string('tbltarget', manager::PLUGINNAME), + get_string('passed', manager::PLUGINNAME), + get_string('failed', manager::PLUGINNAME), + get_string('total') + ]; + + foreach ($data->combotardata as $tar => $tarvalue) { + $table->data[] = [$data->tarlabels[$tar], + $tarvalue['passed'], $tarvalue['failed'], $tarvalue['total']]; + } + + $table->size = ['40%', '20%', '20%', '20%']; + $table->align = ['left', 'center', 'center', 'center']; + $str4 .= \html_writer::table($table, true); + $out .= \html_writer::div($str4, '', ['class' => 'col-sm-4']); + + $str5 = \html_writer::tag('h4', get_string('titleerrors', manager::PLUGINNAME) . + get_string('titleerrorscount', manager::PLUGINNAME, $data->errordetailscount)); + $table = new \html_table(); + $table->head = [ + get_string('tbltarget', manager::PLUGINNAME), + get_string('tblcheck', manager::PLUGINNAME), + get_string('tblline', manager::PLUGINNAME), + get_string('tblhtmlcode', manager::PLUGINNAME) + ]; + $data->errordata = !empty($data->errordata) ? $data->errordata : []; + foreach ($data->errordata as $err) { + $err->htmlcode = htmlentities($err->htmlcode); + $row = [$data->tarlabels[$err->component], $err->shortname, $err->errline, $err->htmlcode]; + $table->data[] = $row; + } + + $table->size = ['10%', '25%', '5%', '60%']; + if (count($data->errordata) > 0) { + $str5 .= \html_writer::table($table, true); + } else { + $str5 .= \html_writer::tag('p', get_string('noerrorsfound', manager::PLUGINNAME)); + } + $out .= \html_writer::div($str5, '', ['class' => 'col-sm-8']); + + $out .= \html_writer::end_div(); // End row3. + + if ($filter->target == 'pdf') { + // Converting divs to spans for better PDF display. + $out = str_replace(['
', '
'], ['', ''], $out); + } + + return $out; + } + + /** + * Return the path to use for PDF images. + * + * @return string + */ + private function image_path(): string { + global $CFG; + return $CFG->wwwroot . '/admin/tool/brickfield/pix/pdf/'; + } + + /** + * Renders the accessability report using the pdflib. + * + * @param \stdClass $data Report data. + * @param filter $filter Display filters. + * @throws \coding_exception + * @throws \dml_exception + * @throws \moodle_exception + * @return void + */ + public function pdf_renderer(\stdClass $data, filter $filter) { + $pdf = new bfpdf(); + + $pdf->setFooterFont(Array('Helvetica', '', 10)); + $pdf->setPrintHeader(false); + $pdf->SetCreator(PDF_CREATOR); + $pdf->SetAuthor('Brickfield Accessibility Report'); + $pdf->SetTitle('Brickfield Accessibility Report'); + $pdf->SetFont('Helvetica'); + + // Set default monospaced font. + $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); + + // Set margins. + $pdf->SetMargins(20, 20, 20, 100); + + $pdf->AddPage('P'); + $errorreporting = error_reporting(0); + + // Get current date for current user. + $date = new \DateTime("now", \core_date::get_user_timezone_object()); + $pdf->SetLineWidth(0.0); + + $html = ' +

' . get_string('accessibilityreport', manager::PLUGINNAME) . '

+

'. accessibility::get_title($filter, $data->countdata) .'

+

' . userdate($date->getTimestamp()) . '

+ + + + + + +
+ ' . + ' '.get_string('totalactivities', manager::PLUGINNAME) . ': ' . + $data->combodata['total'] .' + ' . + ' '.get_string('passed', manager::PLUGINNAME) . ': ' . + $data->combodata['passed'] .' + ' . + ' '.get_string('failed', manager::PLUGINNAME) . ': ' . + $data->combodata['failed'] .'
'; + + $pdf->writeHTML($html); + + if (!empty($data->checkcountdata)) { + $pdf->writeHTML($this->get_errors_table($data)); + + $tablegroup = ' + + + +
'. $this->get_group_table($data) . ''. $this->get_inaccessible_table($data) . '
'; + + $pdf->writeHTML($tablegroup); + + $pdf->AddPage('P'); + } else { + $pdf->writeHTML('
'.get_string('noerrorsfound', manager::PLUGINNAME).'
'); + } + + $pdf->writeHTML($this->get_ratio_table($data)); + + // Output the pdf. + @$pdf->Output(get_string('pdf:filename', 'tool_brickfield', $filter->courseid). + '_' . userdate($date->getTimestamp(), '%Y_%m_%d') . '.pdf', 'D'); + error_reporting($errorreporting); + + } + + /** + * Builds the HTML for a styled table used in the pdf report. + * + * @param array $headers The headers of the table. + * @param array $data The table data. + * @param string $title The title of the table. + * @param array $widths The widths of the table columns. + * @return string The HTML code of the table. + */ + public function render_table(array $headers, array $data, string $title, array $widths): string { + $numheaders = count($headers); + $html = ''; + $html .= ''; + $html .= ''; + $html .= ''; + + for ($i = 0; $i < $numheaders; ++$i) { + $align = $i > 0 ? "center" : "left"; + $html .= ''; + } + $html .= ''; + $j = 1; + foreach ($data as $row) { + ++$j; + $color = $j % 2 == 1 ? "#FFFFFF" : "#F2F2F2"; + $html .= ''; + for ($i = 0; $i < $numheaders; ++$i) { + $align = $i > 0 ? "center" : "left"; + $html .= ''; + } + $html .= ''; + } + $html .= '

'.$title.'

'; + $html .= ''.$headers[$i].''; + $html .= '
'; + $html .= $row[$i]; + $html .= '
'; + return $html; + } + + /** + * Gets the Activity Pass Ratio table. + * + * @param \stdClass $data Report data. + * @return string The HTML code of the table. + */ + public function get_ratio_table(\stdClass $data): string { + $headers = [ + get_string('tbltarget', manager::PLUGINNAME), + get_string('passed', manager::PLUGINNAME), + get_string('failed', manager::PLUGINNAME), + get_string('total') + ]; + + $tabledata = []; + foreach ($data->combotardata as $tar => $tarvalue) { + $tabledata[] = [ + $data->tarlabels[$tar], + $tarvalue['total'] - $tarvalue['failed'], + $tarvalue['failed'], + $tarvalue['total'] + ]; + } + + return $this->render_table( + $headers, + $tabledata, + get_string('targetratio', manager::PLUGINNAME), + ["40%", "20%", "20%", "20%"] + ); + } + + /** + * Gets the Check Errors table. + * + * @param \stdClass $data Report data. + * @return string The HTML code of the table. + */ + public function get_group_table(\stdClass $data): string { + $headers = [ + get_string('checktype', manager::PLUGINNAME), + get_string('count', manager::PLUGINNAME), + ]; + + $tabledata = []; + + // Numbers are constants from \tool_brickfield\area_base::checkgroup. + $icons = [ + area_base::CHECKGROUP_IMAGE => $this->image_path() . 'image-regular.svg', + area_base::CHECKGROUP_LAYOUT => $this->image_path() . 'th-large-solid.svg', + area_base::CHECKGROUP_LINK => $this->image_path() . 'link.png', + area_base::CHECKGROUP_MEDIA => $this->image_path() . 'play-circle-regular.svg', + area_base::CHECKGROUP_TABLE => $this->image_path() . 'table-solid.svg', + area_base::CHECKGROUP_TEXT => $this->image_path() . 'font-solid.svg', + ]; + + foreach ($data->groupdata as $key => $group) { + $checkgroup = area_base::checkgroup_name($key); + $icon = $icons[$key]; + $tabledata[] = ['' . ' ' .' '. + get_string('checktype:' . $checkgroup, manager::PLUGINNAME).'', $group->errorinstances]; + } + + return $this->render_table( + $headers, + $tabledata, + get_string('taberrors', manager::PLUGINNAME), + ["70%", "30%"] + ); + } + + /** + * Gets the Failed Activities table. + * + * @param \stdClass $data Report data. + * @return string The HTML code of the table. + */ + public function get_inaccessible_table(\stdClass $data): string { + $headers = [get_string('tbltarget', manager::PLUGINNAME), + get_string('count', manager::PLUGINNAME)]; + + $tabledata = []; + + foreach ($data->toptargetdata as $key => $value) { + if ($value->errorsum > 0) { + $tabledata[] = [$value->component, $value->errorsum]; + } + } + return $this->render_table( + $headers, + $tabledata, + get_string('toptargets', manager::PLUGINNAME), + ["70%", "30%"] + ); + } + + /** + * Gets the Top Errors table. + * + * @param \stdClass $data Report data. + * @return string The HTML code of the table. + */ + public function get_errors_table(\stdClass $data): string { + $headers = [get_string('tblcheck', manager::PLUGINNAME), get_string('count', manager::PLUGINNAME)]; + $tabledata = []; + + $data->checkcountdata = !empty($data->checkcountdata) ? $data->checkcountdata : []; + + foreach ($data->checkcountdata as $value) { + if ($value->checkcount > 0) { + $tabledata[] = [$value->checkname, $value->checkcount]; + } + } + return $this->render_table($headers, $tabledata, get_string('toperrors', manager::PLUGINNAME), ["80%", "20%"]); + } +} diff --git a/admin/tool/brickfield/classes/output/renderer.php b/admin/tool/brickfield/classes/output/renderer.php new file mode 100644 index 0000000000000..83fc3982ec2d5 --- /dev/null +++ b/admin/tool/brickfield/classes/output/renderer.php @@ -0,0 +1,179 @@ +. + +namespace tool_brickfield\output; + +use tool_brickfield\accessibility; +use plugin_renderer_base; +use moodle_url; +use tabobject; +use tabtree; +use html_writer; +use tool_brickfield\analysis; +use tool_brickfield\local\tool\filter; +use tool_brickfield\local\tool\tool; +use tool_brickfield\manager; +use tool_brickfield\scheduler; + +/** + * tool_brickfield renderer + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @author Bas Brands + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class renderer extends plugin_renderer_base { + + /** + * Render the page containing the tool report. + * + * @param \stdClass $data Report data. + * @param filter $filter Display filters. + * @return String HTML showing charts. + */ + public function display(\stdClass $data, filter $filter): string { + $component = 'tool_brickfield'; + $subtype = $filter->tab; + $toolrenderer = $this->page->get_renderer($component, $subtype); + if (!empty($toolrenderer)) { + return $toolrenderer->display($data, $filter); + } + } + + /** + * Render the valid tabs. + * + * @param filter $filter + * @param array $tools + * @return string + * @throws \moodle_exception + */ + public function tabs(filter $filter, array $tools): string { + $idprefix = 'tab_'; + $tabs = []; + foreach ($tools as $toolname => $tool) { + $link = new moodle_url( + accessibility::get_plugin_url(), + array_merge(['tab' => $toolname, ], $tool->toplevel_arguments($filter)) + ); + if (isset($altlabel[$toolname])) { + $label = $altlabel[$toolname]; + } else { + $label = $tool->get_toolshortname(); + } + $tab = new tabobject($idprefix . $toolname, $link, $label); + $tab->extraclass = isset($extraclass[$toolname]) ? $extraclass[$toolname] : null; + $tabs[] = $tab; + } + return $this->render(new tabtree($tabs, $idprefix . $filter->tab)); + } + + /** + * Renders tabtree + * + * @param tabtree $tabtree + * @return string + * @throws \moodle_exception + */ + protected function render_tabtree(tabtree $tabtree): string { + if (empty($tabtree->subtree)) { + return ''; + } + $data = $tabtree->export_for_template($this); + foreach ($data->tabs as $idx => $tab) { + if (isset($tabtree->subtree[$idx]->extraclass)) { + $data->tabs[$idx]->extraclass = $tabtree->subtree[$idx]->extraclass; + } + } + return $this->render_from_template(manager::PLUGINNAME . '/tabtree', $data); + } + + /** + * Render the cache alert message. + * + * @return string + * @throws \coding_exception + * @throws \dml_exception + */ + public function cachealert(): string { + $html = ''; + if (!analysis::is_enabled()) { + $html = \html_writer::div(get_string('analysistypedisabled', manager::PLUGINNAME), + '', ['class' => 'alert alert-primary']); + } + return $html; + } + + /** + * This function assumes that 'scheduler::is_analysed' has already failed. + * @param int $courseid + * @return string + * @throws \coding_exception + * @throws \moodle_exception + */ + public function analysisalert(int $courseid): string { + $siteorcourse = ($courseid == SITEID) ? 'site' : ''; + if (scheduler::is_course_in_schedule($courseid)) { + $html = \html_writer::div(get_string('schedule:' . $siteorcourse . 'scheduled', manager::PLUGINNAME), + '', ['class' => 'alert alert-primary']); + } else { + $html = \html_writer::div( + get_string('schedule:' . $siteorcourse . 'notscheduled', manager::PLUGINNAME, manager::get_helpurl()), + '', ['class' => 'alert alert-primary'] + ); + $html .= $this->analysisbutton($courseid); + } + return $html; + } + + /** + * Render the "not validated" alert message. + * + * @return string + * @throws \coding_exception + */ + public function notvalidatedalert(): string { + return \html_writer::div(get_string('notvalidated', manager::PLUGINNAME), '', ['class' => 'alert alert-primary']); + } + + /** + * Render the analysis request button. + * + * @param int $courseid + * @return string + * @throws \coding_exception + * @throws \moodle_exception + */ + public function analysisbutton(int $courseid) : string { + $link = new moodle_url(accessibility::get_plugin_url(), [ + 'action' => 'requestanalysis', + 'courseid' => $courseid + ]); + + $classname = manager::PLUGINNAME . '_analysisbutton'; + + $button = new \single_button( + $link, + get_string('schedule:requestanalysis', manager::PLUGINNAME), + 'post', + true, + ['class' => $classname] + ); + + return html_writer::tag('div', $this->render($button), ['class' => $classname]); + } +} diff --git a/admin/tool/brickfield/classes/privacy/provider.php b/admin/tool/brickfield/classes/privacy/provider.php new file mode 100644 index 0000000000000..1a4f65dbae8e7 --- /dev/null +++ b/admin/tool/brickfield/classes/privacy/provider.php @@ -0,0 +1,36 @@ +. + +namespace tool_brickfield\privacy; + +/** + * Privacy Subsystem for tool_brickfield implementing null_provider. + * + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @package tool_brickfield + * @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/admin/tool/brickfield/classes/registration.php b/admin/tool/brickfield/classes/registration.php new file mode 100644 index 0000000000000..e1bbc2b711ee6 --- /dev/null +++ b/admin/tool/brickfield/classes/registration.php @@ -0,0 +1,584 @@ +. + +namespace tool_brickfield; + +/** + * Class registration contains the functions to manage registration validation. + * + * @package tool_brickfield + * @author 2021 Onwards Mike Churchward + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL + */ +class registration { + + /** @var int Registration information has not been entered. */ + const NOT_ENTERED = 0; + + /** @var int Registration information has been entered but not externally validated. */ + const PENDING = 1; + + /** @var int Registration information was entered but was not validated within the defined grace periods. */ + const INVALID = 2; + + /** @var int Registration information has been externally validated. */ + const VALIDATED = 3; + + /** @var int Registration information has expired and needs to be revalidated. */ + const EXPIRED = 4; + + /** @var int Registration validation attempted, but failed. */ + const ERROR = 5; + + /** @var string Name of variable storing the registration status. */ + const STATUS = 'bfregstatus'; + + /** @var string Name of variable storing the last time the registration information was checked. */ + const VALIDATION_CHECK_TIME = 'bfregvalidationchecktime'; + + /** @var string Name of variable storing the time the registration information was validated. */ + const VALIDATION_TIME = 'bfregvalidationtime'; + + /** @var string Name of variable storing the time the summary data was last sent. */ + const SUMMARY_TIME = 'bfsummarytime'; + + /** @var string Name of variable storing the registration API key. */ + const API_KEY = 'key'; + + /** @var string Name of variable storing the registration API key. */ + const SECRET_KEY = 'hash'; + + /** @var string Name of the variable storing the site id. */ + const SITEID = 'id'; + + /** @var int The current validation status. */ + protected $validation; + + /** @var int The last time the validation was checked. */ + protected $checktime; + + /** @var int The last time the validation time was confirmed. */ + protected $validationtime; + + /** @var int The last time the summary data was sent. */ + protected $summarytime; + + /** @var string The API key required for registration. */ + protected $apikey; + + /** @var string The secret key required for registration. */ + protected $secretkey; + + /** @var string The registered site id. */ + protected $siteid; + + /** @var string The URL to register at. */ + private static $regurl = 'https://account.mybrickfield.ie/'; + + /** + * Object registration constructor. + * @throws \dml_exception + */ + public function __construct() { + $this->validation = $this->get_status(); + $this->checktime = $this->get_check_time(); + $this->validationtime = $this->get_validation_time(); + $this->summarytime = $this->get_summary_time(); + $this->apikey = $this->get_api_key(); + $this->secretkey = $this->get_secret_key(); + $this->siteid = $this->get_siteid(); + } + + /** + * System can be used when it has been validated, or when its still awaiting validation. + * @return bool + */ + public function toolkit_is_active(): bool { + return $this->status_is_validated() || $this->validation_pending(); + } + + /** + * The "not validated" state also needs the grace period to still be in effect. + * @return bool + */ + public function validation_pending(): bool { + return ($this->status_is_pending() || $this->status_is_error()) && $this->grace_period_valid(); + } + + /** + * Return true if there was a validation error. + * @return bool + */ + public function validation_error(): bool { + return $this->status_is_error(); + } + + /** + * Perform all necessary steps when new keys are added. Also check that they actually look like keys. + * @param string $apikey + * @param string $secretkey + * @return bool + */ + public function set_keys_for_registration(string $apikey, string $secretkey): bool { + if ($this->keys_are_valid($apikey, $secretkey)) { + $this->set_api_key($apikey); + $this->set_secret_key($secretkey); + $this->set_not_validated(); + if ($this->summarytime <= 0) { + $this->set_summary_time(); + } + return true; + } else { + $this->set_api_key(''); + $this->set_secret_key(''); + $this->set_not_entered(); + return false; + } + } + + /** + * If the registration is not already valid, validate it. This may connect to the registration site. + * @return bool + * @throws \dml_exception + */ + public function validate(): bool { + // If this is currently valid, return true, unless its time to check again. + if ($this->status_is_validated()) { + // If the summary data has not been sent in over a week, invalidate the registration. + if ($this->summarydata_grace_period_expired()) { + $this->set_invalid(); + return false; + } + // Confirm registration after the grace period has expired. + if ($this->grace_period_valid()) { + return true; + } else { + // Recheck the registration. + return $this->revalidate(); + } + } + + // Check for valid keys, and possibly move status to validation stage. + if (!$this->keys_are_valid()) { + // The current stored keys are not valid format, set the status to "not entered". + $this->set_not_entered(); + return false; + } else if ($this->status_is_not_entered()) { + // If no keys have previously been seen, move to validation stage. + $this->set_not_validated(); + } + + // If no validation has been confirmed, check the registration site. + if ($this->validation_pending()) { + $brickfieldconnect = $this->get_registration_connection(); + $this->set_check_time(); + if ($brickfieldconnect->is_registered() || $brickfieldconnect->update_registration($this->apikey, $this->secretkey)) { + // Keys are present and have been validated. + $this->set_valid(); + return true; + } else { + // Keys are present but were not validated. + $this->set_error(); + } + } + + // If any of the grace periods have passed without a validation, invalidate the registration. + if (!$this->grace_period_valid() || $this->summarydata_grace_period_expired()) { + $this->set_invalid(); + return false; + } else { + return true; + } + } + + /** + * Even if the regisration is currently valid, validate it again. + * @return bool + * @throws \dml_exception + */ + public function revalidate(): bool { + if ($this->status_is_validated()) { + $this->set_not_validated(); + } + return $this->validate(); + } + + /** + * Get api key. + * @return string + * @throws \dml_exception + */ + public function get_api_key(): string { + $key = get_config(manager::PLUGINNAME, self::API_KEY); + if ($key === false) { + // Not set in config yet, so default it to "". + $key = ''; + $this->set_api_key($key); + } + return $key; + } + + /** + * Get secret key. + * @return string + * @throws \dml_exception + */ + public function get_secret_key(): string { + $key = get_config(manager::PLUGINNAME, self::SECRET_KEY); + if ($key === false) { + // Not set in config yet, so default it to "". + $key = ''; + $this->set_secret_key($key); + } + return $key; + } + + /** + * Get the registration URL. + * @return string + */ + public function get_regurl(): string { + return self::$regurl; + } + + /** + * Perform all actions needed to note that the summary data was sent. + */ + public function mark_summary_data_sent() { + $this->set_summary_time(); + } + + /** + * Set the registered site id. + * @param int $id + * @return bool + */ + public function set_siteid(int $id): bool { + $this->siteid = $id; + return set_config(self::SITEID, $id, manager::PLUGINNAME); + } + + /** + * Return the registered site id. + * @return int + * @throws \dml_exception + */ + public function get_siteid(): int { + $siteid = get_config(manager::PLUGINNAME, self::SITEID); + if ($siteid === false) { + // Not set in config yet, so default it to 0. + $siteid = 0; + $this->set_siteid($siteid); + } + return (int)$siteid; + } + + /** + * Set the status as keys "not entered". + * @return bool + */ + protected function set_not_entered(): bool { + return $this->set_status(self::NOT_ENTERED); + } + + /** + * "Not validated" means we have keys, but have not confirmed them yet. Set the validation time to start the grace period. + * @return bool + */ + protected function set_not_validated(): bool { + $this->set_validation_time(); + return $this->set_status(self::PENDING); + } + + /** + * Set the registration as invalid. + * @return bool + */ + protected function set_invalid(): bool { + $this->set_api_key(''); + $this->set_secret_key(''); + $this->set_siteid(0); + return $this->set_status(self::INVALID); + } + + /** + * Set the registration as valid. + * @return bool + */ + protected function set_valid(): bool { + $this->set_validation_time(); + $this->set_summary_time(); + return $this->set_status(self::VALIDATED); + } + + /** + * Set the status to "expired". + * @return bool + */ + protected function set_expired(): bool { + return $this->set_status(self::EXPIRED); + } + + /** + * Set the status to "error". + * @return bool + */ + protected function set_error(): bool { + return $this->set_status(self::ERROR); + } + + /** + * Set the configured api key value. + * @param string $keyvalue + * @return bool + */ + protected function set_api_key(string $keyvalue): bool { + $this->apikey = $keyvalue; + return set_config(self::API_KEY, $keyvalue, manager::PLUGINNAME); + } + + /** + * Set the configured secret key value. + * @param string $keyvalue + * @return bool + */ + protected function set_secret_key(string $keyvalue): bool { + $this->secretkey = $keyvalue; + return set_config(self::SECRET_KEY, $keyvalue, manager::PLUGINNAME); + } + + /** + * Return true if the logic says that the registration is valid. + * @return bool + */ + protected function status_is_validated(): bool { + return $this->validation == self::VALIDATED; + } + + /** + * Return true if the current status is "not entered". + * @return bool + */ + protected function status_is_not_entered(): bool { + return $this->validation == self::NOT_ENTERED; + } + + /** + * Return true if the current status is "pending". + * @return bool + */ + protected function status_is_pending(): bool { + return $this->validation == self::PENDING; + } + + /** + * Return true if the current status is "expired". + * @return bool + */ + protected function status_is_expired(): bool { + return $this->validation == self::EXPIRED; + } + + /** + * Return true if the current status is "invalid". + * @return bool + */ + protected function status_is_invalid(): bool { + return $this->validation == self::INVALID; + } + + /** + * Return true if the current status is "error". + * @return bool + */ + protected function status_is_error() { + return $this->validation == self::ERROR; + } + + /** + * Set the current registration status. + * @param int $status + * @return bool + */ + protected function set_status(int $status): bool { + $this->validation = $status; + return set_config(self::STATUS, $status, manager::PLUGINNAME); + } + + /** + * Return the current registration status. + * @return int + * @throws \dml_exception + */ + protected function get_status(): int { + $status = get_config(manager::PLUGINNAME, self::STATUS); + if ($status === false) { + // Not set in config yet, so default it to "NOT_ENTERED". + $status = self::NOT_ENTERED; + $this->set_status($status); + } + return (int)$status; + } + + /** + * Set the time of the last registration check. + * @param int $time + * @return bool + */ + protected function set_check_time(int $time = 0): bool { + $time = ($time == 0) ? time() : $time; + $this->checktime = $time; + return set_config(self::VALIDATION_CHECK_TIME, $time, manager::PLUGINNAME); + } + + /** + * Get the time of the last registration check. + * @return int + * @throws \dml_exception + */ + protected function get_check_time(): int { + $time = get_config(manager::PLUGINNAME, self::VALIDATION_CHECK_TIME); + if ($time === false) { + // Not set in config yet, so default it to 0. + $time = 0; + $this->set_check_time($time); + } + return (int)$time; + } + + /** + * Set the registration validation time. + * @param int $time + * @return bool + */ + protected function set_validation_time(int $time = 0): bool { + $time = ($time == 0) ? time() : $time; + $this->validationtime = $time; + return set_config(self::VALIDATION_TIME, $time, manager::PLUGINNAME); + } + + /** + * Return the time of the registration validation. + * @return int + * @throws \dml_exception + */ + protected function get_validation_time(): int { + $time = get_config(manager::PLUGINNAME, self::VALIDATION_TIME); + if ($time === false) { + // Not set in config yet, so default it to 0. + $time = 0; + $this->set_validation_time($time); + } + return (int)$time; + } + + /** + * Set the time of the summary update. + * @param int $time + * @return bool + */ + protected function set_summary_time(int $time = 0): bool { + $time = ($time == 0) ? time() : $time; + $this->summarytime = $time; + return set_config(self::SUMMARY_TIME, $time, manager::PLUGINNAME); + } + + /** + * Return the time of the last summary update. + * @return int + * @throws \dml_exception + */ + protected function get_summary_time(): int { + $time = get_config(manager::PLUGINNAME, self::SUMMARY_TIME); + if ($time === false) { + // Not set in config yet, so default it to 0. + $time = 0; + $this->set_summary_time($time); + } + return (int)$time; + } + + /** + * Return true if all keys have valid format. + * @param string|null $apikey + * @param string|null $secretkey + * @return bool + */ + protected function keys_are_valid(?string $apikey = null, ?string $secretkey = null): bool { + $apikey = $apikey ?? $this->apikey; + $secretkey = $secretkey ?? $this->secretkey; + return $this->apikey_is_valid($apikey) && $this->secretkey_is_valid($secretkey); + } + + /** + * Validates that the entered API key is in the expected format. + * @param string $apikey + * @return bool + */ + protected function apikey_is_valid(string $apikey): bool { + return $this->valid_key_format($apikey); + } + + /** + * Validates that the entered Secret key is in the expected format. + * @param string $secretkey + * @return bool + */ + protected function secretkey_is_valid(string $secretkey): bool { + return $this->valid_key_format($secretkey); + } + + /** + * Validates that the passed in key looks like an MD5 hash. + * @param string $key + * @return bool + */ + protected function valid_key_format(string $key): bool { + return !empty($key) && (preg_match('/^[a-f0-9]{32}$/', $key) === 1); + } + + /** + * Get the registration grace period. + * @return int + */ + protected function get_grace_period(): int { + return WEEKSECS; + } + + /** + * Check if the unvalidated time is still within the grace period. + * @return bool + */ + protected function grace_period_valid(): bool { + return (time() - $this->validationtime) < $this->get_grace_period(); + } + + /** + * Check if the last time the summary data was sent is within the grace period. + * @return bool + */ + protected function summarydata_grace_period_expired(): bool { + return (time() - $this->summarytime) > $this->get_grace_period(); + } + + /** + * Return an instance of the connection class. + * @return brickfieldconnect + */ + protected function get_registration_connection(): brickfieldconnect { + return new brickfieldconnect(); + } +} diff --git a/admin/tool/brickfield/classes/scheduler.php b/admin/tool/brickfield/classes/scheduler.php new file mode 100644 index 0000000000000..cf058446c70e1 --- /dev/null +++ b/admin/tool/brickfield/classes/scheduler.php @@ -0,0 +1,348 @@ +. + +namespace tool_brickfield; + +/** + * Scheduler class. + * + * @package tool_brickfield + * @author Mike Churchward + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL + */ +class scheduler { + + /** + * Analysis has not been requested. + */ + const STATUS_NOT_REQUESTED = 0; + + /** + * Analysis has been requested but not submitted. + */ + const STATUS_REQUESTED = 1; + + /** + * Analysis has been submitted. + */ + const STATUS_SUBMITTED = 2; + + /** + * The data table used by the scheduler. + */ + const DATA_TABLE = 'tool_brickfield_schedule'; + + /** @var int $instanceid The specific instance id of the context e.g. courseid. */ + public $instanceid; + + /** @var int $contextlevel The context level of the instance id e.g. CONTEXT_COURSE / 50. */ + public $contextlevel; + + /** + * Scheduler constructor. + * @param int $instanceid + * @param int $contextlevel + */ + public function __construct(int $instanceid = 0, int $contextlevel = CONTEXT_COURSE) { + $this->instanceid = $instanceid; + $this->contextlevel = $contextlevel; + } + + /** + * Request this schedule object to be analyzed. Create the schedule if not present. + * @return bool + */ + public function request_analysis(): bool { + global $DB; + if (!$this->create_schedule()) { + return false; + } + if ($DB->set_field(self::DATA_TABLE, 'status', self::STATUS_REQUESTED, $this->standard_search_params())) { + if ($this->contextlevel == CONTEXT_COURSE) { + $context = \context_course::instance($this->instanceid); + } else { + $context = \context_system::instance(); + } + $event = \tool_brickfield\event\analysis_requested::create([ + 'context' => $context, + 'other' => ['course' => $this->instanceid], + ]); + $event->trigger(); + + return true; + } else { + return false; + } + } + + /** + * Mark this schedule object as analyzed. + * @return bool + * @throws \dml_exception + */ + public function mark_analyzed(): bool { + global $DB; + if (!$this->create_schedule()) { + return false; + } + $DB->set_field(self::DATA_TABLE, 'status', self::STATUS_SUBMITTED, $this->standard_search_params()); + $DB->set_field(self::DATA_TABLE, 'timeanalyzed', time(), $this->standard_search_params()); + return true; + } + + /** + * Request this schedule object be added. Return true if already added, or the status of the insert operation. + * @return bool + */ + public function create_schedule(): bool { + global $DB; + if (!$this->is_in_schedule()) { + $datarecord = $this->get_datarecord(); + return $DB->insert_record(self::DATA_TABLE, $datarecord, false); + } + return true; + } + + /** + * Request this schedule object be deleted. + * @return bool + */ + public function delete_schedule(): bool { + global $DB; + if ($this->is_in_schedule()) { + return $DB->delete_records(self::DATA_TABLE, $this->standard_search_params()); + } + return true; + } + + /** + * Return true if this schedule object is in the schedule. + * @return bool + */ + public function is_in_schedule(): bool { + global $DB; + return $DB->record_exists(self::DATA_TABLE, $this->standard_search_params()); + } + + /** + * Return true if this schedule object has been requested to be analyzed. + * @return bool + */ + public function is_scheduled(): bool { + global $DB; + return $DB->record_exists(self::DATA_TABLE, $this->standard_search_params() + ['status' => self::STATUS_REQUESTED]); + } + + /** + * Return true if this schedule object has been submitted. + * @return bool + */ + public function is_submitted(): bool { + global $DB; + return $DB->record_exists(self::DATA_TABLE, $this->standard_search_params() + ['status' => self::STATUS_SUBMITTED]); + } + + /** + * Return true if this schedule object has been analyzed. + * @return bool + */ + public function is_analyzed(): bool { + global $DB; + + // Future... If not a course analysis request, just return the schedule table status. + if ($this->contextlevel != CONTEXT_COURSE) { + return $this->is_submitted(); + } + + // A course is considered analyzed if it has been submitted and there is summary cache data for it. + $sql = 'SELECT * ' . + 'FROM {' . self::DATA_TABLE . '} sch ' . + 'INNER JOIN {' . manager::DB_SUMMARY . '} sum ON sch.instanceid = sum.courseid ' . + 'WHERE (sch.contextlevel = :contextlevel) AND (sch.instanceid = :instanceid) AND (sch.status = :status)'; + if (!$DB->record_exists_sql($sql, $this->standard_search_params() + ['status' => self::STATUS_SUBMITTED])) { + // It may have been created in a prior version, so check before returning false. If it was, add a record for it. + if ($DB->record_exists(manager::DB_SUMMARY, ['courseid' => $this->instanceid])) { + return $this->mark_analyzed(); + } else { + return false; + } + } else { + return true; + } + } + + /** + * The nornal data parameters to search for. + * @return array + */ + protected function standard_search_params(): array { + return ['contextlevel' => $this->contextlevel, 'instanceid' => $this->instanceid]; + } + + /** + * Get the context id for the specified context level and instance. + * @return int + * @throws \dml_exception + */ + protected function get_contextid(): int { + global $DB; + $contextid = $DB->get_field('context', 'id', $this->standard_search_params()); + if ($contextid === false) { + $contextid = 0; + } + return $contextid; + } + + /** + * Create and return a datarecord object for the data table. + * @param int $status + * @return \stdClass + * @throws \dml_exception + */ + public function get_datarecord(int $status = self::STATUS_NOT_REQUESTED): \stdClass { + $datarecord = new \stdClass(); + $datarecord->contextlevel = $this->contextlevel; + $datarecord->instanceid = $this->instanceid; + $datarecord->contextid = $this->get_contextid(); + $datarecord->status = $status; + $datarecord->timeanalyzed = 0; + $datarecord->timemodified = time(); + return $datarecord; + } + + /** + * Process all the course analysis requests, and mark them as analyzed. Limit the number of requests processed by time. + * @throws \ReflectionException + * @throws \dml_exception + */ + public static function process_scheduled_requests() { + global $DB; + + // Run a registration check. + if (!(new registration())->validate()) { + return; + } + + $runtimemax = MINSECS * 5; // Only process requests for five minutes. May want to tie this to task schedule. + $runtime = time(); + $requestset = $DB->get_recordset(self::DATA_TABLE, ['status' => self::STATUS_REQUESTED], 'timemodified ASC'); + foreach ($requestset as $request) { + if ($request->contextlevel == CONTEXT_COURSE) { + manager::find_new_or_updated_areas_per_course($request->instanceid); + $request->status = self::STATUS_SUBMITTED; + $request->timeanalyzed = time(); + $request->timemodified = time(); + $DB->update_record(self::DATA_TABLE, $request); + } + $runtime = time() - $runtime; + if ($runtime >= $runtimemax) { + break; + } + } + $requestset->close(); + } + + // The following are static versions of the above functions for courses that do not require creating an object first. + + /** + * Load all requested context types into the schedule as requested. Write records in groups of 100. + * @param int $contextlevel + * @return bool + * @throws \coding_exception + * @throws \dml_exception + */ + public static function initialize_schedule(int $contextlevel = CONTEXT_COURSE): bool { + global $DB; + + $writelimit = 100; + $recordcount = 0; + $records = []; + $scheduler = new scheduler(0, $contextlevel); + $coursesset = $DB->get_recordset('course', null, 'id', 'id, id as courseid'); + foreach ($coursesset as $course) { + $recordcount++; + $scheduler->instanceid = $course->id; + $records[] = $scheduler->get_datarecord(self::STATUS_REQUESTED); + if ($recordcount >= $writelimit) { + $DB->insert_records(self::DATA_TABLE, $records); + $recordcount = 0; + $records = []; + } + } + + if ($recordcount > 0) { + $DB->insert_records(self::DATA_TABLE, $records); + } + $coursesset->close(); + + return true; + } + + /** + * Request the specified course be analyzed. + * @param int $courseid + * @return bool + */ + public static function request_course_analysis(int $courseid) { + return (new scheduler($courseid))->request_analysis(); + } + + /** + * Request the specified course be added. + * @param int $courseid + * @return bool + */ + public static function create_course_schedule(int $courseid) { + return (new scheduler($courseid))->create_schedule(); + } + + /** + * Delete the specified course from the schedule. + * @param int $courseid + * @return bool + */ + public static function delete_course_schedule(int $courseid) { + return (new scheduler($courseid))->delete_schedule(); + } + + /** + * Return true if the specified course is in the schedule. + * @param int $courseid + * @return bool + */ + public static function is_course_in_schedule(int $courseid) { + return (new scheduler($courseid))->is_in_schedule(); + } + + /** + * Return true if the specified course is scheduled. + * @param int $courseid + * @return bool + */ + public static function is_course_scheduled(int $courseid) { + return (new scheduler($courseid))->is_scheduled(); + } + + /** + * Return true if the specified course has been analyzed. + * @param int $courseid + * @return bool + */ + public static function is_course_analyzed(int $courseid) { + return (new scheduler($courseid))->is_analyzed(); + } +} diff --git a/admin/tool/brickfield/classes/sitedata.php b/admin/tool/brickfield/classes/sitedata.php new file mode 100644 index 0000000000000..441693290ca90 --- /dev/null +++ b/admin/tool/brickfield/classes/sitedata.php @@ -0,0 +1,204 @@ +. + +namespace tool_brickfield; + +use tool_brickfield\local\tool\filter; +use tool_brickfield\local\tool\tool; + +/** + * Provides the Brickfield Accessibility toolkit site data API. + * + * @package tool_brickfield + * @copyright 2020 onward Brickfield Education Labs Ltd, https://www.brickfield.ie + * @author Mike Churchward (mike@brickfieldlabs.ie) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class sitedata { + + /** @var array An array of SQL parts to build an SQL statement. */ + private $sqlparts = ['SELECT' => [], 'FROM' => '', 'WHERE' => '', 'GROUPBY' => '', 'ORDERBY' => '']; + + /** @var array An array of SQL parameters. */ + private $sqlparams = []; + + /** @var array An array of labels to be displayed. */ + private $grouplabels = []; + + /** @var array An array of the used check group numbers. */ + private $groupnumbers = []; + + /** @var int The count of group labels. */ + private $groupcount = 0; + + /** + * Return the total number of courses that have been checked. + * @return int + * @throws \dml_exception + */ + public static function get_total_courses_checked(): int { + global $DB; + return $DB->count_records_select(manager::DB_AREAS, '', [], 'COUNT(DISTINCT courseid)'); + } + + /** + * Get records of component per course summary data. + * @param local\tool\filter $filter + * @return array + * @throws \coding_exception + * @throws \dml_exception + */ + public static function get_component_data(filter $filter): array { + global $DB; + + $data = []; + if ($filter->validate_filters()) { + list($wheresql, $params) = $filter->get_course_sql('', true); + $sql = 'SELECT component, SUM(errorcount) as errorsum, SUM(totalactivities) as total, ' . + 'SUM(failedactivities) as failed, SUM(passedactivities) as passed ' . + 'FROM {' . manager::DB_CACHEACTS . '} area ' . + (empty($wheresql) ? '' : ('WHERE ' . $wheresql . ' ')) . + 'GROUP BY area.component ' . + 'ORDER BY area.component ASC'; + + $data = $DB->get_records_sql($sql, $params); + + foreach ($data as $key => $componentsummary) { + $data[$key]->componentlabel = tool::get_module_label($componentsummary->component); + } + } + + return $data; + } + + /** + * Get records of check group per course summary data. + * @param local\tool\filter $filter + * @return array + * @throws \coding_exception + * @throws \dml_exception + */ + public function get_checkgroup_data(filter $filter): array { + global $DB; + + $data = []; + if ($filter->validate_filters()) { + $this->get_base_checkgroup_sql($filter); + + $sql = $this->get_select_string() . ' ' . + 'FROM ' . $this->sqlparts['FROM'] . ' ' . + (!empty($this->sqlparts['WHERE']) ? 'WHERE ' . $this->sqlparts['WHERE'] . ' ' : '') . + (!empty($this->sqlparts['GROUPBY']) ? 'GROUP BY ' . $this->sqlparts['GROUPBY'] . ' ' : '') . + (!empty($this->sqlparts['ORDERBY']) ? 'ORDER BY ' . $this->sqlparts['ORDERBY'] . ' ' : ''); + $data = array_values($DB->get_records_sql($sql, $this->sqlparams, + ($filter->page * $filter->perpage), $filter->perpage)); + if (empty($data)) { + $data[0] = (object)(array_values($this->grouplabels)); + } else { + $data[0] = (object)(array_merge((array)$data[0], $this->grouplabels)); + } + $data[0]->groupcount = $this->groupcount; + } + + return $data; + } + + /** + * Get records of check group per course summary data. + * @param local\tool\filter $filter + * @return array + * @throws \coding_exception + * @throws \dml_exception + */ + public function get_checkgroup_by_course_data(filter $filter): array { + $this->sqlparts['GROUPBY'] = 'courseid'; + $this->add_select_item('courseid'); + return $this->get_checkgroup_data($filter); + } + + /** + * Get records of check group per course summary data. + * @param local\tool\filter $filter + * @return array + * @throws \coding_exception + * @throws \dml_exception + */ + public function get_checkgroup_with_failed_data(filter $filter): array { + $this->add_select_item('SUM(activitiesfailed) as failed'); + return $this->get_checkgroup_data($filter); + } + + /** + * Load up the base SQL parts. + * @param filter $filter + * @throws \coding_exception + * @throws \dml_exception + */ + private function get_base_checkgroup_sql(filter $filter) { + if ($filter->validate_filters()) { + $this->get_grouplabel_info(); + + list($this->sqlparts['WHERE'], $this->sqlparams) = $filter->get_course_sql('summ', true); + $this->add_select_item('SUM(activities) as activities'); + foreach ($this->groupnumbers as $lab) { + $this->add_select_item("SUM(errorschecktype$lab) as errorsvalue$lab"); + $this->add_select_item("SUM(failedchecktype$lab) as failedvalue$lab"); + $this->add_select_item("AVG(percentchecktype$lab) as percentvalue$lab"); + } + $this->sqlparts['FROM'] = '{' . manager::DB_SUMMARY . '} summ'; + } + } + + /** + * Load the group label information. + * @throws \coding_exception + * @throws \dml_exception + */ + private function get_grouplabel_info() { + global $DB; + + // Don't need to do this more than once. + if (empty($this->grouplabels)) { + // Determine the checkgroups being used by this site. + $labelsql = 'SELECT DISTINCT checkgroup, checkgroup as cg2 FROM {' . manager::DB_CHECKS . '} ' . + 'WHERE status = ? ORDER BY checkgroup ASC'; + $groupvals = $DB->get_records_sql_menu($labelsql, [1]); + $grouplabels = array_intersect_key(area_base::CHECKGROUP_NAMES, $groupvals); + + foreach ($grouplabels as $lab => $label) { + $this->grouplabels['componentlabel' . $lab] = get_string('checktype:' . $label, manager::PLUGINNAME); + $this->groupnumbers[] = $lab; + $this->groupcount++; + } + } + } + + /** + * Add a select item to the sqlparts array. + * @param string $item + */ + private function add_select_item(string $item): void { + $this->sqlparts['SELECT'][] = $item; + } + + /** + * Assemble and return the select portion of the sql. + * @return string + */ + private function get_select_string(): string { + return 'SELECT ' . implode(', ', $this->sqlparts['SELECT']); + } +} diff --git a/admin/tool/brickfield/classes/task/bulk_process_caches.php b/admin/tool/brickfield/classes/task/bulk_process_caches.php new file mode 100644 index 0000000000000..b9e9b5e80dec6 --- /dev/null +++ b/admin/tool/brickfield/classes/task/bulk_process_caches.php @@ -0,0 +1,51 @@ +. + +namespace tool_brickfield\task; + +use tool_brickfield\accessibility; +use tool_brickfield\manager; + +/** + * Task function to bulk process caches for accessibility checks. + * + * This is a Brickfield Premium feature only. + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class bulk_process_caches extends \core\task\scheduled_task { + + /** + * Return the task's name as shown in admin screens. + * + * @return string + */ + public function get_name(): string { + return get_string('bulkprocesscaches', manager::PLUGINNAME); + } + + /** + * Execute the task + */ + public function execute() { + // If this feature has been disabled do nothing. + if (accessibility::is_accessibility_enabled()) { + accessibility::bulk_process_caches_cron(); + } + } +} diff --git a/admin/tool/brickfield/classes/task/bulk_process_courses.php b/admin/tool/brickfield/classes/task/bulk_process_courses.php new file mode 100644 index 0000000000000..d771a3a792bb7 --- /dev/null +++ b/admin/tool/brickfield/classes/task/bulk_process_courses.php @@ -0,0 +1,49 @@ +. + +namespace tool_brickfield\task; + +use tool_brickfield\accessibility; +use tool_brickfield\manager; + +/** + * Task function to bulk process courses for accessibility checks. + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class bulk_process_courses extends \core\task\scheduled_task { + + /** + * Return the task's name as shown in admin screens. + * + * @return string + */ + public function get_name(): string { + return get_string('bulkprocesscourses', manager::PLUGINNAME); + } + + /** + * Execute the task + */ + public function execute() { + // If this feature has been disabled, do nothing. + if (accessibility::is_accessibility_enabled()) { + accessibility::bulk_process_courses_cron(); + } + } +} diff --git a/admin/tool/brickfield/classes/task/checkid_validation.php b/admin/tool/brickfield/classes/task/checkid_validation.php new file mode 100644 index 0000000000000..9528f50fe0c84 --- /dev/null +++ b/admin/tool/brickfield/classes/task/checkid_validation.php @@ -0,0 +1,63 @@ +. + +namespace tool_brickfield\task; + +use tool_brickfield\accessibility; +use tool_brickfield\manager; + +/** + * Task function to run checkid validation for accessibility checks. + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class checkid_validation extends \core\task\scheduled_task { + + /** + * Return the task's name as shown in admin screens. + * + * @return string + */ + public function get_name(): string { + return get_string('checkidvalidation', manager::PLUGINNAME); + } + + /** + * Execute the task + */ + public function execute() { + global $DB; + + // If this feature has been disabled, do nothing. + if (accessibility::is_accessibility_enabled()) { + mtrace('Running checkid_validation'); + + if ($DB->record_exists(manager::DB_RESULTS, ['checkid' => 0])) { + $config = get_config(manager::PLUGINNAME); + + $messagebody = get_string('warningcheckidbody', manager::PLUGINNAME); + $messagesubject = get_string('warningcheckidsubject', manager::PLUGINNAME); + + $receiver = \core_user::get_support_user(); + $receiver->email = !empty($config->warningscontact) ? $config->warningscontact : $receiver->email; + $noreplyuser = \core_user::get_noreply_user(); + email_to_user($receiver, $noreplyuser, $messagesubject, html_to_text($messagebody), $messagebody); + } + } + } +} diff --git a/admin/tool/brickfield/classes/task/process_analysis_requests.php b/admin/tool/brickfield/classes/task/process_analysis_requests.php new file mode 100644 index 0000000000000..1d29554930d44 --- /dev/null +++ b/admin/tool/brickfield/classes/task/process_analysis_requests.php @@ -0,0 +1,50 @@ +. + +namespace tool_brickfield\task; + +use tool_brickfield\accessibility; +use tool_brickfield\manager; +use tool_brickfield\scheduler; + +/** + * Task function to bulk process caches for accessibility checks. + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class process_analysis_requests extends \core\task\scheduled_task { + + /** + * Return the task's name as shown in admin screens. + * + * @return string + */ + public function get_name(): string { + return get_string('processanalysisrequests', manager::PLUGINNAME); + } + + /** + * Execute the task + */ + public function execute() { + // If this feature has been disabled, do nothing. + if (accessibility::is_accessibility_enabled()) { + scheduler::process_scheduled_requests(); + } + } +} diff --git a/admin/tool/brickfield/classes/task/update_summarydata.php b/admin/tool/brickfield/classes/task/update_summarydata.php new file mode 100644 index 0000000000000..86deeb4a60659 --- /dev/null +++ b/admin/tool/brickfield/classes/task/update_summarydata.php @@ -0,0 +1,53 @@ +. + +namespace tool_brickfield\task; + +use tool_brickfield\accessibility; +use tool_brickfield\brickfieldconnect; +use tool_brickfield\manager; +use tool_brickfield\registration; + +/** + * Task function to update this site's summary data to the Brickfield database. + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class update_summarydata extends \core\task\scheduled_task { + + /** + * Return the task's name as shown in admin screens. + * + * @return string + */ + public function get_name() { + return get_string('updatesummarydata', manager::PLUGINNAME); + } + + /** + * Execute the task + */ + public function execute() { + // If this feature has been disabled, do nothing. + if (accessibility::is_accessibility_enabled()) { + if ((new brickfieldconnect())->send_summary()) { + (new registration())->mark_summary_data_sent(); + } + } + } +} diff --git a/admin/tool/brickfield/db/access.php b/admin/tool/brickfield/db/access.php new file mode 100644 index 0000000000000..a3dfdda9b3578 --- /dev/null +++ b/admin/tool/brickfield/db/access.php @@ -0,0 +1,48 @@ +. + +/** + * Capability definition for tool_brickfield. + * + * @package tool_brickfield + * @category admin + * @copyright 2020 Brickfield Education Labs, https://www.brickfield.ie - Author: Karen Holland + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$capabilities = [ + 'tool/brickfield:viewcoursetools' => [ + 'riskbitmask' => RISK_PERSONAL, + 'captype' => 'read', + 'contextlevel' => CONTEXT_COURSE, + 'archetypes' => [ + 'teacher' => CAP_ALLOW, + 'editingteacher' => CAP_ALLOW, + 'manager' => CAP_ALLOW, + ], + 'clonepermissionsfrom' => 'coursereport/participation:view', + ], + 'tool/brickfield:viewsystemtools' => [ + 'riskbitmask' => RISK_CONFIG, + 'captype' => 'read', + 'contextlevel' => CONTEXT_SYSTEM, + 'archetypes' => [ + 'manager' => CAP_ALLOW, + ], + ], +]; diff --git a/admin/tool/brickfield/db/events.php b/admin/tool/brickfield/db/events.php new file mode 100644 index 0000000000000..9c43c5c5c7082 --- /dev/null +++ b/admin/tool/brickfield/db/events.php @@ -0,0 +1,154 @@ +. + +/** + * Add event handlers for the accessibility report + * + * @package tool_brickfield + * @category event + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$observers = [ + [ + 'eventname' => '\tool_brickfield\event\plugin_installed', + 'callback' => '\tool_brickfield\eventobservers::plugin_installed', + 'priority' => 1 + ], + [ + 'eventname' => '\core\event\course_category_created', + 'callback' => '\tool_brickfield\eventobservers::course_category_created', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_category_deleted', + 'callback' => '\tool_brickfield\eventobservers::course_category_deleted', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_category_restored', + 'callback' => '\tool_brickfield\eventobservers::course_category_restored', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_category_updated', + 'callback' => '\tool_brickfield\eventobservers::course_category_updated', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_created', + 'callback' => '\tool_brickfield\eventobservers::course_created', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_deleted', + 'callback' => '\tool_brickfield\eventobservers::course_deleted', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_restored', + 'callback' => '\tool_brickfield\eventobservers::course_restored', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_updated', + 'callback' => '\tool_brickfield\eventobservers::course_updated', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_section_created', + 'callback' => '\tool_brickfield\eventobservers::course_section_created', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_section_deleted', + 'callback' => '\tool_brickfield\eventobservers::course_section_deleted', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_section_updated', + 'callback' => '\tool_brickfield\eventobservers::course_section_updated', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_module_created', + 'callback' => '\tool_brickfield\eventobservers::course_module_created', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_module_restored', + 'callback' => '\tool_brickfield\eventobservers::course_module_restored', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_module_updated', + 'callback' => '\tool_brickfield\eventobservers::course_module_updated', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\course_module_deleted', + 'callback' => '\tool_brickfield\eventobservers::course_module_deleted', + 'internal' => false, + ], + [ + 'eventname' => '\mod_lesson\event\page_created', + 'callback' => '\tool_brickfield\eventobservers::mod_lesson_page_created', + 'internal' => false, + ], + [ + 'eventname' => '\mod_lesson\event\page_deleted', + 'callback' => '\tool_brickfield\eventobservers::mod_lesson_page_deleted', + 'internal' => false, + ], + [ + 'eventname' => '\mod_lesson\event\page_updated', + 'callback' => '\tool_brickfield\eventobservers::mod_lesson_page_updated', + 'internal' => false, + ], + [ + 'eventname' => '\mod_book\event\chapter_created', + 'callback' => '\tool_brickfield\eventobservers::book_chapter_created', + 'internal' => false, + ], + [ + 'eventname' => '\mod_book\event\chapter_deleted', + 'callback' => '\tool_brickfield\eventobservers::book_chapter_deleted', + 'internal' => false, + ], + [ + 'eventname' => '\mod_book\event\chapter_updated', + 'callback' => '\tool_brickfield\eventobservers::book_chapter_updated', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\question_created', + 'callback' => '\tool_brickfield\eventobservers::core_question_created', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\question_updated', + 'callback' => '\tool_brickfield\eventobservers::core_question_updated', + 'internal' => false, + ], + [ + 'eventname' => '\core\event\question_deleted', + 'callback' => '\tool_brickfield\eventobservers::core_question_deleted', + 'internal' => false, + ], +]; diff --git a/admin/tool/brickfield/db/install.php b/admin/tool/brickfield/db/install.php new file mode 100644 index 0000000000000..d4dba10b02634 --- /dev/null +++ b/admin/tool/brickfield/db/install.php @@ -0,0 +1,44 @@ +. + +/** + * Install code for Brickfield accessibility local plugin. + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs, https://www.brickfield.ie - Author: Karen Holland + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die; + +/** + * Perform the post-install procedures. + */ +function xmldb_tool_brickfield_install() { + global $DB, $CFG; + + $filepath = $CFG->dirroot . "/admin/tool/brickfield/json/checks.json"; + $checksjson = file_get_contents($filepath); + $records = json_decode($checksjson); + + foreach ($records->checks as $record) { + // Convert checkgroup names into integer values where necessary. + if (isset($record->checkgroup) && !is_numeric($record->checkgroup)) { + $record->checkgroup = \tool_brickfield\area_base::checkgroup_value($record->checkgroup); + } + $DB->insert_record('tool_brickfield_checks', $record, false); + } +} diff --git a/admin/tool/brickfield/db/install.xml b/admin/tool/brickfield/db/install.xml new file mode 100755 index 0000000000000..03484e3a3ff63 --- /dev/null +++ b/admin/tool/brickfield/db/install.xml @@ -0,0 +1,214 @@ + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + +
+
+
diff --git a/admin/tool/brickfield/db/tasks.php b/admin/tool/brickfield/db/tasks.php new file mode 100644 index 0000000000000..5cb5cf6eb2919 --- /dev/null +++ b/admin/tool/brickfield/db/tasks.php @@ -0,0 +1,78 @@ +. + +/** + * Tasks page + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die; + +$tasks = [ + [ + 'classname' => 'tool_brickfield\task\bulk_process_courses', + 'blocking' => 0, + 'minute' => '*/5', + 'hour' => '*', + 'day' => '*', + 'dayofweek' => '*', + 'month' => '*', + 'disabled' => false + ], + [ + 'classname' => 'tool_brickfield\task\bulk_process_caches', + 'blocking' => 0, + 'minute' => '*/5', + 'hour' => '*', + 'day' => '*', + 'dayofweek' => '*', + 'month' => '*', + 'disabled' => false + ], + [ + 'classname' => 'tool_brickfield\task\checkid_validation', + 'blocking' => 0, + 'minute' => '05', + 'hour' => '9', + 'day' => '*', + 'dayofweek' => '*', + 'month' => '*', + 'disabled' => false + ], + [ + 'classname' => 'tool_brickfield\task\update_summarydata', + 'blocking' => 0, + 'minute' => '50', + 'hour' => '0', + 'day' => '*', + 'dayofweek' => '*', + 'month' => '*', + 'disabled' => false + ], + [ + 'classname' => 'tool_brickfield\task\process_analysis_requests', + 'blocking' => 0, + 'minute' => '*/5', + 'hour' => '*', + 'day' => '*', + 'dayofweek' => '*', + 'month' => '*', + 'disabled' => false + ], +]; diff --git a/admin/tool/brickfield/db/uninstall.php b/admin/tool/brickfield/db/uninstall.php new file mode 100644 index 0000000000000..049faf905ff18 --- /dev/null +++ b/admin/tool/brickfield/db/uninstall.php @@ -0,0 +1,28 @@ +. + +/** + * Uninstall code for Brickfield accessibility local plugin. + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs, https://www.brickfield.ie - Author: Karen Holland + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die; + +// Remove the 'enableaccessibilitytools' configuration setting in case of reinstall. +unset_config('enableaccessibilitytools'); diff --git a/admin/tool/brickfield/index.php b/admin/tool/brickfield/index.php new file mode 100644 index 0000000000000..3f9a4b038b029 --- /dev/null +++ b/admin/tool/brickfield/index.php @@ -0,0 +1,152 @@ +. + +/** + * Accessibility report + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +use tool_brickfield\event\report_downloaded; +use tool_brickfield\event\report_viewed; +use tool_brickfield\accessibility; +use tool_brickfield\analysis; +use tool_brickfield\local\tool\filter; +use tool_brickfield\local\tool\tool; +use tool_brickfield\manager; +use tool_brickfield\output\renderer; +use tool_brickfield\registration; +use tool_brickfield\scheduler; +use tool_brickfield\task\process_analysis_requests; + +require('../../../config.php'); + +// If this feature has been disabled, do nothing. +accessibility::require_accessibility_enabled(); + +// Check for valid registration. +$registration = new registration(); +if (!$registration->toolkit_is_active()) { + $urlregistration = manager::registration_url(); + redirect($urlregistration->out()); +} + +$config = get_config(manager::PLUGINNAME); +$courseid = optional_param('courseid', 0, PARAM_INT); +$categoryid = optional_param('categoryid', 0, PARAM_INT); +$tab = optional_param('tab', 'errors', PARAM_ALPHA); +$page = optional_param('page', 0, PARAM_INT); +$target = optional_param('target', '', PARAM_ALPHA); +$layout = optional_param('layout', 'admin', PARAM_ALPHA); + +if ($courseid != 0) { + // If accessing a course, check that the user has capability to use toolkit at course level. + if (!$course = $DB->get_record('course', ['id' => $courseid], '*')) { + print_error('invalidcourseid', manager::PLUGINNAME); + } + require_login($course); + $context = context_course::instance($courseid); + require_capability(accessibility::get_capability_name('viewcoursetools'), $context); +} else if ($categoryid != 0) { + require_login(); + $context = context_coursecat::instance($categoryid); + require_capability(accessibility::get_capability_name('viewcoursetools'), $context); +} else { + require_login(); + // If accessing system level, check that the user has capability to use toolkit at system level. + $context = context_system::instance(); + require_capability(accessibility::get_capability_name('viewsystemtools'), $context); +} + +// Event logging of page view or summary download. +if ($target == 'pdf') { + $event = report_downloaded::create(['context' => $context]); +} else { + $event = report_viewed::create(['context' => $context, + 'other' => ['course' => $courseid, 'category' => $categoryid, 'tab' => $tab, 'target' => $target]]); +} +$event->trigger(); + +$action = optional_param('action', '', PARAM_ALPHA); +// Handle any single operation actions. +if ($action == 'requestanalysis') { + if ($courseid != 0) { + scheduler::request_course_analysis($courseid); + if ($courseid == SITEID) { + redirect(accessibility::get_plugin_url()); + } else { + redirect(new \moodle_url('/course/view.php', ['id' => $courseid]), analysis::redirect_message()); + } + } +} + +// We need all of the tools available for various functions in the renderers. +$tools = tool::build_all_accessibilitytools(); +if (isset($tools[$tab])) { + $tool = $tools[$tab]; +} else { + print_error('invalidaccessibilitytool', manager::PLUGINNAME); +} + +$perpagedefault = $config->perpage; +$perpage = optional_param('perpage', $perpagedefault, PARAM_INT); +$navurl = new moodle_url(accessibility::get_plugin_url(), ['courseid' => $courseid]); +$url = new moodle_url($navurl, ['tab' => $tab, 'perpage' => $perpage]); + +$tool->set_filter(new filter($courseid, $categoryid, $tab, $page, $perpage, $url, $target)); + +$PAGE->navigation->override_active_url($navurl); +$PAGE->set_context($context); +$PAGE->set_url($url); +$PAGE->set_pagelayout($layout); +$straccessibility = get_string('accessibilityreport', manager::PLUGINNAME); +$output = $PAGE->get_renderer(manager::PLUGINNAME); +$toolname = $tool->get_toolshortname(); +$PAGE->set_title($toolname.' '.$straccessibility); +$PAGE->set_heading($straccessibility); + +if ($tool->data_is_valid() && ($tool->get_output_target() == 'pdf')) { + // PDF output doesn't return. + $tool->get_output(); +} else { + echo $output->header(); + $courseid = ($courseid == 0) ? SITEID : $courseid; + if (analysis::is_course_analyzed($courseid)) { + echo $output->tabs($tool->get_filter(), $tools); + echo $output->cachealert(); + + if ($registration->validation_pending()) { + echo $output->notvalidatedalert(); + } + + if (!$tool->data_is_valid()) { + echo($tool->data_error()); + } else { + echo $tool->get_output(); + } + } else { + $analysisdisabled = $output->cachealert(); + if (!empty($analysisdisabled)) { + echo $analysisdisabled; + } else { + echo $output->analysisalert($courseid); + } + } + + echo $output->footer(); +} diff --git a/admin/tool/brickfield/json/checks.json b/admin/tool/brickfield/json/checks.json new file mode 100644 index 0000000000000..fb8811772c236 --- /dev/null +++ b/admin/tool/brickfield/json/checks.json @@ -0,0 +1,219 @@ +{"checks":[ + { + "checktype":"full", + "shortname":"a_links_dont_open_new_window", + "checkgroup":"link", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"a_must_contain_text", + "checkgroup":"link", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"area_dont_open_new_window", + "checkgroup":"link", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"area_has_alt_value", + "checkgroup":"link", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"a_suspicious_link_text", + "checkgroup":"link", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"basefont_is_not_used", + "checkgroup":"text", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"blink_is_not_used", + "checkgroup":"text", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"bold_is_not_used", + "checkgroup":"text", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"content_too_long", + "checkgroup":"text", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"css_text_has_contrast", + "checkgroup":"text", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"embed_has_associated_no_embed", + "checkgroup":"text", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"header_h3", + "checkgroup":"layout", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"headers_have_text", + "checkgroup":"layout", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"i_is_not_used", + "checkgroup":"text", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"img_alt_is_different", + "checkgroup":"image", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"img_alt_is_too_long", + "checkgroup":"image", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"img_alt_not_empty_in_anchor", + "checkgroup":"image", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"img_alt_not_place_holder", + "checkgroup":"image", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"img_has_alt", + "checkgroup":"image", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"img_with_map_has_use_map", + "checkgroup":"image", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"legend_text_not_empty", + "checkgroup":"text", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"marquee_is_not_used", + "checkgroup":"text", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"no_headings", + "checkgroup":"layout", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"object_must_have_embed", + "checkgroup":"media", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"object_must_have_title", + "checkgroup":"media", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"object_must_have_valid_title", + "checkgroup":"media", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"strike_is_not_used", + "checkgroup":"text", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"table_data_should_have_th", + "checkgroup":"table", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"table_summary_does_not_duplicate_caption", + "checkgroup":"table", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"table_td_should_not_merge", + "checkgroup":"table", + "status":"1", + "severity":"1" + }, + { + "checktype":"full", + "shortname":"table_th_should_have_scope", + "checkgroup":"table", + "status":"1", + "severity":"1" + } +]} diff --git a/admin/tool/brickfield/lang/en/tool_brickfield.php b/admin/tool/brickfield/lang/en/tool_brickfield.php new file mode 100644 index 0000000000000..9667c8888ebbf --- /dev/null +++ b/admin/tool/brickfield/lang/en/tool_brickfield.php @@ -0,0 +1,334 @@ +. + +/** + * Plugin strings are defined here. + * + * @package tool_brickfield + * @category string + * @copyright 2020 Brickfield Education Labs, https://www.brickfield.ie - Author: Karen Holland + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$string['pluginname'] = 'Accessibility toolkit'; +$string['accessibility'] = 'Accessibility'; +$string['accessibilitydisabled'] = 'The Brickfield accessibility toolkit is not enabled on this site. Contact your site administrator to enable.'; +$string['accessibilityreport'] = 'Accessibility Report'; +$string['analysistype'] = 'Enable analysis requests'; +$string['analysistypedisabled'] = 'Content analysis is disabled'; +$string['analysistype_desc'] = 'Prevent content analysis from being requested'; +$string['analysis:disabled'] = 'Disabled'; +$string['analysis:byrequest'] = 'By request'; +$string['brickfield'] = 'Brickfield toolkit'; +$string['brickfield:viewcoursetools'] = 'View reports per courses'; +$string['brickfield:viewsystemtools'] = 'View reports for all courses'; +$string['accessibilitytool'] = 'Brickfield accessibility tool'; +$string['accessibilitytools'] = 'Brickfield accessibility tools'; +$string['allcourses'] = 'All reviewed courses ({$a})'; +$string['allcoursescat'] = 'All reviewed courses for category {$a->catname} ({$a->count})'; +$string['batch'] = 'Batch limit'; +$string['bulkprocesscaches'] = 'Process bulk caching'; +$string['bulkprocesscourses'] = 'Process bulk batch accessibility checking'; +$string['cachepending'] = 'The summary data is being compiled'; +$string['checkidvalidation'] = 'Task to check for any invalid checkids'; +$string['checkscompleted'] = 'Checks completed: {$a}'; +$string['checktype'] = 'Check group'; +$string['checktype:form'] = 'Form'; +$string['checktype:image'] = 'Image'; +$string['checktype:layout'] = 'Layout'; +$string['checktype:link'] = 'Link'; +$string['checktype:media'] = 'Media'; +$string['checktype:table'] = 'Table'; +$string['checktype:text'] = 'Text'; +$string['cmpercent'] = 'Percentage of activities overall'; +$string['cmpercenterrors'] = 'Percentage of errors overall'; +$string['cmpercenttitle'] = 'Overall % breakdown of activities versus errors'; +$string['confirmationmessage'] = 'This course has been scheduled for analysis. Analysis will be completed at the earliest +by {$a}. Check back after then.'; +$string['contactadmin'] = 'Please contact your administrator to complete the registration.'; +$string['contextid'] = 'Contextid'; +$string['core_course'] = 'Course'; +$string['core_question'] = 'Question Banks'; +$string['count'] = 'Count'; +$string['coursecount'] = 'Num of Courses'; +$string['deletehistoricaldata'] = 'Delete historical checks results'; +$string['dependency'] = 'Dependent on'; +$string['emptycategory'] = 'No courses found for category {$a}'; +$string['emptytagcourses'] = 'No results found for courses with configured tags'; +$string['enableaccessibilitytools'] = 'Enable accessibility tools'; +$string['enableaccessibilitytools_desc'] = 'Provides tools to help ensure accessible content for your site'; +$string['errorlink'] = 'Edit error instance for {$a}'; +$string['errors'] = 'Errors: {$a}'; +$string['eventanalysis_requested'] = 'Content analysis requested'; +$string['eventanalysis_requesteddesc'] = 'Content analysis was requested for course {$a}.'; +$string['eventreport_viewed'] = 'Accessibility report viewed'; +$string['eventreport_vieweddesc'] = 'Accessibility report was viewed for course id {$a->course}, +category id {$a->category}, tab {$a->tab}.'; +$string['eventreport_downloaded'] = 'Accessibility summary downloaded'; +$string['eventreport_downloadeddesc'] = 'Accessibility summary was downloaded for course id {$a}.'; +$string['failed'] = 'Failed'; +$string['tools'] = 'Go to reports'; +$string['formcorrectlysubmitted'] = 'Check Process successfully added'; +$string['formdescription'] = 'This will add a new check process record which will run as a scheduled task'; +$string['formtitle'] = 'Add Check Process'; +$string['fullcachedone'] = 'Disable to rerun caching'; +$string['googleapikey'] = 'Google API Key'; +$string['googleapikeydesc'] = 'Allows access to check Google YouTube video captioning data, see + Google Developers Guide'; +$string['grouppercentage'] = 'Percentage passed/not per check group'; +$string['groupratio'] = 'Ratio of area instances passed/not per check group'; +$string['hideshow'] = 'Hide/show'; +$string['innercontextid'] = 'Inner contextid'; +$string['invalidaccessibilitytool'] = 'Invalid accessibility subplugin requested.'; +$string['invalidcategoryid'] = 'Invalid category, please check your input'; +$string['invalidcourseid'] = 'Invalid course, please check your input'; +$string['invalidlinkphrases'] = 'click|click here|here|more|more here|info|info here|information|information here|read more|read more here|further information|further information here|further details|further details here'; +$string['module'] = 'Module'; +$string['modulename'] = 'Name'; +$string['linkdesc:advanced'] = 'There are many more tools available with a premium subscription. Information here.'; +$string['linkdesc:activityresults'] = 'View your rates of accessibility compliance across Moodle activity types'; +$string['linkdesc:checkdescriptions'] = 'Details of accessibility checks conducted'; +$string['linkdesc:checkresults'] = 'View your rates of accessibility compliance across each accessibility check'; +$string['linkdesc:checktyperesults'] = 'View your rates of accessibility compliance across each HTML content type'; +$string['linkdesc:coursecategories'] = 'View your rates of accessibility compliance across each top level category'; +$string['linkdesc:courses'] = 'View your rates of accessibility compliance across each course'; +$string['linkdesc:coursetags'] = 'View your rates of accessibility compliance across each course tag'; +$string['linkdesc:errors'] = 'Review your accessibility error findings, and find and fix them quickly'; +$string['linkdesc:printable'] = 'Review and download your course\'s accessibility transcript.'; +$string['managetools'] = 'Manage tools'; +$string['lookuppending'] = 'Lookup pending'; +$string['noerrorsfound'] = 'No common accessibility errors were found for your search parameters, congratulations!'; +$string['norecords'] = 'No relevant records were found for your search parameters.'; +$string['excludedcategories'] = 'Excluded category IDs'; +$string['excludedcategoriesdesc'] = 'Comma separated string of excluded category IDs, +to limit all processing to exclude courses within these categories and sub-categories'; +$string['notregistered'] = 'Your accessibility toolkit needs to be registered.'; +$string['notvalidated'] = 'Your accessibility toolkit is still being validated.'; +$string['numinstances'] = 'Number of instances'; +$string['pagedesc:checktype'] = '

In order to summarise and analyse the results of the various checks conducted, we group these checks into different content types. Hence, all image-related accessibility check results are in the "Image" content type group, all layout-related accessibility check results are in the "Layout" content type group, and so on.

Activities are included as either activities, resources or content areas relating to the courses themselves.

The content type chart page displays the error breakdown per content type group: Image, Layout, Link, Media, Table, and Text.

'; +$string['pagedesc:pertarget'] = '

In order to summarise and analyse the check results per activity, we group these check results into the different activities detected.

Activities are included as either activities, resources, or other content areas relating to the courses themselves. Each activity with no detected errors is counted as passed, each activity with one or more detected errors is counted as failed. The ratio of passed to failed activities is then displayed.

The activity breakdown chart page displays the ratio of passed to failed instances in total, per activity, such as assignment, course, label etc.

'; +$string['pagedesctitle:checktype'] = 'Content types explained'; +$string['pagedesctitle:pertarget'] = 'Activity breakdown explained'; +$string['passed'] = 'Passed'; +$string['passrate'] = 'Pass rate: {$a}%'; +$string['perpage'] = 'Items to show per page'; +$string['privacy:metadata'] = 'The Accessibility checks report plugin does not store any personal data.'; +$string['processanalysisrequests'] = 'Process content analysis requests'; +$string['processlinktitle'] = 'Process Link Title'; +$string['registernow'] = 'Please register now.'; +$string['registrationinfo'] = '

This registration process allows you to use the Brickfield accessibility toolkit freemium version +for your registered Moodle site.

+

This usage is subject to these {$a} and which you agree to, by using this +product.

'; +$string['remaining'] = ' ({$a} errors remaining)'; +$string['response:0'] = 'This URL doesn\'t point anywhere'; +$string['response:404'] = 'This URL page was not found'; +$string['returntomain'] = 'Return to Overview'; +$string['schedule:blocknotscheduled'] = '

This course has not yet been scheduled for analysis, to find common accessibility issues.

Please view the Accessibility toolkit help page for further details.

'; +$string['schedule:notscheduled'] = '

This course has not yet been scheduled for analysis, to find common accessibility issues.

By clicking on the "Submit for analysis" button, you confirm that you want all your relevant course HTML content, such as course section descriptions, activity descriptions, questions, pages, and more, to be scheduled for analysis.

This analysis will conduct multiple common accessibility checks on your course HTML content, and those results will then display on these Accessibility toolkit report pages.

Please view the Accessibility toolkit help page for further details.

This analysis will be processed in the background, by the Moodle scheduled tasks, so its speed of completion will depend on task timings and task run schedules.'; +$string['schedule:requestanalysis'] = 'Submit for analysis'; +$string['schedule:scheduled'] = 'This course has been scheduled for analysis.'; +$string['schedule:sitenotscheduled'] = 'The global (course independent) content has not yet been scheduled for analysis, to find common accessibility issues.

By clicking on the "Submit for analysis" button, you confirm that you want all your relevant global (course independant) content to be scheduled for analysis.

This analysis will conduct multiple common accessibility checks on this content, and those results will then display on these Accessibility toolkit report pages.

Please view the Accessibility toolkit help page for further details.

This analysis will be processed in the background, by the Moodle scheduled tasks, so its speed of completion will depend on task timings and task run schedules.'; +$string['schedule:sitescheduled'] = 'The global (course independent) content has been scheduled for analysis.'; +$string['setting:checktypestr'] = 'Explanation display for checktype chart'; +$string['setting:pertargetstr'] = 'Explanation display for per activity chart'; +$string['tabamount'] = 'Display Amount'; +$string['taberrors'] = 'Check Errors'; +$string['taberrortotal'] = 'Display Error Totals'; +$string['tabpassrate'] = 'Display Pass Rate'; +$string['tabpercheck'] = 'Per Check Results'; +$string['tabpercent'] = 'Display Percentage'; +$string['tabpercourse'] = 'Courses breakdown'; +$string['tabpertag'] = 'Course tags breakdown'; +$string['tabpertarget'] = 'Per Activity Results'; +$string['tabpertype'] = 'Checktype Results'; +$string['tabresults'] = 'Overview'; +$string['tabshowerrors'] = 'Show Checks With Errors'; +$string['tabshowall'] = 'Show All Checks'; +$string['tabtags'] = 'Tags'; +$string['tagnotshowing'] = 'If your course tag is not showing here, check with your Moodle administrator to add it to the configured tags for this report'; +$string['tagnotshowingadmin'] = 'Click here to add or remove configured tags'; +$string['targetavetitle'] = 'Average errors per activity'; +$string['targetpercentage'] = 'Percentage of instances passed/not per activity'; +$string['targetratio'] = 'Activity Pass Ratio'; +$string['tblcheck'] = 'Check'; +$string['tblcheckexample'] = 'Example'; +$string['tblcheckfailed'] = 'Checks failed'; +$string['tblchecksummary'] = 'Summary'; +$string['tblerrorcount'] = 'Errors'; +$string['tbledit'] = 'Edit'; +$string['tblhtmlcode'] = 'Existing HTML code'; +$string['tblinstance'] = 'Instance'; +$string['tblline'] = 'Line'; +$string['tbloverallpercentage'] = 'Overall errors %'; +$string['tblpercentage'] = 'Percentage'; +$string['tblpreview'] = 'Preview'; +$string['tbltarget'] = 'Activity'; +$string['tblupdateto'] = 'Update to'; +$string['termsandconditions'] = '

These are the terms and conditions you agree to... blah blah...

'; +$string['termsandconditionslink'] = 'terms and conditions'; +$string['titleerrors'] = 'Error details'; +$string['titleerrorscount'] = ' (Showing first {$a} errors)'; +$string['titlepercategory'] = 'Course activities pass rate % per top category'; +$string['titlepercategoryamount'] = 'Course activities failed per top category'; +$string['titlepercheck'] = 'Total errors per check'; +$string['titlepercourse'] = 'Course activities pass rate % per course'; +$string['titlepercourseamount'] = 'Course activities failed per course'; +$string['titlepertag'] = 'Course activities pass rate % per tag'; +$string['titlepertagamount'] = 'Course activities failed per tag'; +$string['titlepertag2'] = 'Shows data related to globally configured tags only'; +$string['titlepertarget'] = 'Results per activity'; +$string['titlepertype'] = 'Results per content type'; +$string['titleresults'] = 'Overview Summary'; +$string['toptargets'] = 'Failed activities'; +$string['toperrors'] = 'Top errors'; +$string['totalactivities'] = 'Total activities'; +$string['totalareas'] = 'Total areas'; +$string['totalerrors'] = 'Total errors'; +$string['totalgrouperrors'] = 'Total (sum) errors per content type'; +$string['totaltargetinstances'] = 'Total instances per activity'; +$string['totaltargeterrors'] = 'Total (sum) errors per activity'; +$string['updatesummarydata'] = 'Update site summarydata'; +$string['messageprovider:warningcheckid'] = 'Warning of invalid checkids'; +$string['warningcheckidbody'] = 'There is an issue with a Brickfield check + which is active but not listed in the database. Please investigate.'; +$string['warningcheckidsubject'] = 'Brickfield Toolkit CheckID warning'; +$string['warningscontact'] = 'Email address for receiving warnings'; +$string['warningscontact_desc'] = 'An email address to receive any Brickfield Toolkit warnings'; + +// Check descriptions. +$string['checkdesc:alinksdontopennewwindow'] = 'Links opening into a new window should warn users in advance'; +$string['checkdesc:amustcontaintext'] = 'A link needs to contain text to be perceivable'; +$string['checkdesc:areadontopennewwindow'] = 'Areas, used in image maps, opening into a new window should warn users in advance'; +$string['checkdesc:areahasaltvalue'] = 'Areas, used in image maps, should not be missing "alt" (alternative) text, similar to images'; +$string['checkdesc:asuspiciouslinktext'] = 'Link text should be descriptive and provide context about its destination'; +$string['checkdesc:basefontisnotused'] = 'Basefont elements (traditionally used for formatting) are not accessible and should not be used'; +$string['checkdesc:blinkisnotused'] = 'Blink elements, which blink on and off, are not accessible and should not be used'; +$string['checkdesc:boldisnotused'] = '"Bold" (b) elements should not be used, "strong" should be used instead'; +$string['checkdesc:contenttoolong'] = 'Overall page content length should not exceed 500 words.'; +$string['checkdesc:csstexthascontrast'] = 'Color contrast between the text and background is too low'; +$string['checkdesc:embedhasassociatednoembed'] = 'Embed elements (for embedding multimedia) should not be missing their corresponding "noembed" elements'; +$string['checkdesc:headerh3'] = 'Headers following after H3 headers (the editor large header option) should not break the page heading hierarchy'; +$string['checkdesc:headershavetext'] = 'A header needs to contain text to be perceivable'; +$string['checkdesc:iisnotused'] = '"Italic" (i) elements should not be used, "em" should be used instead'; +$string['checkdesc:imgaltisdifferent'] = 'Image Alt (Alternative) Text should not be the image filename'; +$string['checkdesc:imgaltistoolong'] = 'Image Alt (Alternative) Text should not be more than the maximum allowed (125) characters'; +$string['checkdesc:imgaltnotemptyinanchor'] = 'Image Alt (Alternative) Text should not be empty, especially when image is a link going elsewhere'; +$string['checkdesc:imgaltnotplaceholder'] = 'Image Alt (Alternative) Text should not be a simple placeholder text, such as "image"'; +$string['checkdesc:imghasalt'] = 'Image Alt (Alternative) Text should not missing for image elements, unless purely decorative with no meaning'; +$string['checkdesc:imgwithmaphasusemap'] = 'Image maps, with clickable areas, need matching "usemap" and "map" elements'; +$string['checkdesc:legendtextnotempty'] = '"Legend" elements, used for captioning fieldset elements, should contain text'; +$string['checkdesc:marqueeisnotused'] = '"Marquee" (auto-scrolling) elements are not accessible and should not be used'; +$string['checkdesc:noheadings'] = 'No headers makes content less structured and harder to read'; +$string['checkdesc:objectmusthaveembed'] = '"Object" elements (for embedding external resources) should not be missing their corresponding "embed" elements'; +$string['checkdesc:objectmusthavetitle'] = '"Object" elements (for embedding external resources) should not be missing their corresponding "title" descriptions'; +$string['checkdesc:objectmusthavevalidtitle'] = '"Object" elements (for embedding external resources) should have corresponding "titles" with text'; +$string['checkdesc:strikeisnotused'] = '"Strike" (strike-through) elements should not be used, "del" (deleted) should be used instead'; +$string['checkdesc:tabledatashouldhaveth'] = 'Tables ideally should not be missing headers'; +$string['checkdesc:tablesummarydoesnotduplicatecaption'] = 'Table "summaries" and "captions" should not be identical'; +$string['checkdesc:tabletdshouldnotmerge'] = 'Tables ideally should not have any merged cells'; +$string['checkdesc:tablethshouldhavescope'] = 'Table row or column "scopes" (used to map row and column to each cell) should be declared'; + +// Registration process. +$string['activate'] = 'Activate'; +$string['activated'] = 'The plugin is activated and ready to use.'; +$string['activationform'] = 'Brickfield registration'; +$string['activationheader'] = 'Brickfield Activation'; +$string['activationinfo'] = 'In order to use this plugin, you must be registered, or have a valid code for this platform. If you are not already registered, please {$a}register your details.
After registration, you will then have online access to the keys that you must submit in this form.'; +$string['automatedsentdaily'] = ''; +$string['country'] = 'Country'; +$string['country_help'] = 'Country of the site'; +$string['hashcorrect'] = 'The entered code is correct.'; +$string['hashincorrect'] = 'The entered code is not correct.'; +$string['inactive'] = 'The plugin is inactive and cannot be used. Please enter valid registration keys, and press activate.'; +$string['installed'] = 'Plugin installed'; +$string['installedcli'] = 'Plugin installed via command line'; +$string['installeddescription'] = 'The plugin has been installed, redirect to activation form.'; +$string['language'] = 'Language'; +$string['language_help'] = 'Language of the site'; +$string['mail'] = 'Email'; +$string['mail_help'] = 'This email will be used to register the account'; +$string['mobileservice'] = 'Mobile services enabled ({$a})'; +$string['moreinfo'] = 'More information'; +$string['notifications'] = 'Receive notifications'; +$string['notifications_help'] = 'Set to "Yes" if you want to receive email notifications. If enabled, you can set another email to receive these notifications.'; +$string['numcourses'] = 'Number of courses ({$a})'; +$string['numfactivities'] = 'Number of activities ({$a})'; +$string['numfiles'] = 'Number of files ({$a})'; +$string['numusers'] = 'Number of users ({$a})'; +$string['privacy'] = 'Privacy notice and data processing agreement'; +$string['privacy_help'] = 'Access the link to read the entire policy'; +$string['privacydesc'] = 'I agree to the Privacy notice and data processing agreement for someurl.com'; +$string['registerplugin'] = 'Register with {$a}'; +$string['registration'] = 'Registration Form'; +$string['registrationheader'] = 'Register here'; +$string['registrationheaderinfo'] = '

This registration process allows you to use the Brickfield accessibility toolkit freemium version for your registered Moodle site.

This usage is subject to the terms and conditions as stated here and which you agree to, by using this product.

'; +$string['release'] = 'Moodle release ({$a})'; +$string['secretkey'] = 'API key'; +$string['secretkey_help'] = 'This code is received by email after registration.'; +$string['sendfollowinginfo'] = '

The following information will be sent to contribute to overall statistics only. It will not be made public on any central listing.

{$a}'; +$string['sitehash'] = 'Secret key'; +$string['sitehash_help'] = 'This code is received by email after registration.'; +$string['sitename'] = 'Site name'; +$string['sitename_help'] = 'The name of the site'; +$string['siteurl'] = 'Site URL'; +$string['siteurl_help'] = 'The URL of the site'; +$string['usedifferentemail'] = 'Use different email'; +$string['usersmobileregistered'] = 'Number of users with registered mobile devices ({$a})'; +$string['validationerror'] = 'Registration key validation has failed. Check that your keys are correct.'; + +// Tool section. +$string['activityresults:pluginname'] = 'Activity breakdown accessibility tool report'; +$string['activityresults:toolname'] = 'Activity breakdown summary'; +$string['activityresults:toolshortname'] = 'Activity breakdown'; +$string['advanced:pluginname'] = 'Advanced accessibility tool report'; +$string['advanced:toolname'] = 'Advanced summary'; +$string['advanced:toolshortname'] = 'Advanced'; +$string['checktyperesults:pluginname'] = 'Content types accessibility tool report'; +$string['checktyperesults:toolname'] = 'Content types summary'; +$string['checktyperesults:toolshortname'] = 'Content types'; +$string['errors:pluginname'] = 'Error list accessibility tool'; +$string['errors:toolname'] = 'Error list summary'; +$string['errors:toolshortname'] = 'Error list'; +$string['printable:pluginname'] = 'Summary report accessibility tool report'; +$string['printable:toolname'] = 'Summary report'; +$string['printable:toolshortname'] = 'Summary report'; +$string['printable:downloadpdf'] = 'Download PDF'; +$string['printable:printreport'] = 'Printable report'; +$string['error:nocoursespecified'] = '

This summary report requires a valid courseid.

Please access the accessibility toolkit from within a course, by using its Actions menu administration link to the Accessibility toolkit, which will then supply this required courseid.

'; +$string['pdf:filename'] = 'Brickfield_Summaryreport_CourseID-{$a}'; + +// Advanced page. +$string['bannercontentone'] = 'The Enterprise Accessibility Toolkit has a full set of features to help your organisation improve accessibility of your courses. {$a} to book a free demo of the advanced features.'; +$string['bannercontenttwo'] = 'Build an effective and inclusive teaching and learning platform by Finding content that does not meet the guidelines, Fixing the issues and Future-proofing your Moodle course content with accessible files, editor and enhanced features.'; +$string['bannerheadingone'] = 'Upgrade to the Enterprise Accessibility Toolkit'; +$string['contactus'] = 'Contact us'; +$string['buttonone'] = 'Get a Free Demo'; +$string['contentone'] = 'Automatically evaluate your course content and assessments for accessibility issues.'; +$string['contenttwo'] = 'Bulk update unclear or missing text for web links, image descriptions and video subtitles.'; +$string['contentthree'] = 'Provide your students with content in accessible formats including Audio, ePub and Electronic Braille.'; +$string['contentfour'] = 'Identify which activities have the most accessibility issues to prioritise effort.'; +$string['contentfive'] = 'Automatically fix out of date HTML tags.'; +$string['contentsix'] = 'Provide teachers with just in time tips for creating better content.'; +$string['footerheading'] = 'Footer section'; +$string['headingone'] = 'Evaluate content'; +$string['headingtwo'] = 'Remediation'; +$string['headingthree'] = 'Accessible file formats'; +$string['headingfour'] = 'Focus effort'; +$string['headingfive'] = 'HTML fixes'; +$string['headingsix'] = 'Performance support'; diff --git a/admin/tool/brickfield/lib.php b/admin/tool/brickfield/lib.php new file mode 100644 index 0000000000000..bde66b289f9ab --- /dev/null +++ b/admin/tool/brickfield/lib.php @@ -0,0 +1,88 @@ +. + +/** + * This file contains hooks and callbacks needed for the accessibility toolkit. + * + * @package tool_brickfield + * @category admin + * @copyright 2020 Brickfield Education Labs, https://www.brickfield.ie - Author: Karen Holland + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +use tool_brickfield\accessibility; +use tool_brickfield\manager; +use tool_brickfield\registration; + +/** + * This function extends the navigation with the report items + * + * @param navigation_node $navigation The navigation node to extend + * @param stdClass $course The course to object for the report + * @param context $context The context of the course + * @throws coding_exception + * @throws moodle_exception + */ +function tool_brickfield_extend_navigation_course(\navigation_node $navigation, \stdClass $course, \context $context) { + if (!accessibility::is_accessibility_enabled()) { + // The feature has been explicitly disabled. + return; + } + + if (!has_capability(accessibility::get_capability_name('viewcoursetools'), $context)) { + // The user does not have the capability to view the course tools. + return; + } + + // Display in the navigation if the user has site:config ability, or if the site is registered. + $enabled = has_capability('moodle/site:config', \context_system::instance()); + $enabled = $enabled || (new registration())->toolkit_is_active(); + if (!$enabled) { + return; + } + + $url = new moodle_url(accessibility::get_plugin_url(), ['courseid' => $course->id]); + $navigation->add( + get_string('pluginname', manager::PLUGINNAME), + $url, + navigation_node::TYPE_SETTING, + null, + null, + new pix_icon('i/report', '') + ); +} + +/** + * Get icon mapping for font-awesome. + * @return string[] + */ +function tool_brickfield_get_fontawesome_icon_map() { + return [ + manager::PLUGINNAME . ':f/award' => 'fa-tachometer', + manager::PLUGINNAME . ':f/done' => 'fa-check-circle-o', + manager::PLUGINNAME . ':f/done2' => 'fa-check-square-o', + manager::PLUGINNAME . ':f/error' => 'fa-times-circle-o', + manager::PLUGINNAME . ':f/find' => 'fa-bar-chart', + manager::PLUGINNAME . ':f/total' => 'fa-calculator', + manager::PLUGINNAME . ':f/form' => 'fa-pencil-square-o', + manager::PLUGINNAME . ':f/image' => 'fa-image', + manager::PLUGINNAME . ':f/layout' => 'fa-th-large', + manager::PLUGINNAME . ':f/link' => 'fa-link', + manager::PLUGINNAME . ':f/media' => 'fa-play-circle-o', + manager::PLUGINNAME . ':f/table' => 'fa-table', + manager::PLUGINNAME . ':f/text' => 'fa-font', + ]; +} diff --git a/admin/tool/brickfield/pix/b/pdfdown.svg b/admin/tool/brickfield/pix/b/pdfdown.svg new file mode 100644 index 0000000000000..3313da6cae97b --- /dev/null +++ b/admin/tool/brickfield/pix/b/pdfdown.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/tool/brickfield/pix/brickfield-logo-medium.png b/admin/tool/brickfield/pix/brickfield-logo-medium.png new file mode 100644 index 0000000000000..fba9b26573a56 Binary files /dev/null and b/admin/tool/brickfield/pix/brickfield-logo-medium.png differ diff --git a/admin/tool/brickfield/pix/brickfield-logo-small.png b/admin/tool/brickfield/pix/brickfield-logo-small.png new file mode 100644 index 0000000000000..2ab479146bc97 Binary files /dev/null and b/admin/tool/brickfield/pix/brickfield-logo-small.png differ diff --git a/admin/tool/brickfield/pix/brickfield-logo.png b/admin/tool/brickfield/pix/brickfield-logo.png new file mode 100644 index 0000000000000..157fb92226a5f Binary files /dev/null and b/admin/tool/brickfield/pix/brickfield-logo.png differ diff --git a/admin/tool/brickfield/pix/i/Brickfield-logo-black.png b/admin/tool/brickfield/pix/i/Brickfield-logo-black.png new file mode 100644 index 0000000000000..bd7f7db7a1e32 Binary files /dev/null and b/admin/tool/brickfield/pix/i/Brickfield-logo-black.png differ diff --git a/admin/tool/brickfield/pix/i/Brickfield-logo-white.png b/admin/tool/brickfield/pix/i/Brickfield-logo-white.png new file mode 100644 index 0000000000000..937380bbb60f7 Binary files /dev/null and b/admin/tool/brickfield/pix/i/Brickfield-logo-white.png differ diff --git a/admin/tool/brickfield/pix/i/analytics-custom.png b/admin/tool/brickfield/pix/i/analytics-custom.png new file mode 100644 index 0000000000000..c8b04eae8e6f1 Binary files /dev/null and b/admin/tool/brickfield/pix/i/analytics-custom.png differ diff --git a/admin/tool/brickfield/pix/i/brickfield_logo.jpeg b/admin/tool/brickfield/pix/i/brickfield_logo.jpeg new file mode 100644 index 0000000000000..55f94c653b2dd Binary files /dev/null and b/admin/tool/brickfield/pix/i/brickfield_logo.jpeg differ diff --git a/admin/tool/brickfield/pix/i/chart-network-custom.png b/admin/tool/brickfield/pix/i/chart-network-custom.png new file mode 100644 index 0000000000000..97e52593cde3c Binary files /dev/null and b/admin/tool/brickfield/pix/i/chart-network-custom.png differ diff --git a/admin/tool/brickfield/pix/i/edit-custom.png b/admin/tool/brickfield/pix/i/edit-custom.png new file mode 100644 index 0000000000000..cc7569fd35f45 Binary files /dev/null and b/admin/tool/brickfield/pix/i/edit-custom.png differ diff --git a/admin/tool/brickfield/pix/i/file-edit-custom.png b/admin/tool/brickfield/pix/i/file-edit-custom.png new file mode 100644 index 0000000000000..86e4c3342841a Binary files /dev/null and b/admin/tool/brickfield/pix/i/file-edit-custom.png differ diff --git a/admin/tool/brickfield/pix/i/hands-helping-custom.png b/admin/tool/brickfield/pix/i/hands-helping-custom.png new file mode 100644 index 0000000000000..ab732361431b4 Binary files /dev/null and b/admin/tool/brickfield/pix/i/hands-helping-custom.png differ diff --git a/admin/tool/brickfield/pix/i/lightbulb-custom.png b/admin/tool/brickfield/pix/i/lightbulb-custom.png new file mode 100644 index 0000000000000..b4ac5b416091d Binary files /dev/null and b/admin/tool/brickfield/pix/i/lightbulb-custom.png differ diff --git a/admin/tool/brickfield/pix/i/search-plus-custom.png b/admin/tool/brickfield/pix/i/search-plus-custom.png new file mode 100644 index 0000000000000..23862c3c73754 Binary files /dev/null and b/admin/tool/brickfield/pix/i/search-plus-custom.png differ diff --git a/admin/tool/brickfield/pix/i/tools-custom.png b/admin/tool/brickfield/pix/i/tools-custom.png new file mode 100644 index 0000000000000..a14b432dea43e Binary files /dev/null and b/admin/tool/brickfield/pix/i/tools-custom.png differ diff --git a/admin/tool/brickfield/pix/i/wand-magic-custom.png b/admin/tool/brickfield/pix/i/wand-magic-custom.png new file mode 100644 index 0000000000000..d7c1057c596e9 Binary files /dev/null and b/admin/tool/brickfield/pix/i/wand-magic-custom.png differ diff --git a/admin/tool/brickfield/pix/moodle-logo.png b/admin/tool/brickfield/pix/moodle-logo.png new file mode 100644 index 0000000000000..2da7b4af1b8a6 Binary files /dev/null and b/admin/tool/brickfield/pix/moodle-logo.png differ diff --git a/admin/tool/brickfield/pix/pdf/check-square-regular.svg b/admin/tool/brickfield/pix/pdf/check-square-regular.svg new file mode 100644 index 0000000000000..f17eed7250be9 --- /dev/null +++ b/admin/tool/brickfield/pix/pdf/check-square-regular.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/tool/brickfield/pix/pdf/font-solid.svg b/admin/tool/brickfield/pix/pdf/font-solid.svg new file mode 100644 index 0000000000000..48ad54dc2b8e6 --- /dev/null +++ b/admin/tool/brickfield/pix/pdf/font-solid.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/tool/brickfield/pix/pdf/image-regular.svg b/admin/tool/brickfield/pix/pdf/image-regular.svg new file mode 100644 index 0000000000000..1d85822473c2e --- /dev/null +++ b/admin/tool/brickfield/pix/pdf/image-regular.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/tool/brickfield/pix/pdf/link.png b/admin/tool/brickfield/pix/pdf/link.png new file mode 100644 index 0000000000000..12dd1876cbd2e Binary files /dev/null and b/admin/tool/brickfield/pix/pdf/link.png differ diff --git a/admin/tool/brickfield/pix/pdf/logo-black.png b/admin/tool/brickfield/pix/pdf/logo-black.png new file mode 100644 index 0000000000000..abbc392e7e552 Binary files /dev/null and b/admin/tool/brickfield/pix/pdf/logo-black.png differ diff --git a/admin/tool/brickfield/pix/pdf/play-circle-regular.svg b/admin/tool/brickfield/pix/pdf/play-circle-regular.svg new file mode 100644 index 0000000000000..452a779192792 --- /dev/null +++ b/admin/tool/brickfield/pix/pdf/play-circle-regular.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/tool/brickfield/pix/pdf/table-solid.svg b/admin/tool/brickfield/pix/pdf/table-solid.svg new file mode 100644 index 0000000000000..79e417b49cd8f --- /dev/null +++ b/admin/tool/brickfield/pix/pdf/table-solid.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/tool/brickfield/pix/pdf/tachometer-alt-solid.svg b/admin/tool/brickfield/pix/pdf/tachometer-alt-solid.svg new file mode 100644 index 0000000000000..857928212e255 --- /dev/null +++ b/admin/tool/brickfield/pix/pdf/tachometer-alt-solid.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/tool/brickfield/pix/pdf/th-large-solid.svg b/admin/tool/brickfield/pix/pdf/th-large-solid.svg new file mode 100644 index 0000000000000..0618c42ed447f --- /dev/null +++ b/admin/tool/brickfield/pix/pdf/th-large-solid.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/tool/brickfield/pix/pdf/times-circle-regular.svg b/admin/tool/brickfield/pix/pdf/times-circle-regular.svg new file mode 100644 index 0000000000000..3b489cb7bcc93 --- /dev/null +++ b/admin/tool/brickfield/pix/pdf/times-circle-regular.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/tool/brickfield/registration.php b/admin/tool/brickfield/registration.php new file mode 100644 index 0000000000000..f63e5cd321c41 --- /dev/null +++ b/admin/tool/brickfield/registration.php @@ -0,0 +1,91 @@ +. + +/** + * Registration configuration for the Brickfield too. + * + * @package tool_brickfield + * @author 2020 JM Tomas + * @copyright 2020 Brickfield Education Labs https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL + */ + +use tool_brickfield\brickfieldconnect; +use tool_brickfield\form\registration_form; +use tool_brickfield\manager; +use tool_brickfield\registration; + +require(__DIR__ . '/../../../config.php'); + +global $CFG, $OUTPUT, $PAGE; +require_once($CFG->libdir . '/adminlib.php'); +require_once($CFG->libdir . '/moodlelib.php'); + +// If this feature has been disabled, do nothing. +\tool_brickfield\accessibility::require_accessibility_enabled(); + +admin_externalpage_setup('tool_brickfield_activation'); +$PAGE->set_url(__DIR__ . '/registration.php'); + +$termsandconditions = optional_param('terms', 0, PARAM_BOOL); +if ($termsandconditions) { + $PAGE->set_pagelayout('popup'); + echo $OUTPUT->header(); + echo format_text(get_string('termsandconditions', 'tool_brickfield'), FORMAT_HTML, ['noclean' => true]); + echo $OUTPUT->footer(); + exit; +} + +$context = context_system::instance(); +$PAGE->set_context($context); +$PAGE->set_title(get_string('registration', manager::PLUGINNAME)); +$PAGE->set_heading(get_string('registration', manager::PLUGINNAME)); + +$registrationform = new registration_form(); + +echo $OUTPUT->header(); + +echo html_writer::img($OUTPUT->image_url('brickfield-logo-small', manager::PLUGINNAME), 'logo', + ['style' => 'display: block; margin: 0 auto; float: right;']); +echo $OUTPUT->heading(get_string('pluginname', manager::PLUGINNAME), 3); + +$url = new moodle_url('/admin/tool/brickfield/registration.php', ['terms' => 1]); +$action = new popup_action('click', $url, 'popup', ['height' => 400, 'width' => 600]); +$tandclinktext = get_string('termsandconditionslink', 'tool_brickfield'); +$a = $OUTPUT->action_link($url, $tandclinktext, $action, ['target' => '_blank']); +$reginfo = get_string('registrationinfo', 'tool_brickfield', $a); +echo format_text($reginfo, FORMAT_HTML, ['noclean' => true]); + +$registration = new registration(); +if ($fromform = $registrationform->get_data()) { + if (!$registration->set_keys_for_registration($fromform->key, $fromform->hash)) { + echo $OUTPUT->notification(get_string('hashincorrect', manager::PLUGINNAME), 'notifyproblem'); + } +} + +if (!$registration->toolkit_is_active()) { + echo $OUTPUT->notification(get_string('inactive', manager::PLUGINNAME), 'error'); +} else if ($registration->validation_pending()) { + if ($registration->validation_error()) { + echo $OUTPUT->notification(get_string('validationerror', manager::PLUGINNAME), 'error'); + } else { + echo $OUTPUT->notification(get_string('notvalidated', manager::PLUGINNAME), 'warning'); + } +} else { + echo $OUTPUT->notification(get_string('activated', manager::PLUGINNAME), 'success'); +} +$registrationform->display(); +echo $OUTPUT->footer(); diff --git a/admin/tool/brickfield/settings.php b/admin/tool/brickfield/settings.php new file mode 100644 index 0000000000000..f7341923be65e --- /dev/null +++ b/admin/tool/brickfield/settings.php @@ -0,0 +1,134 @@ +. + +/** + * Plugin administration pages are defined here. + * + * @package tool_brickfield + * @category admin + * @copyright 2020 Brickfield Education Labs, https://www.brickfield.ie - Author: Karen Holland + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +use tool_brickfield\accessibility; +use tool_brickfield\manager; +use tool_brickfield\analysis; +use tool_brickfield\output\renderer; +use tool_brickfield\registration; + +defined('MOODLE_INTERNAL') || die(); + +$accessibilitydisabled = !accessibility::is_accessibility_enabled(); + +if ($hassiteconfig) { + // Add an enable subsystem setting to the "Advanced features" settings page. + $optionalsubsystems = $ADMIN->locate('optionalsubsystems'); + $optionalsubsystems->add(new admin_setting_configcheckbox( + 'enableaccessibilitytools', + new lang_string('enableaccessibilitytools', manager::PLUGINNAME), + new lang_string('enableaccessibilitytools_desc', manager::PLUGINNAME), + 1, + 1, + 0 + )); +} + +$moodleurl = accessibility::get_plugin_url(); +if ($hassiteconfig) { + $ADMIN->add( + 'tools', + new admin_category('brickfieldfolder', get_string('accessibility', manager::PLUGINNAME), $accessibilitydisabled) + ); + + $ADMIN->add( + 'brickfieldfolder', + new admin_externalpage( + 'tool_brickfield_activation', + get_string('activationform', manager::PLUGINNAME), + manager::registration_url(), + 'moodle/site:config' + ) + ); + + $settings = new admin_settingpage(manager::PLUGINNAME, get_string('settings')); + + $settings->add(new admin_setting_description( + manager::PLUGINNAME . '/logo', '', + html_writer::img($OUTPUT->image_url('brickfield-logo-small', manager::PLUGINNAME), + 'logo', + ['style' => 'display: block; margin: 0 auto -30px auto; float: right;'] + ) + )); + + $settings->add(new admin_setting_configcheckbox( + manager::PLUGINNAME . '/analysistype', + get_string('analysistype', manager::PLUGINNAME), + get_string('analysistype_desc', manager::PLUGINNAME), + analysis::ANALYSISBYREQUEST, + analysis::ANALYSISBYREQUEST + )); + + $settings->add(new admin_setting_configcheckbox( + manager::PLUGINNAME . '/deletehistoricaldata', + get_string('deletehistoricaldata', manager::PLUGINNAME), + '', + 1 + )); + + $settings->add(new admin_setting_configtext( + manager::PLUGINNAME . '/batch', + get_string('batch', manager::PLUGINNAME), + '', + 1000, + PARAM_INT + )); + + // Need to leave this as last addition to setting variable, as it triggers a callback. + $lastitem = new admin_setting_configtext( + manager::PLUGINNAME . '/perpage', + get_string('perpage', manager::PLUGINNAME), + '', + 50, + PARAM_INT); + $lastitem->set_updatedcallback(static function(){ + accessibility::plugin_installed(); + }); + $settings->add($lastitem); + + $ADMIN->add('brickfieldfolder', $settings); + + $ADMIN->add('brickfieldfolder', new admin_externalpage('tool_brickfield_tool', + get_string('tools', manager::PLUGINNAME), + $moodleurl, + accessibility::get_capability_name('viewsystemtools') + )); +} + +// Add the reports link if the toolkit is enabled, and is either registered, or the user has the ability to register it. +$showreports = has_capability('moodle/site:config', \context_system::instance()); +$showreports = $showreports || (new registration())->toolkit_is_active(); + +// Create a link to the main page in the reports menu. +$ADMIN->add( + 'reports', + new admin_externalpage( + 'tool_brickfield_reports', + get_string('pluginname', manager::PLUGINNAME), + $moodleurl, + accessibility::get_capability_name('viewsystemtools'), + $accessibilitydisabled || !$showreports + ) +); diff --git a/admin/tool/brickfield/styles.css b/admin/tool/brickfield/styles.css new file mode 100644 index 0000000000000..c9c9cd8a21c6f --- /dev/null +++ b/admin/tool/brickfield/styles.css @@ -0,0 +1,118 @@ +.tool_brickfield_floatprinticon { + margin-top: -30px; + float: right; +} + +.tool_brickfield_analysisbutton { + width: 100%; + text-align: center; +} + +/* Advanced Page CSS */ + +@media only screen and (min-width: 768px) { + .tool_brickfield_grid_item { + width: 33.333333333333336%; + } +} + +@media only screen and (max-width: 767px) { + .tool_brickfield_grid_item { + width: 100%; + } +} + +.tool_brickfield_grid { + max-width: 1140px; + margin-right: auto; + margin-left: auto; +} + +.tool_brickfield_grid_inner { + width: 100%; + display: flex; + flex-wrap: wrap; +} + +.tool_brickfield_grid_item_shape { + height: 96%; + background-color: #fff; + padding: 10% 10% 10% 10%; + box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.05); + margin: 1% 1% 1% 1%; + border-radius: 15px 15px 15px 70px; +} + +.tool_brickfield_grid_display { + display: grid; + grid-template-columns: 0.6fr 1.4fr 1fr; + grid-template-rows: 1fr 1fr; +} + +.tool_brickfield_grid_spacing { + margin-bottom: 20px; + margin-left: auto; + margin-right: 1em; +} + +.tool_brickfield_grid_heading { + font-family: 'Varela Round', Sans-serif; + font-size: 20px; + font-weight: 400; + color: #040d29; +} + +.tool_brickfield_grid_content { + color: #040d29; + font-size: 16px; + line-height: 1.4em; + margin: 0; + padding: 0; +} + +.tool_brickfield_logo_height { + height: 3em; +} + +.tool_brickfield_logo_position { + padding-bottom: 2em; +} + +.tool_brickfield_icon_position { + line-height: 1; + font-size: 50px; +} + +.tool_brickfield_icon_height { + height: 30px; +} + +.tool_brickfield_center_button { + text-align: center; +} + +.tool_brickfield_advanced_button { + font-size: 18px; + letter-spacing: 1px; + color: #fff; + background-color: #4054b2; + border-style: solid; + border-color: #fff; + border-radius: 5px 5px 5px 5px; + padding: 15px 50px 15px 50px; + transition: 0.3s; +} + +.tool_brickfield_advanced_button:hover { + background-color: #253687; +} + +.tool_brickfield_banner_heading { + margin-bottom: 1.5em; +} + +.tool_brickfield_banner { + height: 10em; + padding: 2.5em; + margin-bottom: 2em; +} diff --git a/admin/tool/brickfield/templates/advanced.mustache b/admin/tool/brickfield/templates/advanced.mustache new file mode 100644 index 0000000000000..0374b82a91516 --- /dev/null +++ b/admin/tool/brickfield/templates/advanced.mustache @@ -0,0 +1,204 @@ +{{! + 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 tool_brickfield/advanced + + This template renders advanced page. + + Example context (json): + { + "pagetitle": "Advanced" + } +}} + + + +

{{{pagetitle}}}

+ +
+
+ Brickfield Logo +

{{# str }}bannerheadingone, tool_brickfield{{/ str }}

+
+

+ {{# str }}bannercontentone, tool_brickfield, {{# str }}contactus, tool_brickfield{{/ str }}{{/ str }} +

+
+ +
+
+ +
+
+
+
+
+ + Analytics icon + +
+
+
+

+ + {{# str }}headingone, tool_brickfield{{/ str }} + +

+

+ {{# str }}contentone, tool_brickfield{{/ str }} +

+
+
+
+
+ +
+
+
+
+
+ + Tools icon + +
+
+
+

+ + {{# str }}headingtwo, tool_brickfield{{/ str }} + +

+

+ {{# str }}contenttwo, tool_brickfield{{/ str }} +

+
+
+
+
+ +
+
+
+
+
+ + Edit file icon + +
+
+
+

+ + {{# str }}headingthree, tool_brickfield{{/ str }} + +

+

+ {{# str }}contentthree, tool_brickfield{{/ str }} +

+
+
+
+
+ +
+
+
+
+
+ + Search icon + +
+
+
+

+ + {{# str }}headingfour, tool_brickfield{{/ str }} + +

+

+ {{# str }}contentfour, tool_brickfield{{/ str }} +

+
+
+
+
+ +
+
+
+
+
+ + Magic wand icon + +
+
+
+

+ + {{# str }}headingfive, tool_brickfield{{/ str }} + +

+

+ {{# str }}contentfive, tool_brickfield{{/ str }} +

+
+
+
+
+ +
+
+
+
+
+ + Helping hands icon + +
+
+
+

+ + {{# str }}headingsix, tool_brickfield{{/ str }} + +

+

+ {{# str }}contentsix, tool_brickfield{{/ str }} +

+
+
+
+
+ +
+
+ +
+

{{# str }}footerheading, tool_brickfield{{/ str }}

+

+ {{# str }}bannercontenttwo, tool_brickfield{{/ str }} +

+
+ + + +
+
\ No newline at end of file diff --git a/admin/tool/brickfield/templates/chartsingle.mustache b/admin/tool/brickfield/templates/chartsingle.mustache new file mode 100644 index 0000000000000..aa1152864efef --- /dev/null +++ b/admin/tool/brickfield/templates/chartsingle.mustache @@ -0,0 +1,41 @@ +{{! + 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 tool_brickfield/checktypes + + This template renders the charts for the different check groups + + Example context (json): + { + "title": "Totals" + } +}} + +

{{{ title }}}

+
+ {{#chart}} +
+ {{{ chart }}} +
+ {{/chart}} + {{#chartdesc}} +
+

{{{ chartdesctitle }}}

+ {{{ chartdesc }}} +
+ {{/chartdesc}} +
diff --git a/admin/tool/brickfield/templates/errors.mustache b/admin/tool/brickfield/templates/errors.mustache new file mode 100644 index 0000000000000..4b9498322042d --- /dev/null +++ b/admin/tool/brickfield/templates/errors.mustache @@ -0,0 +1,73 @@ +{{! + 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 tool_brickfield/errors + + This template renders the list view for the errors accessibility report. + + Example context (json): + { + "pagetitle": "Error details", + "pagenavigation": " ", + "tableheading1": "Activity", + "tableheading2": "Check", + "tableheading3": "Edit", + "tableheading4": "Line", + "tableheading5": "Existing HTML code", + "tabledata": [ + { + "activity": "Book", + "check": "Headings", + "edit": "Edit", + "line": 2, + "html": "<h3></h3>" + }, + { + "activity": "Label", + "check": "Headings", + "edit": "Edit", + "line": 4, + "html": "<h3></h3>" + } + ] + } +}} + +

{{{pagetitle}}}

+{{{pagenavigation}}} + + + + + + + + + + + + {{#tabledata}} + + + + + + + + {{/tabledata}} + +
{{tableheading1}}{{tableheading2}}{{tableheading3}}{{tableheading4}}{{{tableheading5}}}
{{activity}}{{check}}{{{edit}}}{{line}}{{html}}
diff --git a/admin/tool/brickfield/templates/norecords.mustache b/admin/tool/brickfield/templates/norecords.mustache new file mode 100644 index 0000000000000..8fb65d617ab9b --- /dev/null +++ b/admin/tool/brickfield/templates/norecords.mustache @@ -0,0 +1,30 @@ +{{! + 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 tool_brickfield/norecords + + This template renders the empty view for the no records accessibility report. + + Example context (json): + { + "pagetitle": "Error details", + "noerrorsfound": "No errors found..." + } +}} + +

{{{pagetitle}}}

+

{{{noerrorsfound}}}

diff --git a/admin/tool/brickfield/templates/tabtree.mustache b/admin/tool/brickfield/templates/tabtree.mustache new file mode 100644 index 0000000000000..f6b075c08965f --- /dev/null +++ b/admin/tool/brickfield/templates/tabtree.mustache @@ -0,0 +1,49 @@ +{{! + 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 tabtree + + Tab tree. + + Example context (json): + { + "tabs": [ + { + "active": "true", + "inactive": "false", + "link": [ + { + "link": "http://moodle.org" + } + ], + "title": "Moodle.org", + "text": "Moodle community", + "id": "taberrors" + } + ] + } +}} + +{{#secondrow}} + {{>core/tabtree}} +{{/secondrow}} diff --git a/admin/tool/brickfield/tests/accessibility_test.php b/admin/tool/brickfield/tests/accessibility_test.php new file mode 100644 index 0000000000000..908eb2d8da9fc --- /dev/null +++ b/admin/tool/brickfield/tests/accessibility_test.php @@ -0,0 +1,116 @@ +. + +namespace tool_brickfield; + +use tool_brickfield\local\tool\filter; + +/** + * Unit tests for {@accessibility tool_brickfield\accessibility.php}. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @author Jay Churchward (jay@brickfieldlabs.ie) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class accessibility_test extends \advanced_testcase { + + /** + * Test get_title(). + * + * @throws \coding_exception + * @throws \dml_exception + * @throws \moodle_exception + */ + public function test_get_title() { + $this->resetAfterTest(); + $object = new accessibility(); + $filter = new filter(); + + // Testing the else statement. + $output = $object->get_title($filter, 0); + $this->assertEquals($output, 'All reviewed courses (0)'); + $output = $object->get_title($filter, 5); + $this->assertEquals($output, 'All reviewed courses (5)'); + $output = $object->get_title($filter, 0, ' extra text'); + $this->assertEquals($output, 'All reviewed courses (0) extra text'); + + // Testing the if statement. + $filter->courseid = 1; + $output = $object->get_title($filter, 0); + $this->assertEquals($output, 'Course: PHPUnit test site'); + $output = $object->get_title($filter, 1, ' extra text'); + $this->assertEquals($output, 'Course: PHPUnit test site extra text'); + + // Testing the else if statement. + $filter->categoryid = 1; + $filter->courseid = 0; + $output = $object->get_title($filter, 0); + $this->assertEquals($output, 'All reviewed courses for category Miscellaneous (0)'); + $output = $object->get_title($filter, 2); + $this->assertEquals($output, 'All reviewed courses for category Miscellaneous (2)'); + $output = $object->get_title($filter, 3, ' extra text'); + $this->assertEquals($output, 'All reviewed courses for category Miscellaneous (3) extra text'); + } + + /** + * Test check_ids(). + * + * @throws \dml_exception + */ + public function test_check_ids() { + $this->resetAfterTest(); + $object = new accessibility(); + + $output = $object->checkids(); + $this->assertEquals($output[1], 'a_links_dont_open_new_window'); + $this->assertEquals($output[10], 'css_text_has_contrast'); + + $output = $object->checkids(2); + $this->assertEmpty($output); + } + + /** + * Test get_translations(). + * + * @throws \dml_exception + */ + public function test_get_translations() { + $this->resetAfterTest(); + $object = new accessibility(); + + $output = $object->get_translations(); + $this->assertEquals($output['a_must_contain_text']['title'], 'Links should contain text'); + $this->assertStringContainsString('

Because many users of screen readers use links to ' . + 'navigate the page, providing links with no text (or with images that have empty \'alt\' attributes and no other ' . + 'readable text) hinders these users.

', $output['a_must_contain_text']['description']); + } + + /** + * Test get_category_courseids(). + * + * @throws \dml_exception + */ + public function test_get_category_courseids() { + $this->resetAfterTest(); + $object = new accessibility(); + $category = $this->getDataGenerator()->create_category(); + $course = $this->getDataGenerator()->create_course((object)['category' => $category->id]); + + $output = $object->get_category_courseids($category->id); + $this->assertEquals($output[0], $course->id); + } +} diff --git a/admin/tool/brickfield/tests/activityresults_test.php b/admin/tool/brickfield/tests/activityresults_test.php new file mode 100644 index 0000000000000..4366623f916fc --- /dev/null +++ b/admin/tool/brickfield/tests/activityresults_test.php @@ -0,0 +1,66 @@ +. + +namespace tool_brickfield\local\tool; + +/** + * Unit tests for {@activityresults tool_brickfield\local\tool\activityresults\tool}. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @author Jay Churchward (jay.churchward@poetopensource.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class activityresults_test extends \advanced_testcase { + + public function test_toolname() { + $this->resetAfterTest(); + + $object = new activityresults(); + $output = $object->toolname(); + $this->assertEquals($output, 'Activity breakdown summary'); + } + + public function test_toolshortname() { + $this->resetAfterTest(); + + $object = new activityresults(); + $output = $object->toolshortname(); + $this->assertEquals($output, 'Activity breakdown'); + } + + public function test_pluginname() { + $this->resetAfterTest(); + + $object = new activityresults(); + $output = $object->pluginname(); + $this->assertEquals($output, 'activityresults'); + } + + public function test_get_output() { + $this->resetAfterTest(); + + $category = $this->getDataGenerator()->create_category(); + $filter = new filter(1, $category->id, 'tab', 3, 4); + $filter->courseids = []; + + $object = new activityresults(); + $object->set_filter($filter); + $output = $object->get_output(); + $this->assertIsString($output); + $this->assertStringContainsString('Results per activity :', $output); + } +} diff --git a/admin/tool/brickfield/tests/area_test.php b/admin/tool/brickfield/tests/area_test.php new file mode 100644 index 0000000000000..29db239f1efef --- /dev/null +++ b/admin/tool/brickfield/tests/area_test.php @@ -0,0 +1,240 @@ +. + +namespace tool_brickfield; + +/** + * Class tool_brickfield_area_testcase + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class area_test extends \advanced_testcase { + + /** + * Test for the area assign intro + */ + public function test_assign() { + $this->resetAfterTest(); + $course = $this->getDataGenerator()->create_course(); + $assign1 = $this->getDataGenerator()->create_module('assign', array( + 'course' => $course->id, 'name' => 'Test!', 'intro' => '

Here we go

', + 'introformat' => FORMAT_HTML)); + list($course1, $cm1) = get_course_and_cm_from_instance($assign1->id, 'assign'); + $assign2 = $this->getDataGenerator()->create_module('assign', array( + 'course' => SITEID, 'name' => 'Test2!', 'intro' => 'Something', + 'introformat' => FORMAT_MOODLE)); + list($course2, $cm2) = get_course_and_cm_from_instance($assign2->id, 'assign'); + + $c = new \tool_brickfield\local\areas\mod_assign\intro(); + $this->assertEquals('mod_assign', $c->get_component()); + $this->assertEquals('assign', $c->get_tablename()); + $resultsrs = $c->find_course_areas($course1->id); + $resultsrs2 = $c->find_course_areas($course2->id); + // Set up a results array from the recordset for easier testing. + $results = array_merge(self::array_from_recordset($resultsrs), self::array_from_recordset($resultsrs2)); + $this->assertEquals([ + (object)[ + 'type' => area_base::TYPE_FIELD, + 'contextid' => \context_module::instance($cm1->id)->id, + 'component' => $c->get_component(), + 'tablename' => $c->get_tablename(), + 'fieldorarea' => $c->get_fieldname(), + 'itemid' => $assign1->id, + 'cmid' => $cm1->id, + 'courseid' => $course1->id, + 'content' => $assign1->intro, + ], + (object)[ + 'type' => area_base::TYPE_FIELD, + 'contextid' => \context_module::instance($cm2->id)->id, + 'component' => $c->get_component(), + 'tablename' => $c->get_tablename(), + 'fieldorarea' => $c->get_fieldname(), + 'itemid' => $assign2->id, + 'cmid' => $cm2->id, + 'courseid' => $course2->id, + 'content' => $assign2->intro, + ] + ], $results); + + // Emulate the course_module_updated event. + $event = \core\event\course_module_updated::create_from_cm($cm1); + $relevantresultsrs = $c->find_relevant_areas($event); + // Set up a relevantresults array from the recordset for easier testing. + $relevantresults = self::array_from_recordset($relevantresultsrs); + $this->assertEquals([$results[0]], $relevantresults); + } + + /** + * Test for the area questiontext + */ + public function test_questiontext() { + $this->resetAfterTest(); + /** @var \core_question_generator $generator */ + $generator = $this->getDataGenerator()->get_plugin_generator('core_question'); + list($category1, $course1, $qcat1, $questions1) = $generator->setup_course_and_questions('course'); + list($category2, $course2, $qcat2, $questions2) = $generator->setup_course_and_questions('category'); + list($category3, $course3, $qcat3, $questions3) = $generator->setup_course_and_questions('system'); + + $c = new \tool_brickfield\local\areas\core_question\questiontext(); + $results1 = self::array_from_recordset($c->find_course_areas($course1->id)); + $results2 = self::array_from_recordset($c->find_course_areas($course2->id)); + $results3 = self::array_from_recordset($c->find_course_areas($course3->id)); + $results4 = self::array_from_recordset($c->find_system_areas()); + // Set up a results array from the recordset for easier testing. + + $this->assertCount(2, $results1); + $this->assertCount(0, $results2); + $this->assertCount(0, $results3); + $this->assertCount(4, $results4); + + // Validate the contexts, courseid and categoryid of the returned results. + $this->assertEquals(\context_course::instance($course1->id)->id, $results1[0]->contextid); + $this->assertEquals($course1->id, $results1[0]->courseid); + $this->assertEmpty($results1[0]->categoryid); + $this->assertEquals(\context_coursecat::instance($category2->id)->id, $results4[0]->contextid); + $this->assertEquals(SITEID, $results4[0]->courseid); + $this->assertEquals($category2->id, $results4[0]->categoryid); + $this->assertEquals(\context_system::instance()->id, $results4[2]->contextid); + $this->assertEmpty($results4[2]->categoryid); + $this->assertEquals(SITEID, $results4[2]->courseid); + // Results4 should contain id's for questions 1 and 2. + $this->assertTrue(($questions3[0]->id == $results4[2]->itemid) || ($questions3[0]->id == $results4[3]->itemid)); + $this->assertTrue(($questions3[1]->id == $results4[2]->itemid) || ($questions3[1]->id == $results4[3]->itemid)); + + // Emulate the question_created event. + $event = \core\event\question_created::create_from_question_instance($questions1[1], + \context_course::instance($course1->id)); + $relevantresultsrs = $c->find_relevant_areas($event); + // Set up a relevantresults array from the recordset for easier testing. + $relevantresults = self::array_from_recordset($relevantresultsrs); + $this->assertEquals([$results1[1]], $relevantresults); + } + + /** + * test for the area questionanswers + */ + public function test_questionanswers() { + global $DB; + + $this->resetAfterTest(); + /** @var \core_question_generator $generator */ + $generator = $this->getDataGenerator()->get_plugin_generator('core_question'); + $course = $this->getDataGenerator()->create_course(); + $cat = $generator->create_question_category(['contextid' => \context_course::instance($course->id)->id]); + $question1 = $generator->create_question('multichoice', null, + ['name' => 'Example multichoice question', 'category' => $cat->id]); + $question2 = $generator->create_question('numerical', null, + ['name' => 'Example numerical question', 'category' => $cat->id]); + + $dbanswers = $DB->get_records('question_answers', [] , 'id'); + $this->assertNotEmpty(count($dbanswers)); + + $c = new \tool_brickfield\local\areas\core_question\questionanswers(); + $resultsrs = $c->find_course_areas($course->id); + $results = self::array_from_recordset($resultsrs); + + // There will be the same number of results as the number of records in the question_answers table. + $this->assertEquals(count($dbanswers), count($results)); + + // Emulate the question_updated event. + $event = \core\event\question_updated::create_from_question_instance($question1, + \context_course::instance($course->id)); + $relevantresultsrs = $c->find_relevant_areas($event); + // Set up a relevantresults array from the recordset for easier testing. + $relevantresults = self::array_from_recordset($relevantresultsrs); + + $dbanswers = array_values($DB->get_records('question_answers', ['question' => $question1->id], 'id')); + $this->assertEquals(count($dbanswers), count($relevantresults)); + foreach ($dbanswers as $i => $dbanswer) { + $relevantresult = $relevantresults[$i]; + $this->assertEquals($dbanswer->answer, $relevantresult->content); + $this->assertEquals('question', $relevantresult->reftable); + $this->assertEquals($question1->id, $relevantresult->refid); + $this->assertEquals($dbanswer->id, $relevantresult->itemid); + } + } + + /** + * Test for the areas choice intro and choice options + */ + public function test_choice() { + global $DB; + $this->resetAfterTest(); + $course = $this->getDataGenerator()->create_course(); + $choice1 = $this->getDataGenerator()->create_module('choice', [ + 'course' => $course->id, 'option' => ['fried rice', 'spring rolls', 'sweet and sour pork'] + ]); + list($course1, $cm1) = get_course_and_cm_from_instance($choice1->id, 'choice'); + $choice2 = $this->getDataGenerator()->create_module('choice', [ + 'course' => $course->id, 'option' => ['blue', 'red'] + ]); + list($course2, $cm2) = get_course_and_cm_from_instance($choice2->id, 'choice'); + + // Testing the choice intro. + $c = new \tool_brickfield\local\areas\mod_choice\intro(); + $resultsrs = $c->find_course_areas($course->id); + // Set up a results array from the recordset for easier testing. + $results = self::array_from_recordset($resultsrs); + + $this->assertCount(2, $results); + $this->assertEquals($cm1->id, $results[0]->cmid); + $this->assertEquals($choice2->id, $results[1]->itemid); + + // Emulate the course_module_created event. + $event = \core\event\course_module_created::create_from_cm($cm1); + $relevantresultsrs = $c->find_relevant_areas($event); + $relevantresults = self::array_from_recordset($relevantresultsrs); + $this->assertEquals([$results[0]], $relevantresults); + + // Testing the choice options. + $c = new \tool_brickfield\local\areas\mod_choice\option(); + $resultsrs = $c->find_course_areas($course->id); + // Set up a results array from the recordset for easier testing. + $results = self::array_from_recordset($resultsrs); + + $this->assertCount(5, $results); + $this->assertEquals($cm2->id, $results[3]->cmid); + $this->assertEquals('choice_options', $results[3]->tablename); + $this->assertEquals('choice', $results[3]->reftable); + $this->assertEquals($choice2->id, $results[3]->refid); + $options3 = $DB->get_records_menu('choice_options', ['choiceid' => $choice2->id], 'id', 'text,id'); + $this->assertEquals($options3['blue'], $results[3]->itemid); + $this->assertEquals('blue', $results[3]->content); + + // Emulate the course_module_updated event. + $event = \core\event\course_module_updated::create_from_cm($cm2); + $relevantresultsrs = $c->find_relevant_areas($event); + $relevantresults = self::array_from_recordset($relevantresultsrs); + $this->assertEquals([$results[3], $results[4]], $relevantresults); + } + + /** + * Array from recordset. + * @param \moodle_recordset $rs + * @return array + */ + private static function array_from_recordset($rs) { + $records = []; + foreach ($rs as $record) { + $records[] = $record; + } + $rs->close(); + return $records; + } +} diff --git a/admin/tool/brickfield/tests/checktyperesults_test.php b/admin/tool/brickfield/tests/checktyperesults_test.php new file mode 100644 index 0000000000000..21252a534cb22 --- /dev/null +++ b/admin/tool/brickfield/tests/checktyperesults_test.php @@ -0,0 +1,67 @@ +. + +namespace tool_brickfield\local\tool; + +/** + * Unit tests for {@checktyperesults tool_brickfield\local\tool\checktyperesults\tool}. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @author Jay Churchward (jay.churchward@poetopensource.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class checktyperesults_test extends \advanced_testcase { + + public function test_toolname() { + $this->resetAfterTest(); + + $object = new checktyperesults(); + $output = $object->toolname(); + $this->assertEquals($output, 'Content types summary'); + } + + public function test_toolshortname() { + $this->resetAfterTest(); + + $object = new checktyperesults(); + $output = $object->toolshortname(); + $this->assertEquals($output, 'Content types'); + } + + public function test_pluginname() { + $this->resetAfterTest(); + + $object = new checktyperesults(); + $output = $object->pluginname(); + $this->assertEquals($output, 'checktyperesults'); + } + + public function test_get_output() { + $this->resetAfterTest(); + $category = $this->getDataGenerator()->create_category(); + + $filter = new filter(1, $category->id, 'checktyperesults', 3, 4); + $filter->courseids = []; + + $object = new checktyperesults(); + $object->set_filter($filter); + $object->get_data(); + $output = $object->get_output(); + $this->assertIsString($output); + $this->assertStringContainsString('Results per content type :', $output); + } +} diff --git a/admin/tool/brickfield/tests/errors_test.php b/admin/tool/brickfield/tests/errors_test.php new file mode 100644 index 0000000000000..5299ab0403300 --- /dev/null +++ b/admin/tool/brickfield/tests/errors_test.php @@ -0,0 +1,66 @@ +. + +namespace tool_brickfield\local\tool; + +/** + * Unit tests for {@errors tool_brickfield\local\tool\errors\tool}. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @author Jay Churchward (jay.churchward@poetopensource.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class errors_test extends \advanced_testcase { + + public function test_toolname() { + $this->resetAfterTest(); + + $object = new errors(); + $output = $object->toolname(); + $this->assertEquals($output, 'Error list summary'); + } + + public function test_toolshortname() { + $this->resetAfterTest(); + + $object = new errors(); + $output = $object->toolshortname(); + $this->assertEquals($output, 'Error list'); + } + + public function test_pluginname() { + $this->resetAfterTest(); + + $object = new errors(); + $output = $object->pluginname(); + $this->assertEquals($output, 'errors'); + } + + public function test_get_output() { + $this->resetAfterTest(); + $category = $this->getDataGenerator()->create_category(); + + $filter = new filter(1, $category->id, 'tab', 3, 4); + $filter->courseids = []; + + $object = new errors(); + $object->set_filter($filter); + $output = $object->get_output(); + $this->assertIsString($output); + $this->assertStringContainsString('Error details :', $output); + } +} diff --git a/admin/tool/brickfield/tests/filters_test.php b/admin/tool/brickfield/tests/filters_test.php new file mode 100644 index 0000000000000..f68171b19b00c --- /dev/null +++ b/admin/tool/brickfield/tests/filters_test.php @@ -0,0 +1,216 @@ +. + +namespace tool_brickfield; + +use tool_brickfield\local\tool\filter; + +/** + * Unit tests for {@filter tool_brickfield\local\tool\filter}. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @author Jay Churchward (jay.churchward@poetopensource.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class filter_test extends \advanced_testcase { + public function test_constructor() { + $this->resetAfterTest(); + + // Variables. + $courseid = 1; + $categoryid = 2; + $tab = 'tab'; + $page = 3; + $perpage = 4; + $url = 'url'; + + // Test responses. + $object = new filter(); + $this->assertEquals($object->courseid, 0); + $this->assertEquals($object->categoryid, 0); + $this->assertEquals($object->tab, ''); + $this->assertEquals($object->page, 0); + $this->assertEquals($object->perpage, 0); + $this->assertEquals($object->url, ''); + + $object = new filter($courseid, $categoryid, $tab, $page, $perpage, $url); + $this->assertEquals($object->courseid, $courseid); + $this->assertEquals($object->categoryid, $categoryid); + $this->assertEquals($object->tab, $tab); + $this->assertEquals($object->page, $page); + $this->assertEquals($object->perpage, $perpage); + $this->assertEquals($object->url, $url); + } + + public function test_get_course_sql() { + $this->resetAfterTest(); + $object = new filter(); + + $output = $object->get_course_sql(); + + $this->assertIsArray($output); + $this->assertEquals($output[0], ''); + + $object = $this->create_object_with_params(); + $output = $object->get_course_sql(); + + $this->assertEquals($output[0], ' AND (courseid = ?)'); + $this->assertEquals($output[1][0], $object->courseid); + + } + + public function test_validate_filters() { + $this->resetAfterTest(); + // Variables. + $courseid = 0; + $categoryid = 2; + $tab = 'tab'; + $page = 3; + $perpage = 4; + $url = 'url'; + $object = new filter(); + + $output = $object->validate_filters(); + $this->assertTrue($output); + + $object = $this->create_object(); + $output = $object->validate_filters(); + $this->assertTrue($output); + + $object = new filter($courseid, $categoryid, $tab, $page, $perpage); + $output = $object->validate_filters(); + $this->assertFalse($output); + + $category = $this->getDataGenerator()->create_category(); + + $object = new filter($courseid, $category->id, $tab, $page, $perpage); + $output = $object->validate_filters(); + $this->assertFalse($output); + } + + public function test_has_course_filters() { + $this->resetAfterTest(); + + $object = new filter(); + $output = $object->has_course_filters(); + $this->assertFalse($output); + + $object = $this->create_object(); + $output = $object->has_course_filters(); + $this->assertTrue($output); + } + + public function test_has_capability_in_context() { + global $DB; + + $this->resetAfterTest(); + + $object = $this->create_object_with_params(); + $capability = accessibility::get_capability_name('viewcoursetools'); + $output = $object->has_capability_in_context($capability, \context_system::instance()); + $this->assertFalse($output); + + $output = $object->has_capability_in_context($capability, \context_coursecat::instance($object->categoryid)); + $this->assertFalse($output); + + $output = $object->has_capability_in_context($capability, \context_course::instance($object->courseid)); + $this->assertFalse($output); + + $course = $this->getDataGenerator()->create_course(); + $user = $this->getDataGenerator()->create_and_enrol($course, 'teacher'); + $this->setUser($user); + + $output = $object->has_capability_in_context($capability, \context_system::instance()); + $this->assertFalse($output); + + $output = $object->has_capability_in_context($capability, \context_coursecat::instance($object->categoryid)); + $this->assertFalse($output); + + $output = $object->has_capability_in_context($capability, \context_course::instance($course->id)); + $this->assertTrue($output); + + $teacherrole = $DB->get_record('role', ['shortname' => 'teacher']); + $categorycontext = \context_coursecat::instance($object->categoryid); + $this->getDataGenerator()->role_assign($teacherrole->id, $user->id, $categorycontext->id); + + $output = $object->has_capability_in_context($capability, $categorycontext); + $this->assertTrue($output); + } + + public function test_get_errormessage() { + $this->resetAfterTest(); + // Variables. + $courseid = 0; + $categoryid = 2; + $tab = 'tab'; + $page = 3; + $perpage = 4; + $url = 'url'; + + $object = new filter(); + $output = $object->get_errormessage(); + $this->assertNull($output); + + $object = new filter($courseid, $categoryid, $tab, $page, $perpage); + $object->validate_filters(); + $output = $object->get_errormessage(); + $this->assertEquals($output, 'Invalid category, please check your input'); + + $category = $this->getDataGenerator()->create_category(); + $object = new filter($courseid, $category->id, $tab, $page, $perpage); + $object->validate_filters(); + $output = $object->get_errormessage(); + $this->assertEquals($output, 'No courses found for category ' . $category->id); + } + + /** + * Create a filter object and return it. + * @return filter + */ + private function create_object() { + // Variables. + $courseid = 1; + $categoryid = 2; + $tab = 'tab'; + $page = 3; + $perpage = 4; + $url = 'url'; + + $object = new filter($courseid, $categoryid, $tab, $page, $perpage); + + return $object; + } + + /** + * Create a filter object with some parameters and return it. + * @return filter + */ + private function create_object_with_params() { + // Variables. + $tab = 'tab'; + $page = 3; + $perpage = 4; + $url = 'url'; + + $category = $this->getDataGenerator()->create_category(); + $course = $this->getDataGenerator()->create_course((object)['category' => $category->id]); + + $object = new filter($course->id, $category->id, $tab, $page, $perpage); + + return $object; + } +} diff --git a/admin/tool/brickfield/tests/generator/mock_brickfieldconnect.php b/admin/tool/brickfield/tests/generator/mock_brickfieldconnect.php new file mode 100644 index 0000000000000..46c829073169f --- /dev/null +++ b/admin/tool/brickfield/tests/generator/mock_brickfieldconnect.php @@ -0,0 +1,70 @@ +. + +/** + * PHPUnit tool_brickfield tests + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @author Mike Churchward (mike@brickfieldlabs.ie) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Mock brickfield connect. + */ +class mock_brickfieldconnect extends brickfieldconnect { + + /** + * Valid api key. + */ + const VALIDAPIKEY = '123456789012345678901234567890ab'; + + /** + * Valid secret key. + */ + const VALIDSECRETKEY = 'ab123456789012345678901234567890'; + + /** @var string api key. */ + protected $apikey = ''; + + /** @var string Secret key. */ + protected $secretkey = ''; + + /** + * Is registered. + * @return bool is registered + */ + public function is_registered(): bool { + return ($this->apikey == self::VALIDAPIKEY) && ($this->secretkey == self::VALIDSECRETKEY); + } + + /** + * Update Registration. + * @param string $apikey + * @param string $secretkey + * @return bool + */ + public function update_registration(string $apikey, string $secretkey): bool { + $this->apikey = $apikey; + $this->secretkey = $secretkey; + return $this->is_registered(); + } +} diff --git a/admin/tool/brickfield/tests/generator/mock_registration.php b/admin/tool/brickfield/tests/generator/mock_registration.php new file mode 100644 index 0000000000000..05f560f58c964 --- /dev/null +++ b/admin/tool/brickfield/tests/generator/mock_registration.php @@ -0,0 +1,72 @@ +. + +/** + * PHPUnit tool_brickfield tests + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @author Mike Churchward (mike@brickfieldlabs.ie) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield; + +defined('MOODLE_INTERNAL') || die(); + +global $CFG; +require_once($CFG->dirroot . '/admin/tool/brickfield/tests/generator/mock_brickfieldconnect.php'); + +/** + * Mock registration. + */ +class mock_registration extends registration { + /** + * Get registration connection. + * @return brickfieldconnect + */ + protected function get_registration_connection(): brickfieldconnect { + return new mock_brickfieldconnect(); + } + + /** + * Is not entered. + * @return bool + */ + public function is_not_entered() { + return $this->status_is_not_entered(); + } + + /** + * Invalidate validation time. + * @return int + * @throws \dml_exception + */ + public function invalidate_validation_time() { + $this->set_validation_time(time() - (7 * 24 * 60 * 60)); + return $this->get_validation_time(); + } + + /** + * Invalidate summary time. + * @return int + * @throws \dml_exception + */ + public function invalidate_summary_time() { + $this->set_summary_time(time() - (7 * 24 * 60 * 60) - 1); + return $this->get_summary_time(); + } +} \ No newline at end of file diff --git a/admin/tool/brickfield/tests/local/areas/core_question/questionanswers_test.php b/admin/tool/brickfield/tests/local/areas/core_question/questionanswers_test.php new file mode 100644 index 0000000000000..30d7c842384bf --- /dev/null +++ b/admin/tool/brickfield/tests/local/areas/core_question/questionanswers_test.php @@ -0,0 +1,191 @@ +. + +namespace tool_brickfield\local\areas\core_question; + +/** + * Tests for questionanswer. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class questionanswers_test extends \advanced_testcase { + + /** + * Set up before class. + */ + public static function setUpBeforeClass(): void { + global $CFG; + require_once($CFG->dirroot . '/mod/quiz/locallib.php'); + } + + /** + * Test find course areas. + */ + public function test_find_course_areas() { + $this->resetAfterTest(); + $this->setAdminUser(); + + $category = $this->getDataGenerator()->create_category(); + $course = $this->getDataGenerator()->create_course(['category' => $category->id]); + $coursecontext = \context_course::instance($course->id); + $catcontext = \context_coursecat::instance($category->id); + $generator = $this->getDataGenerator()->get_plugin_generator('core_question'); + $cat1 = $generator->create_question_category(['contextid' => $coursecontext->id]); + $question1 = $generator->create_question('multichoice', null, ['category' => $cat1->id]); + $question2 = $generator->create_question('multichoice', null, ['category' => $cat1->id]); + $questionanswers = new questionanswers(); + $rs = $questionanswers->find_course_areas($course->id); + $this->assertNotNull($rs); + + // Each multichoice question generated has four answers. So there should be eight records. + $count = 0; + foreach ($rs as $rec) { + $count++; + $this->assertEquals($coursecontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + if ($count <= 4) { + $this->assertEquals($question1->id, $rec->refid); + } else { + $this->assertEquals($question2->id, $rec->refid); + } + } + $rs->close(); + $this->assertEquals(8, $count); + + // Add a question to a quiz in the course. + $quiz = $this->getDataGenerator()->create_module('quiz', ['course' => $course->id, 'name' => 'Quiz1']); + $quizmodule = get_coursemodule_from_instance('quiz', $quiz->id, $course->id); + $quizcontext = \context_module::instance($quizmodule->id); + + // Add a question to the quiz context. + $cat2 = $generator->create_question_category(['contextid' => $quizcontext->id]); + $question3 = $generator->create_question('multichoice', null, ['category' => $cat2->id]); + $rs2 = $questionanswers->find_course_areas($course->id); + $this->assertNotNull($rs2); + + // Each multichoice question generated has four answers. So there should be twelve records now. + $count = 0; + foreach ($rs2 as $rec) { + $count++; + if ($count <= 4) { + $this->assertEquals($coursecontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + $this->assertEquals($question1->id, $rec->refid); + } else if ($count <= 8) { + $this->assertEquals($coursecontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + $this->assertEquals($question2->id, $rec->refid); + } else { + $this->assertEquals($quizcontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + $this->assertEquals($question3->id, $rec->refid); + } + } + $rs2->close(); + $this->assertEquals(12, $count); + + // Add a question to the category context. + $cat3 = $generator->create_question_category(['contextid' => $catcontext->id]); + $question4 = $generator->create_question('multichoice', null, ['category' => $cat3->id]); + $rs3 = $questionanswers->find_course_areas($course->id); + $this->assertNotNull($rs3); + + // The category level questions should not be found. + $count = 0; + foreach ($rs3 as $rec) { + $count++; + if ($count > 8) { + $this->assertEquals($quizcontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + $this->assertEquals($question3->id, $rec->refid); + } + } + $rs2->close(); + $this->assertEquals(12, $count); + } + + /** + * Test find relevant areas. + */ + public function test_find_relevant_areas() { + $this->resetAfterTest(); + $this->setAdminUser(); + + $course = $this->getDataGenerator()->create_course(); + $coursecontext = \context_course::instance($course->id); + $generator = $this->getDataGenerator()->get_plugin_generator('core_question'); + $cat1 = $generator->create_question_category(['contextid' => $coursecontext->id]); + $question1 = $generator->create_question('multichoice', null, ['category' => $cat1->id]); + $question2 = $generator->create_question('multichoice', null, ['category' => $cat1->id]); + $questionanswers = new questionanswers(); + $event = \core\event\question_updated::create_from_question_instance($question1, + \context_course::instance($course->id)); + $rs = $questionanswers->find_relevant_areas($event); + $this->assertNotNull($rs); + + // Each multichoice question generated has four answers. + $count = 0; + foreach ($rs as $rec) { + $count++; + $this->assertEquals($coursecontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + $this->assertEquals($question1->id, $rec->refid); + } + $rs->close(); + $this->assertEquals(4, $count); + } + + /** + * Test find system areas. + */ + public function test_find_system_areas() { + $this->resetAfterTest(); + $this->setAdminUser(); + + $category = $this->getDataGenerator()->create_category(); + $catcontext = \context_coursecat::instance($category->id); + $systemcontext = \context_system::instance(); + $generator = $this->getDataGenerator()->get_plugin_generator('core_question'); + $cat = $generator->create_question_category(['contextid' => $catcontext->id]); + $cat2 = $generator->create_question_category(['contextid' => $systemcontext->id]); + $question = $generator->create_question('multichoice', null, ['category' => $cat2->id]); + $question2 = $generator->create_question('multichoice', null, ['category' => $cat->id]); + $questionanswers = new questionanswers(); + $rs = $questionanswers->find_system_areas(); + $this->assertNotNull($rs); + + // Each multichoice question generated has four answers. + $count = 0; + foreach ($rs as $rec) { + $count++; + if ($count <= 4) { + $this->assertEquals($systemcontext->id, $rec->contextid); + $this->assertEquals(1, $rec->courseid); + $this->assertEquals(0, $rec->categoryid); + $this->assertEquals($question->id, $rec->refid); + } else { + $this->assertEquals($catcontext->id, $rec->contextid); + $this->assertEquals(1, $rec->courseid); + $this->assertEquals($category->id, $rec->categoryid); + $this->assertEquals($question2->id, $rec->refid); + } + } + $rs->close(); + $this->assertEquals(8, $count); + } +} diff --git a/admin/tool/brickfield/tests/local/areas/core_question/questiontext_test.php b/admin/tool/brickfield/tests/local/areas/core_question/questiontext_test.php new file mode 100644 index 0000000000000..0f779e53905a0 --- /dev/null +++ b/admin/tool/brickfield/tests/local/areas/core_question/questiontext_test.php @@ -0,0 +1,187 @@ +. + +namespace tool_brickfield\local\areas\core_question; + +/** + * Tests for questiontext. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class questiontext_test extends \advanced_testcase { + + /** + * Set up before class. + */ + public static function setUpBeforeClass(): void { + global $CFG; + require_once($CFG->dirroot . '/mod/quiz/locallib.php'); + } + + /** + * Test find course areas. + */ + public function test_find_course_areas() { + $this->resetAfterTest(); + $this->setAdminUser(); + + $category = $this->getDataGenerator()->create_category(); + $course = $this->getDataGenerator()->create_course(['category' => $category->id]); + $coursecontext = \context_course::instance($course->id); + $catcontext = \context_coursecat::instance($category->id); + $generator = $this->getDataGenerator()->get_plugin_generator('core_question'); + $cat1 = $generator->create_question_category(['contextid' => $coursecontext->id]); + $question1 = $generator->create_question('multichoice', null, ['category' => $cat1->id]); + $question2 = $generator->create_question('multichoice', null, ['category' => $cat1->id]); + $questiontext = new questiontext(); + $rs = $questiontext->find_course_areas($course->id); + $this->assertNotNull($rs); + + $count = 0; + foreach ($rs as $rec) { + $count++; + $this->assertEquals($coursecontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + if ($count <= 1) { + $this->assertEquals($question1->id, $rec->itemid); + } else { + $this->assertEquals($question2->id, $rec->itemid); + } + } + $rs->close(); + $this->assertEquals(2, $count); + + // Add a question to a quiz in the course. + $quiz = $this->getDataGenerator()->create_module('quiz', ['course' => $course->id, 'name' => 'Quiz1']); + $quizmodule = get_coursemodule_from_instance('quiz', $quiz->id, $course->id); + $quizcontext = \context_module::instance($quizmodule->id); + + // Add a question to the quiz context. + $cat2 = $generator->create_question_category(['contextid' => $quizcontext->id]); + $question3 = $generator->create_question('multichoice', null, ['category' => $cat2->id]); + $rs2 = $questiontext->find_course_areas($course->id); + $this->assertNotNull($rs2); + + $count = 0; + foreach ($rs2 as $rec) { + $count++; + if ($count <= 1) { + $this->assertEquals($coursecontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + $this->assertEquals($question1->id, $rec->itemid); + } else if ($count <= 2) { + $this->assertEquals($coursecontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + $this->assertEquals($question2->id, $rec->itemid); + } else { + $this->assertEquals($quizcontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + $this->assertEquals($question3->id, $rec->itemid); + } + } + $rs2->close(); + $this->assertEquals(3, $count); + + // Add a question to the category context. + $cat3 = $generator->create_question_category(['contextid' => $catcontext->id]); + $question4 = $generator->create_question('multichoice', null, ['category' => $cat3->id]); + $rs3 = $questiontext->find_course_areas($course->id); + $this->assertNotNull($rs3); + + // The category level questions should not be found. + $count = 0; + foreach ($rs3 as $rec) { + $count++; + if ($count > 2) { + $this->assertEquals($quizcontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + $this->assertEquals($question3->id, $rec->itemid); + } + } + $rs2->close(); + $this->assertEquals(3, $count); + } + + /** + * Test find relevant areas. + */ + public function test_find_relevant_areas() { + $this->resetAfterTest(); + $this->setAdminUser(); + + $course = $this->getDataGenerator()->create_course(); + $coursecontext = \context_course::instance($course->id); + $generator = $this->getDataGenerator()->get_plugin_generator('core_question'); + $cat1 = $generator->create_question_category(['contextid' => $coursecontext->id]); + $question1 = $generator->create_question('multichoice', null, ['category' => $cat1->id]); + $question2 = $generator->create_question('multichoice', null, ['category' => $cat1->id]); + $questiontext = new questiontext(); + $event = \core\event\question_updated::create_from_question_instance($question1, + \context_course::instance($course->id)); + $rs = $questiontext->find_relevant_areas($event); + $this->assertNotNull($rs); + + $count = 0; + foreach ($rs as $rec) { + $count++; + $this->assertEquals($coursecontext->id, $rec->contextid); + $this->assertEquals($course->id, $rec->courseid); + $this->assertEquals($question1->id, $rec->itemid); + } + $rs->close(); + $this->assertEquals(1, $count); + } + + /** + * Test find system areas. + */ + public function test_find_system_areas() { + $this->resetAfterTest(); + $this->setAdminUser(); + + $category = $this->getDataGenerator()->create_category(); + $catcontext = \context_coursecat::instance($category->id); + $systemcontext = \context_system::instance(); + $generator = $this->getDataGenerator()->get_plugin_generator('core_question'); + $cat = $generator->create_question_category(['contextid' => $catcontext->id]); + $cat2 = $generator->create_question_category(['contextid' => $systemcontext->id]); + $question = $generator->create_question('multichoice', null, ['category' => $cat2->id]); + $question2 = $generator->create_question('multichoice', null, ['category' => $cat->id]); + $questiontext = new questiontext(); + $rs = $questiontext->find_system_areas(); + $this->assertNotNull($rs); + + $count = 0; + foreach ($rs as $rec) { + $count++; + if ($count <= 1) { + $this->assertEquals($systemcontext->id, $rec->contextid); + $this->assertEquals(1, $rec->courseid); + $this->assertEquals(0, $rec->categoryid); + $this->assertEquals($question->id, $rec->itemid); + } else { + $this->assertEquals($catcontext->id, $rec->contextid); + $this->assertEquals(1, $rec->courseid); + $this->assertEquals($category->id, $rec->categoryid); + $this->assertEquals($question2->id, $rec->itemid); + } + } + $rs->close(); + $this->assertEquals(2, $count); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/a_links_dont_open_new_window_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/a_links_dont_open_new_window_test.php new file mode 100644 index 0000000000000..b60a9baaac432 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/a_links_dont_open_new_window_test.php @@ -0,0 +1,106 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class a_links_dont_open_new_window_testcase + */ +class a_links_dont_open_new_window_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'a_links_dont_open_new_window'; + + /** @var string Html fail */ + private $htmlfail = << + + + A links must not open a new tab or window + + + This is google + + +EOD; + + /** @var string Html pass 1 */ + private $htmlpass1 = << + + + A links must not open a new tab or window + + + This is google + + +EOD; + + /** @var string Html pass 2 */ + private $htmlpass2 = << + + + A links must not open a new tab or window + + + This is youtube + + +EOD; + + /** @var string Html pass 3 */ + private $htmlpass3 = << + + + A links must not open a new tab or window + + + This is youtube + + +EOD; + + /** + * Test for links opening a new tab or window + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'a'); + + $results = $this->get_checker_results($this->htmlpass1); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass2); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass3); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/a_must_contain_text_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/a_must_contain_text_test.php new file mode 100644 index 0000000000000..840258a47b571 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/a_must_contain_text_test.php @@ -0,0 +1,74 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class a_must_contain_text_testcase + */ +class a_must_contain_text_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'a_must_contain_text'; + + /** @var string Html fail */ + private $htmlfail = << + + + Anchor tags must contain text + + + + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Anchor tags must contain text + + + This is youtube + + +EOD; + + /** + * Test for anchor tags containing text + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'a'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/a_suspicious_link_text_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/a_suspicious_link_text_test.php new file mode 100644 index 0000000000000..61e55df229fd8 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/a_suspicious_link_text_test.php @@ -0,0 +1,106 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class a_suspicious_link_text + */ +class a_suspicious_link_text_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'a_suspicious_link_text'; + + /** @var string Html fail */ + private $htmlfail = << + + + Anchor tag text must be specific + + + click here + + +EOD; + + /** @var string Html fail 2 */ + private $htmlfail2 = << + + + Anchor tag text must be specific + + +

www.bbc.com

+ + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Anchor tag text must be specific + + + YouTube + + +EOD; + + /** @var string Html pass 2 */ + private $htmlpass2 = << + + + Anchor tag text must be specific + + + http://www.google.com + + +EOD; + + /** + * Test for anchor tags not containing susplicious link text + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass2); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'a'); + + $results = $this->get_checker_results($this->htmlfail2); + $this->assertTrue($results[0]->element->tagName == 'a'); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/all_checks.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/all_checks.php new file mode 100644 index 0000000000000..099dcd553ffbb --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/all_checks.php @@ -0,0 +1,42 @@ +. + +namespace tool_brickfield\local\htmlchecker\common\checks; + +use tool_brickfield\local\htmlchecker\brickfield_accessibility; + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +abstract class all_checks extends \advanced_testcase { + // Extending class must define this. + /** @var string Check type */ + protected $checktype; + + /** + * Parent function to be called in every check testcase + * @param string $html + */ + public function get_checker_results(string $html) { + $checker = new brickfield_accessibility($html, 'brickfield', 'string'); + $checker->run_check(); + return $checker->get_test($this->checktype); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/area_dont_open_new_window_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/area_dont_open_new_window_test.php new file mode 100644 index 0000000000000..37f9e4c911d98 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/area_dont_open_new_window_test.php @@ -0,0 +1,106 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class area_dont_open_new_window_testcase + */ +class area_dont_open_new_window_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'area_dont_open_new_window'; + + /** @var string Html fail */ + private $htmlfail = << + + + Area tags must not open new window without warning + + + + + +EOD; + + /** @var string Html pass 1 */ + private $htmlpass1 = << + + + Area tags must not open new window without warning + + + + + +EOD; + + /** @var string Html pass 2 */ + private $htmlpass2 = << + + + Area tags must not open new window without warning + + + + + +EOD; + + /** @var string Html pass 3 */ + private $htmlpass3 = << + + + Area tags must not open new window without warning + + + + + +EOD; + + /** + * Test Area tags opening new window without warning + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'area'); + + $results = $this->get_checker_results($this->htmlpass1); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass2); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass3); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/area_has_alt_value_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/area_has_alt_value_test.php new file mode 100644 index 0000000000000..216b24e6d8903 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/area_has_alt_value_test.php @@ -0,0 +1,74 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class area_has_alt_value_testcase + */ +class area_has_alt_value_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'area_has_alt_value'; + + /** @var string Html fail */ + private $htmlfail = << + + + Area tags must have an alt value + + + + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Area tags must have an alt value + + + this is alt text + + +EOD; + + /** + * Test for area tags containing an alt value + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'area'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/basefont_is_not_used_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/basefont_is_not_used_test.php new file mode 100644 index 0000000000000..e1bca45514fd9 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/basefont_is_not_used_test.php @@ -0,0 +1,74 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class basefont_is_not_used_testcase + */ +class basefont_is_not_used_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'basefont_is_not_used'; + + /** @var string Html fail */ + private $htmlfail = << + + + Basefont tags must not be used + + + This is a basefont tag> + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Basefont tags must not be used + + +

This is not a basefont tag

+ + +EOD; + + /** + * Test for basefont tags being used + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'basefont'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/blink_is_not_used_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/blink_is_not_used_test.php new file mode 100644 index 0000000000000..66a4ce965ac48 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/blink_is_not_used_test.php @@ -0,0 +1,74 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class blink_is_not_used_testcase + */ +class blink_is_not_used_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'blink_is_not_used'; + + /** @var string Html fail */ + private $htmlfail = << + + + Blink tags must not be used + + + This text is blinking + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Blink tags must not be used + + +

This text does not blink

+ + +EOD; + + /** + * Test for blink tags being used + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'blink'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/bold_is_not_used_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/bold_is_not_used_test.php new file mode 100644 index 0000000000000..a99978976b5f9 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/bold_is_not_used_test.php @@ -0,0 +1,76 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class bold_is_not_used_testcase + */ +class bold_is_not_used_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'bold_is_not_used'; + + /** @var string Html fail */ + private $htmlfail = << + + + b tags must not be used + + + This text is bold + This text is also bold + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + b tags must not be used + + + This text is strong + + +EOD; + + /** + * Test for b tags being used + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'b'); + $this->assertTrue($results[1]->element->tagName == 'b'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/content_too_long_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/content_too_long_test.php new file mode 100644 index 0000000000000..bd1fed83d8347 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/content_too_long_test.php @@ -0,0 +1,107 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class content_too_long_testcase + */ +class content_too_long_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'content_too_long'; + + /** @var string Html fail */ + private $htmlfail = << + + + Content must not exceed a certain length + + +

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent accumsan, ante varius viverra aliquam, dolor risus + scelerisque massa, ut lacinia ipsum felis id est. Nullam convallis odio ante, in commodo elit fermentum sed. Vivamus ullamcorper + tincidunt sagittis. Sed et semper sapien. Quisque malesuada lacus nec libero cursus, aliquam malesuada neque ultricies. Cras sit + amet enim vel orci tristique porttitor a vitae urna. Suspendisse mi leo, hendrerit et eleifend a, mollis at ex. Maecenas eget + magna nec sem dignissim pharetra vel nec ex. Donec in porta lectus. Aenean porttitor euismod lectus, sodales eleifend ex egestas + in. Donec sed metus sodales, lobortis velit quis, dictum arcu. + Praesent mollis urna eget odio cursus, sit amet sollicitudin ante aliquam. Integer nec massa nec ipsum tincidunt laoreet in + vitae metus. Integer massa lacus, elementum quis dui sed, eleifend fringilla turpis. In hac habitasse platea dictumst. Phasellus + efficitur quis felis non eleifend. Sed et mauris vel lorem ultrices porta. Mauris commodo condimentum felis, vel dictum ex + laoreet sit amet. Duis venenatis ut lacus non ultrices. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per + inceptos himenaeos. Nam nunc magna, semper feugiat feugiat a, pellentesque vel nulla. + Sed lacinia nunc lobortis, vestibulum nisi dictum, pulvinar tellus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed + sodales, mauris vitae vulputate porttitor, urna tellus tempor turpis, sed hendrerit metus turpis at est. Etiam augue purus, + blandit eget elit sit amet, suscipit mollis ligula. Suspendisse rutrum sem ex, eu commodo nisi aliquam sit amet. Fusce ut felis + justo. Sed a quam at lectus consectetur vulputate. Proin elementum dui nisi, in condimentum diam porttitor eget. Donec vehicula + condimentum velit vel semper. Mauris vehicula tortor lectus, quis convallis erat aliquet vel. In dictum nunc ac posuere porta. + Sed vel leo aliquam, volutpat ligula ac, blandit diam. Donec nec ligula lacus. + Mauris ac libero vel ex fringilla fringilla. Ut vehicula justo eu nunc imperdiet ultricies. Sed interdum ligula at nisi rhoncus + auctor. Sed tempus tellus eget risus placerat, et viverra dolor gravida. Sed ultricies neque id ex tempor viverra. Ut imperdiet + pharetra magna sed tristique. Pellentesque blandit elit ac neque lacinia finibus. Lorem ipsum dolor sit amet, consectetur + adipiscing elit. Donec vel auctor dolor. Morbi id elit mollis ante mattis semper eu ac lectus. Integer elit turpis, facilisis + vel metus eget, blandit tempus arcu. Pellentesque eget magna eu ex eleifend tincidunt. Curabitur sit amet congue nisi. + Cras mauris risus, malesuada egestas dapibus et, pharetra in ante. Aenean sit amet augue non ligula tempor scelerisque eget ac + turpis. Aenean tincidunt tristique dui, pretium lacinia felis posuere vel. Donec massa ligula, luctus vitae enim nec, sagittis + hendrerit lorem. In consequat sodales metus vel porttitor. Aenean fringilla fringilla risus, vitae interdum turpis egestas quis. + Aenean volutpat arcu leo, ut dictum purus consectetur id. Cras enim ipsum, tincidunt vitae mi vel, varius convallis ex. Fusce + pretium porttitor tempus. + Morbi laoreet dapibus lectus ut efficitur. Donec at hendrerit nunc. Vivamus venenatis augue non nulla finibus vestibulum. Nam + nunc magna, hendrerit a ipsum nec, pulvinar imperdiet augue. Fusce vel metus maximus, mattis magna at, egestas enim. Suspendisse + et nisl at enim mollis scelerisque. Duis ut ipsum vel turpis eleifend aliquet a a ante. Nam lacinia purus vulputate purus + tincidunt, aliquet sagittis nisi sagittis. Pellentesque efficitur massa non ex sodales pretium. Cras convallis vitae ex et + dignissim. Nunc suscipit bibendum aliquam. Maecenas interdum tellus varius, laoreet velit sed, ornare arcu. Nunc pulvinar + elementum sem eget scelerisque. Duis volutpat tellus ut risus finibus, nec molestie erat fermentum +

+ + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Content must not exceed a certain length/title> + </head> + <body> + <p>Nice and short text</p> + </body> + </html> +EOD; + + /** + * Test for checking the length of the content + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->message == '<p id=\'wc\'>Word Count: 578</p>'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/css_text_has_contrast_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/css_text_has_contrast_test.php new file mode 100644 index 0000000000000..f5c1fa59f2f3e --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/css_text_has_contrast_test.php @@ -0,0 +1,74 @@ +<?php +// 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 <http://www.gnu.org/licenses/>. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class test_css_text_has_contrast_testcase + */ +class css_text_has_contrast_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'css_text_has_contrast'; + + /** @var string Html fail */ + private $htmlfail = <<<EOD + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN""http://www.w3.org/TR/REC-html40/loose.dtd"> + <html lang="en"> + <head> + <title>OAC Testfile - Check #6 - Positive + + +

This is not contrasty enough.

+ + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + OAC Testfile - Check #6 - Positive + + +

This is contrasty enough.

+ + +EOD; + + /** + * Test for the area assign intro + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'p'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/embed_has_associated_no_embed_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/embed_has_associated_no_embed_test.php new file mode 100644 index 0000000000000..64e283f91d11c --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/embed_has_associated_no_embed_test.php @@ -0,0 +1,94 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class embed_has_associated_no_embed_testcase + */ +class embed_has_associated_no_embed_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'embed_has_associated_no_embed'; + + /** @var string Html fail 1 */ + private $htmlfail = << + + + Embed tags must have a noembed child tag + + + + + +EOD; + + /** @var string Html fail 2 */ + private $htmlfail2 = << + + + Embed tags must have a noembed child tag + + + + + + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Embed tags must have a noembed child tag + + + + <img src = "yourimage.gif" alt = "Alternative Media" > + + + +EOD; + + /** + * Test for noembed child tags + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'embed'); + + $results = $this->get_checker_results($this->htmlfail2); + $this->assertTrue($results[0]->element->tagName == 'embed'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/header_h3_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/header_h3_test.php new file mode 100644 index 0000000000000..2941ebe595ca1 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/header_h3_test.php @@ -0,0 +1,144 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class header_h3_testcase + */ +class header_h3_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'header_h3'; + + /** @var string Html fail 1 */ + private $htmlfail1 = << + + + The header following an h3 must be h1, h2, h3 or h4. + + +

This is h3

+
This is h5
+ + +EOD; + + /** @var string Html fail 2 */ + private $htmlfail2 = << + + + The header following an h3 must be h1, h2, h3 or h4. + + +

This is h3

+
This is h6
+ + +EOD; + + /** @var string Html pass 1 */ + private $htmlpass1 = << + + + The header following an h3 must be h1, h2, h3 or h4. + + +

This is h3

+

This is h1

+ + +EOD; + + /** @var string Html pass 2 */ + private $htmlpass2 = << + + + The header following an h3 must be h1, h2, h3 or h4. + + +

This is h3

+

This is h2

+ + +EOD; + + /** @var string Html pass 3 */ + private $htmlpass3 = << + + + The header following an h3 must be h1, h2, h3 or h4. + + +

This is h3

+

This is h3

+ + +EOD; + + /** @var string Html pass 4 */ + private $htmlpass4 = << + + + The header following an h3 must be h1, h2, h3 or h4. + + +

This is h3

+

This is h4

+ + +EOD; + + /** + * Test the header following an h3 must be h1, h2, h3 or h4. + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail1); + $this->assertTrue($results[0]->element->tagName == 'h5'); + + $results = $this->get_checker_results($this->htmlfail2); + $this->assertTrue($results[0]->element->tagName == 'h6'); + + $results = $this->get_checker_results($this->htmlpass1); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass3); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass3); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass4); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/headers_have_text_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/headers_have_text_test.php new file mode 100644 index 0000000000000..43b55534f7739 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/headers_have_text_test.php @@ -0,0 +1,86 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class headers_have_text_testcase + */ +class headers_have_text_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'headers_have_text'; + + /** @var string Html fail */ + private $htmlfail = << + + + Header has text - Fail + + +

This is a correct header

+

Intrinsicly actualize web-enabled users and cross functional growth strategies. Monotonectally simplify B2B opportunities + vis-a-vis top-line processes.

+

+

Globally synergize ethical process improvements before go forward technology. Synergistically seize backward-compatible + quality vectors through magnetic sources. Distinctively reintermediate virtual "outside the box" thinking without market + positioning supply chains.

+ + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Header has text - Fail + + +

This is a correct header

+

Intrinsicly actualize web-enabled users and cross functional growth strategies. Monotonectally simplify B2B opportunities + vis-a-vis top-line processes.

+

This header is also OK.

+

Globally synergize ethical process improvements before go forward technology. Synergistically seize backward-compatible + quality vectors through magnetic sources. Distinctively reintermediate virtual "outside the box" thinking without market + positioning supply chains.

+ + +EOD; + + /** + * Test for headers not containing text + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'h2'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/i_is_not_used_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/i_is_not_used_test.php new file mode 100644 index 0000000000000..29bea3ea8be22 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/i_is_not_used_test.php @@ -0,0 +1,74 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class i_is_not_used_testcase + */ +class i_is_not_used_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'i_is_not_used'; + + /** @var string Html fail */ + private $htmlfail = << + + + i tags must not be used + + + This text is italicized + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + i tags must not be used + + +

This text is not

+ + +EOD; + + /** + * Test for i tags being used + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'i'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_is_different_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_is_different_test.php new file mode 100644 index 0000000000000..89503bc02292e --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_is_different_test.php @@ -0,0 +1,74 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class img_alt_is_different_testcase + */ +class img_alt_is_different_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'img_alt_is_different'; + + /** @var string Html fail */ + private $htmlfail = << + + + Image alt attributes need to be specified - fail + + + rex.jpg + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Image alt attributes need to be specified - fail + + + this is an image of rex + + +EOD; + + /** + * Test for img alt attributes matching the src attribute + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'img'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_is_too_long_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_is_too_long_test.php new file mode 100644 index 0000000000000..ed207dca9db3e --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_is_too_long_test.php @@ -0,0 +1,78 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class img_alt_is_too_long_testcase + */ +class img_alt_is_too_long_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'img_alt_is_too_long'; + + /** @var string Html fail */ + private $htmlfail = << + + + Image alt attributes must not be too long + + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent accumsan, ante varius viverra aliquam,
+	 dolor risus scelerisque massa, ut lacinia ipsum felis id est. Nullam convallis odio ante, in commodo elit fermentum sed.
+	 Vivamus ullamcorper tincidunt sagittis. Sed et semper sapien. Quisque malesuada lacus nec libero cursus, aliquam malesuada
+	 neque ultricies. Cras sit amet enim vel orci tristique porttitor a vitae urna. Suspendisse mi leo, hendrerit et eleifend a,
+	 mollis at ex. Maecenas eget magna nec sem dignissim pharetra vel nec ex. Donec in porta lectus. Aenean porttitor euismod
+	 lectus, sodales eleifend ex egestas in. Donec sed metus sodales, lobortis velit quis, dictum arcu. + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Image alt attributes must not be too long + + + this is an image of rex + + +EOD; + /** + * Test for image alt attributes being too long + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'img'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_not_empty_in_anchor_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_not_empty_in_anchor_test.php new file mode 100644 index 0000000000000..12b02defe859e --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_not_empty_in_anchor_test.php @@ -0,0 +1,73 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class img_alt_not_empty_in_anchor_testcase + */ +class img_alt_not_empty_in_anchor_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'img_alt_not_empty_in_anchor'; + + /** @var string Html fail */ + private $htmlfail = << + + + Anchor tags containing a nested img tag, must not have an empty alt attribute + + + + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Anchor tags containing a nested img tag, must not have an empty alt attribute + + + Picture of Rex + + +EOD; + /** + * Test for >Anchor tags containing a nested img tag, must not have an empty alt attribute + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'img'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_not_place_holder_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_not_place_holder_test.php new file mode 100644 index 0000000000000..85fd7f5a0c207 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_alt_not_place_holder_test.php @@ -0,0 +1,163 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class img_alt_not_placeholder_testcase + */ +class img_alt_not_place_holder_test extends all_checks { + /** @var string Check type */ + protected $checktype = 'img_alt_not_place_holder'; + + /** @var string Html fail 1 */ + private $htmlfail1 = << + + + Image alt attributes match the specified string array in imgAltNotPlaceHolder- fail + + + nbsp + + +EOD; + + /** @var string Html fail 2 */ + private $htmlfail2 = << + + + Image alt attributes match the specified string array in imgAltNotPlaceHolder- fail + + +   + + +EOD; + + /** @var string Html fail 3 */ + private $htmlfail3 = << + + + Image alt attributes match the specified string array in imgAltNotPlaceHolder- fail + + + spacer + + +EOD; + + /** @var string Html fail 4 */ + private $htmlfail4 = << + + + Image alt attributes match the specified string array in imgAltNotPlaceHolder- fail + + + image + + +EOD; + + /** @var string Html fail 5 */ + private $htmlfail5 = << + + + Image alt attributes match the specified string array in imgAltNotPlaceHolder- fail + + + img + + +EOD; + + /** @var string Html fail 6 */ + private $htmlfail6 = << + + + Image alt attributes match the specified string array in imgAltNotPlaceHolder- fail + + + photo + + +EOD; + + /** @var string Html pass 1 */ + private $htmlpass1 = << + + + Image alt attributes must not match the string array specified in imgAltNotPlaceHolder - pass + + + A mountian with a sunset + + +EOD; + + /** + * Notes: espacio & imagen & foto within the 'es' lang_string, all pass - they shouldn't. + */ + + /** + * Test for the each en string specified in $strings - line 43 in imgAltNotPlaceHolder. + */ + public function test_failcheck() { + $results = $this->get_checker_results($this->htmlfail1); + $this->assertTrue($results[0]->element->tagName == 'img'); + + $results = $this->get_checker_results($this->htmlfail2); + $this->assertTrue($results[0]->element->tagName == 'img'); + + $results = $this->get_checker_results($this->htmlfail3); + $this->assertTrue($results[0]->element->tagName == 'img'); + + $results = $this->get_checker_results($this->htmlfail4); + $this->assertTrue($results[0]->element->tagName == 'img'); + + $results = $this->get_checker_results($this->htmlfail5); + $this->assertTrue($results[0]->element->tagName == 'img'); + + $results = $this->get_checker_results($this->htmlfail6); + $this->assertTrue($results[0]->element->tagName == 'img'); + } + + /** + * Test with alt that was not specified in the $strings array. + */ + public function test_passcheck1() { + $results = $this->get_checker_results($this->htmlpass1); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_has_alt_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_has_alt_test.php new file mode 100644 index 0000000000000..20e7d5e2f12b5 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_has_alt_test.php @@ -0,0 +1,94 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class test_css_text_has_contrast_testcase + */ +class img_has_alt_test extends all_checks { + /** @var string Check type */ + public $checktype = 'img_has_alt'; + + /** @var string Html fail 1 */ + private $htmlfail1 = << + + + Image alt attributes need to be specified - fail + + + + + +EOD; + + /** @var string Html fail 2 */ + private $htmlfail2 = << + + + Image alt attributes need to be specified - fail + + + + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Image alt attributes need to be specified - fail + + + this is an image of rex + + +EOD; + /** + * Test for missing image alt text. + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail1); + $this->assertTrue($results[0]->element->tagName == 'img'); + + $results = $this->get_checker_results($this->htmlfail2); + $this->assertTrue($results[0]->element->tagName == 'img'); + } + + /** + * Test for present image alt text. + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass); + $this->assertTrue(count($results) == 0); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_with_map_has_use_map_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_with_map_has_use_map_test.php new file mode 100644 index 0000000000000..991742a627ca0 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/img_with_map_has_use_map_test.php @@ -0,0 +1,81 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class img_with_map_has_use_map_test + */ +class img_with_map_has_use_map_test extends all_checks { + /** @var string Check type */ + public $checktype = 'img_with_map_has_use_map'; + + /** @var string Html fail */ + private $htmlfail = << + + + Usemap cannot be used without a matching map - fail + + + + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Usemap with a matching map can be used - pass + + + + + + + + +EOD; + /** + * Test for usemap attribute. + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'img'); + } + + /** + * Test for ismap attribute. + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/legend_text_not_empty_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/legend_text_not_empty_test.php new file mode 100644 index 0000000000000..76a631f2fbc24 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/legend_text_not_empty_test.php @@ -0,0 +1,94 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class legend_text_not_empty_test + */ +class legend_text_not_empty_test extends all_checks { + /** @var string Check type */ + public $checktype = 'legend_text_not_empty'; + + /** @var string Html fail 1 */ + private $htmlfail1 = << + + + Legend is empty - fail + + + + + +EOD; + + /** @var string Html pass 2 */ + private $htmlfail2 = << + + + Legend contains only white space - fail + + + + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Legend containts text - pass + + + This is a very descriptive legend + + +EOD; + /** + * Test for if legend is empty or only has white spaces. + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail1); + $this->assertTrue($results[0]->element->tagName == 'legend'); + + $results = $this->get_checker_results($this->htmlfail2); + $this->assertTrue($results[0]->element->tagName == 'legend'); + } + + /** + * Test for if legend has text. + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/marquee_is_not_used.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/marquee_is_not_used.php new file mode 100644 index 0000000000000..7c8d9dcd25d7a --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/marquee_is_not_used.php @@ -0,0 +1,81 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class marquee_is_not_used_test + * + * This check test does not currently exist + */ +class marquee_is_not_used_test extends all_checks { + /** @var string Check type */ + public $checktype = 'marquee_is_not_used'; + + /** @var string Html fail */ + private $htmlfail = << + + + Marquee is used - fail + + + This should not work + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Marquee is not used - pass + + + + + +EOD; + + /** + * Test for if marquee does exist. + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'marquee'); + } + + /** + * Test for if marquee does not exist. + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass); + $this->assertTrue($results[0]->element->tagName == 'marquee'); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/no_headings_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/no_headings_test.php new file mode 100644 index 0000000000000..3730b03e22a0d --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/no_headings_test.php @@ -0,0 +1,285 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class no_headings_test + */ +class no_headings_test extends all_checks { + /** @var string Check type */ + public $checktype = 'no_headings'; + + /** @var string Html fail */ + private $htmlfail = << + + + Doc does not contain any h tag and has more than 1800 characters - fail + + +

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut varius elit, vel euismod neque. Nunc vulputate elit at + lacus tincidunt tempus eget non urna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. + Duis vel ipsum commodo, egestas erat ac, finibus orci. Nunc massa est, convallis at libero et, convallis rhoncus turpis. + Aliquam eu ipsum egestas, blandit odio quis, mattis enim. Sed libero ante, condimentum ut sodales eget, viverra vitae dolor. + Nulla venenatis, enim ut hendrerit placerat, neque tellus ultricies erat, a congue odio elit ac lorem. Duis quis nisl + placerat, pulvinar ipsum nec, pretium urna. Sed id hendrerit felis. Aliquam sit amet dui justo. Donec in quam sit amet + lectus mollis sodales. Etiam turpis purus, suscipit vel luctus quis, scelerisque id nisl. Cras elit mauris, ultricies ac + facilisis vitae, lacinia at purus. + Fusce pellentesque, turpis non tempus malesuada, lectus risus mollis metus, a gravida urna est sit amet diam. Fusce ut + sapien tempus, rutrum nisi in, consequat lacus. Aliquam pretium libero dignissim tempus scelerisque. Cras eget consequat + purus. Ut ultricies est urna, non euismod sem faucibus eget. Suspendisse venenatis iaculis augue, imperdiet sollicitudin + metus. Fusce vitae nisl arcu. Proin fermentum sollicitudin libero eu rutrum. + Praesent consequat hendrerit aliquam. Nunc sem turpis, vehicula et dui ac, gravida consequat quam. Sed vestibulum, risus et + sodales condimentum, purus nunc consectetur dolor, in tempor mi ex et ligula. Sed volutpat orci nisl, at scelerisque mauris + interdum ac. Maecenas sed sodales dui. Integer sed elit cursus, tincidunt neque sed, lobortis erat. Sed feugiat id nulla + quis auctor. Donec in rhoncus nunc. Vestibulum in sagittis sem. Aenean ut iaculis nisi. +

+ + +EOD; + + /** @var string Html pass 1 */ + private $htmlpass1 = << + + + Doc contains more than 1800 characters within a p tag and a h1 tag - pass + + +

This a h1 heading

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut varius elit, vel euismod neque. Nunc vulputate elit at + lacus tincidunt tempus eget non urna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. + Duis vel ipsum commodo, egestas erat ac, finibus orci. Nunc massa est, convallis at libero et, convallis rhoncus turpis. + Aliquam eu ipsum egestas, blandit odio quis, mattis enim. Sed libero ante, condimentum ut sodales eget, viverra vitae dolor. + Nulla venenatis, enim ut hendrerit placerat, neque tellus ultricies erat, a congue odio elit ac lorem. Duis quis nisl + placerat, pulvinar ipsum nec, pretium urna. Sed id hendrerit felis. Aliquam sit amet dui justo. Donec in quam sit amet + lectus mollis sodales. Etiam turpis purus, suscipit vel luctus quis, scelerisque id nisl. Cras elit mauris, ultricies ac + facilisis vitae, lacinia at purus. + Fusce pellentesque, turpis non tempus malesuada, lectus risus mollis metus, a gravida urna est sit amet diam. Fusce ut + sapien tempus, rutrum nisi in, consequat lacus. Aliquam pretium libero dignissim tempus scelerisque. Cras eget consequat + purus. Ut ultricies est urna, non euismod sem faucibus eget. Suspendisse venenatis iaculis augue, imperdiet sollicitudin + metus. Fusce vitae nisl arcu. Proin fermentum sollicitudin libero eu rutrum. + Praesent consequat hendrerit aliquam. Nunc sem turpis, vehicula et dui ac, gravida consequat quam. Sed vestibulum, risus et + sodales condimentum, purus nunc consectetur dolor, in tempor mi ex et ligula. Sed volutpat orci nisl, at scelerisque mauris + interdum ac. Maecenas sed sodales dui. Integer sed elit cursus, tincidunt neque sed, lobortis erat. Sed feugiat id nulla + quis auctor. Donec in rhoncus nunc. Vestibulum in sagittis sem. Aenean ut iaculis nisi. +

+ + +EOD; + + /** @var string Html pass 2 */ + private $htmlpass2 = << + + + Doc contains more than 1800 characters within a p tag and a h2 tag - pass + + +

This a h2 heading

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut varius elit, vel euismod neque. Nunc vulputate elit at + lacus tincidunt tempus eget non urna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. + Duis vel ipsum commodo, egestas erat ac, finibus orci. Nunc massa est, convallis at libero et, convallis rhoncus turpis. + Aliquam eu ipsum egestas, blandit odio quis, mattis enim. Sed libero ante, condimentum ut sodales eget, viverra vitae dolor. + Nulla venenatis, enim ut hendrerit placerat, neque tellus ultricies erat, a congue odio elit ac lorem. Duis quis nisl + placerat, pulvinar ipsum nec, pretium urna. Sed id hendrerit felis. Aliquam sit amet dui justo. Donec in quam sit amet + lectus mollis sodales. Etiam turpis purus, suscipit vel luctus quis, scelerisque id nisl. Cras elit mauris, ultricies ac + facilisis vitae, lacinia at purus. + Fusce pellentesque, turpis non tempus malesuada, lectus risus mollis metus, a gravida urna est sit amet diam. Fusce ut + sapien tempus, rutrum nisi in, consequat lacus. Aliquam pretium libero dignissim tempus scelerisque. Cras eget consequat + purus. Ut ultricies est urna, non euismod sem faucibus eget. Suspendisse venenatis iaculis augue, imperdiet sollicitudin + metus. Fusce vitae nisl arcu. Proin fermentum sollicitudin libero eu rutrum. + Praesent consequat hendrerit aliquam. Nunc sem turpis, vehicula et dui ac, gravida consequat quam. Sed vestibulum, risus et + sodales condimentum, purus nunc consectetur dolor, in tempor mi ex et ligula. Sed volutpat orci nisl, at scelerisque mauris + interdum ac. Maecenas sed sodales dui. Integer sed elit cursus, tincidunt neque sed, lobortis erat. Sed feugiat id nulla + quis auctor. Donec in rhoncus nunc. Vestibulum in sagittis sem. Aenean ut iaculis nisi. +

+ + +EOD; + + /** @var string Html pass 3 */ + private $htmlpass3 = << + + + Doc contains more than 1800 characters within a p tag and a h3 tag - pass + + +

This a h3 heading

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut varius elit, vel euismod neque. Nunc vulputate elit at + lacus tincidunt tempus eget non urna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. + Duis vel ipsum commodo, egestas erat ac, finibus orci. Nunc massa est, convallis at libero et, convallis rhoncus turpis. + Aliquam eu ipsum egestas, blandit odio quis, mattis enim. Sed libero ante, condimentum ut sodales eget, viverra vitae dolor. + Nulla venenatis, enim ut hendrerit placerat, neque tellus ultricies erat, a congue odio elit ac lorem. Duis quis nisl + placerat, pulvinar ipsum nec, pretium urna. Sed id hendrerit felis. Aliquam sit amet dui justo. Donec in quam sit amet + lectus mollis sodales. Etiam turpis purus, suscipit vel luctus quis, scelerisque id nisl. Cras elit mauris, ultricies ac + facilisis vitae, lacinia at purus. + Fusce pellentesque, turpis non tempus malesuada, lectus risus mollis metus, a gravida urna est sit amet diam. Fusce ut + sapien tempus, rutrum nisi in, consequat lacus. Aliquam pretium libero dignissim tempus scelerisque. Cras eget consequat + purus. Ut ultricies est urna, non euismod sem faucibus eget. Suspendisse venenatis iaculis augue, imperdiet sollicitudin + metus. Fusce vitae nisl arcu. Proin fermentum sollicitudin libero eu rutrum. + Praesent consequat hendrerit aliquam. Nunc sem turpis, vehicula et dui ac, gravida consequat quam. Sed vestibulum, risus et + sodales condimentum, purus nunc consectetur dolor, in tempor mi ex et ligula. Sed volutpat orci nisl, at scelerisque mauris + interdum ac. Maecenas sed sodales dui. Integer sed elit cursus, tincidunt neque sed, lobortis erat. Sed feugiat id nulla + quis auctor. Donec in rhoncus nunc. Vestibulum in sagittis sem. Aenean ut iaculis nisi. +

+ + +EOD; + + /** @var string Html pass 4 */ + private $htmlpass4 = << + + + Doc contains more than 1800 characters within a p tag and a h4 tag - pass + + +

This a h4 heading

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut varius elit, vel euismod neque. Nunc vulputate elit at + lacus tincidunt tempus eget non urna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. + Duis vel ipsum commodo, egestas erat ac, finibus orci. Nunc massa est, convallis at libero et, convallis rhoncus turpis. + Aliquam eu ipsum egestas, blandit odio quis, mattis enim. Sed libero ante, condimentum ut sodales eget, viverra vitae dolor. + Nulla venenatis, enim ut hendrerit placerat, neque tellus ultricies erat, a congue odio elit ac lorem. Duis quis nisl + placerat, pulvinar ipsum nec, pretium urna. Sed id hendrerit felis. Aliquam sit amet dui justo. Donec in quam sit amet + lectus mollis sodales. Etiam turpis purus, suscipit vel luctus quis, scelerisque id nisl. Cras elit mauris, ultricies ac + facilisis vitae, lacinia at purus. + Fusce pellentesque, turpis non tempus malesuada, lectus risus mollis metus, a gravida urna est sit amet diam. Fusce ut + sapien tempus, rutrum nisi in, consequat lacus. Aliquam pretium libero dignissim tempus scelerisque. Cras eget consequat + purus. Ut ultricies est urna, non euismod sem faucibus eget. Suspendisse venenatis iaculis augue, imperdiet sollicitudin + metus. Fusce vitae nisl arcu. Proin fermentum sollicitudin libero eu rutrum. + Praesent consequat hendrerit aliquam. Nunc sem turpis, vehicula et dui ac, gravida consequat quam. Sed vestibulum, risus et + sodales condimentum, purus nunc consectetur dolor, in tempor mi ex et ligula. Sed volutpat orci nisl, at scelerisque mauris + interdum ac. Maecenas sed sodales dui. Integer sed elit cursus, tincidunt neque sed, lobortis erat. Sed feugiat id nulla + quis auctor. Donec in rhoncus nunc. Vestibulum in sagittis sem. Aenean ut iaculis nisi. +

+ + +EOD; + + /** @var string Html pass 5 */ + private $htmlpass5 = << + + + Doc contains more than 1800 characters within a p tag and a h5 tag - pass + + +
This a h5 heading
+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut varius elit, vel euismod neque. Nunc vulputate elit at + lacus tincidunt tempus eget non urna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. + Duis vel ipsum commodo, egestas erat ac, finibus orci. Nunc massa est, convallis at libero et, convallis rhoncus turpis. + Aliquam eu ipsum egestas, blandit odio quis, mattis enim. Sed libero ante, condimentum ut sodales eget, viverra vitae dolor. + Nulla venenatis, enim ut hendrerit placerat, neque tellus ultricies erat, a congue odio elit ac lorem. Duis quis nisl + placerat, pulvinar ipsum nec, pretium urna. Sed id hendrerit felis. Aliquam sit amet dui justo. Donec in quam sit amet + lectus mollis sodales. Etiam turpis purus, suscipit vel luctus quis, scelerisque id nisl. Cras elit mauris, ultricies ac + facilisis vitae, lacinia at purus. + Fusce pellentesque, turpis non tempus malesuada, lectus risus mollis metus, a gravida urna est sit amet diam. Fusce ut + sapien tempus, rutrum nisi in, consequat lacus. Aliquam pretium libero dignissim tempus scelerisque. Cras eget consequat + purus. Ut ultricies est urna, non euismod sem faucibus eget. Suspendisse venenatis iaculis augue, imperdiet sollicitudin + metus. Fusce vitae nisl arcu. Proin fermentum sollicitudin libero eu rutrum. + Praesent consequat hendrerit aliquam. Nunc sem turpis, vehicula et dui ac, gravida consequat quam. Sed vestibulum, risus et + sodales condimentum, purus nunc consectetur dolor, in tempor mi ex et ligula. Sed volutpat orci nisl, at scelerisque mauris + interdum ac. Maecenas sed sodales dui. Integer sed elit cursus, tincidunt neque sed, lobortis erat. Sed feugiat id nulla + quis auctor. Donec in rhoncus nunc. Vestibulum in sagittis sem. Aenean ut iaculis nisi. +

+ + +EOD; + + /** @var string Html pass 6 */ + private $htmlpass6 = << + + + Doc contains more than 1800 characters within a p tag and a h6 tag - pass + + +
This a h6 heading
+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut varius elit, vel euismod neque. Nunc vulputate elit at + lacus tincidunt tempus eget non urna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. + Duis vel ipsum commodo, egestas erat ac, finibus orci. Nunc massa est, convallis at libero et, convallis rhoncus turpis. + Aliquam eu ipsum egestas, blandit odio quis, mattis enim. Sed libero ante, condimentum ut sodales eget, viverra vitae dolor. + Nulla venenatis, enim ut hendrerit placerat, neque tellus ultricies erat, a congue odio elit ac lorem. Duis quis nisl + placerat, pulvinar ipsum nec, pretium urna. Sed id hendrerit felis. Aliquam sit amet dui justo. Donec in quam sit amet + lectus mollis sodales. Etiam turpis purus, suscipit vel luctus quis, scelerisque id nisl. Cras elit mauris, ultricies ac + facilisis vitae, lacinia at purus. + Fusce pellentesque, turpis non tempus malesuada, lectus risus mollis metus, a gravida urna est sit amet diam. Fusce ut + sapien tempus, rutrum nisi in, consequat lacus. Aliquam pretium libero dignissim tempus scelerisque. Cras eget consequat + purus. Ut ultricies est urna, non euismod sem faucibus eget. Suspendisse venenatis iaculis augue, imperdiet sollicitudin + metus. Fusce vitae nisl arcu. Proin fermentum sollicitudin libero eu rutrum. + Praesent consequat hendrerit aliquam. Nunc sem turpis, vehicula et dui ac, gravida consequat quam. Sed vestibulum, risus et + sodales condimentum, purus nunc consectetur dolor, in tempor mi ex et ligula. Sed volutpat orci nisl, at scelerisque mauris + interdum ac. Maecenas sed sodales dui. Integer sed elit cursus, tincidunt neque sed, lobortis erat. Sed feugiat id nulla + quis auctor. Donec in rhoncus nunc. Vestibulum in sagittis sem. Aenean ut iaculis nisi. +

+ + +EOD; + + /** + * Test for if heading exists where doc length is above 1800 + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertNotEmpty($results); + + } + + /** + * Test for if marquee does not exist. + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass1); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass2); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass3); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass4); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass5); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass6); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/object_must_have_embed_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/object_must_have_embed_test.php new file mode 100644 index 0000000000000..f560f92aecf6f --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/object_must_have_embed_test.php @@ -0,0 +1,81 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class object_must_have_embeded_test + */ +class object_must_have_embed_test extends all_checks { + /** @var string Check type */ + public $checktype = 'object_must_have_embed'; + + /** @var string Html fail */ + private $htmlfail = << + + + Embed element does not exist - fail + + + + + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Embed element exists - pass + + + + + + + +EOD; + /** + * Test for missing embed element within object element. + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'object'); + } + + /** + * Test for present embed element within object element. + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/object_must_have_title_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/object_must_have_title_test.php new file mode 100644 index 0000000000000..7235169afddb6 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/object_must_have_title_test.php @@ -0,0 +1,78 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class object_must_have_title_test + */ +class object_must_have_title_test extends all_checks { + /** @var string Check type */ + public $checktype = 'object_must_have_title'; + + /** @var string Html fail */ + private $htmlfail = << + + + Object does not have title attribute - fail + + + + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Object has title attribute - pass + + + + + +EOD; + /** + * Test for missing title attribute within object element. + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'object'); + } + + /** + * Test for present title attribute within object element. + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/object_must_have_valid_title_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/object_must_have_valid_title_test.php new file mode 100644 index 0000000000000..17498863a0d56 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/object_must_have_valid_title_test.php @@ -0,0 +1,159 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class object_must_have_valid_title_test + */ +class object_must_have_valid_title_test extends all_checks { + /** @var string Check type */ + public $checktype = 'object_must_have_valid_title'; + + /** @var string Html fail */ + private $htmlfail = << + + + Title attribute does not exist within string array - fail + + + + + +EOD; + + /** @var string Html pass 1 */ + private $htmlpass1 = << + + + Title attribute must exist within string array - pass + + + + + +EOD; + + /** @var string Html pass 3 */ + private $htmlpass3 = << + + + Title attribute must exist within string array - pass + + + + + +EOD; + + /** @var string Html pass 4 */ + private $htmlpass4 = << + + + Title attribute must exist within string array - pass + + + + + +EOD; + + /** @var string Html pass 5 */ + private $htmlpass5 = << + + + Title attribute must exist within string array - pass + + + + + +EOD; + + /** @var string Html pass 6 */ + private $htmlpass6 = << + + + Title attribute must exist within string array - pass + + + + + +EOD; + + /** @var string Html pass 7 */ + private $htmlpass7 = << + + + Title attribute must exist within string array - pass + + + + + +EOD; + + /** + * Test that embed element within object element. + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'object'); + } + + /** + * Test for embed element within object element. + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass1); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass3); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass4); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass5); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass6); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass7); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/strike_is_not_used_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/strike_is_not_used_test.php new file mode 100644 index 0000000000000..2d89dbc5d89c0 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/strike_is_not_used_test.php @@ -0,0 +1,90 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class strike_is_not_used_testcase + */ +class strike_is_not_used_test extends all_checks { + /** @var string Check type */ + public $checktype = 'strike_is_not_used'; + + /** @var string Html fail */ + private $htmlfail = << + + + strike tags must not be used + + + This text is using the strike tag + + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + strike tags must not be used + + + This text is using the s tag + + +EOD; + + /** @var string Html pass 1 */ + private $htmlpass1 = << + + + strike tags must not be used + + + This text is using the del tag + + +EOD; + + /** + * Test for b tags being used + */ + public function test_check() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'strike'); + + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass1); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_data_should_have_th_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_data_should_have_th_test.php new file mode 100644 index 0000000000000..ba703684ff82b --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_data_should_have_th_test.php @@ -0,0 +1,138 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class table_data_should_have_th_test + */ +class table_data_should_have_th_test extends all_checks { + /** @var string Check type */ + public $checktype = 'table_data_should_have_th'; + + /** @var string Html fail 1 */ + private $htmlfail1 = << + + + Table should have at least one th - fail + + + + + + + + + + + + + +
This is a tables data
+ + +EOD; + + /** @var string Html fail 2 */ + private $htmlfail2 = << + + + Table should have at least one th - fail + + + + + + + + + +
This is a tables data
+ + +EOD; + + /** @var string Html pass 1 */ + private $htmlpass1 = << + + + Table should have at least one th - pass + + + + + + + + + +
This is table heading
This is a tables data
+ + +EOD; + + /** @var string Html pass 2 */ + private $htmlpass2 = << + + + Table should have at least one th - pass + + + + + +
This is table heading
This is a tables data
+ + +EOD; + /** + * Test that th does not exist + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail1); + $this->assertTrue($results[0]->element->tagName == 'table'); + + $results = $this->get_checker_results($this->htmlfail2); + $this->assertTrue($results[0]->element->tagName == 'table'); + } + + /** + * Test that th does exist + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass1); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass2); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_summary_does_not_duplicate_caption_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_summary_does_not_duplicate_caption_test.php new file mode 100644 index 0000000000000..03df83ff36a94 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_summary_does_not_duplicate_caption_test.php @@ -0,0 +1,82 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class table_summary_does_not_duplicate_caption_test + */ +class table_summary_does_not_duplicate_caption_test extends all_checks { + /** @var string Check type */ + public $checktype = 'table_summary_does_not_duplicate_caption'; + + /** @var string Html fail */ + private $htmlfail = << + + + Summary attribute and caption element contain the same text - fail + + + + +
testing
+ + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + Summary attribute and caption element contain different text - pass + + + + +
testing a caption
+ + +EOD; + /** + * Test that caption and summary are equal + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail); + $this->assertTrue($results[0]->element->tagName == 'table'); + } + + /** + * Test that caption and summary are not equal + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_td_should_not_merge_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_td_should_not_merge_test.php new file mode 100644 index 0000000000000..11c7b087040c2 --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_td_should_not_merge_test.php @@ -0,0 +1,143 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class table_td_should_not_merge_test + */ +class table_td_should_not_merge_test extends all_checks { + /** @var string Check type */ + public $checktype = 'table_td_should_not_merge'; + + /** @var string Html fail 1 */ + private $htmlfail1 = << + + + Rowspan exists - fail + + + + + + + + + + + + + + + + + + +
1
23
45
+ + +EOD; + + /** @var string Html fail 2 */ + private $htmlfail2 = << + + + Colspan exists - fail + + + + + + + + + + + + + + + + + + +
1
23
45
+ + +EOD; + + /** @var string Html pass */ + private $htmlpass = << + + + colspan or rowspan do not exist - pass + + + + + + + + + + + + + + + + + + +
1
23
45
+ + +EOD; + + /** + * Test for rowspan and colspan + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail1); + $this->assertNotEmpty($results); + + $results = $this->get_checker_results($this->htmlfail2); + $this->assertNotEmpty($results); + } + + /** + * Test for rowspan and colspan + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_th_should_have_scope_test.php b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_th_should_have_scope_test.php new file mode 100644 index 0000000000000..709fb4edef00d --- /dev/null +++ b/admin/tool/brickfield/tests/local/htmlchecker/common/checks/table_th_should_have_scope_test.php @@ -0,0 +1,187 @@ +. + +/** + * tool_brickfield check test. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace tool_brickfield\local\htmlchecker\common\checks; + +defined('MOODLE_INTERNAL') || die(); + +require_once('all_checks.php'); + +/** + * Class table_th_should_have_scope_test + */ +class table_th_should_have_scope_test extends all_checks { + /** @var string Check type */ + public $checktype = 'table_th_should_have_scope'; + + /** @var string Html fail 1 */ + private $htmlfail1 = << + + + Scope exists whilst specifying "col" - fail + + + + + + + + + + + + + + + + + + + + +
1
23
45
+ + +EOD; + + /** @var string Html fail 2 */ + private $htmlfail2 = << + + + Scope exists whilst specifying "row" - fail + + + + + + + + + + + + + + + + + + + + + +
123
234
45
+ + +EOD; + + /** @var string Html pass 1 */ + private $htmlpass1 = << + + + Scope exists whilst specifying something that isn't "col" or "row" - pass + + + + + + + + + + + + + + + + + + + + +
123
23
45
+ + +EOD; + + /** @var string Html pass 2 */ + private $htmlpass2 = << + + + Scope is not specified - pass + + + + + + + + + + + + + + + + + + + + + +
123
234
45
+ + +EOD; + /** + * Test that th has scope that is equal to col or row + */ + public function test_check_fail() { + $results = $this->get_checker_results($this->htmlfail1); + $this->assertEquals(2, count($results)); + $this->assertTrue($results[0]->element->tagName == 'th'); + $this->assertTrue($results[1]->element->tagName == 'th'); + + $results = $this->get_checker_results($this->htmlfail2); + $this->assertEquals(1, count($results)); + $this->assertTrue($results[0]->element->tagName == 'th'); + } + + /** + * Test that th has scope but != col || row. Test that th has no scope + */ + public function test_check_pass() { + $results = $this->get_checker_results($this->htmlpass1); + $this->assertEmpty($results); + + $results = $this->get_checker_results($this->htmlpass2); + $this->assertEmpty($results); + } +} diff --git a/admin/tool/brickfield/tests/manager_test.php b/admin/tool/brickfield/tests/manager_test.php new file mode 100644 index 0000000000000..9e01f9ddeb602 --- /dev/null +++ b/admin/tool/brickfield/tests/manager_test.php @@ -0,0 +1,41 @@ +. + +namespace tool_brickfield; + +/** + * Class tool_brickfield_manager_test + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, https://www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class manager_test extends \advanced_testcase { + + /** + * Tests for the function manager::get_all_areas() + */ + public function test_get_areas() { + $this->resetAfterTest(); + $areas = manager::get_all_areas(); + $areaclassnames = array_map('get_class', $areas); + + // Make sure the list of areas contains some known areas. + $this->assertContains(\tool_brickfield\local\areas\mod_assign\intro::class, $areaclassnames); + $this->assertContains(\tool_brickfield\local\areas\core_question\questiontext::class, $areaclassnames); + $this->assertContains(\tool_brickfield\local\areas\mod_choice\option::class, $areaclassnames); + } +} diff --git a/admin/tool/brickfield/tests/printable_test.php b/admin/tool/brickfield/tests/printable_test.php new file mode 100644 index 0000000000000..192020ecc0365 --- /dev/null +++ b/admin/tool/brickfield/tests/printable_test.php @@ -0,0 +1,106 @@ +. + +namespace tool_brickfield\local\tool; + +/** + * Unit tests for {@printable tool_brickfield\local\tool\printable\tool}. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @author Jay Churchward (jay.churchward@poetopensource.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class printable_test extends \advanced_testcase { + + /** + * Test tool name. + */ + public function test_toolname() { + $this->resetAfterTest(); + + $object = new printable(); + $output = $object->toolname(); + $this->assertEquals($output, 'Summary report'); + } + + /** + * Test tool short name. + */ + public function test_toolshortname() { + $this->resetAfterTest(); + + $object = new printable(); + $output = $object->toolshortname(); + $this->assertEquals($output, 'Summary report'); + } + + /** + * Test plugin name. + */ + public function test_pluginname() { + $this->resetAfterTest(); + + $object = new printable(); + $output = $object->pluginname(); + $this->assertEquals($output, 'printable'); + } + + /** + * Can access. + */ + public function can_access() { + $this->resetAfterTest(); + $category = $this->getDataGenerator()->create_category(); + + $filter = new filter(1, $category->id, 'tab', 3, 4); + $filter->courseids = []; + + $object = new printable(); + $output = $object->can_access($filter); + $this->assertFalse($output); + } + + /** + * Test get output. + */ + public function test_get_output() { + $this->resetAfterTest(); + $category = $this->getDataGenerator()->create_category(); + + $filter = new filter(1, $category->id, 'printable', 3, 4); + $filter->courseids = []; + + $filter->target = 'html'; + $object = new printable(); + $object->set_filter($filter); + $output = $object->get_output(); + $this->assertStringContainsString('

Course: PHPUnit test site

set_filter($filter); + $output = $object->get_output(); + $this->assertStringContainsString('

Course: PHPUnit test site

set_filter($filter); + $output = $object->get_output(); + $this->assertStringContainsString('', $output); + } +} diff --git a/admin/tool/brickfield/tests/registration_test.php b/admin/tool/brickfield/tests/registration_test.php new file mode 100644 index 0000000000000..6015eba03bf72 --- /dev/null +++ b/admin/tool/brickfield/tests/registration_test.php @@ -0,0 +1,187 @@ +. + +/** + * PHPUnit tool_brickfield tests + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @author Mike Churchward (mike@brickfieldlabs.ie) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +namespace tool_brickfield; + +/** + * Unit tests for {@registration tool_brickfield\registration.php}. + * @group tool_brickfield + */ +class registration_test extends \advanced_testcase { + public static function setUpBeforeClass(): void { + global $CFG; + + require_once($CFG->dirroot . '/admin/tool/brickfield/tests/generator/mock_registration.php'); + require_once($CFG->dirroot . '/admin/tool/brickfield/tests/generator/mock_brickfieldconnect.php'); + } + + /** + * Tests the state of the registration system when first installed. + * @throws \dml_exception + */ + public function test_initial_state() { + $this->resetAfterTest(); + $regobj = new mock_registration(); + + // Initial state of system. + $this->assertFalse($regobj->toolkit_is_active()); + $this->assertFalse($regobj->validation_pending()); + $this->assertFalse($regobj->validation_error()); + $this->assertEmpty($regobj->get_api_key()); + $this->assertEmpty($regobj->get_secret_key()); + } + + /** + * Test the various states for setting registration keys. + * @throws \dml_exception + */ + public function test_set_keys_for_registration() { + $this->resetAfterTest(); + $regobj = new mock_registration(); + + // State when invalid format keys are sent. + $this->assertFalse($regobj->set_keys_for_registration('123', 'abc')); + $this->assertTrue($regobj->is_not_entered()); + $this->assertFalse($regobj->validation_pending()); + $this->assertEmpty($regobj->get_api_key()); + $this->assertEmpty($regobj->get_secret_key()); + + // State when valid format keys are sent. + $this->assertTrue($regobj->set_keys_for_registration(mock_brickfieldconnect::VALIDAPIKEY, + mock_brickfieldconnect::VALIDSECRETKEY)); + $this->assertTrue($regobj->validation_pending()); + $this->assertEquals($regobj->get_api_key(), mock_brickfieldconnect::VALIDAPIKEY); + $this->assertEquals($regobj->get_secret_key(), mock_brickfieldconnect::VALIDSECRETKEY); + } + + /** + * Test the validation system through its several states. + * @throws \dml_exception + */ + public function test_validation() { + $this->resetAfterTest(); + $regobj = new mock_registration(); + + // Set invalid format keys and validate the system. + $this->assertFalse($regobj->set_keys_for_registration('123', 'abc')); + // Run validate function. State should end up as 'NOT_ENTERED'. + $this->assertFalse($regobj->validate()); + $this->assertTrue($regobj->is_not_entered()); + + // Set valid keys and validate the system. + $this->assertTrue($regobj->set_keys_for_registration(mock_brickfieldconnect::VALIDAPIKEY, + mock_brickfieldconnect::VALIDSECRETKEY)); + // Run validate function. State should end up as valid, 'VALIDATED'. + $this->assertTrue($regobj->validate()); + $this->assertTrue($regobj->toolkit_is_active()); + $this->assertFalse($regobj->validation_pending()); + $this->assertFalse($regobj->validation_error()); + + // Set invalid keys and validate the system. + $this->assertTrue($regobj->set_keys_for_registration('123456789012345678901234567890cd', + 'cd123456789012345678901234567890')); + // Run validate function. State should end up as valid, not validated, 'ERROR'. + $this->assertTrue($regobj->validate()); + $this->assertTrue($regobj->toolkit_is_active()); + $this->assertTrue($regobj->validation_pending()); + $this->assertTrue($regobj->validation_error()); + } + + /** + * Tests the system after validation grace periods expire. + * @throws \dml_exception + */ + public function test_validation_time_expiry() { + $this->resetAfterTest(); + $regobj = new mock_registration(); + + // Set valid keys and validate the system. + $this->assertTrue($regobj->set_keys_for_registration(mock_brickfieldconnect::VALIDAPIKEY, + mock_brickfieldconnect::VALIDSECRETKEY)); + // Run validate function. State should end up as valid, 'VALIDATED'. + $this->assertTrue($regobj->validate()); + $this->assertTrue($regobj->toolkit_is_active()); + + // Invalidate the validation time. + $regobj->invalidate_validation_time(); + // Run validate function. State should end up as valid, 'VALIDATED'. + $this->assertTrue($regobj->validate()); + $this->assertTrue($regobj->toolkit_is_active()); + + // Set invalid keys and validate the system. + $this->assertTrue($regobj->set_keys_for_registration('123456789012345678901234567890cd', + 'cd123456789012345678901234567890')); + // Run validate function. State should end up as valid, not validated, 'ERROR'. + $this->assertTrue($regobj->validate()); + $this->assertTrue($regobj->toolkit_is_active()); + $this->assertTrue($regobj->validation_pending()); + $this->assertTrue($regobj->validation_error()); + + // Invalidate the validation time. + $regobj->invalidate_validation_time(); + // Run validate function. State should end up as not valid. + $this->assertFalse($regobj->validate()); + $this->assertFalse($regobj->toolkit_is_active()); + } + + /** + * Tests the system after summary data time periods expire. + * @throws \dml_exception + */ + public function test_summary_time_expiry() { + $this->resetAfterTest(); + $regobj = new mock_registration(); + + // Set valid keys and validate the system. + $this->assertTrue($regobj->set_keys_for_registration(mock_brickfieldconnect::VALIDAPIKEY, + mock_brickfieldconnect::VALIDSECRETKEY)); + // Run validate function. State should end up as valid, 'VALIDATED'. + $this->assertTrue($regobj->validate()); + $this->assertTrue($regobj->toolkit_is_active()); + + // Invalidate the summary time. + $regobj->invalidate_summary_time(); + // Run validate function. State should end up as not valid. + $this->assertFalse($regobj->validate()); + $this->assertFalse($regobj->toolkit_is_active()); + + // Set invalid keys and validate the system. + $this->assertTrue($regobj->set_keys_for_registration('123456789012345678901234567890cd', + 'cd123456789012345678901234567890')); + // Run validate function. State should end up as invalid. + $this->assertFalse($regobj->validate()); + $this->assertFalse($regobj->toolkit_is_active()); + + // Set invalid keys and validate the system. + $this->assertTrue($regobj->set_keys_for_registration('123456789012345678901234567890cd', + 'cd123456789012345678901234567890')); + // Mark the summary data as sent, and revalidate the system. + $regobj->mark_summary_data_sent(); + // Run validate function. State should end up as valid, not validated, 'ERROR'. + $this->assertTrue($regobj->validate()); + $this->assertTrue($regobj->toolkit_is_active()); + $this->assertTrue($regobj->validation_pending()); + $this->assertTrue($regobj->validation_error()); + } +} diff --git a/admin/tool/brickfield/tests/scheduler_test.php b/admin/tool/brickfield/tests/scheduler_test.php new file mode 100644 index 0000000000000..07fc7d6dc2243 --- /dev/null +++ b/admin/tool/brickfield/tests/scheduler_test.php @@ -0,0 +1,305 @@ +. + +namespace tool_brickfield; + +/** + * Unit tests for {@scheduler tool_brickfield\scheduler.php}. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @author Jay Churchward (jay@brickfieldlabs.ie) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class scheduler_test extends \advanced_testcase { + + public function test_request_analysis() { + $this->resetAfterTest(); + + // I believe there is a bug where the code won't work with the default constructor values. + // Can't find data record in database table course. + // (SELECT id,category FROM {course} WHERE id = ?[array (0 => 0,)]) + // There is no course with an id of 0 so it throws an error, however it is never used like this in the current code. + + $object = new scheduler(1); + $output = $object->request_analysis(); + $this->assertTrue($output); + + $object = new scheduler(1, 1); + $output = $object->request_analysis(); + $this->assertTrue($output); + + $object = new scheduler(0, 2); + $output = $object->request_analysis(); + $this->assertTrue($output); + + } + + public function test_mark_analyzed() { + $this->resetAfterTest(); + $object = new scheduler(); + $output = $object->mark_analyzed(); + $this->assertTrue($output); + + $object = new scheduler(1, 1); + $output = $object->mark_analyzed(); + $this->assertTrue($output); + } + + public function test_create_schedule() { + global $DB; + + $this->resetAfterTest(); + $object = new scheduler(); + $output = $object->create_schedule(); + $record = $DB->get_record($object::DATA_TABLE, ['contextlevel' => 50]); + $this->assertTrue($output); + $this->assertEquals($record->instanceid, 0); + + $object = new scheduler(1, 1); + $output = $object->mark_analyzed(); + $record = $DB->get_record($object::DATA_TABLE, ['contextlevel' => 1]); + $this->assertTrue($output); + $this->assertEquals($record->instanceid, 1); + } + + public function test_delete_schedule() { + global $DB; + + // Call create_record() to insert a record into the table. + $this->resetAfterTest(); + $object = new scheduler(); + $object->create_schedule(); + $record = $DB->get_record($object::DATA_TABLE, ['contextlevel' => 50]); + + // Assert that the record is in the table. + $this->assertEquals($record->instanceid, 0); + + // Assert that the record is deleted after calling delete_schedule(). + $output = $object->delete_schedule(); + $record = $DB->get_record($object::DATA_TABLE, ['contextlevel' => 50]); + $this->assertTrue($output); + $this->assertFalse($record); + } + + public function test_is_in_schedule() { + $this->resetAfterTest(); + + // This should assert to false as no record has been inserted. + $object = new scheduler(); + $output = $object->is_in_schedule(); + $this->assertFalse($output); + + // This should assert to true because create_schedule inserts a record to the table. + $object->create_schedule(); + $output = $object->is_in_schedule(); + $this->assertTrue($output); + } + + public function test_is_scheduled() { + $this->resetAfterTest(); + + // This should assert to false as no record has been inserted. + $object = new scheduler(1, 1); + $output = $object->is_scheduled(); + $this->assertFalse($output); + + // This should assert to false because the record has been created but not requested. + $object->create_schedule(); + $output = $object->is_scheduled(); + $this->assertFalse($output); + + // This should assert to true because the record has been created and requested. + $object->create_schedule(); + $object->request_analysis(); + $output = $object->is_scheduled(); + $this->assertTrue($output); + } + + public function test_is_submitted() { + $this->resetAfterTest(); + + // This should assert to false as no record has been inserted. + $object = new scheduler(1, 1); + $output = $object->is_submitted(); + $this->assertFalse($output); + + // This should assert to false because the record has been created but not submitted. + $object->create_schedule(); + $output = $object->is_submitted(); + $this->assertFalse($output); + + // This should assert to true because the record has been created and submitted. + $object->create_schedule(); + $object->mark_analyzed(); + $output = $object->is_submitted(); + $this->assertTrue($output); + } + + public function test_is_analyzed() { + $this->resetAfterTest(); + + // This should assert to false as no record has been inserted. + $object = new scheduler(1, 1); + $output = $object->is_analyzed(); + $this->assertFalse($output); + + // This should assert to false because the record has been created but not submitted. + $object->create_schedule(); + $output = $object->is_analyzed(); + $this->assertFalse($output); + + // This should assert to true because the record has been created and submitted. + $object->create_schedule(); + $object->mark_analyzed(); + $output = $object->is_analyzed(); + $this->assertTrue($output); + } + + // Can't test because it's a protected function. + public function test_standard_search_params() { + } + + // Can't test because it's a protected function. + public function test_get_contextid() { + } + + public function test_get_datarecord() { + $this->resetAfterTest(); + + $object = new scheduler(); + $output = $object->get_datarecord(); + $this->assertEquals($output->contextlevel, 50); + $this->assertEquals($output->instanceid, 0); + $this->assertEquals($output->status, 0); + + $object = new scheduler(1, 1); + $output = $object->get_datarecord(2); + $this->assertEquals($output->contextlevel, 1); + $this->assertEquals($output->instanceid, 1); + $this->assertEquals($output->status, 2); + + $object = new scheduler(10, 143); + $output = $object->get_datarecord(5); + $this->assertEquals($output->contextlevel, 143); + $this->assertEquals($output->instanceid, 10); + $this->assertEquals($output->status, 5); + } + + // No return statement. + public function test_process_scheduled_requests() { + + } + + public function test_initialize_schedule() { + global $DB; + $this->resetAfterTest(); + + $output = scheduler::initialize_schedule(); + $record = $DB->get_record(scheduler::DATA_TABLE, ['contextlevel' => 50]); + $this->assertTrue($output); + $this->assertEquals($record->contextlevel, 50); + + $output = scheduler::initialize_schedule(20); + $record = $DB->get_record(scheduler::DATA_TABLE, ['contextlevel' => 20]); + $this->assertTrue($output); + $this->assertEquals($record->contextlevel, 20); + } + + public function test_request_course_analysis() { + $this->resetAfterTest(); + + $output = scheduler::request_course_analysis(1); + $this->assertTrue($output); + } + + public function test_create_course_schedule() { + global $DB; + $this->resetAfterTest(); + + $output = scheduler::create_course_schedule(1); + $record = $DB->get_record(scheduler::DATA_TABLE, ['contextlevel' => 50]); + $this->assertTrue($output); + $this->assertEquals($record->instanceid, 1); + + } + + public function test_delete_course_schedule() { + global $DB; + $this->resetAfterTest(); + + scheduler::create_course_schedule(1); + $record = $DB->get_record(scheduler::DATA_TABLE, ['contextlevel' => 50]); + $this->assertEquals($record->instanceid, 1); + + $output = scheduler::delete_course_schedule(1); + $record = $DB->get_record(scheduler::DATA_TABLE, ['contextlevel' => 50]); + $this->assertTrue($output); + $this->assertFalse($record); + } + + public function test_is_course_in_schedule() { + $this->resetAfterTest(); + + // This should assert to false as no record has been inserted. + $output = scheduler::is_course_in_schedule(1); + $this->assertFalse($output); + + // This should assert to true because create_schedule inserts a record to the table. + scheduler::create_course_schedule(1); + $output = scheduler::is_course_in_schedule(1); + $this->assertTrue($output); + } + + public function test_is_course_scheduled() { + $this->resetAfterTest(); + + // This should assert to false as no record has been inserted. + $output = scheduler::is_course_scheduled(1); + $this->assertFalse($output); + + // This should assert to false because the record has been created but not requested. + scheduler::create_course_schedule(1); + $output = scheduler::is_course_scheduled(1); + $this->assertFalse($output); + + // This should assert to true because the record has been created and requested. + scheduler::create_course_schedule(1); + scheduler::request_course_analysis(1); + $output = scheduler::is_course_scheduled(1); + $this->assertTrue($output); + } + + public function test_is_course_analyzed() { + $this->resetAfterTest(); + $object = new scheduler(10, 1); + + // This should assert to false as no record has been inserted. + $output = scheduler::is_course_analyzed(10); + $this->assertFalse($output); + + // This should assert to false because the record has been created but not submitted. + scheduler::create_course_schedule(10); + $output = scheduler::is_course_analyzed(10); + $this->assertFalse($output); + + // This should assert to true because the record has been created and submitted. + $object->create_schedule(); + $object->mark_analyzed(); + $output = $object->is_analyzed(); + $this->assertTrue($output); + } +} diff --git a/admin/tool/brickfield/tests/tool_test.php b/admin/tool/brickfield/tests/tool_test.php new file mode 100644 index 0000000000000..1b23a062e709f --- /dev/null +++ b/admin/tool/brickfield/tests/tool_test.php @@ -0,0 +1,168 @@ +. + +namespace tool_brickfield; + +use tool_brickfield\local\tool\filter; +use tool_brickfield\local\tool\tool; + +/** + * Unit tests for {@tool tool_brickfield\local\tool\tool}. + * + * @package tool_brickfield + * @copyright 2020 onward: Brickfield Education Labs, www.brickfield.ie + * @author Jay Churchward (jay.churchward@poetopensource.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class tool_test extends \advanced_testcase { + + /** @var string base 64 image */ + protected $base64img = <<'; +EOF; + + + public function test_build_all_accessibilitytools() { + $tools = tool::build_all_accessibilitytools(); + + $this->assertEquals($tools['errors']::toolshortname(), 'Error list'); + $this->assertEquals($tools['activityresults']::toolshortname(), 'Activity breakdown'); + $this->assertEquals($tools['checktyperesults']::toolshortname(), 'Content types'); + $this->assertEquals($tools['printable']::toolshortname(), 'Summary report'); + $this->assertEquals($tools['advanced']::toolshortname(), 'Advanced'); + } + + public function test_data_is_valid() { + $object = $this->getMockForAbstractClass(tool::class); + $object->set_filter(new filter()); + $output = $object->data_is_valid(); + $this->assertFalse($output); + } + + public function test_can_access() { + $this->resetAfterTest(); + $category = $this->getDataGenerator()->create_category(); + $filter = new filter(1, $category->id, 'tab', 3, 4); + + $tool = $this->getMockForAbstractClass(tool::class); + + $output = $tool->can_access($filter); + $this->assertFalse($output); + } + + public function test_get_error_message() { + $tool = $this->getMockForAbstractClass(tool::class); + + $output = $tool->get_error_message(); + $this->assertEquals($output, ''); + } + + public function test_get_module_label() { + $output = tool::get_module_label('core_course'); + $this->assertEquals($output, 'Course'); + + $output = tool::get_module_label('mod_book'); + $this->assertEquals($output, 'Book'); + } + + public function test_toplevel_arguments() { + $this->resetAfterTest(); + $category = $this->getDataGenerator()->create_category(); + $filter = new filter(1, $category->id, 'tab', 3, 4); + + $output = tool::toplevel_arguments(); + $this->assertEmpty($output); + + $output = tool::toplevel_arguments($filter); + $this->assertEquals($output['courseid'], 1); + $this->assertEquals($output['categoryid'], $category->id); + } + + /** + * Base64 image provider. + * @return array + */ + public function base64_img_provider(): array { + $img = ''; + return [ + 'Image tag alone (base64)' => [ + $this->base64img, + true, + ], + 'Image tag alone (link)' => [ + $img, + false, + ], + 'Image tag in string (base64)' => [ + "This is my image {$this->base64img}.", + true, + ], + 'Image tag in string (link)' => [ + "This is my image {$img}.", + false, + ], + 'Image tag with string base64 in alt' => [ + "base64", + false, + ], + 'base64 string in text' => [ + "An example base 64 format string is 'data:image/gif;base64'./>", + false, + ], + ]; + } + + /** + * Test base 64 image provider. + * @dataProvider base64_img_provider + * @param string $content + * @param bool $expectation + */ + public function test_base64_img_detected(string $content, bool $expectation) { + $this->assertEquals( + $expectation, + tool::base64_img_detected($content) + ); + } + + public function test_truncate_base64() { + $truncated = tool::truncate_base64($this->base64img); + $this->assertStringContainsString('. + +/** + * Plugin version and other meta-data are defined here. + * + * @package tool_brickfield + * @copyright 2020 Brickfield Education Labs, https://www.brickfield.ie - Author: Karen Holland + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$plugin->component = 'tool_brickfield'; +$plugin->release = '1.2 (Build - 2021031500)'; +$plugin->version = 2020101917; +$plugin->requires = 2018051700; // Moodle 3.5 and up. +$plugin->maturity = MATURITY_STABLE; diff --git a/blocks/accessreview/amd/build/module.min.js b/blocks/accessreview/amd/build/module.min.js new file mode 100755 index 0000000000000..8eca927ea8111 --- /dev/null +++ b/blocks/accessreview/amd/build/module.min.js @@ -0,0 +1,2 @@ +function _typeof(a){"@babel/helpers - typeof";if("function"==typeof Symbol&&"symbol"==typeof Symbol.iterator){_typeof=function(a){return typeof a}}else{_typeof=function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a}}return _typeof(a)}define ("block_accessreview/module",["exports","core/ajax","core/templates","core/notification"],function(a,b,c,d){"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.init=void 0;c=f(c);function e(){if("function"!=typeof WeakMap)return null;var a=new WeakMap;e=function(){return a};return a}function f(a){if(a&&a.__esModule){return a}if(null===a||"object"!==_typeof(a)&&"function"!=typeof a){return{default:a}}var b=e();if(b&&b.has(a)){return b.get(a)}var c={},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var f in a){if(Object.prototype.hasOwnProperty.call(a,f)){var g=d?Object.getOwnPropertyDescriptor(a,f):null;if(g&&(g.get||g.set)){Object.defineProperty(c,f,g)}else{c[f]=a[f]}}}c.default=a;if(b){b.set(a,c)}return c}function g(a,b){return m(a)||l(a,b)||j(a,b)||h()}function h(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function j(a,b){if(!a)return;if("string"==typeof a)return k(a,b);var c=Object.prototype.toString.call(a).slice(8,-1);if("Object"===c&&a.constructor)c=a.constructor.name;if("Map"===c||"Set"===c)return Array.from(c);if("Arguments"===c||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c))return k(a,b)}function k(a,b){if(null==b||b>a.length)b=a.length;for(var c=0,d=Array(b);cc.maxViews){c.maxViews=a.numerrors}c.totalUsers+=a.numchecks});c.viewDelta=c.maxViews-c.minViews+1;return c},t=function(a,b){document.addEventListener("click",function(c){if(c.target.closest("#toggle-accessmap")){c.preventDefault();r(a,b)}})},u=function(a){return{methodname:"core_user_update_user_preferences",args:{preferences:[{type:"block_accessreviewtogglestate",value:a}]}}},v=function(a){return(0,b.call)([u(a)])},w=function(a){var c=1.\n\n/**\n *\n * @package block_accessreview\n * @author Max Larkin \n * @copyright 2020 Brickfield Education Labs \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport {call as fetchMany} from 'core/ajax';\nimport * as Templates from 'core/templates';\nimport {exception as displayError} from 'core/notification';\n\n/**\n * The number of colours used to represent the heatmap. (Indexed on 0.)\n * @type {number}\n */\nconst numColours = 2;\n\n/**\n * The toggle state of the heatmap.\n * @type {boolean}\n */\nlet toggleState = true;\n\n/**\n * Renders the HTML template onto a particular HTML element.\n * @param {HTMLElement} element The element to attach the HTML to.\n * @param {number} errorCount The number of errors on this module/section.\n * @param {number} checkCount The number of checks triggered on this module/section.\n * @param {String} displayFormat\n * @param {Number} minViews\n * @param {Number} viewDelta\n * @returns {Promise}\n */\nconst renderTemplate = (element, errorCount, checkCount, displayFormat, minViews, viewDelta) => {\n // Calculate a weight?\n const weight = parseInt((errorCount - minViews) / viewDelta * numColours);\n\n const context = {\n resultPassed: !errorCount,\n classList: '',\n passRate: {\n errorCount,\n checkCount,\n failureRate: Math.round(errorCount / checkCount * 100),\n },\n };\n\n if (!element) {\n return Promise.resolve();\n }\n\n const elementClassList = ['block_accessreview'];\n if (context.resultPassed) {\n elementClassList.push('block_accessreview_success');\n } else if (weight) {\n elementClassList.push('block_accessreview_danger');\n } else {\n elementClassList.push('block_accessreview_warning');\n }\n\n const showIcons = (displayFormat == 'showicons') || (displayFormat == 'showboth');\n const showBackground = (displayFormat == 'showbackground') || (displayFormat == 'showboth');\n\n if (showBackground && !showIcons) {\n // Only the background is displayed.\n // No need to display the template.\n // Note: The case where both the background and icons are shown is handled later to avoid jankiness.\n element.classList.add(...elementClassList, 'alert');\n\n return Promise.resolve();\n }\n\n if (showIcons && !showBackground) {\n context.classList = elementClassList.join(' ');\n }\n\n // The icons are displayed either with, or without, the background.\n return Templates.renderForPromise('block_accessreview/status', context)\n .then(({html, js}) => {\n Templates.appendNodeContents(element, html, js);\n\n if (showBackground) {\n element.classList.add(...elementClassList, 'alert');\n }\n\n return;\n })\n .catch();\n};\n\n/**\n * Applies the template to all sections and modules on the course page.\n *\n * @param {Number} courseId\n * @param {String} displayFormat\n * @param {Boolean} updatePreference\n * @returns {Promise}\n */\nconst showAccessMap = (courseId, displayFormat, updatePreference = false) => {\n // Get error data.\n return Promise.all(fetchReviewData(courseId, updatePreference))\n .then(([sectionData, moduleData]) => {\n // Get total data.\n const {minViews, viewDelta} = getErrorTotals(sectionData, moduleData);\n\n sectionData.forEach(section => {\n const element = document.querySelector(`#section-${section.section} .summary`);\n if (!element) {\n return;\n }\n\n renderTemplate(element, section.numerrors, section.numchecks, displayFormat, minViews, viewDelta);\n });\n\n moduleData.forEach(module => {\n const element = document.getElementById(`module-${module.cmid}`);\n if (!element) {\n return;\n }\n\n renderTemplate(element, module.numerrors, module.numchecks, displayFormat, minViews, viewDelta);\n });\n\n return {\n sectionData,\n moduleData,\n };\n })\n .catch(displayError);\n};\n\n\n/**\n * Hides or removes the templates from the HTML of the current page.\n *\n * @param {Boolean} updatePreference\n */\nconst hideAccessMap = (updatePreference = false) => {\n // Removes the added elements.\n document.querySelectorAll('.block_accessreview_view').forEach(node => node.remove());\n\n const classList = [\n 'block_accessreview',\n 'block_accessreview_success',\n 'block_accessreview_warning',\n 'block_accessreview_danger',\n 'block_accessreview_view',\n ];\n\n // Removes the added classes.\n document.querySelectorAll('.block_accessreview').forEach(node => node.classList.remove(...classList));\n\n if (updatePreference) {\n setToggleStatePreference(false);\n }\n};\n\n\n/**\n * Toggles the heatmap on/off.\n *\n * @param {Number} courseId\n * @param {String} displayFormat\n */\nconst toggleAccessMap = (courseId, displayFormat) => {\n toggleState = !toggleState;\n if (!toggleState) {\n hideAccessMap(true);\n } else {\n showAccessMap(courseId, displayFormat, true);\n }\n};\n\n/**\n * Parses information on the errors, generating the min, max and totals.\n *\n * @param {Object[]} sectionData The error data for course sections.\n * @param {Object[]} moduleData The error data for course modules.\n * @returns {Object} An object representing the extra error information.\n*/\nconst getErrorTotals = (sectionData, moduleData) => {\n const totals = {\n totalErrors: 0,\n totalUsers: 0,\n minViews: 0,\n maxViews: 0,\n viewDelta: 0,\n };\n\n [].concat(sectionData, moduleData).forEach(item => {\n totals.totalErrors += item.numerrors;\n if (item.numerrors < totals.minViews) {\n totals.minViews = item.numerrors;\n }\n\n if (item.numerrors > totals.maxViews) {\n totals.maxViews = item.numerrors;\n }\n totals.totalUsers += item.numchecks;\n });\n\n totals.viewDelta = totals.maxViews - totals.minViews + 1;\n\n return totals;\n};\n\nconst registerEventListeners = (courseId, displayFormat) => {\n document.addEventListener('click', e => {\n if (e.target.closest('#toggle-accessmap')) {\n e.preventDefault();\n toggleAccessMap(courseId, displayFormat);\n }\n });\n};\n\n/**\n * Set the user preference for the toggle value.\n *\n * @param {Boolean} toggleState\n * @returns {Promise}\n */\nconst getTogglePreferenceParams = toggleState => {\n return {\n methodname: 'core_user_update_user_preferences',\n args: {\n preferences: [{\n type: 'block_accessreviewtogglestate',\n value: toggleState,\n }],\n }\n };\n};\n\nconst setToggleStatePreference = toggleState => fetchMany([getTogglePreferenceParams(toggleState)]);\n\n/**\n * Fetch the review data.\n *\n * @param {Number} courseid\n * @param {Boolean} updatePreference\n * @returns {Promise[]}\n */\nconst fetchReviewData = (courseid, updatePreference = false) => {\n const calls = [\n {\n methodname: 'block_accessreview_get_section_data',\n args: {courseid}\n },\n {\n methodname: 'block_accessreview_get_module_data',\n args: {courseid}\n },\n ];\n\n if (updatePreference) {\n calls.push(getTogglePreferenceParams(true));\n }\n\n return fetchMany(calls);\n};\n\n/**\n * Setting up the access review module.\n * @param {number} toggled A number represnting the state of the review toggle.\n * @param {string} displayFormat A string representing the display format for icons.\n * @param {number} courseId The course ID.\n * @param {number} userId The id of the currently logged-in user.\n */\nexport const init = (toggled, displayFormat, courseId) => {\n // Settings consts.\n toggleState = toggled == 1;\n\n if (toggleState) {\n showAccessMap(courseId, displayFormat);\n }\n\n registerEventListeners(courseId, displayFormat);\n};\n"],"file":"module.min.js"} \ No newline at end of file diff --git a/blocks/accessreview/amd/src/module.js b/blocks/accessreview/amd/src/module.js new file mode 100755 index 0000000000000..bbc45ee43eb8d --- /dev/null +++ b/blocks/accessreview/amd/src/module.js @@ -0,0 +1,294 @@ +// 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 . + +/** + * + * @package block_accessreview + * @author Max Larkin + * @copyright 2020 Brickfield Education Labs + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +import {call as fetchMany} from 'core/ajax'; +import * as Templates from 'core/templates'; +import {exception as displayError} from 'core/notification'; + +/** + * The number of colours used to represent the heatmap. (Indexed on 0.) + * @type {number} + */ +const numColours = 2; + +/** + * The toggle state of the heatmap. + * @type {boolean} + */ +let toggleState = true; + +/** + * Renders the HTML template onto a particular HTML element. + * @param {HTMLElement} element The element to attach the HTML to. + * @param {number} errorCount The number of errors on this module/section. + * @param {number} checkCount The number of checks triggered on this module/section. + * @param {String} displayFormat + * @param {Number} minViews + * @param {Number} viewDelta + * @returns {Promise} + */ +const renderTemplate = (element, errorCount, checkCount, displayFormat, minViews, viewDelta) => { + // Calculate a weight? + const weight = parseInt((errorCount - minViews) / viewDelta * numColours); + + const context = { + resultPassed: !errorCount, + classList: '', + passRate: { + errorCount, + checkCount, + failureRate: Math.round(errorCount / checkCount * 100), + }, + }; + + if (!element) { + return Promise.resolve(); + } + + const elementClassList = ['block_accessreview']; + if (context.resultPassed) { + elementClassList.push('block_accessreview_success'); + } else if (weight) { + elementClassList.push('block_accessreview_danger'); + } else { + elementClassList.push('block_accessreview_warning'); + } + + const showIcons = (displayFormat == 'showicons') || (displayFormat == 'showboth'); + const showBackground = (displayFormat == 'showbackground') || (displayFormat == 'showboth'); + + if (showBackground && !showIcons) { + // Only the background is displayed. + // No need to display the template. + // Note: The case where both the background and icons are shown is handled later to avoid jankiness. + element.classList.add(...elementClassList, 'alert'); + + return Promise.resolve(); + } + + if (showIcons && !showBackground) { + context.classList = elementClassList.join(' '); + } + + // The icons are displayed either with, or without, the background. + return Templates.renderForPromise('block_accessreview/status', context) + .then(({html, js}) => { + Templates.appendNodeContents(element, html, js); + + if (showBackground) { + element.classList.add(...elementClassList, 'alert'); + } + + return; + }) + .catch(); +}; + +/** + * Applies the template to all sections and modules on the course page. + * + * @param {Number} courseId + * @param {String} displayFormat + * @param {Boolean} updatePreference + * @returns {Promise} + */ +const showAccessMap = (courseId, displayFormat, updatePreference = false) => { + // Get error data. + return Promise.all(fetchReviewData(courseId, updatePreference)) + .then(([sectionData, moduleData]) => { + // Get total data. + const {minViews, viewDelta} = getErrorTotals(sectionData, moduleData); + + sectionData.forEach(section => { + const element = document.querySelector(`#section-${section.section} .summary`); + if (!element) { + return; + } + + renderTemplate(element, section.numerrors, section.numchecks, displayFormat, minViews, viewDelta); + }); + + moduleData.forEach(module => { + const element = document.getElementById(`module-${module.cmid}`); + if (!element) { + return; + } + + renderTemplate(element, module.numerrors, module.numchecks, displayFormat, minViews, viewDelta); + }); + + return { + sectionData, + moduleData, + }; + }) + .catch(displayError); +}; + + +/** + * Hides or removes the templates from the HTML of the current page. + * + * @param {Boolean} updatePreference + */ +const hideAccessMap = (updatePreference = false) => { + // Removes the added elements. + document.querySelectorAll('.block_accessreview_view').forEach(node => node.remove()); + + const classList = [ + 'block_accessreview', + 'block_accessreview_success', + 'block_accessreview_warning', + 'block_accessreview_danger', + 'block_accessreview_view', + ]; + + // Removes the added classes. + document.querySelectorAll('.block_accessreview').forEach(node => node.classList.remove(...classList)); + + if (updatePreference) { + setToggleStatePreference(false); + } +}; + + +/** + * Toggles the heatmap on/off. + * + * @param {Number} courseId + * @param {String} displayFormat + */ +const toggleAccessMap = (courseId, displayFormat) => { + toggleState = !toggleState; + if (!toggleState) { + hideAccessMap(true); + } else { + showAccessMap(courseId, displayFormat, true); + } +}; + +/** + * Parses information on the errors, generating the min, max and totals. + * + * @param {Object[]} sectionData The error data for course sections. + * @param {Object[]} moduleData The error data for course modules. + * @returns {Object} An object representing the extra error information. +*/ +const getErrorTotals = (sectionData, moduleData) => { + const totals = { + totalErrors: 0, + totalUsers: 0, + minViews: 0, + maxViews: 0, + viewDelta: 0, + }; + + [].concat(sectionData, moduleData).forEach(item => { + totals.totalErrors += item.numerrors; + if (item.numerrors < totals.minViews) { + totals.minViews = item.numerrors; + } + + if (item.numerrors > totals.maxViews) { + totals.maxViews = item.numerrors; + } + totals.totalUsers += item.numchecks; + }); + + totals.viewDelta = totals.maxViews - totals.minViews + 1; + + return totals; +}; + +const registerEventListeners = (courseId, displayFormat) => { + document.addEventListener('click', e => { + if (e.target.closest('#toggle-accessmap')) { + e.preventDefault(); + toggleAccessMap(courseId, displayFormat); + } + }); +}; + +/** + * Set the user preference for the toggle value. + * + * @param {Boolean} toggleState + * @returns {Promise} + */ +const getTogglePreferenceParams = toggleState => { + return { + methodname: 'core_user_update_user_preferences', + args: { + preferences: [{ + type: 'block_accessreviewtogglestate', + value: toggleState, + }], + } + }; +}; + +const setToggleStatePreference = toggleState => fetchMany([getTogglePreferenceParams(toggleState)]); + +/** + * Fetch the review data. + * + * @param {Number} courseid + * @param {Boolean} updatePreference + * @returns {Promise[]} + */ +const fetchReviewData = (courseid, updatePreference = false) => { + const calls = [ + { + methodname: 'block_accessreview_get_section_data', + args: {courseid} + }, + { + methodname: 'block_accessreview_get_module_data', + args: {courseid} + }, + ]; + + if (updatePreference) { + calls.push(getTogglePreferenceParams(true)); + } + + return fetchMany(calls); +}; + +/** + * Setting up the access review module. + * @param {number} toggled A number represnting the state of the review toggle. + * @param {string} displayFormat A string representing the display format for icons. + * @param {number} courseId The course ID. + * @param {number} userId The id of the currently logged-in user. + */ +export const init = (toggled, displayFormat, courseId) => { + // Settings consts. + toggleState = toggled == 1; + + if (toggleState) { + showAccessMap(courseId, displayFormat); + } + + registerEventListeners(courseId, displayFormat); +}; diff --git a/blocks/accessreview/block_accessreview.php b/blocks/accessreview/block_accessreview.php new file mode 100755 index 0000000000000..9bd366871c465 --- /dev/null +++ b/blocks/accessreview/block_accessreview.php @@ -0,0 +1,309 @@ +. + +use tool_brickfield\accessibility; +use tool_brickfield\analysis; +use tool_brickfield\area_base; +use tool_brickfield\local\tool\filter; +use tool_brickfield\manager; +use tool_brickfield\registration; +use tool_brickfield\scheduler; +use tool_brickfield\sitedata; + +/** + * Definition of the accessreview block. + * + * @package block_accessreview + * @copyright 2019 Karen Holland LTS.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class block_accessreview extends block_base { + /** + * Sets the block title. + */ + public function init(): void { + $this->title = get_string('errorssummary', 'block_accessreview'); + } + + /** + * Defines where the block can be added. + * + * @return array + */ + public function applicable_formats(): array { + // If Brickfield accessibility toolkit has been disabled, do nothing. + if (accessibility::is_accessibility_enabled()) { + return [ + 'course-view' => true, + 'site' => true, + 'mod' => false, + 'my' => false, + ]; + } else { + return []; + } + } + + /** + * Controls global configurability of block. + * + * @return bool + */ + public function has_config(): bool { + return true; + } + + /** + * Controls whether multiple block instances are allowed. + * + * @return bool + */ + public function instance_allow_multiple(): bool { + return false; + } + + /** + * Creates the block's main content + * + * @return string|stdClass + */ + public function get_content() { + global $COURSE, $OUTPUT; + + // If Brickfield accessibility toolkit has been disabled, do nothing. + if (!accessibility::is_accessibility_enabled()) { + return ''; + } + + if (isset($this->content)) { + return $this->content; + } + + $this->content = new stdClass; + $this->content->text = ''; + + // Check to see user can view/use the accessmap. + $context = context_course::instance($COURSE->id); + if (!isloggedin() || isguestuser() || !has_capability('block/accessreview:view', $context)) { + return $this->content; + } + + // Check for valid registration. + if (!(new registration())->toolkit_is_active()) { + $this->content->text = manager::registration_message(); + } else if (scheduler::is_course_analyzed($COURSE->id)) { + // Build error data table. + $table = new html_table(); + $table->head = [ + get_string('checktypes', 'block_accessreview'), get_string('errors', 'block_accessreview') + ]; + $table->align = ['left', 'center']; + $tabledata = $this->get_table_data($COURSE->id); + // Handling no data. + if ($tabledata === null) { + $this->content->text = get_string('nodata', 'block_accessreview'); + return $this->content; + } + $table->data = $tabledata; + $table->attributes['class'] = 'generaltable table-sm block_accessreview_table'; + $this->content->text .= html_writer::table($table, true); + + // Check for compatible course formats for highlighting. + $showhighlighting = false; + switch ($COURSE->format) { + case accessibility::TOOL_BRICKFIELD_FORMAT_TOPIC: + case accessibility::TOOL_BRICKFIELD_FORMAT_WEEKLY: + $showhighlighting = true; + break; + } + + // Toggle overlay link. + $toggle = ($showhighlighting) ? $this->get_toggle_link() : ''; + // Report download link. + $download = $this->get_download_link($context); + // Report view link. + $view = $this->get_report_link($context); + + $this->content->text .= html_writer::tag('div', $toggle . $view . $download, [ + 'class' => 'block_accessreview_links' + ] + ); + + if ($showhighlighting) { + // Setting up AMD module. + $whattoshow = get_config('block_accessreview', 'whattoshow'); + $toggled = get_user_preferences('block_accessreviewtogglestate', true); + $arguments = [$toggled, $whattoshow, $COURSE->id]; + $this->page->requires->js_call_amd('block_accessreview/module', 'init', $arguments); + } + } else if (scheduler::is_course_in_schedule($COURSE->id)) { + // Display a message that the course is awaiting analysis. + $this->content->text = get_string('schedule:scheduled', manager::PLUGINNAME); + } else if (!analysis::is_enabled()) { + $this->content->text = get_string('analysistypedisabled', manager::PLUGINNAME); + } else { + // Display a button to request analysis. + $this->content->text = get_string('schedule:blocknotscheduled', manager::PLUGINNAME, manager::get_helpurl()); + + $button = new single_button( + new moodle_url(accessibility::get_plugin_url(), ['action' => 'requestanalysis', 'courseid' => $COURSE->id]), + get_string('schedule:requestanalysis', manager::PLUGINNAME), 'post', true, + ['class' => 'block_accessreview_analysisbutton']); + $this->content->text .= html_writer::tag('div', $OUTPUT->render($button), + ['class' => 'block_accessreview_analysisbutton']); + } + + return $this->content; + } + + /** + * Fetches and groups the relevent error data for the table to display. + * @param int $courseid The ID of the course. + * @return array The data required by the table. + * @throws coding_exception + * @throws moodle_exception + */ + protected function get_table_data($courseid): array { + global $OUTPUT; + $datafilters = new filter($courseid, 0); + $errordisplay = get_config('block_accessreview', 'errordisplay'); + $summarydata = (new sitedata())->get_checkgroup_data($datafilters); + $data = []; + $count = 0; + for ($i = 1; $count < $summarydata[0]->groupcount; $i++) { + if (isset($summarydata[0]->{'componentlabel' . $i})) { + $data[$i] = $summarydata[0]->{'errorsvalue' . $i}; + $count++; + } + } + $files = [ + 'form' => '', + 'image' => '231/', + 'layout' => '234/', + 'link' => '237/', + 'media' => '240/', + 'table' => '243/', + 'text' => '246/', + ]; + // Populating table data. + $tabledata = []; + foreach ($data as $key => $total) { + // If the total is empty it means there is no results yet in the table. + if ($total === null) { + continue; + } + $type = area_base::checkgroup_name($key); + // Error display data. + $display = $total; + // Icons. + $typeicon = $OUTPUT->pix_icon('f/' . $type, '', 'block_accessreview'); + if ($errordisplay == 'showicon') { + $thistype = $total == 0 ? 'smile' : 'frown'; + $display = $OUTPUT->pix_icon($thistype, + get_string($thistype, 'block_accessreview'), 'block_accessreview' + ); + } else if ($errordisplay == 'showpercent') { + $display = round(($total), 1) . '%'; + } + $tabledata[] = [$typeicon . get_string('checktype:' . $type, manager::PLUGINNAME), $display]; + } + return $tabledata; + } + + /** + * Get the link to toggle the heatmap. + * + * @return string + * @throws coding_exception + */ + protected function get_toggle_link(): string { + global $OUTPUT; + + // Toggle overlay link. + return html_writer::link( + '#', + $OUTPUT->pix_icon('t/hide', get_string('togglealt', 'block_accessreview')), + [ + 'title' => get_string('togglealt', 'block_accessreview'), + 'style' => 'cursor: pointer;', + 'id' => 'toggle-accessmap', + 'class' => 'block_accessreview_link', + ] + ); + } + + /** + * Get the link to download a report for the specified context. + * + * @param context $context + * @return string + * @throws coding_exception + * @throws moodle_exception + */ + protected function get_download_link(context $context): string { + global $OUTPUT, $COURSE; + + if (has_capability(accessibility::get_capability_name('viewcoursetools'), $context)) { + return html_writer::link( + new moodle_url(accessibility::get_plugin_url(), + [ + 'courseid' => $COURSE->id, + 'tab' => 'printable', + 'target' => 'pdf', + ] + ), + $OUTPUT->pix_icon('a/download_all', get_string('downloadreportalt', 'block_accessreview')), + [ + 'title' => get_string('downloadreportalt', 'block_accessreview'), + 'class' => 'block_accessreview_link download-accessmap', + ] + ); + } else { + return ''; + } + } + + /** + * Get the report link for the specified context. + * + * @param context $context + * @return string + * @throws coding_exception + * @throws dml_exception + * @throws moodle_exception + */ + protected function get_report_link(context $context): string { + global $OUTPUT, $COURSE; + + if (has_capability(accessibility::get_capability_name('viewcoursetools'), $context)) { + return html_writer::link( + new moodle_url(accessibility::get_plugin_url(), + [ + 'courseid' => $COURSE->id, + 'tab' => get_config('block_accessreview', 'toolpage'), + ] + ), + $OUTPUT->pix_icon('f/find', get_string('viewreportalt', 'block_accessreview'), 'block_accessreview'), + [ + 'title' => get_string('viewreportalt', 'block_accessreview'), + 'class' => 'block_accessreview_link report-accessmap', + ] + ); + } else { + return ''; + } + } +} diff --git a/blocks/accessreview/classes/external/get_module_data.php b/blocks/accessreview/classes/external/get_module_data.php new file mode 100644 index 0000000000000..d6933f5d28b77 --- /dev/null +++ b/blocks/accessreview/classes/external/get_module_data.php @@ -0,0 +1,95 @@ +. + +/** + * Web service to fetch module data. + * + * @package block_accessreview + * @copyright 2020 onward Brickfield Education Labs Ltd, https://www.brickfield.ie + * @author 2020 Max Larkin + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace block_accessreview\external; + +use external_api; +use external_function_parameters; +use external_multiple_structure; +use external_single_structure; +use external_value; +use tool_brickfield\manager; + +defined('MOODLE_INTERNAL') || die(); +require_once($CFG->libdir . '/externallib.php'); + +/** + * Web service to fetch module data. + * + * @package block_accessreview + * @copyright 2020 onward Brickfield Education Labs Ltd, https://www.brickfield.ie + * @author 2020 Max Larkin + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class get_module_data extends external_api { + /** + * Describes the parameters. + * + * @return external_function_parameters + */ + public static function execute_parameters() { + return new external_function_parameters([ + 'courseid' => new external_value(PARAM_INT, 'The course id to obtain results for.', VALUE_REQUIRED), + ]); + } + + /** + * Execute the service. + * + * @param int $courseid + * @return array + */ + public static function execute(int $courseid) { + [ + 'courseid' => $courseid, + ] = self::validate_parameters(self::execute_parameters(), [ + 'courseid' => $courseid, + ]); + + $context = \context_course::instance($courseid); + self::validate_context($context); + + require_capability('block/accessreview:view', $context); + + return array_values(manager::get_cm_summary_for_course($courseid)); + } + + /** + * Describes the return structure of the service.. + * + * @return external_multiple_structure + */ + public static function execute_returns() { + return new external_multiple_structure( + new external_single_structure( + [ + 'cmid' => new external_value(PARAM_INT, 'ID'), + 'numerrors' => new external_value(PARAM_INT, 'Number of errors.'), + 'numchecks' => new external_value(PARAM_INT, 'Number of checks.'), + ] + ) + ); + } +} diff --git a/blocks/accessreview/classes/external/get_section_data.php b/blocks/accessreview/classes/external/get_section_data.php new file mode 100644 index 0000000000000..29d9836be9c52 --- /dev/null +++ b/blocks/accessreview/classes/external/get_section_data.php @@ -0,0 +1,94 @@ +. + +/** + * Web service to fetch section data. + * + * @package block_accessreview + * @copyright 2020 onward Brickfield Education Labs Ltd, https://www.brickfield.ie + * @author 2020 Max Larkin + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +namespace block_accessreview\external; + +use external_api; +use external_function_parameters; +use external_multiple_structure; +use external_single_structure; +use external_value; +use tool_brickfield\manager; + +defined('MOODLE_INTERNAL') || die(); +require_once($CFG->libdir . '/externallib.php'); + +/** + * Web service to fetch section data. + * + * @package block_accessreview + * @copyright 2020 onward Brickfield Education Labs Ltd, https://www.brickfield.ie + * @author 2020 Max Larkin + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class get_section_data extends external_api { + /** + * Describes the parameters. + * + * @return external_function_parameters + */ + public static function execute_parameters() { + return new external_function_parameters([ + 'courseid' => new external_value(PARAM_INT, 'The course id to obtain results for.', VALUE_REQUIRED), + ]); + } + + /** + * Execute the service. + * + * @param int $courseid + * @return array + */ + public static function execute($courseid) { + [ + 'courseid' => $courseid, + ] = self::validate_parameters(self::execute_parameters(), [ + 'courseid' => $courseid, + ]); + + $context = \context_course::instance($courseid); + self::validate_context($context); + + require_capability('block/accessreview:view', $context); + + return array_values(manager::get_section_summary_for_course($courseid)); + } + + /** + * Describes the return structure of the service.. + * + * @return external_multiple_structure + */ + public static function execute_returns() { + return new external_multiple_structure( + new external_single_structure( + [ + 'section' => new external_value(PARAM_INT, 'ID'), + 'numerrors' => new external_value(PARAM_INT, 'Number of errors.'), + 'numchecks' => new external_value(PARAM_INT, 'Number of checks.'), + ] + ) + ); + } +} diff --git a/blocks/accessreview/classes/privacy/provider.php b/blocks/accessreview/classes/privacy/provider.php new file mode 100644 index 0000000000000..7ccfd5ae3bb44 --- /dev/null +++ b/blocks/accessreview/classes/privacy/provider.php @@ -0,0 +1,78 @@ +. + +/** + * Privacy Subsystem implementation for block_accessreview. + * + * @package block_accessreview + * @copyright 2020 Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace block_accessreview\privacy; + +use \core_privacy\local\metadata\collection; + +defined('MOODLE_INTERNAL') || die(); + +/** + * The accessreview block stores a user preference data. + * + * @copyright 2020 Brickfield Education Labs, www.brickfield.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class provider implements + // This plugin has data. + \core_privacy\local\metadata\provider, + // This plugin has some sitewide user preferences to export. + \core_privacy\local\request\user_preference_provider { + + /** The user preference for the toggle state. */ + const TOGGLE_STATE = 'block_accessreviewtogglestate'; + + /** + * Returns meta data about this system. + * + * @param collection $items The initialised item collection to add items to. + * @return collection A listing of user data stored through this system. + */ + public static function get_metadata(collection $items) : collection { + $items->add_user_preference(self::TOGGLE_STATE, 'privacy:metadata:preference:block_accessreviewtogglestate'); + return $items; + } + + /** + * Store all user preferences for the plugin. + * + * @param int $userid The userid of the user whose data is to be exported. + */ + public static function export_user_preferences(int $userid) { + $togglestate = get_user_preferences(self::TOGGLE_STATE, null, $userid); + + if (isset($togglestate)) { + $preferencestring = get_string('privacy:togglestateoff', 'block_accessreview'); + if ($togglestate == true) { + $preferencestring = get_string('privacy:togglestateon', 'block_accessreview'); + } + \core_privacy\local\request\writer::export_user_preference( + 'block_accessreview', + self::TOGGLE_STATE, + ($togglestate) ? 'On' : 'Off', + $preferencestring + ); + } + } +} diff --git a/blocks/accessreview/db/access.php b/blocks/accessreview/db/access.php new file mode 100644 index 0000000000000..19bf71e84a4d6 --- /dev/null +++ b/blocks/accessreview/db/access.php @@ -0,0 +1,49 @@ +. + + +/** + * accessreview capabilities definition + * + * @package block_accessreview + * @copyright 2019 Karen Holland LTS.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$capabilities = array( + + 'block/accessreview:addinstance' => array( + 'captype' => 'write', + 'contextlevel' => CONTEXT_BLOCK, + 'archetypes' => array( + 'editingteacher' => CAP_ALLOW, + 'manager' => CAP_ALLOW + ), + + 'clonepermissionsfrom' => 'moodle/site:manageblocks' + ), + + 'block/accessreview:view' => array( + 'captype' => 'read', + 'contextlevel' => CONTEXT_BLOCK, + 'archetypes' => array( + 'editingteacher' => CAP_ALLOW, + 'manager' => CAP_ALLOW + ), + ), +); diff --git a/blocks/accessreview/db/services.php b/blocks/accessreview/db/services.php new file mode 100644 index 0000000000000..55b17df727e2e --- /dev/null +++ b/blocks/accessreview/db/services.php @@ -0,0 +1,45 @@ +. + +/** + * External service definitions for the accessreview block. + * + * @package block_accessreview + * @author Max Larkin + * @copyright 2020 Brickfield Education Labs + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$functions = [ + 'block_accessreview_get_module_data' => [ + 'classname' => 'block_accessreview\external\get_module_data', + 'methodname' => 'execute', + 'description' => 'Gets error data for course modules.', + 'type' => 'read', + 'ajax' => true, + 'capabilities' => 'block/accessreview:view', + ], + 'block_accessreview_get_section_data' => [ + 'classname' => 'block_accessreview\external\get_section_data', + 'methodname' => 'execute', + 'description' => 'Gets error data for course sections.', + 'type' => 'read', + 'ajax' => true, + 'capabilities' => 'block/accessreview:view', + ] +]; diff --git a/blocks/accessreview/lang/en/block_accessreview.php b/blocks/accessreview/lang/en/block_accessreview.php new file mode 100755 index 0000000000000..b24f69f8c24d5 --- /dev/null +++ b/blocks/accessreview/lang/en/block_accessreview.php @@ -0,0 +1,64 @@ +. + + +/** + * Simple block language strings + * + * @package block_accessreview + * @copyright 2019 Karen Holland LTS.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$string['accessreview:addinstance'] = 'Add an Accessibility Review block to a course'; +$string['accessreview:view'] = 'View the Accessibility Review'; +$string['checktypes'] = 'Types'; +$string['errors'] = 'Errors'; +$string['errordisplay'] = 'Display errors in this format'; +$string['errorssummary'] = 'Accessibility Review'; +$string['frown'] = 'Errors found, sorry!'; +$string['guides'] = 'Guides'; +$string['link:pdf'] = 'Link to PDF resource on {$a} - opens in new window'; +$string['link:video'] = 'Link to Video resource on {$a} - opens in new window'; +$string['nodata'] = 'No accessibility results data was found.'; +$string['pluginname'] = 'Accessibility Review'; +$string['privacy:metadata'] = 'The Accessibility Review plugin does not store any personal data.'; +$string['privacy:metadata:preference:block_accessreviewtogglestate'] = 'The user\'s preference for hiding or showing the course accessibility highlighting.'; +$string['privacy:togglestateoff'] = 'The current preference for the course accessibility highlighting is off.'; +$string['privacy:togglestateon'] = 'The current preference for the course accessibility highlighting is on.'; +$string['showbackground'] = 'Show background colouring only'; +$string['showboth'] = 'Show both background colour and status icons'; +$string['showicon'] = 'Display smiley'; +$string['showicons'] = 'Show count icons only'; +$string['showint'] = 'Display amount'; +$string['showpercent'] = 'Display percentage'; +$string['smile'] = '0 errors, congratulations!'; +$string['status:successalt'] = 'Passed'; +$string['status:success'] = 'Passed'; +$string['status:errors'] = 'Failed {$a->errorCount} errors ({$a->failureRate}% of all checks)'; +$string['status:errorsalt'] = 'Errors'; +$string['toggleaccessreview'] = 'Toggle highlighting'; +$string['toolpage'] = 'Report page to show'; +$string['totalerrors'] = 'Total errors: {$a}
(total excludes course settings)'; +$string['viewreportalt'] = 'View Brickfield Accessibility Report'; +$string['viewreport'] = 'View'; +$string['downloadreportalt'] = 'Download Brickfield Accessibility Report'; +$string['downloadreport'] = 'Download'; +$string['togglealt'] = 'Toggle Brickfield Accessibility Heatmap'; +$string['toggle'] = 'Toggle highlighting'; +$string['whattoshow'] = 'What to show on course page'; diff --git a/blocks/accessreview/lib.php b/blocks/accessreview/lib.php new file mode 100644 index 0000000000000..81942fe3687f0 --- /dev/null +++ b/blocks/accessreview/lib.php @@ -0,0 +1,65 @@ +. + + +/** + * Lib library of functions. + * + * @package block_accessreview + * @copyright 2019 Karen Holland LTS.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +/** + * Get icon mapping for font-awesome. + */ +function block_accessreview_get_fontawesome_icon_map() { + return [ + 'block_accessreview:smile' => 'fa-smile-o', + 'block_accessreview:frown' => 'fa-frown-o', + 'block_accessreview:errorsfound' => 'fa-ban', + 'block_accessreview:f/pdf' => 'fa-file-pdf-o', + 'block_accessreview:f/video' => 'fa-file-video-o', + 'block_accessreview:f/find' => 'fa-bar-chart', + 'block_accessreview:f/form' => 'fa-pencil-square-o', + 'block_accessreview:f/image' => 'fa-image', + 'block_accessreview:f/layout' => 'fa-th-large', + 'block_accessreview:f/link' => 'fa-link', + 'block_accessreview:f/media' => 'fa-play-circle-o', + 'block_accessreview:f/table' => 'fa-table', + 'block_accessreview:f/text' => 'fa-font', + 'block_accessreview:t/fail' => 'fa-ban', + 'block_accessreview:t/pass' => 'fa-check', + ]; +} + +/** + * Define preferences which may be set via the core_user_set_user_preferences external function. + * + * @return array + */ +function block_accessreview_user_preferences(): array { + return [ + 'block_accessreviewtogglestate' => [ + 'type' => PARAM_INT, + 'null' => NULL_NOT_ALLOWED, + 'default' => 0, + 'choices' => [0, 1], + ], + ]; +} diff --git a/blocks/accessreview/pix/t/fail.png b/blocks/accessreview/pix/t/fail.png new file mode 100644 index 0000000000000..611b4bdb8ad73 Binary files /dev/null and b/blocks/accessreview/pix/t/fail.png differ diff --git a/blocks/accessreview/pix/t/fail.svg b/blocks/accessreview/pix/t/fail.svg new file mode 100644 index 0000000000000..f5d942a7b3564 --- /dev/null +++ b/blocks/accessreview/pix/t/fail.svg @@ -0,0 +1,3 @@ + +]> \ No newline at end of file diff --git a/blocks/accessreview/pix/t/pass.png b/blocks/accessreview/pix/t/pass.png new file mode 100644 index 0000000000000..49e8c48a6c781 Binary files /dev/null and b/blocks/accessreview/pix/t/pass.png differ diff --git a/blocks/accessreview/pix/t/pass.svg b/blocks/accessreview/pix/t/pass.svg new file mode 100644 index 0000000000000..33045f105be4e --- /dev/null +++ b/blocks/accessreview/pix/t/pass.svg @@ -0,0 +1,3 @@ + +]> \ No newline at end of file diff --git a/blocks/accessreview/settings.php b/blocks/accessreview/settings.php new file mode 100644 index 0000000000000..e56be264c92af --- /dev/null +++ b/blocks/accessreview/settings.php @@ -0,0 +1,66 @@ +. + +/** + * accessreview block settings + * + * @package block_accessreview + * @copyright 2019 Karen Holland LTS.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +use tool_brickfield\local\tool\tool as base_tool; + +if ($ADMIN->fulltree) { + + // Control background display and icons. + $options = [ + 'showboth' => get_string('showboth', 'block_accessreview'), + 'showbackground' => get_string('showbackground', 'block_accessreview'), + 'showicons' => get_string('showicons', 'block_accessreview'), + ]; + $settings->add(new admin_setting_configselect('block_accessreview/whattoshow', + get_string('whattoshow', 'block_accessreview'), + '', + 'showboth', + $options) + ); + + // Control display format for errors. + $erroroptions = [ + 'showint' => get_string('showint', 'block_accessreview'), + 'showpercent' => get_string('showpercent', 'block_accessreview'), + 'showicon' => get_string('showicon', 'block_accessreview'), + ]; + $settings->add(new admin_setting_configselect('block_accessreview/errordisplay', + get_string('errordisplay', 'block_accessreview'), + '', + 'showint', + $erroroptions) + ); + + // Tool page to display by default. + $options = base_tool::get_tool_names(); + $settings->add(new admin_setting_configselect( + 'block_accessreview/toolpage', + get_string('toolpage', 'block_accessreview'), + '', + key($options), + $options + )); +} diff --git a/blocks/accessreview/styles.css b/blocks/accessreview/styles.css new file mode 100755 index 0000000000000..72b12c337f152 --- /dev/null +++ b/blocks/accessreview/styles.css @@ -0,0 +1,41 @@ +.block_accessreview_success, +.block_accessreview.block_accessreview_success.hasinfo { + color: #1e451e; + background: #d7e6d7; + border-color: #c8ddc8; +} + +.block_accessreview_danger, +.block_accessreview.block_accessreview_danger.hasinfo { + color: #6e211e; + background: #f6d9d8; + border-color: #f3c9c8; +} + +.block_accessreview_warning, +.block_accessreview.block_accessreview_warning.hasinfo { + color: #7d5a29; + background: #fcefdc; + border-color: #fbe8cd; +} + +.block_accessreview_table { + border-bottom: 1px solid; + border-color: #eee8e8; +} + +.block_accessreview_links { + display: flex; + flex-flow: row; + flex-wrap: wrap; + justify-content: center; +} + +.block_accessreview_link { + padding-left: 10px; + padding-right: 10px; +} + +.block_accessreview_analysisbutton { + text-align: center; +} diff --git a/blocks/accessreview/templates/status.mustache b/blocks/accessreview/templates/status.mustache new file mode 100644 index 0000000000000..ac55d5356558b --- /dev/null +++ b/blocks/accessreview/templates/status.mustache @@ -0,0 +1,63 @@ +{{! + 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 block_accessreview/status + + Accessibility review result information. + + Classes required for JS: + * none + + Data attributes required for JS: + * none + + Context variables required for this template: + * classList - array of block_accessreview classes + * resultPassed - boolean indicating that the item is correct + * passRate - object containing metrics + * errorCount - the number of failures + * checkCount - the number of items checked + * failureRate - the percentage of items failing + + Example context (json): + { + "classList": "block_accessreview_danger", + "passRate": { + "checkCount": "60", + "errorCount": "12", + "failureRate": "20" + } + } +}} +
+ {{#resultPassed}} + {{#pix}}t/pass, block_accessreview, {{#str}}status:successalt, block_accessreview{{/str}}{{/pix}} + {{#str}}status:success, block_accessreview, { + "errorCount": {{passRate.errorCount}}, + "checkCount": {{passRate.checkCount}}, + "failureRate": {{passRate.failureRate}} + }{{/str}} + {{/resultPassed}} + {{^resultPassed}} + {{#pix}}t/fail, block_accessreview, {{#str}}status:errorsalt, block_accessreview{{/str}}{{/pix}} + {{#str}}status:errors, block_accessreview, { + "errorCount": {{passRate.errorCount}}, + "checkCount": {{passRate.checkCount}}, + "failureRate": {{passRate.failureRate}} + }{{/str}} + {{/resultPassed}} +
diff --git a/blocks/accessreview/tests/accessibility_review_test.php b/blocks/accessreview/tests/accessibility_review_test.php new file mode 100644 index 0000000000000..cf21466bc46ce --- /dev/null +++ b/blocks/accessreview/tests/accessibility_review_test.php @@ -0,0 +1,99 @@ +. + +namespace block_accessreview\tests; + +use ReflectionClass; +use advanced_testcase; +use block_accessreview; +use context_course; + +/** + * PHPUnit block_accessibility_review tests + * + * @package block_accessreview + * @copyright 2020 onward: Learning Technology Services, www.lts.ie + * @author Jay Churchward (jay.churchward@poetopensource.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class accessibility_review_test extends advanced_testcase { + public static function setUpBeforeClass(): void { + require_once(__DIR__ . '/../../moodleblock.class.php'); + require_once(__DIR__ . '/../block_accessreview.php'); + } + + public function test_get_toggle_link() { + $rc = new ReflectionClass(block_accessreview::class); + $rm = $rc->getMethod('get_toggle_link'); + $rm->setAccessible(true); + + $block = new block_accessreview(); + $output = $rm->invoke($block); + $this->assertNotEmpty($output); + } + + public function test_get_download_link() { + $this->resetAfterTest(); + + $user1 = $this->getDataGenerator()->create_user(); + $user2 = $this->getDataGenerator()->create_user(); + + $course = $this->getDataGenerator()->create_course(); + + // Enrol users in the course. + $this->getDataGenerator()->enrol_user($user1->id, $course->id, 'teacher'); + $this->getDataGenerator()->enrol_user($user2->id, $course->id, 'student'); + + $rc = new ReflectionClass(block_accessreview::class); + $rm = $rc->getMethod('get_download_link'); + $rm->setAccessible(true); + $block = new block_accessreview(); + + $this->setUser($user1); + $result = $rm->invoke($block, context_course::instance($course->id)); + $this->assertNotEmpty($result); + + $this->setUser($user2); + $result = $rm->invoke($block, context_course::instance($course->id)); + $this->assertEmpty($result); + } + + public function test_get_report_link() { + $this->resetAfterTest(); + + $user1 = $this->getDataGenerator()->create_user(); + $user2 = $this->getDataGenerator()->create_user(); + + $course = $this->getDataGenerator()->create_course(); + + // Enrol users in the course. + $this->getDataGenerator()->enrol_user($user1->id, $course->id, 'teacher'); + $this->getDataGenerator()->enrol_user($user2->id, $course->id, 'student'); + + $rc = new ReflectionClass(block_accessreview::class); + $rm = $rc->getMethod('get_report_link'); + $rm->setAccessible(true); + $block = new block_accessreview(); + + $this->setUser($user1); + $result = $rm->invoke($block, context_course::instance($course->id)); + $this->assertNotEmpty($result); + + $this->setUser($user2); + $result = $rm->invoke($block, context_course::instance($course->id)); + $this->assertEmpty($result); + } +} diff --git a/blocks/accessreview/tests/behat/accessreview.feature b/blocks/accessreview/tests/behat/accessreview.feature new file mode 100644 index 0000000000000..b6e59f54e2c3a --- /dev/null +++ b/blocks/accessreview/tests/behat/accessreview.feature @@ -0,0 +1,30 @@ +@block @block_accessreview @javascript +Feature: Block accessreview + In order to overview accessibility information on my course + As a manager + I can add the accessreview block in a course + + Background: + Given the following "courses" exist: + | fullname | shortname | format | + | Course 1 | C1 | topics | + + Scenario: View accessreview block on a course + Given I log in as "admin" + And I am on "Course 1" course homepage with editing mode on + When I add the "Accessibility Review" block + Then I should see "Accessibility Review" + And I should see "No accessibility results data was found." + + Scenario: Hide/show accessreview view + Given I log in as "admin" + And I am on "Course 1" course homepage with editing mode on + When I add the "Accessibility Review" block + Then I should see "Accessibility Review" + And I should see "No accessibility results data was found." + And I click on "Actions menu" "icon" in the "Accessibility Review" "block" + And I follow "Hide Accessibility Review block" + And I should not see "No accessibility results data was found." + And I click on "Actions menu" "icon" in the "Accessibility Review" "block" + And I follow "Show Accessibility Review block" + And I should see "No accessibility results data was found." diff --git a/blocks/accessreview/tests/behat/accessreview_results.feature b/blocks/accessreview/tests/behat/accessreview_results.feature new file mode 100644 index 0000000000000..81c097c01ef5d --- /dev/null +++ b/blocks/accessreview/tests/behat/accessreview_results.feature @@ -0,0 +1,38 @@ +@block @block_accessreview @javascript +Feature: Block accessreview results + In order to overview accessibility information on my course + As a manager + I can add the accessreview block in a course after running the scheduled task + + Background: + Given the following "courses" exist: + | fullname | shortname | format | + | Course 1 | C1 | topics | + And the following "activities" exist: + | activity | name | intro | course | idnumber | + | label | Label one | Bold text is bold. | C1 | id001 | + And I run the scheduled task "\tool_brickfield\task\bulk_process_courses" + + Scenario: View accessreview block results on a course + Given I log in as "admin" + And I am on "Course 1" course homepage with editing mode on + When I add the "Accessibility Review" block + Then I should see "Accessibility Review" + And I should not see "No accessibility results data was found." + And I should see "Image" + And I should see "Layout" + And I should see "Link" + And I should see "Media" + And I should see "Table" + And I should see "Text" + And I should see "View" + And I should see "Toggle highlighting" + + Scenario: Toggle highlighting on/off + Given I log in as "admin" + And I am on "Course 1" course homepage with editing mode on + When I add the "Accessibility Review" block + Then I should see "Toggle highlighting" + And ".block_accessreview_view" "css_element" should be visible + And I click on "Toggle highlighting" "text" + And ".block_accessreview_view" "css_element" should not be visible diff --git a/blocks/accessreview/version.php b/blocks/accessreview/version.php new file mode 100644 index 0000000000000..c7af8bcd3425c --- /dev/null +++ b/blocks/accessreview/version.php @@ -0,0 +1,35 @@ +. + + +/** + * Simple block version identification + * + * @package block_accessreview + * @copyright 2019 Karen Holland LTS.ie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$plugin->component = 'block_accessreview'; +$plugin->release = '1.1 (Build - 2021012500)'; +$plugin->version = 2020101904; +$plugin->requires = 2018051700; // Moodle 3.5 and up. +$plugin->maturity = MATURITY_STABLE; +$plugin->dependencies = array( + 'tool_brickfield' => ANY_VERSION, +);