diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f88e96bc5f699af3c3e35586c8500bdd5a6b3a65 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM amazoncorretto:17.0.3-alpine as corretto-jdk + +ENV BASEDIR /data +ENV TESTDIR $BASEDIR/test +ENV SOURCEDIR $BASEDIR/src +ENV RESULTDIR $BASEDIR/result +ENV LIBSDIR $BASEDIR/libs + +RUN mkdir -p $TESTDIR \ + && mkdir $SOURCEDIR \ + && mkdir $RESULTDIR \ + && mkdir -p /$LIBSDIR/additional + +ADD target/dta-jdk17-junit5-runner-jar-with-dependencies.jar /$BASEDIR/app.jar +ADD https://repo1.maven.org/maven2/org/junit/jupiter/junit-jupiter-api/5.10.0/junit-jupiter-api-5.10.0.jar /$LIBSDIR/ +ADD https://repo1.maven.org/maven2/org/junit/jupiter/junit-jupiter-engine/5.10.0/junit-jupiter-engine-5.10.0.jar /$LIBSDIR/ +ADD https://repo1.maven.org/maven2/org/junit/platform/junit-platform-engine/1.10.0/junit-platform-engine-1.10.0.jar /$LIBSDIR/ +ADD https://repo1.maven.org/maven2/org/junit/platform/junit-platform-commons/1.10.0/junit-platform-commons-1.10.0.jar /$LIBSDIR/ +ADD https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/1.10.0/junit-platform-launcher-1.10.0.jar /$LIBSDIR/ +ADD https://repo1.maven.org/maven2/org/apiguardian/apiguardian-api/1.1.1/apiguardian-api-1.1.1.jar /$LIBSDIR/ +ADD https://repo1.maven.org/maven2/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar /$LIBSDIR/ + +WORKDIR $BASEDIR + +ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -jar /$BASEDIR/app.jar "$SOURCEDIR/src:$TESTDIR/test" "$LIBSDIR/*:$TESTDIR/libs/*" $RESULTDIR \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9cecc1d4669ee8af2ca727a5d8cde10cd8b2d7cc --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/README.md b/README.md index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0b95c53f2ef837d88e2c1e30b9239ad1697960f0 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,164 @@ +# Moodle Dockerized Test Agent (MoDTA) Plugin + +This is the source code repository for the MoDTA plugin. It is an extended and enhanced version of the approved Moodle JUnit Exercise Corrector (MoJEC) plugin, and the Moodle Dockerized Code Testing (MoDoCoT) and Moodle Dockerized Test Tool (Moodle DTT) plugins - for which no approval was requested, which all still run up to Moodle 4.3. MoDTA can thus be considered MoJEC version 4, thought it can test code in any programming language for which a teacher provides a test runner docker image. + +The zip archive in the root directory contains the files from the dta directory for easy installation as long as it is unavailable via Moodle Plugins Directory. + +## Goals + +MoDTA empowers teachers to provide programming Moodle assignments for their students, which are automatically corrected upon hand-in using teacher-provided tests and the results provided as extended submission feedback. + +Corrections optionally include a pedagogic agent giving feedback on student competencies and in the next version recommending next exercises based on student competency levels and resilience. + +Furthermore, MoDTA optionally provides the errors as tickets in supported ticketing systems to resemble current state-of-the-art software development workflows. + +### Motivation + +Due to contact time constraints, assignments for a new topic typically include about three tasks (one easy introductory, one standard usage, and one advanced combination with previous topics). Students e.g. stuck at the standard level assignment may face frustration and only little opportunity for qualified feedback. Especially in beginners’ programming education, many students struggle with the way of thinking and at the same time feel reluctant to ask teachers for help. + +MoDTA allows for teachers to provide additional assignments at intermediate levels from their typically existing assignment collection. Teachers have to create automated tests for the assignments and place them in a git repository. Afterwards students can practice their skills 24/7 with a less steep learning curve and without having to overcome their potential reluctance to ask a teacher for help. They receive feedback consistent with other assignment results integrated into the Moodle environment. + +MoDTA supports beginners not educated in state-of-the-art repository-based workflows by offering hand-ins in a zip archive containing the code to lower the learning curve. It also supports hand-in via repository URL and optionally repository credentials for advanced students. + +Optionally, if a teacher provides competency profiles and difficulties for tasks and tests, students also receive feedback about their achieved competencies by a pedagogic agent, which in the next version optionally recommends a learning path to the students based on their resilience. + +Furthermore and independent of the other optional features, MoDTA optionally supports a state-of-the-art workflow by placing tickets for compile errors in a student-provided ticketing system link (currently supported: GitLab and Atlassian Jira). + +## Overview + +The MoDTA system comprises two key components: + +• The MoDTA Moodle plugin, designed as an assignment submission tool. +• The DTA backend web service, which interfaces with the Moodle plugin through REST and employs the JSON file format for communication. + +The plugin establishes communication with the external DTA backend REST web service offering the endpoints: + +• POST /v1/unittest:** This endpoint requires the assignment ID and a text file containing the repository link (see usage below for an example). Optionally, it may include credentials, if the repository is private. Credentials should be formatted as "username:password" or "username:auth-token". Also optionally, the file may contain a link to a ticketing system in a new line of the same format. The results are returned in JSON format. + +• POST /v1/tasks:** This API expects the assignment ID and a text file containing a repository link. Similar to the previous endpoint, it can also include an optional line for credentials when dealing with private repositories, using the same "username:password" or "username:auth-token" format. The results are provided in JSON format. + +• DELETE /v1/unittest?assignmentId={id}:** Initiates the deletion of test files when provided with the assignment ID as a query parameter. + +## Installation & Configuration + +After approval, install the plugin directly from the Moodle Plugins Directory via Site Administration/Plugins/Install Plugins. + +Before that or alternatively: zip the plugin code from https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/moodledta (here). The readily-zipped current version also sits in the repository’s main directory. Then install the plugin from zip via Site Administration/Plugins/Install Plugins, or by extracting the plugin archive to {Moodle_Root}/mod/assign/submission/dta and visiting the admins notifications page. + +Visit Site Administration/Plugins/Plugin Overview and select Settings next to the Moodle Dockerized Test Agent (MoDTA) entry to enter the URI of your backend as shown in Fig. 1.  Finally, configure via Site Administration/Security/HTTP Security settings permitting communication with the backend URI and port as seen in Fig. 2.  The plugin requires the external DTA REST webservice backend. + +Notes: + +The universal DTA REST webservice backend is available under the GPLv3 as well at https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/dtabackend and the docker image at https://hub.docker.com/r/hftstuttgart/dta-backend . See the documentation in the repository for the necessary setup. + +An example JDK 17 JUnit 5 test runner is available under GPLv3 as well at https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/dtatestrunner and the pre-built docker image at https://hub.docker.com/r/hftstuttgart/dta-jdk17-junit5-testrunner . The repository contains an example docker-compose.yaml for tests with a bitnami Moodle and MariaDB setup and the backend. + +## Usage + +With the MoDTA plugin installed and configured backend URI (including Moodle Security/HTTP Security settings permitting communication with that URI): + +### Teacher + +When creating an assignment, a teacher can select the MoDTA exercise as a new assignment type via an additional checkbox on the assignment creation page as shown at the bottom of Fig. 3.  A new standard file upload field appears as indicated in Fig. 4. . There, the teacher must upload a text file with the git repository URI containing the tests as shown in Fig. 5.  The text file has to adhere to the following format also given in the example repository: + +The text file has to contain the following, each separated by :: +- dtt as the URI-type +- \<git https repository URI> +- \<git user name or the fixed string “none†for publicly accessible repositories> +- \<git password for the given user, git read access token for the repository, or the fixed string “none†for publicly accessible repositories> +- \<docker hub image for the test runner> +- optionally, an additional line of the same structure containing a ticketing system URI, user name and password or write access token + +An example text file content looks like this: +dtt::https://transfer.hft-stuttgart.de/gitlab/dtt/example_openjdk11-junit5-calculator-test.git::none::none::hftstuttgart/dta-jdk17-junit5-testrunner:latest + +Students use the same format, just without the runner part at the end. + +### Student + +Students use an additional MoDTA standard file upload field in the standard submission processs in Moodle like in Fig. 6. [Fig. 6: Moodle DTA Student File Upload](doc/usage_student_1.png) There, they place either a zip archive or a text file adhering to the same format as the teacher’s file with their code repository URI and optionally credentials and/or a ticketing system URI as shown in Fig. 7.  + +Upon completion, students see a summarized overview of their test results in an additional column of the submission feedback table like in Fig. 8.  Clicking on a new expansion icon in that column, they reach a detailed feedback dialog including stack traces of compile errors and test failures as in Fig. 9.  Optionally, the MoDTA backend creates tickets for compile failures in the ticketing system under the URI provided by the student upon hand-in. + +Note: Teachers have access to the Moodle submission result view to assess student results. However, teacher control and grading are not the focus of MoDTA. + +### Technical Workflow + +Assignment creation: The backend creates a temporary directory and checks out the test code from the given repository to that directory's subdirectory test. If the repository contains a file test-competencies.mft in its root directory with a structure described in the backend documentation, this enables the optional competency feedback. + +Assignment submission: The MoDTA plugin passes the submission id and submitted text or zip file – no personal teacher student data – to the external DTA backend REST web service. The DTA backend REST web service fetches or extracts the code to the temporary directory's subdirectory src. It launches via docker a dedicated test runner based on the docker image provided in the teacher’s text file. This test runner compiles and executes the code, running the teacher-defined tests to evaluate the students' submission. + +The runner returns the result in a file named result.json in the temporary directory's subdirectory result. The backend optionally enriches the result with competency feedback. It then returns the json result structure to the MoDTA moodle plugin. The MoDTA moodle plugin adds a new column to the submission result table and shows a result summary as well as an + button. Clicking on the + button, the student sees the detailed test results and, optionally, competency feedback. + +## Plugin Detail Documentation – MoDTA Assignment Submission Plugin + +The assignment submission plugin type was the most suitable choice with assignment feedback as another related option. It empowers you to present customized form fields to students during the assignment submission process and to teachers when configuring assignment settings. Moreover, it grants complete control over how submitted assignments are displayed to both graders and students. + +The primary features of this plugin type include the ability to: + +• Integrate additional settings into the module settings page for assignments. +• Provide a summary of the submission to students and teachers. +• Incorporate form fields into the student submission page for added flexibility and customization. + +### File Structure + +To ensure proper organization, all files related to the MoDTA assignment submission plugin reside in the directory path "mod/assign/submission/dta" within {Moodle_Root}. + +### Language + +The language files for our plugin are found under "lang/<country_code>/assignsubmission_dta.php." These files are organized into different subfolders depending on the language to be supported. For instance: + +- English: "lang/en/assignsubmission_dta.php" + +The filename corresponds to the component name of the plugin, structured as <plugintype>_<pluginname>, which, in our case, is "assignsubmission_dta." The repository delivers only English as requested by the Moodle team. + +Each language file contains various key-value entries formatted as $string["key"] = "Value," with the key provided in English as the most widespread language remaining consistent across different language files, while the value varies according to the chosen language. Moodle incorporates a dedicated String API used In the plugin as required In the approval guidelines, allowing for easy value retrieval based on a given key and the selected language (e.g., get_string("key", "default value")). + +### version.php + +This file provides version information about the plugin to manage installation and upgrades. + +### settings.php + +The settings file defines two settings for the MoDTA plugin: + +1. Default: This setting offers a checkbox to determine whether the plugin should be enabled by default when creating a new assignment. + +2. Web Service Base URL: It features a text field where you can specify the base URL for the web service, facilitating file communication and actual testing. + +### db/upgrade.php + +This file is currently empty, as the data structure for the plugin has not changed so far. + +### db/install.xml + +This file defines the necessary database tables and rows for storing data associated with the MoDTA plugin. Moodle offers a specialized XML schema designed for modeling this information, featuring elements like TABLENAME, FIELDS, and KEY. The plugin utilizes two additional tables for cleanliness not to alter moodle standard tables: +assignsubmission_dta_summary which is related 1:1 to the submission and uses the assignment_id and submission_id as foreign keys, and assignsubmission_dta_result which stores the results of a submission as a 1:n relation to the assignsubmission_dta_summary. Whenever a new MoDTA assignment is submitted, the backend web service is engaged, returning one or more test results or compilation errors in the form of a JSON string. The front end parses this JSON string for the result summary and results and stores them in the appropriate tables. + +### locallib.php + +This is where all the functionality for this plugin is defined. All submission plugins must define a class with the component name of the plugin that extends assign_submission_plugin . + +That yields the following class hierarchy: + +The "assign_submission_plugin" class serves as an abstract foundation that all assignment submission plugins must build upon. It incorporates a limited set of supplementary functions tailored exclusively to submission plugins. On the other hand, the "assign_plugin" class is also an abstract class, but it functions as the fundamental class for all assignment plugins, encompassing both feedback and submission plugins. This class facilitates access to the assignment instance, represented as "$this->assignment." Collectively, these two classes offer a series of public functions, often referred to as "hooks," which are designed to be overridden to implement the required functionality. + +The following provides brief descriptions of a selection of functions to illustrate the types of hooks available: + +• get_settings(): This function comes into play during the creation of the assignment settings page. For the MoDTA plugin, this involves adding a file manager that permits teachers to upload their test repo and docker Image URI as a textfile. This function is overridden from the assign_plugin class. + +• save_settings(): The save_settings function is invoked when the assignment settings page is submitted, whether for a new assignment or the modification of an existing one. In the MoDTA plugin, this function is responsible for preserving the text file chosen by the teacher and transmitting the file to the backend web service. Like the previous function, this one is overridden from the assign_plugin class. + +• get_form_elements_for_user(): During the construction of the submission form, this function plays a similar role to the get_settings() function for settings. In the context of the MoDTA plugin, it adds a file manager to enable students to upload their text or zip file. Once again, this function is overridden from the assign_plugin class. + +• save():This function is invoked to save a user's submission. Within the MoDTA plugin, this function sends the student's submission to the backend and receives the result as the response. For details see the technical details section above. + +• view_summary(): This function is called to display a summary of the submission to both teachers and students. For the students, this summary will be shown within the submission status table and for the teachers within a column of the grading table. In the MoDTA plugin this method returns a more compact view (only essential data) for the grading table and a detailed view for the students submission status table. + +### lib.php + +This file serves as the gateway to various standard Moodle APIs designed for plugins. In the content of the MoDTA plugin, this function is denoted as "assignsubmission_dta_pluginfile." + +### util folder + +The folder contains various utility files, e.g. displaying the new test summary pages is delegated from the locallib.php for brevity of that source. diff --git a/doc/install_conf_1.png b/doc/install_conf_1.png new file mode 100644 index 0000000000000000000000000000000000000000..500aa5be6c5928a34f51a76e041f10515f931026 Binary files /dev/null and b/doc/install_conf_1.png differ diff --git a/doc/install_conf_2.png b/doc/install_conf_2.png new file mode 100644 index 0000000000000000000000000000000000000000..8ac26bfed096aa65fb53ff871db49284e5b8706e Binary files /dev/null and b/doc/install_conf_2.png differ diff --git a/doc/usage_student_1.png b/doc/usage_student_1.png new file mode 100644 index 0000000000000000000000000000000000000000..d299f03b1114118a5988374c7b05c6d4ecd83152 Binary files /dev/null and b/doc/usage_student_1.png differ diff --git a/doc/usage_student_2.png b/doc/usage_student_2.png new file mode 100644 index 0000000000000000000000000000000000000000..208429bd8858ed372e53c34b29b0867e257502b8 Binary files /dev/null and b/doc/usage_student_2.png differ diff --git a/doc/usage_student_3.png b/doc/usage_student_3.png new file mode 100644 index 0000000000000000000000000000000000000000..0d1dbc2ae842cf03d6b6c2781a9fcd5605c3eb1e Binary files /dev/null and b/doc/usage_student_3.png differ diff --git a/doc/usage_student_4.png b/doc/usage_student_4.png new file mode 100644 index 0000000000000000000000000000000000000000..36a9e8536daf1c3d4b0bf891b2453d8637e5e017 Binary files /dev/null and b/doc/usage_student_4.png differ diff --git a/doc/usage_teacher_1.png b/doc/usage_teacher_1.png new file mode 100644 index 0000000000000000000000000000000000000000..df9f231d6c68d8b6ad7537b1fa49b81b869aa19f Binary files /dev/null and b/doc/usage_teacher_1.png differ diff --git a/doc/usage_teacher_2.png b/doc/usage_teacher_2.png new file mode 100644 index 0000000000000000000000000000000000000000..3c48277223dc2513a6f19a4da998298d0545fb35 Binary files /dev/null and b/doc/usage_teacher_2.png differ diff --git a/doc/usage_teacher_3.png b/doc/usage_teacher_3.png new file mode 100644 index 0000000000000000000000000000000000000000..509510a26bf29744ab5aae33a917786f6c9170c9 Binary files /dev/null and b/doc/usage_teacher_3.png differ diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ed075ff204dc37f5984e2b12a92fed44b3c9217c --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,47 @@ +version: '2' +services: +services: + mariadb-dtt: + container_name: moodledb-dtt + image: docker.io/bitnami/mariadb:11.1 + environment: + # ALLOW_EMPTY_PASSWORD is recommended only for development. + - ALLOW_EMPTY_PASSWORD=yes + - MARIADB_USER=bn_moodle + - MARIADB_DATABASE=bitnami_moodle + - MARIADB_CHARACTER_SET=utf8mb4 + - MARIADB_COLLATE=utf8mb4_unicode_ci + volumes: + - 'mariadb_data_dtt:/bitnami/mariadb' + moodle-dtt: + container_name: moodle-dtt + image: docker.io/bitnami/moodle:4.3 + ports: + - '81:8080' + - '444:8443' + environment: + - MOODLE_DATABASE_HOST=mariadb-dtt + - MOODLE_DATABASE_PORT_NUMBER=3306 + - MOODLE_DATABASE_USER=bn_moodle + - MOODLE_DATABASE_NAME=bitnami_moodle + # ALLOW_EMPTY_PASSWORD is recommended only for development. + - ALLOW_EMPTY_PASSWORD=yes + volumes: + - 'moodle_data_dtt:/bitnami/moodle' + - 'moodledata_data_dtt:/bitnami/moodledata' + depends_on: + - mariadb-dtt + backend: + container_name: backendcomposedtt + image: hftstuttgart/dta-backend:latest + user: "${UID}:${GID}" + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - '/tmp/dta-tests:/tmp/dta-tests' +volumes: + mariadb_data_dtt: + driver: local + moodle_data_dtt: + driver: local + moodledata_data_dtt: + driver: local \ No newline at end of file diff --git a/dta.zip b/dta.zip new file mode 100644 index 0000000000000000000000000000000000000000..01aa7904c3ee85d7f0d91d2f601f81b77e96df83 Binary files /dev/null and b/dta.zip differ diff --git a/dta/README.md b/dta/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c07b4cf50c2f52b9f5ab6ee02849ff06aa535981 --- /dev/null +++ b/dta/README.md @@ -0,0 +1,164 @@ +# Moodle Dockerized Test Agent (MoDTA) Plugin + +This is the source code repository for the MoDTA plugin. It is an extended and enhanced version of the approved Moodle JUnit Exercise Corrector (MoJEC) plugin, and the Moodle Dockerized Code Testing (MoDoCoT) and Moodle Dockerized Test Tool (Moodle DTT) plugins - for which no approval was requested, which all still run up to Moodle 4.3. MoDTA can thus be considered MoJEC version 4, thought it can test code in any programming language for which a teacher provides a test runner docker image. + +The zip archive in the root directory contains the files from the dta directory for easy installation as long as it is unavailable via Moodle Plugins Directory. + +## Goals + +MoDTA empowers teachers to provide programming Moodle assignments for their students, which are automatically corrected upon hand-in using teacher-provided tests and the results provided as extended submission feedback. + +Corrections optionally include a pedagogic agent giving feedback on student competencies and in the next version recommending next exercises based on student competency levels and resilience. + +Furthermore, MoDTA optionally provides the errors as tickets in supported ticketing systems to resemble current state-of-the-art software development workflows. + +### Motivation + +Due to contact time constraints, assignments for a new topic typically include about three tasks (one easy introductory, one standard usage, and one advanced combination with previous topics). Students e.g. stuck at the standard level assignment may face frustration and only little opportunity for qualified feedback. Especially in beginners’ programming education, many students struggle with the way of thinking and at the same time feel reluctant to ask teachers for help. + +MoDTA allows for teachers to provide additional assignments at intermediate levels from their typically existing assignment collection. Teachers have to create automated tests for the assignments and place them in a git repository. Afterwards students can practice their skills 24/7 with a less steep learning curve and without having to overcome their potential reluctance to ask a teacher for help. They receive feedback consistent with other assignment results integrated into the Moodle environment. + +MoDTA supports beginners not educated in state-of-the-art repository-based workflows by offering hand-ins in a zip archive containing the code to lower the learning curve. It also supports hand-in via repository URL and optionally repository credentials for advanced students. + +Optionally, if a teacher provides competency profiles and difficulties for tasks and tests, students also receive feedback about their achieved competencies by a pedagogic agent, which in the next version optionally recommends a learning path to the students based on their resilience. + +Furthermore and independent of the other optional features, MoDTA optionally supports a state-of-the-art workflow by placing tickets for compile errors in a student-provided ticketing system link (currently supported: GitLab and Atlassian Jira). + +## Overview + +The MoDTA system comprises two key components: + +• The MoDTA Moodle plugin, designed as an assignment submission tool. +• The DTA backend web service, which interfaces with the Moodle plugin through REST and employs the JSON file format for communication. + +The plugin establishes communication with the external DTA backend REST web service offering the endpoints: + +• POST /v1/unittest:** This endpoint requires the assignment ID and a text file containing the repository link (see usage below for an example). Optionally, it may include credentials, if the repository is private. Credentials should be formatted as "username:password" or "username:auth-token". Also optionally, the file may contain a link to a ticketing system in a new line of the same format. The results are returned in JSON format. + +• POST /v1/tasks:** This API expects the assignment ID and a text file containing a repository link. Similar to the previous endpoint, it can also include an optional line for credentials when dealing with private repositories, using the same "username:password" or "username:auth-token" format. The results are provided in JSON format. + +• DELETE /v1/unittest?assignmentId={id}:** Initiates the deletion of test files when provided with the assignment ID as a query parameter. + +## Installation & Configuration + +After approval, install the plugin directly from the Moodle Plugins Directory via Site Administration/Plugins/Install Plugins. + +Before that or alternatively: zip the plugin code from https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/moodledta (here). The readily-zipped current version also sits in the repository’s main directory. Then install the plugin from zip via Site Administration/Plugins/Install Plugins, or by extracting the plugin archive to {Moodle_Root}/mod/assign/submission/dta and visiting the admins notifications page. + +Visit Site Administration/Plugins/Plugin Overview and select Settings next to the Moodle Dockerized Test Agent (MoDTA) entry to enter the URI of your backend as shown in Fig. 1.  Finally, configure via Site Administration/Security/HTTP Security settings permitting communication with the backend URI and port as seen in Fig. 2.  The plugin requires the external DTA REST webservice backend. + +Notes: + +The universal DTA REST webservice backend is available under the GPLv3 as well at https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/dtabackend and the docker image at https://hub.docker.com/r/hftstuttgart/dta-backend . See the documentation in the repository for the necessary setup. + +An example JDK 17 JUnit 5 test runner is available under GPLv3 as well at https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/dtatestrunner and the pre-built docker image at https://hub.docker.com/r/hftstuttgart/dta-jdk17-junit5-testrunner . The repository contains an example docker-compose.yaml for tests with a bitnami Moodle and MariaDB setup and the backend. + +## Usage + +With the MoDTA plugin installed and configured backend URI (including Moodle Security/HTTP Security settings permitting communication with that URI): + +### Teacher + +When creating an assignment, a teacher can select the MoDTA exercise as a new assignment type via an additional checkbox on the assignment creation page as shown at the bottom of Fig. 3.  A new standard file upload field appears as indicated in Fig. 4. . There, the teacher must upload a text file with the git repository URI containing the tests as shown in Fig. 5.  The text file has to adhere to the following format also given in the example repository: + +The text file has to contain the following, each separated by :: +- dtt as the URI-type +- \<git https repository URI> +- \<git user name or the fixed string “none†for publicly accessible repositories> +- \<git password for the given user, git read access token for the repository, or the fixed string “none†for publicly accessible repositories> +- \<docker hub image for the test runner> +- optionally, an additional line of the same structure containing a ticketing system URI, user name and password or write access token + +An example text file content looks like this: +dtt::https://transfer.hft-stuttgart.de/gitlab/dtt/example_openjdk11-junit5-calculator-test.git::none::none::hftstuttgart/dta-jdk17-junit5-testrunner:latest + +Students use the same format, just without the runner part at the end. + +### Student + +Students use an additional MoDTA standard file upload field in the standard submission processs in Moodle like in Fig. 6. [Fig. 6: Moodle DTA Student File Upload](doc/usage_student_1.png) There, they place either a zip archive or a text file adhering to the same format as the teacher’s file with their code repository URI and optionally credentials and/or a ticketing system URI as shown in Fig. 7.  + +Upon completion, students see a summarized overview of their test results in an additional column of the submission feedback table like in Fig. 8.  Clicking on a new expansion icon in that column, they reach a detailed feedback dialog including stack traces of compile errors and test failures as in Fig. 9.  Optionally, the MoDTA backend creates tickets for compile failures in the ticketing system under the URI provided by the student upon hand-in. + +Note: Teachers have access to the Moodle submission result view to assess student results. However, teacher control and grading are not the focus of MoDTA. + +### Technical Workflow + +Assignment creation: The backend creates a temporary directory and checks out the test code from the given repository to that directory's subdirectory test. If the repository contains a file test-competencies.mft in its root directory with a structure described in the backend documentation, this enables the optional competency feedback. + +Assignment submission: The MoDTA plugin passes the submission id and submitted text or zip file – no personal teacher student data – to the external DTA backend REST web service. The DTA backend REST web service fetches or extracts the code to the temporary directory's subdirectory src. It launches via docker a dedicated test runner based on the docker image provided in the teacher’s text file. This test runner compiles and executes the code, running the teacher-defined tests to evaluate the students' submission. + +The runner returns the result in a file named result.json in the temporary directory's subdirectory result. The backend optionally enriches the result with competency feedback. It then returns the json result structure to the MoDTA moodle plugin. The MoDTA moodle plugin adds a new column to the submission result table and shows a result summary as well as an + button. Clicking on the + button, the student sees the detailed test results and, optionally, competency feedback. + +## Plugin Detail Documentation – MoDTA Assignment Submission Plugin + +The assignment submission plugin type was the most suitable choice with assignment feedback as another related option. It empowers you to present customized form fields to students during the assignment submission process and to teachers when configuring assignment settings. Moreover, it grants complete control over how submitted assignments are displayed to both graders and students. + +The primary features of this plugin type include the ability to: + +• Integrate additional settings into the module settings page for assignments. +• Provide a summary of the submission to students and teachers. +• Incorporate form fields into the student submission page for added flexibility and customization. + +### File Structure + +To ensure proper organization, all files related to the MoDTA assignment submission plugin reside in the directory path "mod/assign/submission/dta" within {Moodle_Root}. + +### Language + +The language files for our plugin are found under "lang/<country_code>/assignsubmission_dta.php." These files are organized into different subfolders depending on the language to be supported. For instance: + +- English: "lang/en/assignsubmission_dta.php" + +The filename corresponds to the component name of the plugin, structured as <plugintype>_<pluginname>, which, in our case, is "assignsubmission_dta." The repository delivers only English as requested by the Moodle team. + +Each language file contains various key-value entries formatted as $string["key"] = "Value," with the key provided in English as the most widespread language remaining consistent across different language files, while the value varies according to the chosen language. Moodle incorporates a dedicated String API used In the plugin as required In the approval guidelines, allowing for easy value retrieval based on a given key and the selected language (e.g., get_string("key", "default value")). + +### version.php + +This file provides version information about the plugin to manage installation and upgrades. + +### settings.php + +The settings file defines two settings for the MoDTA plugin: + +1. Default: This setting offers a checkbox to determine whether the plugin should be enabled by default when creating a new assignment. + +2. Web Service Base URL: It features a text field where you can specify the base URL for the web service, facilitating file communication and actual testing. + +### db/upgrade.php + +This file is currently empty, as the data structure for the plugin has not changed so far. + +### db/install.xml + +This file defines the necessary database tables and rows for storing data associated with the MoDTA plugin. Moodle offers a specialized XML schema designed for modeling this information, featuring elements like TABLENAME, FIELDS, and KEY. The plugin utilizes two additional tables for cleanliness not to alter moodle standard tables: +assignsubmission_dta_summary which is related 1:1 to the submission and uses the assignment_id and submission_id as foreign keys, and assignsubmission_dta_result which stores the results of a submission as a 1:n relation to the assignsubmission_dta_summary. Whenever a new MoDTA assignment is submitted, the backend web service is engaged, returning one or more test results or compilation errors in the form of a JSON string. The front end parses this JSON string for the result summary and results and stores them in the appropriate tables. + +### locallib.php + +This is where all the functionality for this plugin is defined. All submission plugins must define a class with the component name of the plugin that extends assign_submission_plugin . + +That yields the following class hierarchy: + +The "assign_submission_plugin" class serves as an abstract foundation that all assignment submission plugins must build upon. It incorporates a limited set of supplementary functions tailored exclusively to submission plugins. On the other hand, the "assign_plugin" class is also an abstract class, but it functions as the fundamental class for all assignment plugins, encompassing both feedback and submission plugins. This class facilitates access to the assignment instance, represented as "$this->assignment." Collectively, these two classes offer a series of public functions, often referred to as "hooks," which are designed to be overridden to implement the required functionality. + +The following provides brief descriptions of a selection of functions to illustrate the types of hooks available: + +• get_settings(): This function comes into play during the creation of the assignment settings page. For the MoDTA plugin, this involves adding a file manager that permits teachers to upload their test repo and docker Image URI as a textfile. This function is overridden from the assign_plugin class. + +• save_settings(): The save_settings function is invoked when the assignment settings page is submitted, whether for a new assignment or the modification of an existing one. In the MoDTA plugin, this function is responsible for preserving the text file chosen by the teacher and transmitting the file to the backend web service. Like the previous function, this one is overridden from the assign_plugin class. + +• get_form_elements_for_user(): During the construction of the submission form, this function plays a similar role to the get_settings() function for settings. In the context of the MoDTA plugin, it adds a file manager to enable students to upload their text or zip file. Once again, this function is overridden from the assign_plugin class. + +• save():This function is invoked to save a user's submission. Within the MoDTA plugin, this function sends the student's submission to the backend and receives the result as the response. For details see the technical details section above. + +• view_summary(): This function is called to display a summary of the submission to both teachers and students. For the students, this summary will be shown within the submission status table and for the teachers within a column of the grading table. In the MoDTA plugin this method returns a more compact view (only essential data) for the grading table and a detailed view for the students submission status table. + +### lib.php + +This file serves as the gateway to various standard Moodle APIs designed for plugins. In the content of the MoDTA plugin, this function is denoted as "assignsubmission_dta_pluginfile." + +### util folder + +The folder contains various utility files, e.g. displaying the new test summary pages is delegated from the locallib.php for brevity of that source. diff --git a/dta/classes/backend.php b/dta/classes/backend.php new file mode 100644 index 0000000000000000000000000000000000000000..7ca08f49e180ca0a2bd41bfe06c9bbf2bc15c01f --- /dev/null +++ b/dta/classes/backend.php @@ -0,0 +1,144 @@ +<?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/>. + +/** + * This file contains the backend webservice contact functionality for the DTA plugin + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ + +/** + * backend webservice contact utility class + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ +class DtaBackendUtils { + + /** + * Returns the base url of the backend webservice as configured in the administration settings. + * @return string backend host base url + */ + private static function getbackendbaseurl(): string { + $backendaddress = get_config(assign_submission_dta::COMPONENT_NAME, "backendHost"); + + if (empty($backendaddress)) { + \core\notification::error(get_string("backendHost_not_set", assign_submission_dta::COMPONENT_NAME)); + } + + return $backendaddress; + } + + /** + * Sends the configuration textfile uploaded by prof to the backend. + * + * @param stdClass $assignment assignment this test-config belongs to + * @param stdClass $file uploaded test-config + * @return bool true if no error occurred + */ + public static function sendtestconfigtobackend($assignment, $file): bool { + $backendaddress = self::getbackendbaseurl(); + if (empty($backendaddress)) { + return true; + } + + // Set endpoint for test upload. + $url = $backendaddress . "/v1/unittest"; + + // Prepare params. + $params = [ + "unitTestFile" => $file, + "assignmentId" => $assignment->get_instance()->id, + ]; + + // If request returned null, return false to indicate failure. + if (is_null(self::post($url, $params))) { + return false; + } else { + return true; + } + } + + /** + * Sends submission config or archive to backend to be tested. + * + * @param stdClass $assignment assignment for the submission + * @param int $submissionid submissionid of the current file + * @param stdClass $file submission config file or archive with submission + * @return string json string with testresults or null on error + */ + public static function sendsubmissiontobackend($assignment, $submissionid, $file): ?string { + $backendaddress = self::getbackendbaseurl(); + if (empty($backendaddress)) { + return true; + } + + // Set endpoint for test upload. + $url = $backendaddress . "/v1/task/" . $submissionid; + + // Prepare params. + $params = [ + "taskFile" => $file, + "assignmentId" => $assignment->get_instance()->id, + ]; + + return self::post($url, $params); + } + + /** + * Posts the given params to the given url and returns the response as a string. + * @param string $url full url to request to + * @param array $params parameters for http-request + * + * @return string received body on success or null on error + */ + private static function post($url, $params): ?string { + if (!isset($url) || !isset($params)) { + return false; + } + + $options = ["CURLOPT_RETURNTRANSFER" => true]; + + $curl = new curl(); + $response = $curl->post($url, $params, $options); + + // Check state of request, if response code is a 2xx return the answer. + $info = $curl->get_info(); + if ($info["http_code"] >= 200 && $info["http_code"] < 300) { + return $response; + } + + // Something went wrong, return null and give an error message. + debugging(assign_submission_dta::COMPONENT_NAME . ": Post file to server was not successful: http_code=" . + $info["http_code"]); + + if ($info['http_code'] >= 400 && $info['http_code'] < 500) { + \core\notification::error(get_string("http_client_error_msg", assign_submission_dta::COMPONENT_NAME)); + return null; + } else if ($info['http_code'] >= 500 && $info['http_code'] < 600) { + \core\notification::error(get_string("http_server_error_msg", assign_submission_dta::COMPONENT_NAME)); + return null; + } else { + \core\notification::error(get_string("http_unknown_error_msg", assign_submission_dta::COMPONENT_NAME) . + $info["http_code"] . $response); + return null; + } + } + +} diff --git a/dta/classes/database.php b/dta/classes/database.php new file mode 100644 index 0000000000000000000000000000000000000000..6f5c82a94f5545911657831ebbadbe1ca5f0ece0 --- /dev/null +++ b/dta/classes/database.php @@ -0,0 +1,165 @@ +<?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/>. + +/** + * persistence layer utility class + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ +class DbUtils { + + /** + * Summary database table name. + */ + private const TABLE_SUMMARY = "assignsubmission_dta_summary"; + /** + * Result database table name. + */ + private const TABLE_RESULT = "assignsubmission_dta_result"; + + /** + * gets summary with all corresponding result entries + * + * @param int $assignmentid assignment id to search for + * @param int $submissionid submission id to search for + * @return DttResultSummary representing given submission + */ + public static function getresultsummaryfromdatabase( + int $assignmentid, + int $submissionid + ): DtaResultSummary { + global $DB; + + // Fetch data from database. + $summaryrecord = $DB->get_record(self::TABLE_SUMMARY, [ + "assignment_id" => $assignmentid, + "submission_id" => $submissionid, + ]); + + $resultsarray = $DB->get_records(self::TABLE_RESULT, [ + "assignment_id" => $assignmentid, + "submission_id" => $submissionid, + ]); + + // Create a summary instance. + $summary = new DtaResultSummary(); + $summary->timestamp = $summaryrecord->timestamp; + $summary->globalstacktrace = $summaryrecord->global_stacktrace; + $summary->successfultestcompetencies = $summaryrecord->successful_competencies; + $summary->overalltestcompetencies = $summaryrecord->tested_competencies; + $summary->results = []; + + // Create result instances and add to array of summary instance. + foreach ($resultsarray as $rr) { + $result = new DtaResult(); + $result->packagename = $rr->package_name; + $result->classname = $rr->class_name; + $result->name = $rr->name; + $result->state = $rr->state; + $result->failuretype = $rr->failure_type; + $result->failurereason = $rr->failure_reason; + $result->stacktrace = $rr->stacktrace; + $result->columnnumber = $rr->column_number; + $result->linenumber = $rr->line_number; + $result->position = $rr->position; + + $summary->results[] = $result; + } + + return $summary; + } + + /** + * save given result summary and single results to database + * under given assignment and submission id + * + * @param int $assignmentid assigment this is submission is linked to + * @param int $submissionid submission of this result + * @param DtaResultSummary $summary instance to persist + */ + public static function storeresultsummarytodatabase( + int $assignmentid, + int $submissionid, + DtaResultSummary $summary + ): void { + global $DB; + + // Prepare new database entries. + $summaryrecord = new stdClass(); + $summaryrecord->assignment_id = $assignmentid; + $summaryrecord->submission_id = $submissionid; + $summaryrecord->timestamp = $summary->timestamp; + $summaryrecord->global_stacktrace = $summary->globalstacktrace; + $summaryrecord->successful_competencies = $summary->successfultestcompetencies; + $summaryrecord->tested_competencies = $summary->overalltestcompetencies; + + // Prepare results to persist to array. + $resultrecords = []; + foreach ($summary->results as $r) { + $record = new stdClass(); + $record->assignment_id = $assignmentid; + $record->submission_id = $submissionid; + $record->package_name = $r->packagename; + $record->class_name = $r->classname; + $record->name = $r->name; + $record->state = $r->state; + $record->failure_type = $r->failuretype; + $record->failure_reason = $r->failurereason; + $record->stacktrace = $r->stacktrace; + $record->column_number = $r->columnnumber; + $record->line_number = $r->linenumber; + $record->position = $r->position; + $resultrecords[] = $record; + } + + // If results already exist, delete old values beforehand. + $submission = $DB->get_record(self::TABLE_SUMMARY, [ + 'assignment_id' => $assignmentid, + 'submission_id' => $submissionid, + ]); + + if ($submission) { + $DB->delete_records(self::TABLE_RESULT, [ + 'assignment_id' => $assignmentid, + 'submission_id' => $submissionid, + ]); + + $DB->delete_records(self::TABLE_SUMMARY, [ + 'assignment_id' => $assignmentid, + 'submission_id' => $submissionid, + ]); + } + + // Create summary and single result entries. + $DB->insert_record(self::TABLE_SUMMARY, $summaryrecord); + foreach ($resultrecords as $rr) { + $DB->insert_record(self::TABLE_RESULT, $rr); + } + } + + /** + * cleans up database if plugin is uninstalled + */ + public static function uninstallplugincleaup(): void { + global $DB; + + $DB->delete_records(self::TABLE_RESULT, null); + $DB->delete_records(self::TABLE_SUMMARY, null); + } + +} diff --git a/dta/classes/privacy/provider.php b/dta/classes/privacy/provider.php new file mode 100644 index 0000000000000000000000000000000000000000..9e36d5cd63c0a1fb48918504afaf5a8bb516f311 --- /dev/null +++ b/dta/classes/privacy/provider.php @@ -0,0 +1,262 @@ +<?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/>. + +namespace assignsubmission_dta\privacy; + +use core_privacy\local\metadata\collection; +use core_privacy\local\request\writer; +use core_privacy\local\request\contextlist; +use mod_assign\privacy\assign_plugin_request_data; + +/** + * provider for data privacy + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ +class provider implements \core_privacy\local\metadata\provider, + \mod_assign\privacy\assignsubmission_provider, + \mod_assign\privacy\assignsubmission_user_provider { + + /** + * File area for dta submission assignment. + */ + const ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION = "submissions_dta"; + + /** + * This is the metadata information for the assignsubmission_dta plugin. + * @param collection $collection the collection of metadata filled by the plugin + */ + public static function get_metadata(collection $collection): collection { + $collection->add_subsystem_link( + 'core_files', + [], + 'privacy:metadata:core_files' + ); + + $collection->add_database_table( + 'assignsubmission_dta_summary', + [ + 'assignmentid' => 'privacy:metadata:assignsubmission_dta_summary:assignmentid', + 'submissionid' => 'privacy:metadata:assignsubmission_dta_summary:submissionid', + 'timestamp' => 'privacy:metadata:assignsubmission_dta_summary:timestamp', + 'global_stacktrace' => 'privacy:metadata:assignsubmission_dta_summary:global_stacktrace', + 'successful_competencies' => 'privacy:metadata:assignsubmission_dta_summary:successful_competencies', + 'tested_competencies' => 'privacy:metadata:assignsubmission_dta_summary:tested_competencies', + ], + 'privacy:metadata:assignsubmission_dta_summary' + ); + + $collection->add_database_table( + 'assignsubmission_dta_result', + [ + 'assignmentid' => 'privacy:metadata:assignsubmission_dta_summary:assignmentid', + 'submissionid' => 'privacy:metadata:assignsubmission_dta_summary:submissionid', + 'package_name' => 'privacy:metadata:assignsubmission_dta_result:package_name', + 'class_name' => 'privacy:metadata:assignsubmission_dta_result:class_name', + 'name' => 'privacy:metadata:assignsubmission_dta_result:name', + 'state' => 'privacy:metadata:assignsubmission_dta_result:state', + 'failure_type' => 'privacy:metadata:assignsubmission_dta_result:failure_type', + 'failure_reason' => 'privacy:metadata:assignsubmission_dta_result:failure_reason', + 'stacktrace' => 'privacy:metadata:assignsubmission_dta_result:stacktrace', + 'column_number' => 'privacy:metadata:assignsubmission_dta_result:column_number', + 'line_number' => 'privacy:metadata:assignsubmission_dta_result:line_number', + 'position' => 'privacy:metadata:assignsubmission_dta_result:position', + ], + 'privacy:metadata:assignsubmission_dta_result' + ); + + $collection->add_external_location_link('dta_backend', [ + 'assignmentid' => 'privacy:metadata:assignsubmission_dta_summary:assignmentid', + 'submissionid' => 'privacy:metadata:assignsubmission_dta_summary:submissionid', + 'submissioncontent' => 'privacy:metadata:core_files', + ], + 'privacy:metadata:dta_backend' + ); + + return $collection; + } + + /** + * This is covered by mod_assign provider and the query on assign_submissions. + * + * @param int $userid The user ID that we are finding contexts for. + * @param contextlist $contextlist A context list to add sql and params to for contexts. + */ + public static function get_context_for_userid_within_submission(int $userid, contextlist $contextlist) { + // This is already fetched from mod_assign. + } + + /** + * This is also covered by the mod_assign provider and its queries. + * + * @param \mod_assign\privacy\useridlist $useridlist An object for obtaining user IDs of students. + */ + public static function get_student_user_ids(\mod_assign\privacy\useridlist $useridlist) { + // This is already fetched from mod_assign. + } + + /** + * If you have tables that contain userids and you can generate entries in your tables without creating an + * entry in the assign_submission table then please fill in this method. + * + * @param userlist $userlist The userlist object + */ + public static function get_userids_from_context(\core_privacy\local\request\userlist $userlist) { + // Not required. + } + + /** + * Export all user data for this plugin. + * + * @param assign_plugin_request_data $exportdata Data used to determine which context and user to export and other useful + * information to help with exporting. + */ + public static function export_submission_user_data(assign_plugin_request_data $exportdata) { + // We currently don't show submissions to teachers when exporting their data. + $context = $exportdata->get_context(); + if ($exportdata->get_user() != null) { + return null; + } + $user = new \stdClass(); + $assign = $exportdata->get_assign(); + $submission = $exportdata->get_pluginobject(); + $files = get_files($submission, $user); + foreach ($files as $file) { + $userid = $exportdata->get_pluginobject()->userid; + $dtaresultsummary = DBUtils::getresultsummaryfromdatabase($assign->id, $submission->id); + // Submitted file. + writer::with_context($exportdata->get_context())->export_file($exportdata->get_subcontext(), $file) + // DTA result. + ->export_related_data($dtaresultsummary); + + // Plagiarism data. + $coursecontext = $context->get_course_context(); + \core_plagiarism\privacy\provider::export_plagiarism_user_data($userid, $context, $exportdata->get_subcontext(), [ + 'cmid' => $context->instanceid, + 'course' => $coursecontext->instanceid, + 'userid' => $userid, + 'file' => $file, + ]); + } + } + + /** + * Any call to this method should delete all user data for the context defined in the deletion_criteria. + * + * @param assign_plugin_request_data $requestdata Information useful for deleting user data. + */ + public static function delete_submission_for_context(assign_plugin_request_data $requestdata) { + global $DB; + + \core_plagiarism\privacy\provider::delete_plagiarism_for_context($requestdata->get_context()); + + $fs = get_file_storage(); + $fs->delete_area_files($requestdata->get_context()->id, 'assignsubmission_dta', ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION); + + $assignmentid = $requestdata->get_assign()->get_instance()->id; + + // Delete records from assignsubmission_dta tables. + $DB->delete_records('assignsubmission_dta_result', ['assignmentid' => $assignmentid]); + $DB->delete_records('assignsubmission_dta_summary', ['assignmentid' => $assignmentid]); + } + + /** + * A call to this method should delete user data (where practical) using the userid and submission. + * + * @param assign_plugin_request_data $deletedata Details about the user and context to focus the deletion. + */ + public static function delete_submission_for_userid(assign_plugin_request_data $deletedata) { + global $DB; + + \core_plagiarism\privacy\provider::delete_plagiarism_for_user($deletedata->get_user()->id, $deletedata->get_context()); + + $assignmentid = $deletedata->get_assign()->get_instance()->id; + $submissionid = $deletedata->get_pluginobject()->id; + + $fs = get_file_storage(); + $fs->delete_area_files($deletedata->get_context()->id, 'assignsubmission_dta', ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION, + $submissionid); + + // Delete records from assignsubmission_dta tables. Also possible with a list as below. + $DB->delete_records('assignsubmission_dta_result', [ + 'assignmentid' => $assignmentid, + 'submissionid' => $submissionid, + ]); + $DB->delete_records('assignsubmission_dta_summary', [ + 'assignmentid' => $assignmentid, + 'submissionid' => $submissionid, + ]); + } + + /** + * Deletes all submissions for the submission ids / userids provided in a context. + * assign_plugin_request_data contains: + * - context + * - assign object + * - submission ids (pluginids) + * - user ids + * @param assign_plugin_request_data $deletedata A class that contains the relevant information required for deletion. + */ + public static function delete_submissions(assign_plugin_request_data $deletedata) { + global $DB; + + \core_plagiarism\privacy\provider::delete_plagiarism_for_users($deletedata->get_userids(), $deletedata->get_context()); + + if (empty($deletedata->get_submissionids())) { + return; + } + $fs = get_file_storage(); + list($sql, $params) = $DB->get_in_or_equal($deletedata->get_submissionids(), SQL_PARAMS_NAMED); + $fs->delete_area_files_select($deletedata->get_context()->id, 'assignsubmission_file', ASSIGNSUBMISSION_FILE_FILEAREA, + $sql, $params); + + $params['assignid'] = $deletedata->get_assignid(); + $DB->delete_records_select('assignsubmission_dta_result', "assignmentid = :assignid AND submissionid $sql", $params); + $DB->delete_records_select('assignsubmission_dta_summary', "assignmentid = :assignid AND submissionid $sql", $params); + } + + /** + * Produce a list of files suitable for export that represent this feedback or submission + * + * @param stdClass $submission The submission + * @param stdClass $user The user record - unused + * @return array - return an array of files indexed by filename + */ + public function get_files(stdClass $submission, stdClass $user) { + $result = []; + $fs = get_file_storage(); + + $files = $fs->get_area_files($this->assignment->get_context()->id, + 'assignsubmission_file', + ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION, + $submission->id, + 'timemodified', + false); + + foreach ($files as $file) { + // Do we return the full folder path or just the file name? + if (isset($submission->exportfullpath) && $submission->exportfullpath == false) { + $result[$file->get_filename()] = $file; + } else { + $result[$file->get_filepath().$file->get_filename()] = $file; + } + } + return $result; + } + +} diff --git a/dta/classes/view.php b/dta/classes/view.php new file mode 100644 index 0000000000000000000000000000000000000000..b93d3e57ead9c84bee90de33277b149217d65668 --- /dev/null +++ b/dta/classes/view.php @@ -0,0 +1,426 @@ +<?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/>. + +/** + * utility class for DTA submission plugin result display + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ +class view_submission_utils { + + /** + * Broadly used in logic, parametrized for easier change. + */ + const COMPONENT_NAME = "assignsubmission_dta"; + + /** + * generates a short summary html + * + * @param int $assignmentid assignment + * @param int $submissionid submission to create a report for + * @return string html + */ + public static function generatesummaryhtml( + int $assignmentid, + int $submissionid + ): string { + + // Fetch data. + $summary = DbUtils::getResultSummaryFromDatabase($assignmentid, $submissionid); + $html = ""; + + // Calculate success rate, if no unknown result states or compilation errors. + $successrate = "?"; + if ($summary->unknownCount() == 0 && $summary->compilationErrorCount() == 0) { + $successrate = round(($summary->successfulCount() / $summary->resultCount()) * 100, 2 ); + } + + // Generate html. + $html .= $summary->successfulCount() . "/"; + $html .= ($summary->compilationErrorCount() == 0 && $summary->unknownCount() == 0) + ? $summary->resultCount() . " (" . $successrate . "%)" + : "?"; + $html .= get_string("tests_successful", self::COMPONENT_NAME) . "<br />"; + + if ($summary->compilationErrorCount() > 0) { + $html .= $summary->compilationErrorCount() . get_string("compilation_errors", self::COMPONENT_NAME) . "<br />"; + } + + if ($summary->unknownCount() > 0) { + $html .= $summary->unknownCount() . get_string("unknown_state", self::COMPONENT_NAME) . "<br />"; + } + + $showncompetencies = explode(";", $summary->successfultestcompetencies); + $overallcompetencies = explode(";", $summary->overalltestcompetencies); + + $tmp = ""; + for ($index = 0, $size = count($showncompetencies); $index < $size; $index++) { + $shown = $showncompetencies[$index]; + $comp = $overallcompetencies[$index]; + // If the competency was actually assessed by the assignment and tests, add a summary entry. + if ($shown != "0") { + $tmp .= get_string("comp" . $index, self::COMPONENT_NAME) . + " " . 100 * floatval($shown) / floatval($comp) . "% " . "<br />"; + } + } + + $html .= get_string("success_competencies", self::COMPONENT_NAME) . "<br />" . $tmp . "<br />"; + + return html_writer::div($html, "dtaSubmissionSummary"); + } + + /** + * generates detailed view html + * + * @param int $assignmentid assignment + * @param int $submissionid submission to create a report for + */ + public static function generatedetailhtml( + int $assignmentid, + int $submissionid + ): string { + + // Fetch data. + $summary = DbUtils::getResultSummaryFromDatabase($assignmentid, $submissionid); + $html = ""; + + // Define a few css classes and prepare html attribute arrays to beautify the output. + $tableheaderrowattributes = ["class" => "dtaTableHeaderRow"]; + $tablerowattributes = ["class" => "dtaTableRow"]; + $resultrowattributes = $tablerowattributes; + $unknownattributes = 'dtaResultUnknown'; + $successattributes = 'dtaResultSuccess'; + $failureattributes = 'dtaResultFailure'; + $compilationerrorattributes = 'dtaResultCompilationError'; + + // Summary table. + $tmp = ""; + $tmp .= html_writer::tag("th", get_string("summary", self::COMPONENT_NAME), ["class" => "dtaTableHeader"]); + $tmp .= html_writer::empty_tag("th", ["class" => "dtaTableHeader"]); + $header = html_writer::tag("tr", $tmp, $tableheaderrowattributes); + $header = html_writer::tag("thead", $header); + + $body = ""; + $tmp = ""; + $attributes = ["class" => "dtaTableData"]; + $tmp .= html_writer::tag( + "td", + get_string("total_items", self::COMPONENT_NAME), + $attributes); + + $tmp .= html_writer::tag( + "td", + $summary->resultCount(), + $attributes); + + $resultrowattributes = $tablerowattributes; + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes; + + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + + $tmp = ""; + $tmp .= html_writer::tag("td", get_string("tests_successful", self::COMPONENT_NAME), $attributes); + $tmp .= html_writer::tag( "td", $summary->successfulCount(), $attributes); + + $resultrowattributes = $tablerowattributes; + $successrate = "?"; + + if ($summary->unknownCount() > 0 || $summary->compilationErrorCount() > 0) { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes; + } else { + $successrate = round(($summary->successfulCount() / $summary->resultCount()) * 100, 2 ); + if ($successrate < 50) { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $compilationerrorattributes; + } else if ($successrate < 75) { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $failureattributes; + } else { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes; + } + } + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + + $tmp = ""; + $tmp .= html_writer::tag("td", get_string("failures", self::COMPONENT_NAME), $attributes); + $tmp .= html_writer::tag("td", $summary->failedCount(), $attributes); + + $resultrowattributes = $tablerowattributes; + if ($summary->failedCount() > 0) { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $failureattributes; + } else { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes; + } + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + + $tmp = ""; + $tmp .= html_writer::tag("td", get_string("compilation_errors", self::COMPONENT_NAME), $attributes); + $tmp .= html_writer::tag("td", $summary->compilationErrorCount(), $attributes); + + $resultrowattributes = $tablerowattributes; + if ($summary->compilationErrorCount() > 0) { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $compilationerrorattributes; + } else { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes; + } + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + + $tmp = ""; + $tmp .= html_writer::tag("td", get_string("unknown_state", self::COMPONENT_NAME), $attributes); + $tmp .= html_writer::tag("td", $summary->unknownCount(), $attributes); + + $resultrowattributes = $tablerowattributes; + if ($summary->unknownCount() > 0) { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes; + } else { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes; + } + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + + $tmp = ""; + $tmp .= html_writer::tag("td", html_writer::tag("b", get_string("success_rate", self::COMPONENT_NAME)), $attributes); + $tmp .= html_writer::tag( + "td", + html_writer::tag("b", $summary->successfulCount() + . "/" . (($summary->compilationErrorCount() == 0 && $summary->unknownCount() == 0) ? $summary->resultCount() + . " (" . $successrate . "%)" + : "?")), + $attributes); + + $resultrowattributes = $tablerowattributes; + if ($summary->unknownCount() > 0 || $summary->compilationErrorCount() > 0) { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $unknownattributes; + } else { + if ($successrate < 50) { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $compilationerrorattributes; + } else if ($successrate < 75) { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $failureattributes; + } else { + $resultrowattributes['class'] = $resultrowattributes['class'] . " " . $successattributes; + } + } + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + + $body = html_writer::tag("tbody", $body); + $table = html_writer::tag("table", $header . $body, ["class" => "dtaTable"]); + + $html .= $table; + + // Add empty div for spacing between summary and compentency table. + $html .= html_writer::empty_tag("div", ["class" => "dtaSpacer"]); + + // Competency assessment table. + $body = ""; + $tmp = ""; + $tmp .= html_writer::tag("th", get_string("competencies", self::COMPONENT_NAME), ["class" => "dtaTableHeader"]); + $tmp .= html_writer::empty_tag("th", ["class" => "dtaTableHeader"]); + $header = html_writer::tag("tr", $tmp, $tableheaderrowattributes); + $header = html_writer::tag("thead", $header); + + $showncompetencies = explode(";", $summary->successfultestcompetencies); + $overallcompetencies = explode(";", $summary->overalltestcompetencies); + + for ($index = 0, $size = count($overallcompetencies); $index < $size; $index++) { + $comp = $overallcompetencies[$index]; + $shown = $showncompetencies[$index]; + // If the competency was actually assessed by the assignment and tests, add a row in the table. + if ($comp != "0") { + // New copy of base attributes array. + $resultrowattributes = $tablerowattributes; + $tmp = ""; + $tmp .= html_writer::tag("td", get_string("comp" . $index, self::COMPONENT_NAME), $resultrowattributes); + $tmp .= html_writer::tag("td", 100 * floatval($shown) / floatval($comp) . "% " . + "(" . $shown . " / " . $comp . ")", $resultrowattributes); + $tmp .= html_writer::tag("td", get_string("comp_expl" . $index, self::COMPONENT_NAME), $resultrowattributes); + + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + } + } + $body = html_writer::tag("tbody", $body); + $html .= html_writer::tag("table", $header . $body, ["class" => "dtaTable"]); + + // Add empty div for spacing between competency and details table. + $html .= html_writer::empty_tag("div", ["class" => "dtaSpacer"]); + + // Details table. + $tmp = ""; + $tmp .= html_writer::tag("th", get_string("details", self::COMPONENT_NAME), ["class" => "dtaTableHeader"]); + $tmp .= html_writer::empty_tag("th", ["class" => "dtaTableHeader"]); + $header = html_writer::tag("tr", $tmp, $tableheaderrowattributes); + $header = html_writer::tag("thead", $header); + + $body = ""; + $spacerrow = null; + foreach ($summary->results as $r) { + // Add spacer first if not null. + if (!is_null($spacerrow)) { + $body .= $spacerrow; + } + + // New copy of base attributes array. + $resultrowattributes = $tablerowattributes; + + // Check which css class to add for the colored left-border according to resuls state. + if ($r->state == 0) { + $resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultUnknown'; + } else if ($r->state == 1) { + $resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultSuccess'; + } else if ($r->state == 2) { + $resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultFailure'; + } else if ($r->state == 3) { + $resultrowattributes['class'] = $resultrowattributes['class'] . ' dtaResultCompilationError'; + } + + $tmp = ""; + $tmp .= html_writer::tag( + "td", + get_string("package_name", self::COMPONENT_NAME), + $attributes); + + $tmp .= html_writer::tag( + "td", + $r->packagename, + $attributes); + + $tmp .= html_writer::tag( + "td", + get_string("unit_name", self::COMPONENT_NAME), + $attributes); + + $tmp .= html_writer::tag( + "td", + $r->classname, + $attributes); + + $tmp .= html_writer::tag( + "td", + get_string("test_name", self::COMPONENT_NAME), + $attributes); + + $tmp .= html_writer::tag( + "td", + $r->name, + $attributes); + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + + $tmp = ""; + $tmp .= html_writer::tag( + "td", + get_string("status", self::COMPONENT_NAME), + $attributes); + + $tmp .= html_writer::tag( + "td", + DtaResult::getStateName($r->state), + $attributes); + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + + // If state is something different than successful, show additional rows. + if ($r->state != 1) { + $tmp = ""; + $tmp .= html_writer::tag( + "td", + get_string("failure_type", self::COMPONENT_NAME), + $attributes); + + $tmp .= html_writer::tag( + "td", + $r->failureType, + $attributes); + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + + $tmp = ""; + $tmp .= html_writer::tag( + "td", + get_string("failure_reason", self::COMPONENT_NAME), + $attributes); + + $tmp .= html_writer::tag( + "td", + $r->failureReason, + $attributes); + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + + // Only show line, column and position if they have useful values. + if (!is_null($r->lineNumber) && $r->lineNumber > 0) { + $tmp = ""; + $tmp .= html_writer::tag( + "td", + get_string("line_no", self::COMPONENT_NAME), + $attributes); + + $tmp .= html_writer::tag( + "td", + $r->lineNumber, + $attributes); + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + } + + if (!is_null($r->columnNumber) && $r->columnNumber > 0) { + $tmp = ""; + $tmp .= html_writer::tag( + "td", + get_string("col_no", self::COMPONENT_NAME), + $attributes); + + $tmp .= html_writer::tag( + "td", + $r->columnNumber, + $attributes); + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + } + + if (!is_null($r->position) && $r->position > 0) { + $tmp = ""; + $tmp .= html_writer::tag( + "td", + get_string("pos", self::COMPONENT_NAME), + $attributes); + + $tmp .= html_writer::tag( + "td", + $r->position, + $attributes); + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + } + + $tmp = ""; + $tmp .= html_writer::tag( + "td", + get_string("stacktrace", self::COMPONENT_NAME), + $attributes); + + $tmp .= html_writer::tag( + "td", + html_writer::tag("details", $r->stacktrace, ["class" => "dtaStacktraceDetails"]), + $attributes); + $body .= html_writer::tag("tr", $tmp, $resultrowattributes); + } + + // Set spacerrow value if null for next round separation. + if (is_null($spacerrow)) { + $spacerrow = html_writer::empty_tag("tr", ["class" => "dtaTableSpacer"]); + } + } + $html .= html_writer::tag("table", $header . $body, ["class" => "dtaTable"]); + + // Wrap generated html into final div. + $html = html_writer::div($html, "dtaSubmissionDetails"); + + return $html; + } + +} diff --git a/dta/db/install.xml b/dta/db/install.xml new file mode 100644 index 0000000000000000000000000000000000000000..bb61014e8d10d3461ae85578ab25fc3affd0baf3 --- /dev/null +++ b/dta/db/install.xml @@ -0,0 +1,46 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<XMLDB PATH="mod/assign/submission/dta/db" VERSION="20210107" COMMENT="XMLDB file for Moodle mod/assign/submission/dta" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="../../../../../lib/xmldb/xmldb.xsd" +> + <TABLES> + <TABLE NAME="assignsubmission_dta_summary" COMMENT="DTA testrun summary"> + <FIELDS> + <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/> + <FIELD NAME="assignment_id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/> + <FIELD NAME="submission_id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/> + <FIELD NAME="successful_competencies" TYPE="char" LENGTH="80" NOTNULL="false"/> + <FIELD NAME="tested_competencies" TYPE="char" LENGTH="80" NOTNULL="false"/> + <FIELD NAME="timestamp" TYPE="int" LENGTH="10"/> + <FIELD NAME="global_stacktrace" TYPE="text"/> + </FIELDS> + <KEYS> + <KEY NAME="primary" TYPE="primary" FIELDS="id"/> + <KEY NAME="fk_assignment" TYPE="foreign" FIELDS="assignment_id" REFTABLE="assign" REFFIELDS="id" COMMENT="The assignment instance this summary relates to"/> + <KEY NAME="fk_submission" TYPE="foreign" FIELDS="submission_id" REFTABLE="assign_submission" REFFIELDS="id" COMMENT="The submission this summary relates to."/> + </KEYS> + </TABLE> + <TABLE NAME="assignsubmission_dta_result" COMMENT="DTA testrun single test results"> + <FIELDS> + <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true"/> + <FIELD NAME="assignment_id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/> + <FIELD NAME="submission_id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/> + <FIELD NAME="package_name" TYPE="char" LENGTH="255" NOTNULL="false"/> + <FIELD NAME="class_name" TYPE="char" LENGTH="255" NOTNULL="false"/> + <FIELD NAME="name" TYPE="char" LENGTH="255" NOTNULL="true"/> + <FIELD NAME="state" TYPE="int" LENGTH="10" NOTNULL="true"/> + <FIELD NAME="failure_type" TYPE="char" LENGTH="255"/> + <FIELD NAME="failure_reason" TYPE="char" LENGTH="255"/> + <FIELD NAME="stacktrace" TYPE="text"/> + <FIELD NAME="column_number" TYPE="int" LENGTH="10"/> + <FIELD NAME="line_number" TYPE="int" LENGTH="10"/> + <FIELD NAME="position" TYPE="int" LENGTH="10"/> + </FIELDS> + <KEYS> + <KEY NAME="primary" TYPE="primary" FIELDS="id,assignment_id,submission_id"/> + <KEY NAME="fk_assignment" TYPE="foreign" FIELDS="assignment_id" REFTABLE="assign" REFFIELDS="id" COMMENT="The assignment instance this result relates to"/> + <KEY NAME="fk_submission" TYPE="foreign" FIELDS="submission_id" REFTABLE="assign_submission" REFFIELDS="id" COMMENT="The submission this result relates to."/> + </KEYS> + </TABLE> + </TABLES> +</XMLDB> \ No newline at end of file diff --git a/dta/db/upgrade.php b/dta/db/upgrade.php new file mode 100644 index 0000000000000000000000000000000000000000..65e64b47ffd5b0bc063936a8a3d6a32cfe83db9d --- /dev/null +++ b/dta/db/upgrade.php @@ -0,0 +1,34 @@ +<?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/>. + +/** + * Upgrade code for install + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ + +/** + * Stub for upgrade code + * @param int $oldversion + * @return bool + */ +function xmldb_assignsubmission_dta_upgrade($oldversion) { + global $CFG; + // Currently no adjustments necessary for Moodle upgrades. Works without changes since the first MoJEC version. + return true; +} diff --git a/dta/lang/en/assignsubmission_dta.php b/dta/lang/en/assignsubmission_dta.php new file mode 100644 index 0000000000000000000000000000000000000000..4f3cf89c06c9ba92450f1a350e1b941f0ae829fc --- /dev/null +++ b/dta/lang/en/assignsubmission_dta.php @@ -0,0 +1,166 @@ +<?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/>. + +/** + * Strings for component "assignsubmission_dta", language "en" + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ + +// General. +$string["pluginname"] = "Dockerized Testing Agent (DTA)"; +$string["enabled"] = $string["pluginname"]; + +// Dialog field labels. +$string["submission_label"] = "DTA submission configuration or zip-packed project"; +$string["submission_label_help"] = "Either upload a single textfile containing one DTA URI pointing to the repository with your submission or pack your project as zip and upload it directly. Using the textfile you can additionally add as many unified-ticketing URI (one per line) as you wish for feedback into one or more ticketsystems."; +$string["submission_settings_label"] = "DTA test configuration"; +$string["submission_settings_label_help"] = "single text file with DTA test URI"; +$string["enabled_help"] = "If enabled, you will have to upload a textfile containing a valid DTA URI pointing to the repository with your test logic and defining a docker image on dockerhub used as testrunner. Your students will have to either upload their code in a zip archive resembling the expected repository structure or as well by providing a textifle with a valid DTA URI pointing to the repository with their submission logic"; + +// Content. +$string["tests_successful"] = " successful"; +$string["failures"] = " failure"; +$string["compilation_errors"] = " compilation error"; +$string["unknown_state"] = " with unknown state"; +$string["success_competencies"] = "Successfully tested competency profile "; +$string["summary"] = "Summary"; +$string["total_items"] = "Total items"; +$string["success_rate"] = "Success rate"; +$string["details"] = "Details"; +$string["competencies"] = "Competencies"; +$string["package_name"] = "Package Name"; +$string["unit_name"] = "Unit Name"; +$string["test_name"] = "Test Name"; +$string["status"] = "Status"; +$string["failure_type"] = "Failure Type"; +$string["failure_reason"] = "Failure Reason"; +$string["line_no"] = "Line Number"; +$string["col_no"] = "Column Number"; +$string["pos"] = "Position"; +$string["stacktrace"] = "Stack Trace"; + +// Comeptencies. +$string["comp_statement"] = "Statement"; +$string["comp_block"] = "Block"; +$string["comp_flow"] = "Flow of Control"; +$string["comp_loop"] = "Repetition"; +$string["comp_const"] = "Constant"; +$string["comp_var"] = "Variable"; +$string["comp_type"] = "Type"; +$string["comp_datastructure"] = "Data Structure"; +$string["comp_interface"] = "Interface"; +$string["comp_unit"] = "Unit of Code"; +$string["comp_proc_usage"] = "Procedure Usage"; +$string["comp_proc_sign"] = "Procedure Signature"; +$string["comp_library"] = "Library Usage"; +$string["comp_ext_api"] = "External API Usage"; +$string["comp_simple"] = "Simplicity"; +$string["comp_abstraction"] = "Abstraction"; + +// Competencies for index calculation. +$string["comp0"] = $string["comp_statement"]; +$string["comp1"] = $string["comp_block"]; +$string["comp2"] = $string["comp_flow"]; +$string["comp3"] = $string["comp_loop"]; +$string["comp4"] = $string["comp_const"]; +$string["comp5"] = $string["comp_var"]; +$string["comp6"] = $string["comp_type"]; +$string["comp7"] = $string["comp_datastructure"]; +$string["comp8"] = $string["comp_interface"]; +$string["comp9"] = $string["comp_unit"]; +$string["comp10"] = $string["comp_proc_usage"]; +$string["comp11"] = $string["comp_proc_sign"]; +$string["comp12"] = $string["comp_library"]; +$string["comp13"] = $string["comp_ext_api"]; +$string["comp14"] = $string["comp_simple"]; +$string["comp15"] = $string["comp_abstraction"]; + +// Competency explanations. +$string["comp_statement_expl"] = "formulate a syntactically correct statement that contributes to the solution of the given problem."; +$string["comp_block_expl"] = "structure code into syntactically correct small unnamed units that contribute to the solution of the given problem."; +$string["comp_flow_expl"] = "formulate syntax elements guiding the control flow such that it contributes to the solution of the given problem."; +$string["comp_loop_expl"] = "use syntax elements repeating statements such that it contributes to the solution of the given problem."; +$string["comp_const_expl"] = "identify and syntactically correctly define constants that contribute to the understanding and solution of the given problem."; +$string["comp_var_expl"] = "identify and syntactically correctly define variables that contribute to the solution of the given problem."; +$string["comp_type_expl"] = "define and/or choose appropriate data types for data elements such that they contribute to the solution of the given problem."; +$string["comp_datastructure_expl"] = "define and/or choose appropriate data structures for data elements such that they contribute to the solution of the given problem."; +$string["comp_interface_expl"] = "define and use interfaces for larger units of code such that it contributes to the solution of the given problem."; +$string["comp_unit_expl"] = "define and larger units of code such that it contributes to the solution of the given problem."; +$string["comp_proc_usage_expl"] = "use existing named structure blocks with a pre-defined behavior and signature such that it contributes to the solution of the given problem."; +$string["comp_proc_sign_expl"] = "define named structure blocks with a pre-defined behavior and signature such that it contributes to the solution of the given problem."; +$string["comp_library_expl"] = "use existing larger collections of named structure blocks with a pre-defined behavior and signature such that it contributes to the solution of the given problem."; +$string["comp_ext_api_expl"] = "use standardized existing external collections of named structure blocks with a pre-defined behavior and signature such that it contributes to the solution of the given problem."; +$string["comp_simple_expl"] = "create a simple solution of the given problem."; +$string["comp_abstraction_expl"] = "create a sufficiently abstract solution for the given problem."; + +// Competency explanations for index calculations. +$string["comp_expl0"] = $string["comp_statement_expl"]; +$string["comp_expl1"] = $string["comp_block_expl"]; +$string["comp_expl2"] = $string["comp_flow_expl"]; +$string["comp_expl3"] = $string["comp_loop_expl"]; +$string["comp_expl4"] = $string["comp_const_expl"]; +$string["comp_expl5"] = $string["comp_var_expl"]; +$string["comp_expl6"] = $string["comp_type_expl"]; +$string["comp_expl7"] = $string["comp_datastructure_expl"]; +$string["comp_expl8"] = $string["comp_interface_expl"]; +$string["comp_expl9"] = $string["comp_unit_expl"]; +$string["comp_expl10"] = $string["comp_proc_usage_expl"]; +$string["comp_expl11"] = $string["comp_proc_sign_expl"]; +$string["comp_expl12"] = $string["comp_library_expl"]; +$string["comp_expl13"] = $string["comp_ext_api_expl"]; +$string["comp_expl14"] = $string["comp_simple_expl"]; +$string["comp_expl15"] = $string["comp_abstraction_expl"]; + +// Warnings. +$string["no_testfile_warning"] = "Submission type is \"Dockerized Testing Agent\" but no configuration file uploaded"; + +// Error messages. +$string["backendHost_not_set"] = "The Dockerized Testing Agent backend URL is not configured"; +$string["no_submissionfile_warning"] = "Submission type is \"Dockerized Testing Agent\" but no configuration file or submission archive uploaded"; +$string["http_client_error_msg"] = "A client error occured (HTTP 4xx)"; +$string["http_server_error_msg"] = "A server error occured (HTTP 5xx)"; +$string["http_unknown_error_msg"] = "An unknown HTTP error occured on backend transfer"; + +// Admin settings. +$string["default"] = "Enabled by default"; +$string["default_help"] = "If set, this submission method will be enabled by default for all new assignments."; +$string["backendHost"] = "Backend Server Address"; +$string["backendHost_help"] = "Address/Name and Port of backend server"; + +// Database field descriptions for privacy API. +$string["privacy:metadata:core_files"] = "Moodle core files."; +$string["privacy:metadata:assignsubmission_dta_summary:assignmentid"] = "ID of the assignment"; +$string["privacy:metadata:assignsubmission_dta_summary:submissionid"] = "ID of the submission"; +$string["privacy:metadata:assignsubmission_dta_summary:timestamp"] = "Date and time of the submission"; +$string["privacy:metadata:assignsubmission_dta_summary"] = "Stack trace of the compilation and test if major problems occur"; +$string["privacy:metadata:assignsubmission_dta_summary:successful_competencies"] = "List of the successfully tested competencies"; +$string["privacy:metadata:assignsubmission_dta_summary:tested_competencies"] = "List of the tested competencies"; +$string["privacy:metadata:assignsubmission_dta_summary"] = "Summary of Dockerized Test Agent (DTA) results"; +$string["privacy:metadata:assignsubmission_dta_result:package_name"] = "Package name of individual test"; +$string["privacy:metadata:assignsubmission_dta_result:class_name"] = "Class name of individual test"; +$string["privacy:metadata:assignsubmission_dta_result:name"] = "Name of individual test"; +$string["privacy:metadata:assignsubmission_dta_result:state"] = "State of individual test"; +$string["privacy:metadata:assignsubmission_dta_result:failure_type"] = "Failure type of individual test"; +$string["privacy:metadata:assignsubmission_dta_result:failure_reason"] = "Failure reason of individual test"; +$string["privacy:metadata:assignsubmission_dta_result:stacktrace"] = "Stack trace of failed compilation or individual test"; +$string["privacy:metadata:assignsubmission_dta_result:column_number"] = "Column number of failed individual compilation or test"; +$string["privacy:metadata:assignsubmission_dta_result:line_number"] = "Line number of failed individual compilation or test"; +$string["privacy:metadata:assignsubmission_dta_result:position"] = "Position of failed individual compilation or test"; +$string["privacy:metadata:assignsubmission_dta_result"] = "Individual Dockerized Test Agent (DTA) results"; +$string["privacy:metadata:dta_backend"] = "Dockerized Test Agent (DTA) backend ReST web service"; diff --git a/dta/lib.php b/dta/lib.php new file mode 100644 index 0000000000000000000000000000000000000000..c090bfc9e6b6524bbb50867fdc2d5e9b6e568103 --- /dev/null +++ b/dta/lib.php @@ -0,0 +1,88 @@ +<?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/>. + +/** + * This file contains the moodle hooks for the submission DTA plugin + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ + +/** + * Serves assignment submissions and other files. + * + * @param mixed $course course or id of the course + * @param mixed $cm course module or id of the course module + * @param context $context + * @param string $filearea + * @param array $args + * @param bool $forcedownload + * @return bool false if file not found, does not return if found - just send the file + */ +function assignsubmission_dta_pluginfile( + $course, + $cm, + context $context, + $filearea, + $args, + $forcedownload + ) { + global $DB, $CFG; + + if ($context->contextlevel != CONTEXT_MODULE) { + return false; + } + + require_login($course, false, $cm); + $itemid = (int)array_shift($args); + $record = $DB->get_record('assign_submission', + ['id' => $itemid], + 'userid, assignment, groupid', + MUST_EXIST); + $userid = $record->userid; + $groupid = $record->groupid; + + require_once($CFG->dirroot . '/mod/assign/locallib.php'); + + $assign = new assign($context, $cm, $course); + + if ($assign->get_instance()->id != $record->assignment) { + return false; + } + + if ($assign->get_instance()->teamsubmission && + !$assign->can_view_group_submission($groupid)) { + return false; + } + + if (!$assign->get_instance()->teamsubmission && + !$assign->can_view_submission($userid)) { + return false; + } + + $relativepath = implode('/', $args); + + $fullpath = "/{$context->id}/assignsubmission_dta/$filearea/$itemid/$relativepath"; + + $fs = get_file_storage(); + if (!($file = $fs->get_file_by_hash(sha1($fullpath))) || $file->is_directory()) { + return false; + } + + // Download MUST be forced - security! + send_stored_file($file, 0, 0, true); +} diff --git a/dta/locallib.php b/dta/locallib.php new file mode 100644 index 0000000000000000000000000000000000000000..cff2b4e98d786fb48d150c6aea543304ecf32625 --- /dev/null +++ b/dta/locallib.php @@ -0,0 +1,407 @@ +<?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/>. + +defined('MOODLE_INTERNAL') || die(); + +// Import various entity and application logic files. +require_once($CFG->dirroot . '/mod/assign/submission/dta/models/DtaResult.php'); +require_once($CFG->dirroot . '/mod/assign/submission/dta/classes/database.php'); +require_once($CFG->dirroot . '/mod/assign/submission/dta/classes/backend.php'); +require_once($CFG->dirroot . '/mod/assign/submission/dta/classes/view.php'); + +/** + * library class for DTA submission plugin extending assign submission plugin base class + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class assign_submission_dta extends assign_submission_plugin { + + /** + * Broadly used in logic, parametrized for easier change. + */ + const COMPONENT_NAME = "assignsubmission_dta"; + /** + * Draft file area for dta tests to be uploaded by the teacher. + */ + const ASSIGNSUBMISSION_DTA_DRAFT_FILEAREA_TEST = "tests_draft_dta"; + /** + * File area for dta tests to be uploaded by the teacher. + */ + const ASSIGNSUBMISSION_DTA_FILEAREA_TEST = "tests_dta"; + /** + * File area for dta submission assignment. + */ + const ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION = "submissions_dta"; + + /** + * get plugin name + * @return string + */ + public function get_name(): string { + return get_string("pluginname", self::COMPONENT_NAME); + } + + /** + * Get default settings for assignment submission settings + * + * @param MoodleQuickForm $mform form to add elements to + * @return void + */ + public function get_settings(MoodleQuickForm $mform): void { + // Add draft filemanager to form. + $mform->addElement( + "filemanager", + self::ASSIGNSUBMISSION_DTA_DRAFT_FILEAREA_TEST, + get_string("submission_settings_label", self::COMPONENT_NAME), + null, + $this->get_file_options(true) + ); + + // Add help button to added filemanager. + $mform->addHelpButton( + // Form-unique element id to which to add button. + self::ASSIGNSUBMISSION_DTA_DRAFT_FILEAREA_TEST, + // Key. + "submission_settings_label", + // Language file to use. + self::COMPONENT_NAME + ); + + // Only show filemanager if plugin is enabled. + $mform->hideIf( + // Form-unique element id to hide. + self::ASSIGNSUBMISSION_DTA_DRAFT_FILEAREA_TEST, + // Condition to check. + self::COMPONENT_NAME . '_enabled', + // State to match for hiding. + 'notchecked' + ); + } + + /** + * Allows the plugin to update the defaultvalues passed in to + * the settings form (needed to set up draft areas for editor + * and filemanager elements) + * @param array $defaultvalues + */ + public function data_preprocessing(&$defaultvalues): void { + // Get id of draft area for file manager creation. + $draftitemid = file_get_submitted_draft_itemid(self::ASSIGNSUBMISSION_DTA_DRAFT_FILEAREA_TEST); + + // Prepare draft area with created draft filearea. + file_prepare_draft_area( + $draftitemid, + $this->assignment->get_context()->id, + self::COMPONENT_NAME, + self::ASSIGNSUBMISSION_DTA_FILEAREA_TEST, + 0, + ['subdirs' => 0] + ); + + $defaultvalues[self::ASSIGNSUBMISSION_DTA_DRAFT_FILEAREA_TEST] = $draftitemid; + } + + /** + * Save settings of assignment submission settings + * + * @param stdClass $data + * @return bool + */ + public function save_settings(stdClass $data): bool { + + // If the assignment has no filemanager for our plugin just leave. + $draftfilemanagerid = self::ASSIGNSUBMISSION_DTA_DRAFT_FILEAREA_TEST; + if (!isset($data->$draftfilemanagerid)) { + return true; + } + + // Store files from draft filearea to final one. + file_save_draft_area_files( + // Form-unique element id of draft filemanager from the edit. + $data->$draftfilemanagerid, + // Id of the assignment in edit. + $this->assignment->get_context()->id, + self::COMPONENT_NAME, + self::ASSIGNSUBMISSION_DTA_FILEAREA_TEST, + 0 + ); + + // Get files from proper filearea. + $fs = get_file_storage(); + $files = $fs->get_area_files( + // Id of the current assignment. + $this->assignment->get_context()->id, + self::COMPONENT_NAME, + self::ASSIGNSUBMISSION_DTA_FILEAREA_TEST, + 0, + 'id', + false + ); + + // Check if a file was uploaded. + if (empty($files)) { + \core\notification::error(get_string("no_testfile_warning", self::COMPONENT_NAME)); + return true; + } + + // Get the file. + $file = reset($files); + + // Send file to backend. + return DtaBackendUtils::sendtestconfigtobackend($this->assignment, $file); + } + + /** + * Add elements to submission form + * + * @param mixed $submissionorgrade stdClass|null submission or grade to show in the form + * @param MoodleQuickForm $mform form for adding elements + * @param stdClass $data data for filling the elements + * @param int $userid current user + * @return bool form elements added + */ + public function get_form_elements_for_user($submissionorgrade, MoodleQuickForm $mform, stdClass $data, $userid): bool { + // Prepare submission filearea. + $data = file_prepare_standard_filemanager( + $data, + 'tasks', + $this->get_file_options(false), + $this->assignment->get_context(), + self::COMPONENT_NAME, + self::ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION, + $submissionorgrade ? $submissionorgrade->id : 0 + ); + + // Add filemanager to form. + $mform->addElement( + 'filemanager', + // Form-unique identifier. + 'tasks_filemanager', + // Label to show next to the filemanager. + get_string("submission_label", self::COMPONENT_NAME), + // Attributes. + null, + // Options. + $this->get_file_options(false) + ); + + // Add help button. + $mform->addHelpButton( + // Related form item. + "tasks_filemanager", + // Key. + "submission_label", + // Language file. + self::COMPONENT_NAME + ); + + return true; + } + + /** + * Determines if a submission file area contains any files. + * @param stdClass $submission submission to check + * @return bool true if file count is zero + */ + public function is_empty(stdClass $submission): bool { + return $this->count_files($submission->id, self::ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION) == 0; + } + + /** + * Counts the number of files in a filearea + * + * @param int $submissionid submission id to check + * @param string $areaid filearea id to count + * @return int number of files submitted in the filearea + */ + private function count_files(int $submissionid, $areaid) { + $fs = get_file_storage(); + $files = $fs->get_area_files($this->assignment->get_context()->id, + self::COMPONENT_NAME, + $areaid, + $submissionid, + 'id', + false); + + return count($files); + } + + /** + * Save data to the database + * + * @param stdClass $submission + * @param stdClass $data + * @return bool + */ + public function save(stdClass $submission, stdClass $data) { + $data = file_postupdate_standard_filemanager( + $data, + 'tasks', + $this->get_file_options(false), + $this->assignment->get_context(), + self::COMPONENT_NAME, + self::ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION, + $submission->id + ); + + // If submission is empty leave directly. + if ($this->is_empty($submission)) { + return true; + } + + // Get submitted files. + $fs = get_file_storage(); + $files = $fs->get_area_files( + // Id of current assignment. + $this->assignment->get_context()->id, + self::COMPONENT_NAME, + self::ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION, + $submission->id, + 'id', + false + ); + + // Check if a file is uploaded. + if (empty($files)) { + \core\notification::error(get_string("no_submissionfile_warning", self::COMPONENT_NAME)); + return true; + } + + // Get the file. + $file = reset($files); + + // Send file to backend. + $response = DtaBackendUtils::sendsubmissiontobackend($this->assignment, $submission->id, $file); + + // With a null response, return an error. + if (is_null($response)) { + return false; + } + + // Convert received json to valid class instances. + $resultsummary = DtaResultSummary::decodejson($response); + + // Persist new results to database. + DbUtils::storeresultsummarytodatabase($this->assignment->get_instance()->id, $submission->id, $resultsummary); + + return true; + } + + /** + * Display a short summary of the test results of the submission + * This is diplayed as default view, with the option to expand + * to the full detailed results. + * + * @param stdClass $submission to show + * @param bool $showviewlink configuration variable to show expand option + * @return string summary results html + */ + public function view_summary(stdClass $submission, & $showviewlink) { + $showviewlink = true; + + return view_submission_utils::generatesummaryhtml( + $this->assignment->get_instance()->id, + $submission->id + ); + } + + /** + * Display detailed results + * + * @param stdClass $submission the submission the results are shown for. + * @return string detailed results html + */ + public function view(stdClass $submission) { + return view_submission_utils::generatedetailhtml( + $this->assignment->get_instance()->id, + $submission->id + ); + } + + /** + * generate array of allowed filetypes to upload. + * + * @param bool $settings switch to define if list for assignment settings + * or active submission should be returned + * + * @return array + */ + private function get_file_options(bool $settings): array { + $fileoptions = [ + 'subdirs' => 0, + "maxfiles" => 1, + 'accepted_types' => ($settings + ? [".txt"] + : [ + ".txt", + ".zip", + ]), + 'return_types' => FILE_INTERNAL, + ]; + return $fileoptions; + } + + /** + * Get file areas returns a list of areas this plugin stores files + * @return array - An array of fileareas (keys) and descriptions (values) + */ + public function get_file_areas() { + return [ + self::ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION => get_string("dta_submissions_fa", self::COMPONENT_NAME), + self::ASSIGNSUBMISSION_DTA_FILEAREA_TEST => get_string("dta_tests_fa", self::COMPONENT_NAME), + ]; + } + + /** + * Produce a list of files suitable for export that represent this feedback or submission + * + * @param stdClass $submission The submission + * @param stdClass $user The user record - unused + * @return array - return an array of files indexed by filename + */ + public function get_files(stdClass $submission, stdClass $user) { + $result = []; + $fs = get_file_storage(); + $files = $fs->get_area_files($this->assignment->get_context()->id, + self::COMPONENT_NAME, + self::ASSIGNSUBMISSION_DTA_FILEAREA_SUBMISSION, + $submission->id, + 'timemodified', + false); + + foreach ($files as $file) { + // Do we return the full folder path or just the file name? + if (isset($submission->exportfullpath) && $submission->exportfullpath == false) { + $result[$file->get_filename()] = $file; + } else { + $result[$file->get_filepath().$file->get_filename()] = $file; + } + } + return $result; + } + + /** + * The plugin is beeing uninstalled - cleanup + * + * @return bool + */ + public function delete_instance() { + DbUtils::uninstallplugincleanup(); + + return true; + } +} diff --git a/dta/models/DtaResult.php b/dta/models/DtaResult.php new file mode 100644 index 0000000000000000000000000000000000000000..bd7d4b0842ac26d8a94145426fcb096c0014b0ce --- /dev/null +++ b/dta/models/DtaResult.php @@ -0,0 +1,247 @@ +<?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/>. + +/** + * entity classes for DTA submission plugin result summary and test results + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ +defined('MOODLE_INTERNAL') || die(); + +/** + * entity class for DTA submission plugin result + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ +class DtaResult { + + /** + * Broadly used in logic, parametrized for easier change. + */ + const COMPONENT_NAME = "assignsubmission_dta"; + + /** + * @var $packagename Package name of the test. + */ + public $packagename; + + /** + * @var $classname Unit name of the test. + */ + public $classname; + + /** + * @var $name Name of the test. + */ + public $name; + + /** + * @var $state State is defined like below + * + * 0 UNKNOWN + * 1 SUCCESS + * 2 FAILURE + * 3 COMPILATIONERROR + */ + public $state; + + /** + * @var $failuretype Type of test failure if applicable, "" otherwise. + */ + public $failuretype; + + /** + * @var $failurereason Reason of test failure if applicable, "" otherwise. + */ + public $failurereason; + + /** + * @var $stacktrace Stack trace of test failure if applicable, "" otherwise. + */ + public $stacktrace; + + /** + * @var $columnnumber Column number of compile failure if applicable, "" otherwise. + */ + public $columnnumber; + /** + * @var $linenumber Line number of compile failure if applicable, "" otherwise. + */ + public $linenumber; + /** + * @var $position Position of compile failure if applicable, "" otherwise. + */ + public $position; + + /** + * Returns the name of a state with the given number of display. + * @param int $state number of the state + * @return string name of state as defined + */ + public static function getstatename(int $state): string { + if ($state == 1) { + return get_string("tests_successful", self::COMPONENT_NAME); + } else if ($state == 2) { + return get_string("failures", self::COMPONENT_NAME); + } else if ($state == 3) { + return get_string("compilation_errors", self::COMPONENT_NAME); + } else { + return get_string("unknown_state", self::COMPONENT_NAME); + } + } +} + +/** + * entity class for DTA submission plugin result + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ +class DtaResultSummary { + + /** + * @var $timestamp Result timestamp for chronological ordering and deletion of previous results. + */ + public $timestamp; + + /** + * @var $globalstacktrace Global stack trace if applicable, "" otherwise. + */ + public $globalstacktrace; + + /** + * @var $successfultestcompetencies Successfully tested competencies according to tests and weights, "" otherwise. + */ + public $successfultestcompetencies; + /** + * @var overalltestcompetencies Overall tested competencies according to tests and weights, "" otherwise. + */ + public $overalltestcompetencies; + /** + * @var results List of detail results. + */ + public $results; + + /** + * Decodes the JSON result summary returned by the backend service call into the plugin PHP data structure. + * @param string $jsonstring jsonString containing DtaResultSummary + * @return DtaResultSummary the result summary + */ + public static function decodejson(string $jsonstring): DtaResultSummary { + $response = json_decode($jsonstring); + + $summary = new DtaResultSummary(); + $summary->timestamp = $response->timestamp; + $summary->globalstacktrace = $response->globalstacktrace; + + $summary->successfultestcompetencies = $response->successfulTestCompetencyProfile; + $summary->overalltestcompetencies = $response->overallTestCompetencyProfile; + + $summary->results = self::decodejsonresultarray($response->results); + + return $summary; + } + + /** + * Decodes the array of JSON detail results returned by the backend service call into the plugin PHP data structure. + * @param array $jsonarray decoded json array of results array + * @return array of DtaResult + */ + private static function decodejsonresultarray($jsonarray): array { + $ret = []; + foreach ($jsonarray as $entry) { + $value = new DtaResult(); + $value->packagename = $entry->packageName; + $value->classname = $entry->className; + $value->name = $entry->name; + + $value->state = $entry->state; + + $value->failuretype = $entry->failureType; + $value->failurereason = $entry->failureReason; + $value->stacktrace = $entry->stacktrace; + + $value->columnnumber = $entry->columnNumber; + $value->linenumber = $entry->lineNumber; + $value->position = $entry->position; + + $ret[] = $value; + } + return $ret; + } + + + /** + * Returns the number of detail results attached to the summary. + * @return int count of occurences + */ + public function resultcount(): int { + return count($this->results); + } + + /** + * Returns the number of detail results with the given state attached to the summary. + * @param int $state state ordinal number + * @return int count of occurences provided state has + */ + public function stateoccurencecount(int $state): int { + $num = 0; + foreach ($this->results as $r) { + if ($r->state == $state) { + $num++; + } + } + return $num; + } + + /** + * Returns the number of detail results with compilation errors attached to the summary. + * @return int count of occurences + */ + public function compilationerrorcount(): int { + return $this->stateoccurencecount(3); + } + + /** + * Returns the number of detail results with test failures attached to the summary. + * @return int count of occurences + */ + public function failedcount(): int { + return $this->stateoccurencecount(2); + } + + /** + * Returns the number of detail results with successful tests attached to the summary. + * @return int count of occurences + */ + public function successfulcount(): int { + return $this->stateoccurencecount(1); + } + + /** + * Returns the number of detail results with an unknown result - mostly due to compile errors - attached to the summary. + * @return int count of occurences + */ + public function unknowncount(): int { + return $this->stateoccurencecount(0); + } + +} diff --git a/dta/settings.php b/dta/settings.php new file mode 100644 index 0000000000000000000000000000000000000000..fe1071ae451edaea9408c8d23f284e46089ea221 --- /dev/null +++ b/dta/settings.php @@ -0,0 +1,34 @@ +<?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/>. + +/** + * This file defines the admin settings for this plugin + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ + +defined('MOODLE_INTERNAL') || die(); + + +$settings->add(new admin_setting_configcheckbox("assignsubmission_dta/default", + new lang_string("default", "assignsubmission_dta"), + new lang_string("default_help", "assignsubmission_dta"), 0)); + +$settings->add(new admin_setting_configtext("assignsubmission_dta/backendHost", + new lang_string("backendHost", "assignsubmission_dta"), + new lang_string("backendHost_help", "assignsubmission_dta"), "http://dtabackend:8080")); diff --git a/dta/styles.css b/dta/styles.css new file mode 100644 index 0000000000000000000000000000000000000000..9afdd3162f41347d83e644e2991d2a4086f9e17d --- /dev/null +++ b/dta/styles.css @@ -0,0 +1,74 @@ +/* Prevent word breaking in the grading table */ +.dtaSubmissionSummary { + white-space: nowrap; +} + +.dtaSubmissionSummary, +.dtaSubmissionDetails { + margin-top: 15px; +} + +/* empty div between summary and detail table */ +.dtaSpacer { + margin-top: 30px; +} + +/**************************************************************** +* Layout for the Detail view +****************************************************************/ + +.dtaTable { + display: inline-block; + max-width: 100%; + overflow: auto; + background: white !important; + border-radius: .1rem; + box-shadow: 0 .2rem .5rem rgba(0,0,0,.05),0 0 .05rem rgba(0,0,0,.1); + overflow-x: hidden; +} + +.dtaTableHeaderRow { + font-weight: bold; + color: white !important; + background-color: gray !important; +} + +.dtaTableRow { + background-color: unset !important; + border-top: .05rem solid lightgray; +} + +.dtaTableHeaderRow th, +.dtaTableRow td { + padding: .9375em 1.25em; +} + +.dtaStacktraceDetails { + max-height: 300px; + max-width: 70%; + overflow: auto; +} + +.dtaResultUnknown { + border-left: 10px solid gray; +} + +.dtaResultSuccess { + border-left: 10px solid green; +} + +.dtaResultFailure { + border-left: 10px solid orange; +} + +.dtaResultCompilationError { + border-left: 10px solid red; +} + +.dtaTableRow:hover { + background-color: lightgray !important; +} + +.dtaTableSpacer { + border-bottom: 2px solid darkgray; +} diff --git a/dta/version.php b/dta/version.php new file mode 100644 index 0000000000000000000000000000000000000000..fd56733d18bfe98d7b7ccbd0993c01eb22b60983 --- /dev/null +++ b/dta/version.php @@ -0,0 +1,31 @@ +<?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/>. + +/** + * This file contains the version information for the onlinetext DTA plugin + * + * @package assignsubmission_dta + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @copyright Gero Lueckemeyer and student project teams + */ + +defined('MOODLE_INTERNAL') || die(); + +$plugin->version = 2023123001; +$plugin->requires = 2020061525; // Moodle 3.9 LTS. Older unsupported versions from the 3.x branch should also work. +$plugin->component = 'assignsubmission_dta'; +$plugin->maturity = MATURITY_STABLE; +$plugin->release = "3.1.0"; diff --git a/teacher-dta.txt b/teacher-dta.txt new file mode 100644 index 0000000000000000000000000000000000000000..276c40ca98b5f7036c69b17a5a84ebffe77adca8 --- /dev/null +++ b/teacher-dta.txt @@ -0,0 +1 @@ +dtt::https://transfer.hft-stuttgart.de/gitlab/dtt/example_openjdk11-junit5-calculator-test.git::none::none::hftstuttgart/dta-jdk17-junit5-testrunner:latest diff --git a/test/privacy/apicompliance.php b/test/privacy/apicompliance.php new file mode 100644 index 0000000000000000000000000000000000000000..121ad630786845a1575b9cb058284d6dd6279770 --- /dev/null +++ b/test/privacy/apicompliance.php @@ -0,0 +1,99 @@ +<?php + +// Set this if you want to run the script for one component only. Otherwise leave empty. +$CHECK_COMPONENT = ''; + +define('CLI_SCRIPT', true); + +require_once('config.php'); + +$user = \core_user::get_user(2); + +\core\session\manager::init_empty_session(); +\core\session\manager::set_user($user); + +$rc = new \ReflectionClass(\core_privacy\manager::class); +$rcm = $rc->getMethod('get_component_list'); +$rcm->setAccessible(true); + +$manager = new \core_privacy\manager(); +$components = $rcm->invoke($manager); + +$list = (object) [ + 'good' => [], + 'bad' => [], +]; + +foreach ($components as $component) { + if ($CHECK_COMPONENT && $component !== $CHECK_COMPONENT) { + continue; + } + $compliant = $manager->component_is_compliant($component); + if ($compliant) { + $list->good[] = $component; + } else { + $list->bad[] = $component; + } +} + +echo "The following plugins are not compliant:\n"; +echo "=> " . implode("\n=> ", array_values($list->bad)) . "\n"; + +echo "\n"; +echo "Testing the compliant plugins:\n"; +foreach ($list->good as $component) { + $classname = \core_privacy\manager::get_provider_classname_for_component($component); + echo "== {$component} ($classname) ==\n"; + if (check_implements($component, \core_privacy\local\metadata\null_provider::class)) { + echo " Claims not to store any data with reason:\n"; + echo " '" . get_string($classname::get_reason(), $component) . "'\n"; + } + else if (check_implements($component, \core_privacy\local\metadata\provider::class)) { + $collection = new \core_privacy\local\metadata\collection($component); + $classname::get_metadata($collection); + $count = count($collection->get_collection()); + echo " Found {$count} items of metadata\n"; + if (empty($count)) { + echo "!!! No metadata found!!! This an error.\n"; + } + + if (check_implements($component, \core_privacy\local\request\user_preference_provider::class)) { + $userprefdescribed = false; + foreach ($collection->get_collection() as $item) { + if ($item instanceof \core_privacy\local\metadata\types\user_preference) { + $userprefdescribed = true; + echo " ".$item->get_name()." : ".get_string($item->get_summary(), $component) . "\n"; + } + } + if (!$userprefdescribed) { + echo "!!! User preference found, but was not described in metadata\n"; + } + } + + if (check_implements($component, \core_privacy\local\request\core_user_data_provider::class)) { + // No need to check the return type - it's enforced by the interface. + $contextlist = $classname::get_contexts_for_userid($user->id); + $approvedcontextlist = new \core_privacy\local\request\approved_contextlist($user, $contextlist->get_component(), $contextlist->get_contextids()); + if (count($approvedcontextlist)) { + $classname::export_user_data($approvedcontextlist); + echo " Successfully ran a test export\n"; + } else { + echo " Nothing to export.\n"; + } + } + if (check_implements($component, \core_privacy\local\request\shared_data_provider::class)) { + echo " This is a shared data provider\n"; + } + } +} + +echo "\n\n== Done ==\n"; + +function check_implements($component, $interface) { + $manager = new \core_privacy\manager(); + $rc = new \ReflectionClass(\core_privacy\manager::class); + $rcm = $rc->getMethod('component_implements'); + $rcm->setAccessible(true); + + return $rcm->invoke($manager, $component, $interface); +} \ No newline at end of file diff --git a/test/privacy/deletion.php b/test/privacy/deletion.php new file mode 100644 index 0000000000000000000000000000000000000000..8fdb75ce0023ad73b692d4cae61f6dbdb40a58ba --- /dev/null +++ b/test/privacy/deletion.php @@ -0,0 +1,70 @@ +<?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/>. + +define('CLI_SCRIPT', true); +require_once('config.php'); +require_once("$CFG->libdir/clilib.php"); + +list($options, $unrecognized) = cli_get_params( + [ + 'username' => '', + 'userid' => '', + ], + [] +); + +$user = null; +$username = $options['username']; +$userid = $options['userid']; + +if (!empty($options['username'])) { + $user = \core_user::get_user_by_username($options['username']); +} else if (!empty($options['userid'])) { + $user = \core_user::get_user($options['userid']); +} + +while (empty($user)) { + if (!empty($username)) { + echo "Unable to find a user with username '{$username}'.\n"; + echo "Try again.\n"; + } else if (!empty($userid)) { + echo "Unable to find a user with userid '{$userid}'.\n"; + echo "Try again.\n"; + } + $username = readline("Username: "); + $user = \core_user::get_user_by_username($username); +} + +echo "Processing delete for " . fullname($user) . "\n"; + +\core\session\manager::init_empty_session(); +\core\session\manager::set_user($user); + +$manager = new \core_privacy\manager(); + +$approvedlist = new \core_privacy\local\request\contextlist_collection($user->id); + +$trace = new text_progress_trace(); +$contextlists = $manager->get_contexts_for_userid($user->id, $trace); +foreach ($contextlists as $contextlist) { + $approvedlist->add_contextlist(new \core_privacy\local\request\approved_contextlist( + $user, + $contextlist->get_component(), + $contextlist->get_contextids() + )); +} + +$manager->delete_data_for_user($approvedlist, $trace); \ No newline at end of file diff --git a/test/privacy/export.php b/test/privacy/export.php new file mode 100644 index 0000000000000000000000000000000000000000..f56d61711f9fac857730470774ac5551a29d5ecd --- /dev/null +++ b/test/privacy/export.php @@ -0,0 +1,87 @@ +<?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/>. + +/** + * Helper utility to perform a test export. + * + * @copyright 2018 Andrew Nicols <andrew@nicols.co.uk> + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +define('CLI_SCRIPT', true); +require_once('config.php'); +require_once("$CFG->libdir/clilib.php"); + +list($options, $unrecognized) = cli_get_params( + [ + 'username' => '', + 'userid' => '', + ], + [] +); + +$user = null; +$username = $options['username']; +$userid = $options['userid']; + +if (!empty($options['username'])) { + $user = \core_user::get_user_by_username($options['username']); +} else if (!empty($options['userid'])) { + $user = \core_user::get_user($options['userid']); +} + +while (empty($user)) { + if (!empty($username)) { + echo "Unable to find a user with username '{$username}'.\n"; + echo "Try again.\n"; + } else if (!empty($userid)) { + echo "Unable to find a user with userid '{$userid}'.\n"; + echo "Try again.\n"; + } + $username = readline("Username: "); + $user = \core_user::get_user_by_username($username); +} + +echo "Processing export for " . fullname($user) . "\n"; + +\core\session\manager::init_empty_session(); +\core\session\manager::set_user($user); + +$PAGE = new moodle_page(); +$OUTPUT = new core_renderer($PAGE, RENDERER_TARGET_GENERAL); + +$manager = new \core_privacy\manager(); + +$approvedlist = new \core_privacy\local\request\contextlist_collection($user->id); + +$contextlists = $manager->get_contexts_for_userid($user->id); +foreach ($contextlists as $contextlist) { + $approvedlist->add_contextlist(new \core_privacy\local\request\approved_contextlist( + $user, + $contextlist->get_component(), + $contextlist->get_contextids() + )); +} + +$exportedcontent = $manager->export_user_data($approvedlist); +$basedir = make_temp_directory('privacy'); +$exportpath = make_unique_writable_directory($basedir, true); +$fp = get_file_packer(); +$fp->extract_to_pathname($exportedcontent, $exportpath); + +echo "\n"; +echo "== File export was uncompressed to {$exportpath}\n"; +echo "============================================================================\n"; \ No newline at end of file