diff --git a/.bashrc b/.bashrc new file mode 100644 index 0000000..3b9ccf2 --- /dev/null +++ b/.bashrc @@ -0,0 +1,6 @@ +PS1='\[\033[01;31m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ' + +alias ls='ls --color=auto' +alias ll='ls -l' +alias la='ls -A' +alias l='ls -lACF' diff --git a/.gitignore b/.gitignore index 62c8935..1299f3e 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,44 @@ -.idea/ \ No newline at end of file +# Byte-compiled / optimized / DLL files +dist +build +__pycache__ +*.py[cod] +*$py.class +*.swp +*.egg-info +_build +.tox +.coverage +coverage + +# Translations +*.mo +*.pot + +# Jupyter Notebook +.ipynb_checkpoints + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# PyCharm project settings +.idea + +# VSCode project settings +.vscode + +# Local data +secrets.py +*.log +media/ +# Virtualenv +env/ +venv/ +db.sqlite3 + +# Don't git index +whoosh_index/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..49bdcaf --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,27 @@ +stages: + - test + - quality-assurance + +py38: + stage: test + image: python:3.8-alpine + before_script: + - apk add --no-cache gcc libc-dev libffi-dev libmagic libxml2-dev libxslt-dev libxml2-dev libxslt-dev + - pip install tox --no-cache-dir + script: tox -e py38 + +py39: + stage: test + image: python:3.9-alpine + before_script: + - apk add --no-cache gcc libc-dev libffi-dev libmagic libxml2-dev libxslt-dev libxml2-dev libxslt-dev + - pip install tox --no-cache-dir + script: tox -e py39 + +linters: + stage: quality-assurance + image: python:3-alpine + before_script: + - pip install tox --no-cache-dir + script: tox -e linters + allow_failure: true diff --git a/.htaccess b/.htaccess deleted file mode 100644 index 73496ca..0000000 --- a/.htaccess +++ /dev/null @@ -1,4 +0,0 @@ -Options +FollowSymlinks -Options -Indexes -RewriteEngine On -RewriteRule ^(.*)$ dispatcher.php?path=$1 [QSA,L] diff --git a/Dockerfile b/Dockerfile index c550e95..9be9d7f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,39 +1,37 @@ -FROM php:7.3-apache as plateforme-builder +FROM python:3-alpine -# Enabling apache rewrite mod -RUN a2enmod rewrite +ENV PYTHONUNBUFFERED 1 +ENV DJANGO_ALLOW_ASYNC_UNSAFE 1 -RUN apt clean && apt update && apt upgrade -y +# Install LaTeX requirements +RUN apk add --no-cache gettext nginx gcc libc-dev libffi-dev libxml2-dev libxslt-dev postgresql-dev libmagic -# Install MySQL drivers -RUN docker-php-ext-install pdo_mysql \ - && docker-php-ext-enable pdo_mysql +RUN apk add --no-cache bash -# Install zip utilities -RUN apt install -y libzip-dev zip \ - && docker-php-ext-configure zip --with-libzip \ - && docker-php-ext-install zip \ - && docker-php-ext-enable zip +RUN mkdir /code +WORKDIR /code +COPY requirements.txt /code/requirements.txt +RUN pip install -r requirements.txt psycopg2-binary sympasoap --no-cache-dir -# Setup locales -RUN apt install locales locales-all -y && locale-gen fr_FR.UTF-8 -ENV LANG fr_FR.UTF-8 -ENV LANGUAGE fr_FR:fr -ENV LC_ALL fr_FR.UTF-8 +COPY . /code/ -# Setup timezone -RUN echo Europe/Paris > /etc/timezone \ - && ln -sf /usr/share/zoneinfo/Europe/Paris /etc/localtime \ - && dpkg-reconfigure -f noninteractive tzdata +RUN python manage.py collectstatic --noinput && \ + python manage.py compilemessages && \ + python manage.py migrate && \ + python manage.py loaddata initial -# Setup mailing -RUN apt install -yq msmtp ca-certificates -COPY setup/msmtprc /etc/msmtprc -RUN echo "sendmail_path=msmtp -t" >> /usr/local/etc/php/conf.d/php-sendmail.ini +# Configure nginx +RUN mkdir /run/nginx +RUN ln -sf /dev/stdout /var/log/nginx/access.log && ln -sf /dev/stderr /var/log/nginx/error.log +RUN ln -sf /code/nginx_corres2math.conf /etc/nginx/conf.d/corres2math.conf +RUN rm /etc/nginx/conf.d/default.conf -# Setting environment -ENV CORRES2MATH_LOCAL_PATH /var/www/html -ENV CORRES2MATH_MAIL_DOMAIN correspondances-maths.fr -ENV CORRES2MATH_URL_BASE https://inscription.correspondances-maths.fr +RUN crontab /code/corres2math.cron -RUN chmod 0777 /var/www/html +# With a bashrc, the shell is better +RUN ln -s /code/.bashrc /root/.bashrc + +ENTRYPOINT ["/code/entrypoint.sh"] +EXPOSE 80 + +CMD ["./manage.py", "shell_plus", "--ptpython"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..39d7692 --- /dev/null +++ b/README.md @@ -0,0 +1,70 @@ +# Plateforme des Correspondances des Jeunes Mathématicien·nes + +[![pipeline status](https://gitlab.com/animath/si/plateforme-corres2math/badges/master/pipeline.svg)](https://gitlab.com/animath/si/plateforme-corres2math/-/commits/master) +[![coverage report](https://gitlab.com/animath/si/plateforme-corres2math/badges/master/coverage.svg)](https://gitlab.com/animath/si/plateforme-corres2math/-/commits/master) + +La plateforme des Correspondances des Jeunes Mathématicien·nes est née pour la seconde édition en 2019 de l'action. +D'abord codée en PHP, elle a subi une refonte totale en Python, à l'aide du framework Web [Django](https://www.djangoproject.com/). + +Cette plateforme permet aux participants et encadrants de s'inscrire et de déposer leurs autorisations nécessaires. +Ils pourront ensuite déposer leurs solutions et notes de synthèse pour le premier tour en temps voulu. La plateforme +offre également un accès pour les organisateurs et les jurys leur permettant de communiquer avec les équipes et de +récupérer les documents nécessaires. + +Un wiki plus détaillé arrivera ultérieurement. L'interface organisateur et jury est vouée à être plus poussée. + +L'instance de production est disponible à l'adresse [inscription.correspondances-maths.fr](https://inscription.correspondances-maths.fr). + +## Installation + +Le plus simple pour installer la plateforme est d'utiliser l'image Docker incluse, qui fait tourner un serveur Nginx +exposé sur le port 80 avec le serveur Django. Ci-dessous une configuration Docker-Compose, à adapter selon vos besoins : + +```yaml + plateforme-corres2math: + build: https://gitlab.com/animath/si/plateforme-corres2math.git + links: + - postgres + ports: + - "80:80" + env_file: + - ./inscription-corres2math.env + volumes: + # - ./inscription-corres2math:/code + - ./inscription-corres2math/media:/code/media +``` + +Le volume `/code` n'est à ajouter uniquement en développement, et jamais en production. + +Il faut remplir les variables d'environnement suivantes : + +```env +CORRES2MATH_STAGE= # dev ou prod +DJANGO_DB_TYPE= # MySQL, PostgreSQL ou SQLite (par défaut) +DJANGO_DB_HOST= # Hôte de la base de données +DJANGO_DB_NAME= # Nom de la base de données +DJANGO_DB_USER= # Utilisateur de la base de données +DJANGO_DB_PASSWORD= # Mot de passe pour accéder à la base de données +SMTP_HOST= # Hôte SMTP pour l'envoi de mails +SMTP_PORT=465 # Port du serveur SMTP +SMTP_HOST_USER= # Utilisateur du compte SMTP +SMTP_HOST_PASSWORD= # Mot de passe du compte SMTP +FROM_EMAIL=contact@correspondances-maths.fr # Nom de l'expéditeur des mails +SERVER_EMAIL=contact@correspondances-maths.fr # Adresse e-mail expéditrice +SYMPA_URL=lists.example.com # Serveur Sympa à utiliser +SYMPA_EMAIL= # Adresse e-mail du compte administrateur de Sympa +SYMPA_PASSWORD= # Mot de passe du compte administrateur de Sympa +SYNAPSE_PASSWORD= # Mot de passe du robot Matrix +``` + +Si le type de base de données sélectionné est SQLite, la variable `DJANGO_DB_HOST` sera utilisée en guise de chemin vers +le fichier de base de données (par défaut, `db.sqlite3`). + +En développement, il est recommandé d'utiliser SQLite pour des raisons de simplicité. Les paramètres de mail ne seront +pas utilisés, et les mails qui doivent être envoyés seront envoyés dans la console. Les intégrations mail et Matrix +seront également désactivées. + +En production, il est recommandé de ne pas utiliser SQLite pour des raisons de performances. + +La dernière différence entre le développment et la production est qu'en développement, chaque modification d'un fichier +est détectée et le serveur se relance automatiquement dès lors. \ No newline at end of file diff --git a/apps/api/__init__.py b/apps/api/__init__.py new file mode 100644 index 0000000..08884cb --- /dev/null +++ b/apps/api/__init__.py @@ -0,0 +1 @@ +default_app_config = 'api.apps.APIConfig' diff --git a/apps/api/apps.py b/apps/api/apps.py new file mode 100644 index 0000000..6e03468 --- /dev/null +++ b/apps/api/apps.py @@ -0,0 +1,10 @@ +from django.apps import AppConfig +from django.utils.translation import gettext_lazy as _ + + +class APIConfig(AppConfig): + """ + Manage the inscription through a JSON API. + """ + name = 'api' + verbose_name = _('API') diff --git a/apps/api/serializers.py b/apps/api/serializers.py new file mode 100644 index 0000000..0b364e0 --- /dev/null +++ b/apps/api/serializers.py @@ -0,0 +1,16 @@ +from django.contrib.auth.models import User +from rest_framework import serializers + + +class UserSerializer(serializers.ModelSerializer): + """ + Serialize a User object into JSON. + """ + class Meta: + model = User + exclude = ( + 'username', + 'password', + 'groups', + 'user_permissions', + ) diff --git a/apps/api/tests.py b/apps/api/tests.py new file mode 100644 index 0000000..149a76d --- /dev/null +++ b/apps/api/tests.py @@ -0,0 +1,24 @@ +from unittest.case import skipIf + +from django.conf import settings +from django.contrib.auth.models import User +from django.test import TestCase + + +class TestAPIPages(TestCase): + def setUp(self): + self.user = User.objects.create_superuser( + username="admin", + password="apitest", + email="", + ) + self.client.force_login(self.user) + + def test_user_page(self): + response = self.client.get("/api/user/") + self.assertEqual(response.status_code, 200) + + @skipIf("logs" not in settings.INSTALLED_APPS, reason="logs app is not used") + def test_logs_page(self): + response = self.client.get("/api/logs/") + self.assertEqual(response.status_code, 200) diff --git a/apps/api/urls.py b/apps/api/urls.py new file mode 100644 index 0000000..982085a --- /dev/null +++ b/apps/api/urls.py @@ -0,0 +1,23 @@ +from django.conf import settings +from django.conf.urls import include, url +from rest_framework import routers + +from .viewsets import UserViewSet + +# Routers provide an easy way of automatically determining the URL conf. +# Register each app API router and user viewset +router = routers.DefaultRouter() +router.register('user', UserViewSet) + +if "logs" in settings.INSTALLED_APPS: + from logs.api.urls import register_logs_urls + register_logs_urls(router, "logs") + +app_name = 'api' + +# Wire up our API using automatic URL routing. +# Additionally, we include login URLs for the browsable API. +urlpatterns = [ + url('^', include(router.urls)), + url('^api-auth/', include('rest_framework.urls', namespace='rest_framework')), +] diff --git a/apps/api/viewsets.py b/apps/api/viewsets.py new file mode 100644 index 0000000..757993d --- /dev/null +++ b/apps/api/viewsets.py @@ -0,0 +1,17 @@ +from django.contrib.auth.models import User +from django_filters.rest_framework import DjangoFilterBackend +from rest_framework.filters import SearchFilter +from rest_framework.viewsets import ModelViewSet + +from .serializers import UserSerializer + + +class UserViewSet(ModelViewSet): + """ + Display list of users. + """ + queryset = User.objects.order_by("id").all() + serializer_class = UserSerializer + filter_backends = [DjangoFilterBackend, SearchFilter] + filterset_fields = ['id', 'first_name', 'last_name', 'email', 'is_superuser', 'is_staff', 'is_active', ] + search_fields = ['$first_name', '$last_name', ] diff --git a/apps/eastereggs/__init__.py b/apps/eastereggs/__init__.py new file mode 100644 index 0000000..f5d007b --- /dev/null +++ b/apps/eastereggs/__init__.py @@ -0,0 +1 @@ +default_app_config = 'eastereggs.apps.EastereggsConfig' diff --git a/apps/eastereggs/apps.py b/apps/eastereggs/apps.py new file mode 100644 index 0000000..93a00a2 --- /dev/null +++ b/apps/eastereggs/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class EastereggsConfig(AppConfig): + name = 'eastereggs' diff --git a/apps/eastereggs/migrations/__init__.py b/apps/eastereggs/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/eastereggs/templates/eastereggs/xp.html b/apps/eastereggs/templates/eastereggs/xp.html new file mode 100644 index 0000000..00f67b5 --- /dev/null +++ b/apps/eastereggs/templates/eastereggs/xp.html @@ -0,0 +1,19 @@ +{% extends "index.html" %} + +{% block content %} +
+{% include "eastereggs/xp_modal.html" %} +{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/eastereggs/templates/eastereggs/xp_modal.html b/apps/eastereggs/templates/eastereggs/xp_modal.html new file mode 100644 index 0000000..c456517 --- /dev/null +++ b/apps/eastereggs/templates/eastereggs/xp_modal.html @@ -0,0 +1,20 @@ +{% load crispy_forms_filters i18n %} + + \ No newline at end of file diff --git a/apps/eastereggs/urls.py b/apps/eastereggs/urls.py new file mode 100644 index 0000000..64200f1 --- /dev/null +++ b/apps/eastereggs/urls.py @@ -0,0 +1,8 @@ +from django.urls import path +from django.views.generic import TemplateView + +app_name = "eastereggs" + +urlpatterns = [ + path("xp/", TemplateView.as_view(template_name="eastereggs/xp.html")), +] diff --git a/apps/logs/__init__.py b/apps/logs/__init__.py new file mode 100644 index 0000000..58ee5b0 --- /dev/null +++ b/apps/logs/__init__.py @@ -0,0 +1,4 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +default_app_config = 'logs.apps.LogsConfig' diff --git a/apps/logs/api/__init__.py b/apps/logs/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/logs/api/serializers.py b/apps/logs/api/serializers.py new file mode 100644 index 0000000..c76e3a5 --- /dev/null +++ b/apps/logs/api/serializers.py @@ -0,0 +1,19 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from rest_framework import serializers + +from ..models import Changelog + + +class ChangelogSerializer(serializers.ModelSerializer): + """ + REST API Serializer for Changelog types. + The djangorestframework plugin will analyse the model `Changelog` and parse all fields in the API. + """ + + class Meta: + model = Changelog + fields = '__all__' + # noinspection PyProtectedMember + read_only_fields = [f.name for f in model._meta.get_fields()] # Changelogs are read-only protected diff --git a/apps/logs/api/urls.py b/apps/logs/api/urls.py new file mode 100644 index 0000000..9a0ceaa --- /dev/null +++ b/apps/logs/api/urls.py @@ -0,0 +1,11 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from .views import ChangelogViewSet + + +def register_logs_urls(router, path): + """ + Configure router for Activity REST API. + """ + router.register(path, ChangelogViewSet) diff --git a/apps/logs/api/views.py b/apps/logs/api/views.py new file mode 100644 index 0000000..5ac2a07 --- /dev/null +++ b/apps/logs/api/views.py @@ -0,0 +1,28 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from django_filters.rest_framework import DjangoFilterBackend +from rest_framework.filters import OrderingFilter +from rest_framework.viewsets import ModelViewSet + +from .serializers import ChangelogSerializer +from ..models import Changelog + + +class ChangelogViewSet(ModelViewSet): + """ + REST API View set. + The djangorestframework plugin will get all `Changelog` objects, serialize it to JSON with the given serializer, + then render it on /api/logs/ + """ + + def check_permissions(self, request): + # Only superusers can get access to logs + return self.request.user and self.request.user.is_superuser + + queryset = Changelog.objects.all() + serializer_class = ChangelogSerializer + filter_backends = [DjangoFilterBackend, OrderingFilter] + filterset_fields = ['model', 'action', "instance_pk", 'user', 'ip', ] + ordering_fields = ['timestamp', 'id', ] + ordering = ['-id', ] diff --git a/apps/logs/apps.py b/apps/logs/apps.py new file mode 100644 index 0000000..7409c20 --- /dev/null +++ b/apps/logs/apps.py @@ -0,0 +1,18 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.apps import AppConfig +from django.db.models.signals import post_delete, post_save, pre_save +from django.utils.translation import gettext_lazy as _ + + +class LogsConfig(AppConfig): + name = 'logs' + verbose_name = _('Logs') + + def ready(self): + # noinspection PyUnresolvedReferences + from . import signals + pre_save.connect(signals.pre_save_object) + post_save.connect(signals.save_object) + post_delete.connect(signals.delete_object) diff --git a/apps/logs/migrations/0001_initial.py b/apps/logs/migrations/0001_initial.py new file mode 100644 index 0000000..82431ad --- /dev/null +++ b/apps/logs/migrations/0001_initial.py @@ -0,0 +1,37 @@ +# Generated by Django 3.1.1 on 2020-09-21 15:33 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('contenttypes', '0002_remove_content_type_name'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Changelog', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('ip', models.GenericIPAddressField(blank=True, null=True, verbose_name='IP Address')), + ('instance_pk', models.CharField(max_length=255, verbose_name='identifier')), + ('previous', models.TextField(blank=True, default='', verbose_name='previous data')), + ('data', models.TextField(blank=True, default='', verbose_name='new data')), + ('action', models.CharField(choices=[('create', 'create'), ('edit', 'edit'), ('delete', 'delete')], default='edit', max_length=16, verbose_name='action')), + ('timestamp', models.DateTimeField(default=django.utils.timezone.now, verbose_name='timestamp')), + ('model', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contenttypes.contenttype', verbose_name='model')), + ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL, verbose_name='user')), + ], + options={ + 'verbose_name': 'changelog', + 'verbose_name_plural': 'changelogs', + }, + ), + ] diff --git a/apps/logs/migrations/__init__.py b/apps/logs/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/logs/models.py b/apps/logs/models.py new file mode 100644 index 0000000..0077af7 --- /dev/null +++ b/apps/logs/models.py @@ -0,0 +1,88 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.conf import settings +from django.contrib.contenttypes.models import ContentType +from django.core.exceptions import ValidationError +from django.db import models +from django.utils import timezone +from django.utils.translation import gettext_lazy as _ + + +class Changelog(models.Model): + """ + Store each modification in the database (except sessions and logging), + including creating, editing and deleting models. + """ + + user = models.ForeignKey( + settings.AUTH_USER_MODEL, + on_delete=models.PROTECT, + null=True, + verbose_name=_('user'), + ) + + ip = models.GenericIPAddressField( + null=True, + blank=True, + verbose_name=_("IP Address") + ) + + model = models.ForeignKey( + ContentType, + on_delete=models.PROTECT, + null=False, + blank=False, + verbose_name=_('model'), + ) + + instance_pk = models.CharField( + max_length=255, + null=False, + blank=False, + verbose_name=_('identifier'), + ) + + previous = models.TextField( + blank=True, + default="", + verbose_name=_('previous data'), + ) + + data = models.TextField( + blank=True, + default="", + verbose_name=_('new data'), + ) + + action = models.CharField( # create, edit or delete + max_length=16, + null=False, + blank=False, + choices=[ + ('create', _('create')), + ('edit', _('edit')), + ('delete', _('delete')), + ], + default='edit', + verbose_name=_('action'), + ) + + timestamp = models.DateTimeField( + null=False, + blank=False, + default=timezone.now, + name='timestamp', + verbose_name=_('timestamp'), + ) + + def delete(self, using=None, keep_parents=False): + raise ValidationError(_("Logs cannot be destroyed.")) + + class Meta: + verbose_name = _("changelog") + verbose_name_plural = _("changelogs") + + def __str__(self): + return _("Changelog of type \"{action}\" for model {model} at {timestamp}").format( + action=self.get_action_display(), model=str(self.model), timestamp=str(self.timestamp)) diff --git a/apps/logs/signals.py b/apps/logs/signals.py new file mode 100644 index 0000000..cdf8479 --- /dev/null +++ b/apps/logs/signals.py @@ -0,0 +1,132 @@ +import getpass + +from corres2math.middlewares import get_current_authenticated_user, get_current_ip +from django.contrib.auth.models import User +from django.contrib.contenttypes.models import ContentType +from rest_framework.renderers import JSONRenderer +from rest_framework.serializers import ModelSerializer + +from .models import Changelog + + +# Ces modèles ne nécessitent pas de logs +EXCLUDED = [ + 'admin.logentry', + 'authtoken.token', + 'contenttypes.contenttype', + 'logs.changelog', # Never remove this line + 'mailer.dontsendentry', + 'mailer.message', + 'mailer.messagelog', + 'migrations.migration', + 'sessions.session', +] + + +def pre_save_object(sender, instance, **kwargs): + """ + Before a model get saved, we get the previous instance that is currently in the database + """ + qs = sender.objects.filter(pk=instance.pk).all() + if qs.exists(): + instance._previous = qs.get() + else: + instance._previous = None + + +def save_object(sender, instance, **kwargs): + """ + Each time a model is saved, an entry in the table `Changelog` is added in the database + in order to store each modification made + """ + # noinspection PyProtectedMember + if instance._meta.label_lower in EXCLUDED or hasattr(instance, "_no_signal"): + return + + # noinspection PyProtectedMember + previous = instance._previous + + # Si un utilisateur est connecté, on récupère l'utilisateur courant ainsi que son adresse IP + user, ip = get_current_authenticated_user(), get_current_ip() + + if user is None: + # Si la modification n'a pas été faite via le client Web, on suppose que c'est du à `manage.py` + # On récupère alors l'utilisateur·trice connecté·e à la VM, et on récupère la note associée + ip = "127.0.0.1" + username = getpass.getuser() + user = User.objects.get(username=username) if User.objects.filter(username=username).exists() else None + + # On n'enregistre pas les connexions + # noinspection PyProtectedMember + if user is not None and instance._meta.label_lower == "auth.user" and previous \ + and instance.last_login != previous.last_login: + return + + changed_fields = '__all__' + if previous: + # On ne garde que les champs modifiés + changed_fields = [] + for field in instance._meta.fields: + if field.name.endswith("_ptr"): + # A field ending with _ptr is a OneToOneRel with a subclass, e.g. NoteClub.note_ptr -> Note + continue + if getattr(instance, field.name) != getattr(previous, field.name): + changed_fields.append(field.name) + + if len(changed_fields) == 0: + # Pas de log s'il n'y a pas de modification + return + + # On crée notre propre sérialiseur JSON pour pouvoir sauvegarder les modèles avec uniquement les champs modifiés + class CustomSerializer(ModelSerializer): + class Meta: + model = instance.__class__ + fields = changed_fields + + previous_json = JSONRenderer().render(CustomSerializer(previous).data).decode("UTF-8") if previous else "" + instance_json = JSONRenderer().render(CustomSerializer(instance).data).decode("UTF-8") + + Changelog.objects.create(user=user, + ip=ip, + model=ContentType.objects.get_for_model(instance), + instance_pk=instance.pk, + previous=previous_json, + data=instance_json, + action=("edit" if previous else "create") + ).save() + + +def delete_object(sender, instance, **kwargs): + """ + Each time a model is deleted, an entry in the table `Changelog` is added in the database + """ + # noinspection PyProtectedMember + if instance._meta.label_lower in EXCLUDED or hasattr(instance, "_no_signal"): + return + + # Si un utilisateur est connecté, on récupère l'utilisateur courant ainsi que son adresse IP + user, ip = get_current_authenticated_user(), get_current_ip() + + if user is None: + # Si la modification n'a pas été faite via le client Web, on suppose que c'est du à `manage.py` + # On récupère alors l'utilisateur·trice connecté·e à la VM, et on récupère la note associée + ip = "127.0.0.1" + username = getpass.getuser() + user = User.objects.get(username=username) if User.objects.filter(username=username).exists() else None + + # On crée notre propre sérialiseur JSON pour pouvoir sauvegarder les modèles + class CustomSerializer(ModelSerializer): + class Meta: + model = instance.__class__ + fields = '__all__' + + instance_json = JSONRenderer().render(CustomSerializer(instance).data).decode("UTF-8") + + Changelog.objects.create(user=user, + ip=ip, + model=ContentType.objects.get_for_model(instance), + instance_pk=instance.pk, + previous=instance_json, + data="", + action="delete" + ) diff --git a/apps/logs/tests.py b/apps/logs/tests.py new file mode 100644 index 0000000..9c6da02 --- /dev/null +++ b/apps/logs/tests.py @@ -0,0 +1,21 @@ +from django.contrib.auth.models import User +from django.contrib.contenttypes.models import ContentType +from django.core.exceptions import ValidationError +from django.test import TestCase + +from .models import Changelog + + +class TestChangelog(TestCase): + def test_logs(self): + user = User.objects.create(email="admin@example.com") + self.assertTrue(Changelog.objects.filter(action="create", instance_pk=user.pk, + model=ContentType.objects.get_for_model(User)).exists()) + old_user_pk = user.pk + user.delete() + self.assertTrue(Changelog.objects.filter(action="delete", instance_pk=old_user_pk, + model=ContentType.objects.get_for_model(User)).exists()) + + changelog = Changelog.objects.first() + self.assertRaises(ValidationError, changelog.delete) + str(Changelog.objects.all()) diff --git a/apps/participation/__init__.py b/apps/participation/__init__.py new file mode 100644 index 0000000..e784201 --- /dev/null +++ b/apps/participation/__init__.py @@ -0,0 +1 @@ +default_app_config = 'participation.apps.ParticipationConfig' diff --git a/apps/participation/admin.py b/apps/participation/admin.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/participation/apps.py b/apps/participation/apps.py new file mode 100644 index 0000000..e775176 --- /dev/null +++ b/apps/participation/apps.py @@ -0,0 +1,15 @@ +from django.apps import AppConfig +from django.db.models.signals import post_save, pre_delete, pre_save + + +class ParticipationConfig(AppConfig): + """ + The participation app contains the data about the teams, videos, ... + """ + name = 'participation' + + def ready(self): + from participation.signals import create_team_participation, delete_related_videos, update_mailing_list + pre_save.connect(update_mailing_list, "participation.Team") + pre_delete.connect(delete_related_videos, "participation.Participation") + post_save.connect(create_team_participation, "participation.Team") diff --git a/apps/participation/forms.py b/apps/participation/forms.py new file mode 100644 index 0000000..fe083e8 --- /dev/null +++ b/apps/participation/forms.py @@ -0,0 +1,180 @@ +import re + +from bootstrap_datepicker_plus import DateTimePickerInput +from django import forms +from django.core.exceptions import ValidationError +from django.db.models import Q +from django.utils.translation import gettext_lazy as _ + +from .models import Participation, Phase, Question, Team, Video + + +class TeamForm(forms.ModelForm): + """ + Form to create a team, with the name and the trigram, + and if the team accepts that Animath diffuse the videos. + """ + def clean_trigram(self): + trigram = self.cleaned_data["trigram"].upper() + if not re.match("[A-Z]{3}", trigram): + raise ValidationError(_("The trigram must be composed of three uppercase letters.")) + return trigram + + class Meta: + model = Team + fields = ('name', 'trigram', 'grant_animath_access_videos',) + + +class JoinTeamForm(forms.ModelForm): + """ + Form to join a team by the access code. + """ + def clean_access_code(self): + access_code = self.cleaned_data["access_code"] + if not Team.objects.filter(access_code=access_code).exists(): + raise ValidationError(_("No team was found with this access code.")) + return access_code + + def clean(self): + cleaned_data = super().clean() + if "access_code" in cleaned_data: + team = Team.objects.get(access_code=cleaned_data["access_code"]) + self.instance = team + return cleaned_data + + class Meta: + model = Team + fields = ('access_code',) + + +class ParticipationForm(forms.ModelForm): + """ + Form to update the problem of a team participation. + """ + class Meta: + model = Participation + fields = ('problem',) + + +class RequestValidationForm(forms.Form): + """ + Form to ask about validation. + """ + _form_type = forms.CharField( + initial="RequestValidationForm", + widget=forms.HiddenInput(), + ) + + engagement = forms.BooleanField( + label=_("I engage myself to participate to the whole \"Correspondances\"."), + required=True, + ) + + +class ValidateParticipationForm(forms.Form): + """ + Form to let administrators to accept or refuse a team. + """ + _form_type = forms.CharField( + initial="ValidateParticipationForm", + widget=forms.HiddenInput(), + ) + + message = forms.CharField( + label=_("Message to address to the team:"), + widget=forms.Textarea(), + ) + + +class UploadVideoForm(forms.ModelForm): + """ + Form to upload a video, for a solution or a synthesis. + """ + class Meta: + model = Video + fields = ('link',) + + def clean(self): + if Phase.current_phase().phase_number != 1 and self.instance.link: + self.add_error("link", _("You can't upload your video after the deadline.")) + return super().clean() + + +class ReceiveParticipationForm(forms.ModelForm): + """ + Update the received participation of a participation. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["received_participation"].queryset = Participation.objects.filter( + ~Q(pk=self.instance.pk) & Q(problem=self.instance.problem, valid=True) + ) + + class Meta: + model = Participation + fields = ('received_participation',) + + +class SendParticipationForm(forms.ModelForm): + """ + Update the sent participation of a participation. + """ + sent_participation = forms.ModelChoiceField( + queryset=Participation.objects, + label=lambda: _("Send to team"), + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["sent_participation"].initial = self.instance.sent_participation + self.fields["sent_participation"].queryset = Participation.objects.filter( + ~Q(pk=self.instance.pk) & Q(problem=self.instance.problem, valid=True) + ) + + def clean(self, commit=True): + cleaned_data = super().clean() + participation = cleaned_data["sent_participation"] + participation.received_participation = self.instance + self.instance = participation + return cleaned_data + + class Meta: + model = Participation + fields = ('sent_participation',) + + +class QuestionForm(forms.ModelForm): + """ + Create or update a question. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["question"].widget.attrs.update({"placeholder": _("How did you get the idea to ...?")}) + + class Meta: + model = Question + fields = ('question',) + + +class PhaseForm(forms.ModelForm): + """ + Form to update the calendar of a phase. + """ + class Meta: + model = Phase + fields = ('start', 'end',) + widgets = { + 'start': DateTimePickerInput(format='%d/%m/%Y %H:%M'), + 'end': DateTimePickerInput(format='%d/%m/%Y %H:%M'), + } + + def clean(self): + # Ensure that dates are in a right order + cleaned_data = super().clean() + if cleaned_data["end"] <= cleaned_data["start"]: + self.add_error("end", _("Start date must be before the end date.")) + if Phase.objects.filter(phase_number__lt=self.instance.phase_number, end__gt=cleaned_data["start"]).exists(): + self.add_error("start", _("This phase must start after the previous phases.")) + if Phase.objects.filter(phase_number__gt=self.instance.phase_number, start__lt=cleaned_data["end"]).exists(): + self.add_error("end", _("This phase must end after the next phases.")) + return cleaned_data diff --git a/apps/participation/management/commands/__init__.py b/apps/participation/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/participation/management/commands/fix_matrix_channels.py b/apps/participation/management/commands/fix_matrix_channels.py new file mode 100644 index 0000000..427cc8b --- /dev/null +++ b/apps/participation/management/commands/fix_matrix_channels.py @@ -0,0 +1,74 @@ +import os + +from asgiref.sync import async_to_sync +from corres2math.matrix import Matrix, RoomVisibility, UploadError +from django.core.management import BaseCommand +from nio import RoomPreset +from registration.models import AdminRegistration, Registration + + +class Command(BaseCommand): + def handle(self, *args, **options): + Matrix.set_display_name("Bot des Correspondances") + + if not os.path.isfile(".matrix_avatar"): + stat_file = os.stat("corres2math/static/logo.png") + with open("corres2math/static/logo.png", "rb") as f: + resp, _ = Matrix.upload(f, filename="logo.png", content_type="image/png", filesize=stat_file.st_size) + if isinstance(resp, UploadError): + raise Exception(resp) + avatar_uri = resp.content_uri + with open(".matrix_avatar", "w") as f: + f.write(avatar_uri) + Matrix.set_avatar(avatar_uri) + else: + with open(".matrix_avatar", "r") as f: + avatar_uri = f.read().rstrip(" \t\r\n") + + if not async_to_sync(Matrix.resolve_room_alias)("#faq:correspondances-maths.fr"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="faq", + name="FAQ", + topic="Posez toutes vos questions ici !", + federate=False, + preset=RoomPreset.public_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)("#annonces:correspondances-maths.fr"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="annonces", + name="Annonces", + topic="Informations importantes des Correspondances", + federate=False, + preset=RoomPreset.public_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)("#je-cherche-une-equipe:correspondances-maths.fr"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="je-cherche-une-equipe", + name="Je cherche une équipe", + topic="Le Tinder des Correspondances", + federate=False, + preset=RoomPreset.public_chat, + ) + + Matrix.set_room_avatar("#annonces:correspondances-maths.fr", avatar_uri) + Matrix.set_room_avatar("#faq:correspondances-maths.fr", avatar_uri) + Matrix.set_room_avatar("#je-cherche-une-equipe:correspondances-maths.fr", avatar_uri) + + Matrix.set_room_power_level_event("#annonces:correspondances-maths.fr", "events_default", 50) + + for r in Registration.objects.all(): + Matrix.invite("#annonces:correspondances-maths.fr", f"@{r.matrix_username}:correspondances-maths.fr") + Matrix.invite("#faq:correspondances-maths.fr", f"@{r.matrix_username}:correspondances-maths.fr") + Matrix.invite("#je-cherche-une-equipe:correspondances-maths.fr", + f"@{r.matrix_username}:correspondances-maths.fr") + + for admin in AdminRegistration.objects.all(): + Matrix.set_room_power_level("#annonces:correspondances-maths.fr", + f"@{admin.matrix_username}:correspondances-maths.fr", 95) + Matrix.set_room_power_level("#faq:correspondances-maths.fr", + f"@{admin.matrix_username}:correspondances-maths.fr", 95) diff --git a/apps/participation/management/commands/setup_third_phase.py b/apps/participation/management/commands/setup_third_phase.py new file mode 100644 index 0000000..3034354 --- /dev/null +++ b/apps/participation/management/commands/setup_third_phase.py @@ -0,0 +1,41 @@ +from corres2math.matrix import Matrix, RoomVisibility +from django.core.management import BaseCommand +from participation.models import Participation + + +class Command(BaseCommand): + def handle(self, *args, **options): + for participation in Participation.objects.filter(valid=True).all(): + for i, question in enumerate(participation.questions.order_by("id").all()): + solution_author = participation.received_participation.team + alias = f"equipe-{solution_author.trigram.lower()}-question-{i}" + room_id = f"#{alias}:correspondances-maths.fr" + Matrix.create_room( + visibility=RoomVisibility.public, + alias=alias, + name=f"Solution équipe {solution_author.trigram} - question {i+1}", + topic=f"Échange entre l'équipe {solution_author.name} ({solution_author.trigram}) " + f"et l'équipe {participation.team.name} ({participation.team.trigram}) " + f"autour de la question {i+1} sur le problème {participation.problem}", + federate=False, + invite=[f"@{registration.matrix_username}:correspondances-maths.fr" for registration in + list(participation.team.students.all()) + list(participation.team.coachs.all()) + + list(solution_author.students.all()) + list(solution_author.coachs.all())], + ) + Matrix.set_room_power_level_event(room_id, "events_default", 21) + for registration in solution_author.students.all(): + Matrix.set_room_power_level(room_id, + f"@{registration.matrix_username}:correspondances-maths.fr", 42) + + Matrix.send_message(room_id, "Bienvenue dans la troisième phase des Correspondances !") + Matrix.send_message(room_id, f"L'équipe {participation.team.name} a visionné la vidéo de l'équipe " + f"{solution_author.name} sur le problème {participation.problem}, et a posé " + "une série de questions.") + Matrix.send_message(room_id, "L'équipe ayant composé la vidéo doit maintenant proposer une réponse.") + Matrix.send_message(room_id, "Une fois la réponse apportée, vous pourrez ensuite échanger plus " + "librement autour de la question, au travers de ce canal.") + Matrix.send_message(room_id, "**Question posée :**", formatted_body="Question posée :") + Matrix.send_message(room_id, question.question, + formatted_body=f"{question.question}") + + # TODO Setup the bot the set the power level of all members of the room to 42 diff --git a/apps/participation/migrations/0001_initial.py b/apps/participation/migrations/0001_initial.py new file mode 100644 index 0000000..f1eea8d --- /dev/null +++ b/apps/participation/migrations/0001_initial.py @@ -0,0 +1,77 @@ +# Generated by Django 3.1.1 on 2020-09-21 15:51 + +import django.core.validators +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Participation', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('problem', models.IntegerField(choices=[(1, 'Problem #1'), (2, 'Problem #2'), (3, 'Problem #3')], default=None, null=True, verbose_name='problem number')), + ], + options={ + 'verbose_name': 'participation', + 'verbose_name_plural': 'participations', + }, + ), + migrations.CreateModel( + name='Team', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, unique=True, verbose_name='name')), + ('trigram', models.CharField(help_text='The trigram must be composed of three uppercase letters.', max_length=3, unique=True, validators=[django.core.validators.RegexValidator('[A-Z]{3}')], verbose_name='trigram')), + ('access_code', models.CharField(help_text='The access code let other people to join the team.', max_length=6, verbose_name='access code')), + ], + options={ + 'verbose_name': 'team', + 'verbose_name_plural': 'teams', + }, + ), + migrations.CreateModel( + name='Video', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('link', models.URLField(help_text='The full video link.', verbose_name='link')), + ('valid', models.BooleanField(default=None, help_text='The video got the validation of the administrators.', null=True, verbose_name='valid')), + ('participation', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='participation.participation', verbose_name='participation')), + ], + options={ + 'verbose_name': 'video', + 'verbose_name_plural': 'videos', + }, + ), + migrations.AddIndex( + model_name='team', + index=models.Index(fields=['trigram'], name='participati_trigram_239255_idx'), + ), + migrations.AddField( + model_name='participation', + name='received_participation', + field=models.OneToOneField(default=None, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='sent_participation', to='participation.participation', verbose_name='received participation'), + ), + migrations.AddField( + model_name='participation', + name='solution', + field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='participation.video', verbose_name='solution video'), + ), + migrations.AddField( + model_name='participation', + name='synthesis', + field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='participation.video', verbose_name='synthesis video'), + ), + migrations.AddField( + model_name='participation', + name='team', + field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='participation.team', verbose_name='team'), + ), + ] diff --git a/apps/participation/migrations/0002_team_grant_animath_access_videos.py b/apps/participation/migrations/0002_team_grant_animath_access_videos.py new file mode 100644 index 0000000..7832ade --- /dev/null +++ b/apps/participation/migrations/0002_team_grant_animath_access_videos.py @@ -0,0 +1,18 @@ +# Generated by Django 3.1.1 on 2020-09-22 16:21 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('participation', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='team', + name='grant_animath_access_videos', + field=models.BooleanField(default=False, help_text='Give the authorisation to publish the video on the main website to promote the action.', verbose_name='Grant Animath to publish my video'), + ), + ] diff --git a/apps/participation/migrations/0003_auto_20200927_1309.py b/apps/participation/migrations/0003_auto_20200927_1309.py new file mode 100644 index 0000000..a914976 --- /dev/null +++ b/apps/participation/migrations/0003_auto_20200927_1309.py @@ -0,0 +1,28 @@ +# Generated by Django 3.1.1 on 2020-09-27 11:09 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('participation', '0002_team_grant_animath_access_videos'), + ] + + operations = [ + migrations.RemoveField( + model_name='video', + name='participation', + ), + migrations.AlterField( + model_name='participation', + name='solution', + field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='participation', to='participation.video', verbose_name='solution video'), + ), + migrations.AlterField( + model_name='participation', + name='synthesis', + field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='participation_synthesis', to='participation.video', verbose_name='synthesis video'), + ), + ] diff --git a/apps/participation/migrations/0004_auto_20200927_1322.py b/apps/participation/migrations/0004_auto_20200927_1322.py new file mode 100644 index 0000000..ca5f9ae --- /dev/null +++ b/apps/participation/migrations/0004_auto_20200927_1322.py @@ -0,0 +1,24 @@ +# Generated by Django 3.1.1 on 2020-09-27 11:22 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('participation', '0003_auto_20200927_1309'), + ] + + operations = [ + migrations.AlterField( + model_name='participation', + name='solution', + field=models.OneToOneField(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='participation_solution', to='participation.video', verbose_name='solution video'), + ), + migrations.AlterField( + model_name='participation', + name='synthesis', + field=models.OneToOneField(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='participation_synthesis', to='participation.video', verbose_name='synthesis video'), + ), + ] diff --git a/apps/participation/migrations/0005_participation_valid.py b/apps/participation/migrations/0005_participation_valid.py new file mode 100644 index 0000000..f22fc7d --- /dev/null +++ b/apps/participation/migrations/0005_participation_valid.py @@ -0,0 +1,18 @@ +# Generated by Django 3.1.1 on 2020-10-11 13:58 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('participation', '0004_auto_20200927_1322'), + ] + + operations = [ + migrations.AddField( + model_name='participation', + name='valid', + field=models.BooleanField(default=None, help_text='The video got the validation of the administrators.', null=True, verbose_name='valid'), + ), + ] diff --git a/apps/participation/migrations/0006_phase.py b/apps/participation/migrations/0006_phase.py new file mode 100644 index 0000000..2653caa --- /dev/null +++ b/apps/participation/migrations/0006_phase.py @@ -0,0 +1,61 @@ +# Generated by Django 3.1.1 on 2020-10-20 10:39 + +from django.db import migrations, models +import django.utils.timezone + + +def register_phases(apps, schema_editor): + """ + Import the different phases of the action + """ + Phase = apps.get_model("participation", "phase") + Phase.objects.get_or_create( + phase_number=1, + description="Soumission des vidéos", + ) + Phase.objects.get_or_create( + phase_number=2, + description="Phase de questions", + ) + Phase.objects.get_or_create( + phase_number=3, + description="Phase d'échanges entre les équipes", + ) + Phase.objects.get_or_create( + phase_number=4, + description="Synthèse de l'échange", + ) + + +def reverse_phase_registering(apps, schema_editor): + """ + Drop all phases in order to unapply this migration. + """ + Phase = apps.get_model("participation", "phase") + Phase.objects.all().delete() + + +class Migration(migrations.Migration): + dependencies = [ + ('participation', '0005_participation_valid'), + ] + + operations = [ + migrations.CreateModel( + name='Phase', + fields=[ + ('phase_number', models.AutoField(primary_key=True, serialize=False, unique=True, verbose_name='phase number')), + ('description', models.CharField(max_length=255, verbose_name="phase description")), + ('start', models.DateTimeField(default=django.utils.timezone.now, verbose_name='start date of the given phase')), + ('end', models.DateTimeField(default=django.utils.timezone.now, verbose_name='end date of the given phase')), + ], + options={ + 'verbose_name': 'phase', + 'verbose_name_plural': 'phases', + }, + ), + migrations.RunPython( + register_phases, + reverse_phase_registering, + ), + ] diff --git a/apps/participation/migrations/0007_question.py b/apps/participation/migrations/0007_question.py new file mode 100644 index 0000000..814487f --- /dev/null +++ b/apps/participation/migrations/0007_question.py @@ -0,0 +1,22 @@ +# Generated by Django 3.0.10 on 2020-10-31 13:36 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('participation', '0006_phase'), + ] + + operations = [ + migrations.CreateModel( + name='Question', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('question', models.TextField(verbose_name='question')), + ('participation', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='questions', to='participation.Participation', verbose_name='participation')), + ], + ), + ] diff --git a/apps/participation/migrations/__init__.py b/apps/participation/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/participation/models.py b/apps/participation/models.py new file mode 100644 index 0000000..746550f --- /dev/null +++ b/apps/participation/models.py @@ -0,0 +1,296 @@ +import os +import re + +from corres2math.lists import get_sympa_client +from corres2math.matrix import Matrix +from django.core.exceptions import ObjectDoesNotExist +from django.core.validators import RegexValidator +from django.db import models +from django.db.models import Index +from django.template.loader import render_to_string +from django.urls import reverse_lazy +from django.utils import timezone +from django.utils.crypto import get_random_string +from django.utils.text import format_lazy +from django.utils.translation import gettext_lazy as _ +from nio import RoomPreset, RoomVisibility + + +class Team(models.Model): + """ + The Team model represents a real team that participates to the Correspondances. + This only includes the registration detail. + """ + name = models.CharField( + max_length=255, + verbose_name=_("name"), + unique=True, + ) + + trigram = models.CharField( + max_length=3, + verbose_name=_("trigram"), + help_text=_("The trigram must be composed of three uppercase letters."), + unique=True, + validators=[RegexValidator("[A-Z]{3}")], + ) + + access_code = models.CharField( + max_length=6, + verbose_name=_("access code"), + help_text=_("The access code let other people to join the team."), + ) + + grant_animath_access_videos = models.BooleanField( + verbose_name=_("Grant Animath to publish my video"), + help_text=_("Give the authorisation to publish the video on the main website to promote the action."), + default=False, + ) + + @property + def email(self): + """ + :return: The mailing list to contact the team members. + """ + return f"equipe-{self.trigram.lower()}@{os.getenv('SYMPA_HOST', 'localhost')}" + + def create_mailing_list(self): + """ + Create a new Sympa mailing list to contact the team. + """ + get_sympa_client().create_list( + f"equipe-{self.trigram.lower()}", + f"Équipe {self.name} ({self.trigram})", + "hotline", # TODO Use a custom sympa template + f"Liste de diffusion pour contacter l'équipe {self.name} des Correspondances", + "education", + raise_error=False, + ) + + def delete_mailing_list(self): + """ + Drop the Sympa mailing list, if the team is empty or if the trigram changed. + """ + get_sympa_client().delete_list(f"equipe-{self.trigram}") + + def save(self, *args, **kwargs): + if not self.access_code: + # if the team got created, generate the access code, create the contact mailing list + # and create a dedicated Matrix room. + self.access_code = get_random_string(6) + self.create_mailing_list() + + Matrix.create_room( + visibility=RoomVisibility.private, + name=f"#équipe-{self.trigram.lower()}", + alias=f"equipe-{self.trigram.lower()}", + topic=f"Discussion de l'équipe {self.name}", + preset=RoomPreset.private_chat, + ) + + return super().save(*args, **kwargs) + + def get_absolute_url(self): + return reverse_lazy("participation:team_detail", args=(self.pk,)) + + def __str__(self): + return _("Team {name} ({trigram})").format(name=self.name, trigram=self.trigram) + + class Meta: + verbose_name = _("team") + verbose_name_plural = _("teams") + indexes = [ + Index(fields=("trigram", )), + ] + + +class Participation(models.Model): + """ + The Participation model contains all data that are related to the participation: + chosen problem, validity status, videos,... + """ + team = models.OneToOneField( + Team, + on_delete=models.CASCADE, + verbose_name=_("team"), + ) + + problem = models.IntegerField( + choices=[(i, format_lazy(_("Problem #{problem:d}"), problem=i)) for i in range(1, 4)], + null=True, + default=None, + verbose_name=_("problem number"), + ) + + valid = models.BooleanField( + null=True, + default=None, + verbose_name=_("valid"), + help_text=_("The video got the validation of the administrators."), + ) + + solution = models.OneToOneField( + "participation.Video", + on_delete=models.SET_NULL, + related_name="participation_solution", + null=True, + default=None, + verbose_name=_("solution video"), + ) + + received_participation = models.OneToOneField( + "participation.Participation", + on_delete=models.PROTECT, + related_name="sent_participation", + null=True, + default=None, + verbose_name=_("received participation"), + ) + + synthesis = models.OneToOneField( + "participation.Video", + on_delete=models.SET_NULL, + related_name="participation_synthesis", + null=True, + default=None, + verbose_name=_("synthesis video"), + ) + + def get_absolute_url(self): + return reverse_lazy("participation:participation_detail", args=(self.pk,)) + + def __str__(self): + return _("Participation of the team {name} ({trigram})").format(name=self.team.name, trigram=self.team.trigram) + + class Meta: + verbose_name = _("participation") + verbose_name_plural = _("participations") + + +class Video(models.Model): + """ + The Video model only contains a link and a validity status. + """ + link = models.URLField( + verbose_name=_("link"), + help_text=_("The full video link."), + ) + + valid = models.BooleanField( + null=True, + default=None, + verbose_name=_("valid"), + help_text=_("The video got the validation of the administrators."), + ) + + @property + def participation(self): + """ + Retrives the participation that is associated to this video, + whatever it is a solution or a synthesis. + """ + try: + # If this is a solution + return self.participation_solution + except ObjectDoesNotExist: + # If this is a synthesis + return self.participation_synthesis + + @property + def platform(self): + """ + According to the link, retrieve the platform that is used to upload the video. + """ + if "youtube.com" in self.link or "youtu.be" in self.link: + return "youtube" + return "unknown" + + @property + def youtube_code(self): + """ + If the video is uploaded on Youtube, search in the URL the video code. + """ + return re.compile("(https?://|)(www\\.|)(youtube\\.com/watch\\?v=|youtu\\.be/)([a-zA-Z0-9-_]*)?.*?")\ + .match(self.link).group(4) + + def as_iframe(self): + """ + Generate the HTML code to embed the video in an iframe, according to the type of the host platform. + """ + if self.platform == "youtube": + return render_to_string("participation/youtube_iframe.html", context=dict(youtube_code=self.youtube_code)) + return None + + def __str__(self): + return _("Video of team {name} ({trigram})")\ + .format(name=self.participation.team.name, trigram=self.participation.team.trigram) + + class Meta: + verbose_name = _("video") + verbose_name_plural = _("videos") + + +class Question(models.Model): + """ + Question to ask to the team that sent a solution. + """ + participation = models.ForeignKey( + Participation, + on_delete=models.CASCADE, + verbose_name=_("participation"), + related_name="questions", + ) + + question = models.TextField( + verbose_name=_("question"), + ) + + def __str__(self): + return self.question + + +class Phase(models.Model): + """ + The Phase model corresponds to the dates of the phase. + """ + phase_number = models.AutoField( + primary_key=True, + unique=True, + verbose_name=_("phase number"), + ) + + description = models.CharField( + max_length=255, + verbose_name=_("phase description"), + ) + + start = models.DateTimeField( + verbose_name=_("start date of the given phase"), + default=timezone.now, + ) + + end = models.DateTimeField( + verbose_name=_("end date of the given phase"), + default=timezone.now, + ) + + @classmethod + def current_phase(cls): + """ + Retrieve the current phase of this day + """ + qs = Phase.objects.filter(start__lte=timezone.now(), end__gte=timezone.now()) + if qs.exists(): + return qs.get() + qs = Phase.objects.order_by("phase_number").all() + if timezone.now() < qs.first().start: + return qs.first() + return qs.last() + + def __str__(self): + return _("Phase {phase_number:d} starts on {start:%Y-%m-%d %H:%M} and ends on {end:%Y-%m-%d %H:%M}")\ + .format(phase_number=self.phase_number, start=self.start, end=self.end) + + class Meta: + verbose_name = _("phase") + verbose_name_plural = _("phases") diff --git a/apps/participation/search_indexes.py b/apps/participation/search_indexes.py new file mode 100644 index 0000000..734d5bb --- /dev/null +++ b/apps/participation/search_indexes.py @@ -0,0 +1,33 @@ +from haystack import indexes + +from .models import Participation, Team, Video + + +class TeamIndex(indexes.ModelSearchIndex, indexes.Indexable): + """ + Index all teams by their name and trigram. + """ + text = indexes.NgramField(document=True, use_template=True) + + class Meta: + model = Team + + +class ParticipationIndex(indexes.ModelSearchIndex, indexes.Indexable): + """ + Index all participations by their team name and team trigram. + """ + text = indexes.NgramField(document=True, use_template=True) + + class Meta: + model = Participation + + +class VideoIndex(indexes.ModelSearchIndex, indexes.Indexable): + """ + Index all teams by their team name and team trigram. + """ + text = indexes.NgramField(document=True, use_template=True) + + class Meta: + model = Video diff --git a/apps/participation/signals.py b/apps/participation/signals.py new file mode 100644 index 0000000..a7ee7d4 --- /dev/null +++ b/apps/participation/signals.py @@ -0,0 +1,41 @@ +from corres2math.lists import get_sympa_client +from participation.models import Participation, Team, Video + + +def create_team_participation(instance, **_): + """ + When a team got created, create an associated team and create Video objects. + """ + participation = Participation.objects.get_or_create(team=instance)[0] + if not participation.solution: + participation.solution = Video.objects.create() + if not participation.synthesis: + participation.synthesis = Video.objects.create() + participation.save() + + +def update_mailing_list(instance: Team, **_): + """ + When a team name or trigram got updated, update mailing lists and Matrix rooms + """ + if instance.pk: + old_team = Team.objects.get(pk=instance.pk) + if old_team.name != instance.name or old_team.trigram != instance.trigram: + # TODO Rename Matrix room + # Delete old mailing list, create a new one + old_team.delete_mailing_list() + instance.create_mailing_list() + # Subscribe all team members in the mailing list + for student in instance.students.all(): + get_sympa_client().subscribe(student.user.email, f"equipe-{instance.trigram.lower()}", False, + f"{student.user.first_name} {student.user.last_name}") + for coach in instance.coachs.all(): + get_sympa_client().subscribe(coach.user.email, f"equipe-{instance.trigram.lower()}", False, + f"{coach.user.first_name} {coach.user.last_name}") + + +def delete_related_videos(instance: Participation, **_): + if instance.solution: + instance.solution.delete() + if instance.synthesis: + instance.synthesis.delete() diff --git a/apps/participation/tables.py b/apps/participation/tables.py new file mode 100644 index 0000000..2ca91c9 --- /dev/null +++ b/apps/participation/tables.py @@ -0,0 +1,90 @@ +from django.utils import timezone +from django.utils.translation import gettext_lazy as _ +import django_tables2 as tables + +from .models import Phase, Team + + +class CalendarTable(tables.Table): + class Meta: + attrs = { + 'class': 'table table condensed table-striped', + } + row_attrs = { + 'class': lambda record: 'bg-success' if timezone.now() > record.end else + 'bg-warning' if timezone.now() > record.start else + 'bg-danger', + 'data-id': lambda record: str(record.phase_number), + } + model = Phase + fields = ('phase_number', 'description', 'start', 'end',) + template_name = 'django_tables2/bootstrap4.html' + order_by = ('phase_number',) + + +# noinspection PyTypeChecker +class TeamTable(tables.Table): + name = tables.LinkColumn( + 'participation:team_detail', + args=[tables.A("id")], + verbose_name=lambda: _("name").capitalize(), + ) + + problem = tables.Column( + accessor="participation__problem", + verbose_name=lambda: _("problem number").capitalize(), + ) + + class Meta: + attrs = { + 'class': 'table table condensed table-striped', + } + model = Team + fields = ('name', 'trigram', 'problem',) + template_name = 'django_tables2/bootstrap4.html' + + +# noinspection PyTypeChecker +class ParticipationTable(tables.Table): + name = tables.LinkColumn( + 'participation:participation_detail', + args=[tables.A("id")], + verbose_name=lambda: _("name").capitalize(), + accessor="team__name", + ) + + trigram = tables.Column( + verbose_name=lambda: _("trigram").capitalize(), + accessor="team__trigram", + ) + + problem = tables.Column( + verbose_name=lambda: _("problem number").capitalize(), + ) + + class Meta: + attrs = { + 'class': 'table table condensed table-striped', + } + model = Team + fields = ('name', 'trigram', 'problem',) + template_name = 'django_tables2/bootstrap4.html' + + +class VideoTable(tables.Table): + participationname = tables.LinkColumn( + 'participation:participation_detail', + args=[tables.A("participation__pk")], + verbose_name=lambda: _("name").capitalize(), + ) + + def render_participationname(self, record): + return record.participation.team.name + + class Meta: + attrs = { + 'class': 'table table condensed table-striped', + } + model = Team + fields = ('participationname', 'link',) + template_name = 'django_tables2/bootstrap4.html' diff --git a/apps/participation/templates/participation/chat.html b/apps/participation/templates/participation/chat.html new file mode 100644 index 0000000..bbdd0f4 --- /dev/null +++ b/apps/participation/templates/participation/chat.html @@ -0,0 +1,16 @@ +{% extends "base.html" %} + +{% block extracss %} + +{% endblock %} + +{% block fullcontent %} + +{% endblock %} diff --git a/apps/participation/templates/participation/create_team.html b/apps/participation/templates/participation/create_team.html new file mode 100644 index 0000000..1c93537 --- /dev/null +++ b/apps/participation/templates/participation/create_team.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} diff --git a/apps/participation/templates/participation/join_team.html b/apps/participation/templates/participation/join_team.html new file mode 100644 index 0000000..9beef23 --- /dev/null +++ b/apps/participation/templates/participation/join_team.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} \ No newline at end of file diff --git a/apps/participation/templates/participation/mails/request_validation.html b/apps/participation/templates/participation/mails/request_validation.html new file mode 100644 index 0000000..9693d0a --- /dev/null +++ b/apps/participation/templates/participation/mails/request_validation.html @@ -0,0 +1,27 @@ + + + + + Demande de validation - Correspondances des Jeunes Mathématicien·ne·s + + +

+Bonjour {{ user.registration }}, +

+ +

+L'équipe « {{ team.name }} » ({{ team.trigram }}) vient de demander à valider son équipe pour participer +au {{ team.participation.get_problem_display }} des Correspondances des Jeunes Mathématicien·ne·s. +Vous pouvez décider d'accepter ou de refuser l'équipe en vous rendant sur la page de l'équipe : +{% url "participation:team_detail" pk=team.pk %} +

+ +

+Cordialement, +

+ +

+L'organisation des Correspondances des Jeunes Mathématicien·ne·s +

+ + diff --git a/apps/participation/templates/participation/mails/request_validation.txt b/apps/participation/templates/participation/mails/request_validation.txt new file mode 100644 index 0000000..6bd4f3e --- /dev/null +++ b/apps/participation/templates/participation/mails/request_validation.txt @@ -0,0 +1,10 @@ +Bonjour {{ user.registration }}, + +L'équipe « {{ team.name }} » ({{ team.trigram }}) vient de demander à valider son équipe pour participer +au {{ team.participation.get_problem_display }} des Correspondances des Jeunes Mathématicien·ne·s. +Vous pouvez décider d'accepter ou de refuser l'équipe en vous rendant sur la page de l'équipe : +{% url "participation:team_detail" pk=team.pk %} + +Cordialement, + +L'organisation des Correspondances des Jeunes Mathématicien·ne·s diff --git a/apps/participation/templates/participation/mails/team_not_validated.html b/apps/participation/templates/participation/mails/team_not_validated.html new file mode 100644 index 0000000..865bc0c --- /dev/null +++ b/apps/participation/templates/participation/mails/team_not_validated.html @@ -0,0 +1,22 @@ + + + + + Équipe non validée – Correspondances des Jeunes Mathématicien·ne·s + + +Bonjour,
+
+Maleureusement, votre équipe « {{ team.name }} » ({{ team.trigram }}) n'a pas été validée. Veuillez vérifier que vos autorisations +de droit à l'image sont correctes. Les organisateurs vous adressent ce message :
+
+{{ message }}
+
+N'hésitez pas à nous contacter à l'adresse contact@correspondances-maths.fr +pour plus d'informations. +
+Cordialement,
+
+Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s + + diff --git a/apps/participation/templates/participation/mails/team_not_validated.txt b/apps/participation/templates/participation/mails/team_not_validated.txt new file mode 100644 index 0000000..e3d751a --- /dev/null +++ b/apps/participation/templates/participation/mails/team_not_validated.txt @@ -0,0 +1,12 @@ +Bonjour, + +Maleureusement, votre équipe « {{ team.name }} » ({{ team.trigram }}) n'a pas été validée. Veuillez vérifier que vos +autorisations de droit à l'image sont correctes. Les organisateurs vous adressent ce message : + +{{ message }} + +N'hésitez pas à nous contacter à l'adresse contact@correspondances-maths.fr pour plus d'informations. + +Cordialement, + +Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s diff --git a/server_files/services/mail_templates/validate_team.html b/apps/participation/templates/participation/mails/team_validated.html similarity index 58% rename from server_files/services/mail_templates/validate_team.html rename to apps/participation/templates/participation/mails/team_validated.html index f34caab..55df040 100644 --- a/server_files/services/mail_templates/validate_team.html +++ b/apps/participation/templates/participation/mails/team_validated.html @@ -2,17 +2,19 @@ - Équipe validée – Correspondances des Jeunes Mathématicien·ne·s {YEAR} + Équipe validée – Correspondances des Jeunes Mathématicien·ne·s -Bonjour {FIRST_NAME} {SURNAME},
+Bonjour,

-Félicitations ! Votre équipe « {TEAM_NAME} » ({TRIGRAM}) est désormais validée ! Vous êtes désormais apte à travailler sur -votre problème. Lorsque les Correspondances auront débutées, vous pourrez soumettre votre vidéo sur la plateforme d'inscription. -{MESSAGE}
+Félicitations ! Votre équipe « {{ team.name }} » ({{ team.trigram }}) est désormais validée ! Vous êtes désormais apte à travailler sur +votre problème. Lorsque les Correspondances auront débutées, vous pourrez soumettre votre vidéo sur la plateforme d'inscription.
+Les organisateurs vous adressent ce message :
+
+{{ message }}

Cordialement,

Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - \ No newline at end of file + diff --git a/apps/participation/templates/participation/mails/team_validated.txt b/apps/participation/templates/participation/mails/team_validated.txt new file mode 100644 index 0000000..07f4cee --- /dev/null +++ b/apps/participation/templates/participation/mails/team_validated.txt @@ -0,0 +1,12 @@ +Bonjour, + +Félicitations ! Votre équipe « {{ team.name }} » ({{ team.trigram }}) est désormais validée ! Vous êtes désormais apte à travailler sur +votre problème. Lorsque les Correspondances auront débutées, vous pourrez soumettre votre vidéo sur la plateforme d'inscription. + +Les organisateurs vous adressent ce message : + +{{ message }} + +Cordialement, + +Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s diff --git a/apps/participation/templates/participation/participation_detail.html b/apps/participation/templates/participation/participation_detail.html new file mode 100644 index 0000000..a232fbd --- /dev/null +++ b/apps/participation/templates/participation/participation_detail.html @@ -0,0 +1,300 @@ +{% extends "base.html" %} + +{% load i18n %} + +{% block content %} +{% trans "any" as any %} +
+
+

{% trans "Participation of team" %} {{ participation.team.name }} ({{ participation.team.trigram }})

+
+
+
+
{% trans "Team:" %}
+
{{ participation.team }}
+ +
{% trans "Chosen problem:" %}
+
{{ participation.get_problem_display }}
+
+ +
+
+ {% trans "No video sent" as novideo %} +
{% trans "Proposed solution:" %}
+
+ {{ participation.solution.link|default:novideo }} + {% if current_phase.phase_number == 1 or participation.solution.link == "" %} + + {% endif %} + {% if participation.solution.link %} + + {% endif %} +
+
+
+
+
+ + {% if user.registration.is_admin or current_phase.phase_number >= 2 %} +
+ +
+
+
+
+

{% trans "Sent solution" %}

+
+
+
+
{% trans "Team that received your solution:" %}
+
{{ participation.sent_participation.team|default:any }}
+ {% if user.registration.is_admin %} +
+ +
+ {% endif %} +
+ + {% if current_phase.phase_number == 2 %} +
+ {% blocktrans trimmed %} + The mentioned team received your video. They are now watching your video, + and formulating questions. You would be able to exchange with the other phase during + the next phase. + {% endblocktrans %} +
+ {% elif current_phase.phase_number == 3 %} +
+ {% blocktrans trimmed with user_id=user.pk %} + The other team sent you questions about your solution. Your are now able to answer them, + then to exchange freely with the other team. You can click on the Chat button, or to + connect to your dedicated Matrix account: + @corres2math_{{ user_id }}:correspondances-maths.fr. + You can use your own Matrix client, or use the dedicated Element client: + element.correpondances-maths.fr + {% endblocktrans %} +
+ {% elif current_phase.phase_number == 4 %} +
+
{% trans "Synthesis from the other team:" %}
+
+ {{ participation.received_participation.synthesis.link|default:novideo }} + {% if participation.received_participation.synthesis.link %} + + {% endif %} +
+
+ {% endif %} +
+
+
+
+
+
+

{% trans "Received solution" %}

+
+
+
+
{% trans "Team that sent you their solution:" %}
+
{{ participation.received_participation.team|default:any }}
+ {% if user.registration.is_admin %} +
+ +
+ {% endif %} + +
{% trans "Proposed solution:" %}
+
+ {{ participation.received_participation.solution.link|default:novideo }} + {% if participation.received_participation.solution.link %} + + {% endif %} +
+ + {% if current_phase.phase_number == 2 %} +
+ {% blocktrans trimmed %} + You received a solution about the same problem that you treated from another team. + You are now encouraged to see the video, then to ask from 3 to 6 questions about the video. + After that, you will be invited to exchange with the other team about the solution. + {% endblocktrans %} +
+ + {% for question in participation.questions.all %} +
{{ question.question }}
+
+ +
+
+ {% endfor %} + + {% if user.registration.participates %} + + {% endif %} + {% elif current_phase.phase_number == 3 %} +
+ {% blocktrans trimmed with user_id=user.pk %} + You sent your questions to the other team about their solution. When they answer to + your questions, you will be able to exchange freely with the other team. + You can click on the Chat button, or to connect to your dedicated Matrix account: + @corres2math_{{ user_id }}:correspondances-maths.fr. + You can use your own Matrix client, or use the dedicated Element client: + element.correpondances-maths.fr + {% endblocktrans %} +
+ {% elif current_phase.phase_number == 4 %} +
+
+ {% trans "No video sent" as novideo %} +
{% trans "Your synthesis of the exchange:" %}
+
+ {{ participation.synthesis.link|default:novideo }} + + {% if participation.synthesis.link %} + + {% endif %} +
+
+
+ {% endif %} +
+
+
+
+
+ {% endif %} + +{% if user.registration.is_admin %} + {% trans "Define received video" as modal_title %} + {% trans "Update" as modal_button %} + {% url "participation:participation_receive_participation" pk=participation.pk as modal_action %} + {% include "base_modal.html" with modal_id="defineReceivedParticipation" %} + + {% trans "Define team that receives your video" as modal_title %} + {% trans "Update" as modal_button %} + {% url "participation:participation_send_participation" pk=participation.pk as modal_action %} + {% include "base_modal.html" with modal_id="defineSentParticipation" %} +{% endif %} + +{% trans "Upload video" as modal_title %} +{% trans "Upload" as modal_button %} +{% url "participation:upload_video" pk=participation.solution_id as modal_action %} +{% include "base_modal.html" with modal_id="uploadSolution" %} + +{% trans "Display solution" as modal_title %} +{% trans "This video platform is not supported yet." as unsupported_platform %} +{% include "base_modal.html" with modal_id="displaySolution" modal_action="" modal_button="" modal_additional_class="modal-lg" modal_content=participation.solution.as_iframe|default:unsupported_platform %} + + +{% if user.registration.is_admin or current_phase.phase_number >= 2 %} + {% if participation.received_participation.solution.link %} + {% trans "Display solution" as modal_title %} + {% trans "This video platform is not supported yet." as unsupported_platform %} + {% include "base_modal.html" with modal_id="displayOtherSolution" modal_action="" modal_button="" modal_additional_class="modal-lg" modal_content=participation.received_participation.solution.as_iframe|default:unsupported_platform %} + {% endif %} +{% endif %} + +{% if user.registration.participates and current_phase.phase_number == 2 %} + {% trans "Add question" as modal_title %} + {% trans "Add" as modal_button %} + {% url "participation:add_question" pk=participation.pk as modal_action %} + {% include "base_modal.html" with modal_id="addQuestion" modal_button_type="success" %} + {% for question in participation.questions.all %} + {% with number_str=forloop.counter|stringformat:"d"%} + {% with modal_id="updateQuestion"|add:number_str %} + {% trans "Delete" as delete %} + {% with extra_modal_button='"|safe %} + {% trans "Update question" as modal_title %} + {% trans "Update" as modal_button %} + {% url "participation:update_question" pk=question.pk as modal_action %} + {% include "base_modal.html" %} + {% endwith %} + {% endwith %} + + {% with modal_id="deleteQuestion"|add:number_str %} + {% trans "Delete question" as modal_title %} + {% trans "Delete" as modal_button %} + {% url "participation:delete_question" pk=question.pk as modal_action %} + {% include "base_modal.html" with modal_button_type="danger" %} + {% endwith %} + {% endwith %} + {% endfor %} +{% endif %} + +{% if current_phase.phase_number >= 4 %} + {% if participation.received_participation.synthesis.link %} + {% trans "Display synthesis" as modal_title %} + {% trans "This video platform is not supported yet." as unsupported_platform %} + {% include "base_modal.html" with modal_id="displayOtherSynthesis" modal_action="" modal_button="" modal_additional_class="modal-lg" modal_content=participation.received_participation.synthesis.as_iframe|default:unsupported_platform %} + {% endif %} + + {% trans "Upload video" as modal_title %} + {% trans "Upload" as modal_button %} + {% url "participation:upload_video" pk=participation.synthesis_id as modal_action %} + {% include "base_modal.html" with modal_id="uploadSynthesis" %} + + {% if participation.synthesis.link %} + {% trans "Display synthesis" as modal_title %} + {% trans "This video platform is not supported yet." as unsupported_platform %} + {% include "base_modal.html" with modal_id="displaySynthesis" modal_action="" modal_button="" modal_additional_class="modal-lg" modal_content=participation.synthesis.as_iframe|default:unsupported_platform %} + {% endif %} +{% endif %} +{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/participation/templates/participation/phase_form.html b/apps/participation/templates/participation/phase_form.html new file mode 100644 index 0000000..b2b3a5c --- /dev/null +++ b/apps/participation/templates/participation/phase_form.html @@ -0,0 +1,14 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} + diff --git a/apps/participation/templates/participation/phase_list.html b/apps/participation/templates/participation/phase_list.html new file mode 100644 index 0000000..622b8fd --- /dev/null +++ b/apps/participation/templates/participation/phase_list.html @@ -0,0 +1,35 @@ +{% extends "base.html" %} + +{% load django_tables2 i18n static %} + +{% block extracss %} + +{% endblock %} + +{% block contenttitle %} +

{% trans "Calendar" %}

+{% endblock %} + +{% block content %} +
+ {% render_table table %} + + {% trans "Update phase" as modal_title %} + {% trans "Update" as modal_button %} + {% include "base_modal.html" with modal_id="updatePhase" %} +
+{% endblock %} + +{% block extrajavascript %} +{% if user.registration.is_admin %} + +{% endif %} +{% endblock %} diff --git a/apps/participation/templates/participation/question_confirm_delete.html b/apps/participation/templates/participation/question_confirm_delete.html new file mode 100644 index 0000000..6c64cb5 --- /dev/null +++ b/apps/participation/templates/participation/question_confirm_delete.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+
+ {% trans "Are you sure you want to delete this question?" %} +
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} + diff --git a/apps/participation/templates/participation/question_form.html b/apps/participation/templates/participation/question_form.html new file mode 100644 index 0000000..3346075 --- /dev/null +++ b/apps/participation/templates/participation/question_form.html @@ -0,0 +1,14 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} + diff --git a/apps/participation/templates/participation/receive_participation_form.html b/apps/participation/templates/participation/receive_participation_form.html new file mode 100644 index 0000000..a5bb901 --- /dev/null +++ b/apps/participation/templates/participation/receive_participation_form.html @@ -0,0 +1,14 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} + diff --git a/apps/participation/templates/participation/send_participation_form.html b/apps/participation/templates/participation/send_participation_form.html new file mode 100644 index 0000000..a5bb901 --- /dev/null +++ b/apps/participation/templates/participation/send_participation_form.html @@ -0,0 +1,14 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} + diff --git a/apps/participation/templates/participation/team_detail.html b/apps/participation/templates/participation/team_detail.html new file mode 100644 index 0000000..f6fcf21 --- /dev/null +++ b/apps/participation/templates/participation/team_detail.html @@ -0,0 +1,148 @@ +{% extends "base.html" %} + +{% load i18n %} +{% load crispy_forms_filters %} + +{% block content %} + +
+
+

{{ team.name }}

+
+
+
+
{% trans "Name:" %}
+
{{ team.name }}
+ +
{% trans "Trigram:" %}
+
{{ team.trigram }}
+ +
{% trans "Email:" %}
+
{{ team.email }}
+ +
{% trans "Access code:" %}
+
{{ team.access_code }}
+ +
{% trans "Coachs:" %}
+
+ {% for coach in team.coachs.all %} + {{ coach }}{% if not forloop.last %},{% endif %} + {% empty %} + {% trans "any" %} + {% endfor %} +
+ +
{% trans "Participants:" %}
+
+ {% for student in team.students.all %} + {{ student }}{% if not forloop.last %},{% endif %} + {% empty %} + {% trans "any" %} + {% endfor %} +
+ +
{% trans "Chosen problem:" %}
+ {% trans "any" as any %} +
{{ team.participation.get_problem_display|default:any }}
+ +
{% trans "Grant Animath to publish our video:" %}
+
{{ team.grant_animath_access_videos|yesno }}
+ +
{% trans "Authorizations:" %}
+
+ {% for student in team.students.all %} + {% if student.photo_authorization %} + {{ student }}{% if not forloop.last %},{% endif %} + {% else %} + {{ student }} ({% trans "Not uploaded yet" %}){% if not forloop.last %},{% endif %} + {% endif %} + {% endfor %} +
+
+
+ +
+ +
+ + {% if team.participation.valid %} + + {% elif team.participation.valid == None %} {# Team did not ask for validation #} + {% if user.registration.participates %} + {% if can_validate %} +
+ {% trans "Your team has at least 3 members and all photo authorizations were given: the team can be validated." %} +
+
+ {% csrf_token %} + {{ request_validation_form|crispy }} + +
+
+
+ {% else %} +
+ {% trans "Your team must be composed of 3 members and each member must upload its photo authorization and confirm its email address." %} +
+ {% endif %} + {% else %} +
+ {% trans "This team didn't ask for validation yet." %} +
+ {% endif %} + {% else %} {# Team is waiting for validation #} + {% if user.registration.participates %} +
+ {% trans "Your validation is pending." %} +
+ {% else %} +
+ {% trans "The team requested to be validated. You may now control the authorizations and confirm that they can participate." %} +
+
+ {% csrf_token %} + {{ validation_form|crispy }} +
+ + +
+
+ {% endif %} + {% endif %} + + {% trans "Update team" as modal_title %} + {% trans "Update" as modal_button %} + {% url "participation:update_team" pk=team.pk as modal_action %} + {% include "base_modal.html" with modal_id="updateTeam" %} + + {% trans "Leave team" as modal_title %} + {% trans "Leave" as modal_button %} + {% url "participation:team_leave" as modal_action %} + {% include "base_modal.html" with modal_id="leaveTeam" modal_button_type="danger" %} +{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/participation/templates/participation/team_leave.html b/apps/participation/templates/participation/team_leave.html new file mode 100644 index 0000000..72d3db9 --- /dev/null +++ b/apps/participation/templates/participation/team_leave.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {% trans "Are you sure that you want to leave this team?" %} +
+ +
+{% endblock %} diff --git a/apps/participation/templates/participation/update_team.html b/apps/participation/templates/participation/update_team.html new file mode 100644 index 0000000..28f0d28 --- /dev/null +++ b/apps/participation/templates/participation/update_team.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} + {{ participation_form|crispy }} +
+ +
+{% endblock content %} + diff --git a/apps/participation/templates/participation/upload_video.html b/apps/participation/templates/participation/upload_video.html new file mode 100644 index 0000000..5271644 --- /dev/null +++ b/apps/participation/templates/participation/upload_video.html @@ -0,0 +1,14 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} + diff --git a/apps/participation/templates/participation/youtube_iframe.html b/apps/participation/templates/participation/youtube_iframe.html new file mode 100644 index 0000000..4c577d2 --- /dev/null +++ b/apps/participation/templates/participation/youtube_iframe.html @@ -0,0 +1,8 @@ +
+ +
diff --git a/apps/participation/templates/search/indexes/participation/participation_text.txt b/apps/participation/templates/search/indexes/participation/participation_text.txt new file mode 100644 index 0000000..57aa6bc --- /dev/null +++ b/apps/participation/templates/search/indexes/participation/participation_text.txt @@ -0,0 +1,4 @@ +{{ object.team.name }} +{{ object.team.trigram }} +{{ object.problem }} +{{ object.get_problem_display }} diff --git a/apps/participation/templates/search/indexes/participation/team_text.txt b/apps/participation/templates/search/indexes/participation/team_text.txt new file mode 100644 index 0000000..d673407 --- /dev/null +++ b/apps/participation/templates/search/indexes/participation/team_text.txt @@ -0,0 +1,2 @@ +{{ object.name }} +{{ object.trigram }} diff --git a/apps/participation/templates/search/indexes/participation/video_text.txt b/apps/participation/templates/search/indexes/participation/video_text.txt new file mode 100644 index 0000000..4303f3a --- /dev/null +++ b/apps/participation/templates/search/indexes/participation/video_text.txt @@ -0,0 +1,5 @@ +{{ object.link }} +{{ object.participation.team.name }} +{{ object.participation.team.trigram }} +{{ object.participation.problem }} +{{ object.participation.get_problem_display }} diff --git a/apps/participation/tests.py b/apps/participation/tests.py new file mode 100644 index 0000000..abd8dd7 --- /dev/null +++ b/apps/participation/tests.py @@ -0,0 +1,231 @@ +from django.contrib.auth.models import User +from django.test import TestCase +from django.urls import reverse +from registration.models import StudentRegistration + +from .models import Team + + +class TestStudentParticipation(TestCase): + def setUp(self) -> None: + self.user = User.objects.create( + first_name="Toto", + last_name="Toto", + email="toto@example.com", + password="toto", + ) + StudentRegistration.objects.create( + user=self.user, + student_class=12, + school="Earth", + give_contact_to_animath=True, + email_confirmed=True, + ) + self.team = Team.objects.create( + name="Super team", + trigram="AAA", + access_code="azerty", + grant_animath_access_videos=True, + ) + self.client.force_login(self.user) + + # TODO Remove these lines + str(self.team) + str(self.team.participation) + + def test_create_team(self): + """ + Try to create a team. + """ + response = self.client.get(reverse("participation:create_team")) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("participation:create_team"), data=dict( + name="Test team", + trigram="123", + grant_animath_access_videos=False, + )) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("participation:create_team"), data=dict( + name="Test team", + trigram="TES", + grant_animath_access_videos=False, + )) + self.assertTrue(Team.objects.filter(trigram="TES").exists()) + team = Team.objects.get(trigram="TES") + self.assertRedirects(response, reverse("participation:team_detail", args=(team.pk,)), 302, 200) + + # Already in a team + response = self.client.post(reverse("participation:create_team"), data=dict( + name="Test team 2", + trigram="TET", + grant_animath_access_videos=False, + )) + + def test_join_team(self): + """ + Try to join an existing team. + """ + response = self.client.get(reverse("participation:join_team")) + self.assertEqual(response.status_code, 200) + + team = Team.objects.create(name="Test", trigram="TES") + + response = self.client.post(reverse("participation:join_team"), data=dict( + access_code="éééééé", + )) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("participation:join_team"), data=dict( + access_code=team.access_code, + )) + self.assertRedirects(response, reverse("participation:team_detail", args=(team.pk,)), 302, 200) + self.assertTrue(Team.objects.filter(trigram="TES").exists()) + + # Already joined + response = self.client.post(reverse("participation:join_team"), data=dict( + access_code=team.access_code, + )) + self.assertEqual(response.status_code, 403) + + def test_no_myteam_redirect_noteam(self): + """ + Test redirection. + """ + response = self.client.get(reverse("participation:my_team_detail")) + self.assertTrue(response.status_code, 200) + + def test_team_detail(self): + """ + Try to display the information of a team. + """ + self.user.registration.team = self.team + self.user.registration.save() + + response = self.client.get(reverse("participation:my_team_detail")) + self.assertRedirects(response, reverse("participation:team_detail", args=(self.team.pk,)), 302, 200) + + response = self.client.get(reverse("participation:team_detail", args=(self.team.pk,))) + self.assertEqual(response.status_code, 200) + + def test_update_team(self): + """ + Try to update team information. + """ + self.user.registration.team = self.team + self.user.registration.save() + + response = self.client.get(reverse("participation:update_team", args=(self.team.pk,))) + self.assertEqual(response.status_code, 200) + + # Form is invalid + response = self.client.post(reverse("participation:update_team", args=(self.team.pk,)), data=dict( + name="Updated team name", + trigram="BBB", + grant_animath_access_videos=True, + problem=42, + )) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("participation:update_team", args=(self.team.pk,)), data=dict( + name="Updated team name", + trigram="BBB", + grant_animath_access_videos=True, + problem=3, + )) + self.assertRedirects(response, reverse("participation:team_detail", args=(self.team.pk,)), 302, 200) + self.assertTrue(Team.objects.filter(trigram="BBB", participation__problem=3).exists()) + + def test_no_myparticipation_redirect_nomyparticipation(self): + """ + Ensure a permission denied when we search my team participation when we are in no team. + """ + response = self.client.get(reverse("participation:my_participation_detail")) + self.assertEqual(response.status_code, 403) + + def test_participation_detail(self): + """ + Try to display the detail of a team participation. + """ + self.user.registration.team = self.team + self.user.registration.save() + + response = self.client.get(reverse("participation:my_participation_detail")) + self.assertRedirects(response, + reverse("participation:participation_detail", args=(self.team.participation.pk,)), + 302, 403) + + self.team.participation.valid = True + self.team.participation.save() + response = self.client.get(reverse("participation:my_participation_detail")) + self.assertRedirects(response, + reverse("participation:participation_detail", args=(self.team.participation.pk,)), + 302, 200) + + response = self.client.get(reverse("participation:participation_detail", args=(self.team.participation.pk,))) + self.assertEqual(response.status_code, 200) + + def test_upload_video(self): + """ + Try to send a solution video link. + """ + self.user.registration.team = self.team + self.user.registration.save() + + self.team.participation.valid = True + self.team.participation.save() + + response = self.client.get(reverse("participation:upload_video", args=(self.team.participation.solution.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("participation:upload_video", args=(self.team.participation.solution.pk,)), + data=dict(link="https://youtube.com/watch?v=73nsrixx7eI")) + self.assertRedirects(response, + reverse("participation:participation_detail", args=(self.team.participation.id,)), + 302, 200) + self.team.participation.refresh_from_db() + self.assertEqual(self.team.participation.solution.platform, "youtube") + self.assertEqual(self.team.participation.solution.youtube_code, "73nsrixx7eI") + + response = self.client.get(reverse("participation:participation_detail", args=(self.team.participation.pk,))) + self.assertEqual(response.status_code, 200) + + +class TestAdminForbidden(TestCase): + def setUp(self) -> None: + self.user = User.objects.create_superuser( + username="admin@example.com", + email="admin@example.com", + password="admin", + ) + self.client.force_login(self.user) + + def test_create_team_forbidden(self): + """ + Ensure that an admin can't create a team. + """ + response = self.client.post(reverse("participation:create_team"), data=dict( + name="Test team", + trigram="TES", + grant_animath_access_videos=False, + )) + self.assertEqual(response.status_code, 403) + + def test_join_team_forbidden(self): + """ + Ensure that an admin can't join a team. + """ + team = Team.objects.create(name="Test", trigram="TES") + + response = self.client.post(reverse("participation:join_team"), data=dict( + access_code=team.access_code, + )) + self.assertTrue(response.status_code, 403) + + def test_my_team_forbidden(self): + """ + Ensure that an admin can't access to "My team". + """ + response = self.client.get(reverse("participation:my_team_detail")) + self.assertEqual(response.status_code, 403) diff --git a/apps/participation/urls.py b/apps/participation/urls.py new file mode 100644 index 0000000..b3233dc --- /dev/null +++ b/apps/participation/urls.py @@ -0,0 +1,33 @@ +from django.urls import path +from django.views.generic import TemplateView + +from .views import CalendarView, CreateQuestionView, CreateTeamView, DeleteQuestionView, JoinTeamView, \ + MyParticipationDetailView, MyTeamDetailView, ParticipationDetailView, PhaseUpdateView, \ + SetParticipationReceiveParticipationView, SetParticipationSendParticipationView, TeamAuthorizationsView, \ + TeamDetailView, TeamLeaveView, TeamUpdateView, UpdateQuestionView, UploadVideoView + + +app_name = "participation" + +urlpatterns = [ + path("create_team/", CreateTeamView.as_view(), name="create_team"), + path("join_team/", JoinTeamView.as_view(), name="join_team"), + path("team/", MyTeamDetailView.as_view(), name="my_team_detail"), + path("team//", TeamDetailView.as_view(), name="team_detail"), + path("team//update/", TeamUpdateView.as_view(), name="update_team"), + path("team//authorizations/", TeamAuthorizationsView.as_view(), name="team_authorizations"), + path("team/leave/", TeamLeaveView.as_view(), name="team_leave"), + path("detail/", MyParticipationDetailView.as_view(), name="my_participation_detail"), + path("detail//", ParticipationDetailView.as_view(), name="participation_detail"), + path("detail/upload-video//", UploadVideoView.as_view(), name="upload_video"), + path("detail//receive-participation/", SetParticipationReceiveParticipationView.as_view(), + name="participation_receive_participation"), + path("detail//send-participation/", SetParticipationSendParticipationView.as_view(), + name="participation_send_participation"), + path("detail//add-question/", CreateQuestionView.as_view(), name="add_question"), + path("update-question//", UpdateQuestionView.as_view(), name="update_question"), + path("delete-question//", DeleteQuestionView.as_view(), name="delete_question"), + path("calendar/", CalendarView.as_view(), name="calendar"), + path("calendar//", PhaseUpdateView.as_view(), name="update_phase"), + path("chat/", TemplateView.as_view(template_name="participation/chat.html"), name="chat") +] diff --git a/apps/participation/views.py b/apps/participation/views.py new file mode 100644 index 0000000..95b0a75 --- /dev/null +++ b/apps/participation/views.py @@ -0,0 +1,494 @@ +from io import BytesIO +from zipfile import ZipFile + +from corres2math.lists import get_sympa_client +from corres2math.matrix import Matrix +from corres2math.views import AdminMixin +from django.contrib.auth.mixins import LoginRequiredMixin +from django.core.exceptions import PermissionDenied +from django.core.mail import send_mail +from django.db import transaction +from django.http import HttpResponse +from django.shortcuts import redirect +from django.template.loader import render_to_string +from django.urls import reverse_lazy +from django.utils.translation import gettext_lazy as _ +from django.views.generic import CreateView, DeleteView, DetailView, FormView, RedirectView, TemplateView, UpdateView +from django.views.generic.edit import FormMixin, ProcessFormView +from django_tables2 import SingleTableView +from magic import Magic +from registration.models import AdminRegistration + +from .forms import JoinTeamForm, ParticipationForm, PhaseForm, QuestionForm, \ + ReceiveParticipationForm, RequestValidationForm, SendParticipationForm, TeamForm, \ + UploadVideoForm, ValidateParticipationForm +from .models import Participation, Phase, Question, Team, Video +from .tables import CalendarTable + + +class CreateTeamView(LoginRequiredMixin, CreateView): + """ + Display the page to create a team for new users. + """ + + model = Team + form_class = TeamForm + extra_context = dict(title=_("Create team")) + template_name = "participation/create_team.html" + + def dispatch(self, request, *args, **kwargs): + user = request.user + registration = user.registration + if not registration.participates: + raise PermissionDenied(_("You don't participate, so you can't create a team.")) + elif registration.team: + raise PermissionDenied(_("You are already in a team.")) + return super().dispatch(request, *args, **kwargs) + + @transaction.atomic + def form_valid(self, form): + """ + When a team is about to be created, the user automatically + joins the team, a mailing list got created and the user is + automatically subscribed to this mailing list, and finally + a Matrix room is created and the user is invited in this room. + """ + ret = super().form_valid(form) + # The user joins the team + user = self.request.user + registration = user.registration + registration.team = form.instance + registration.save() + + # Subscribe the user mail address to the team mailing list + get_sympa_client().subscribe(user.email, f"equipe-{form.instance.trigram.lower()}", False, + f"{user.first_name} {user.last_name}") + + # Invite the user in the team Matrix room + Matrix.invite(f"#equipe-{form.instance.trigram.lower()}:correspondances-maths.fr", + f"@{user.registration.matrix_username}:correspondances-maths.fr") + return ret + + def get_success_url(self): + return reverse_lazy("participation:team_detail", args=(self.object.pk,)) + + +class JoinTeamView(LoginRequiredMixin, FormView): + """ + Participants can join a team with the access code of the team. + """ + model = Team + form_class = JoinTeamForm + extra_context = dict(title=_("Join team")) + template_name = "participation/create_team.html" + + def dispatch(self, request, *args, **kwargs): + user = request.user + registration = user.registration + if not registration.participates: + raise PermissionDenied(_("You don't participate, so you can't create a team.")) + elif registration.team: + raise PermissionDenied(_("You are already in a team.")) + return super().dispatch(request, *args, **kwargs) + + @transaction.atomic + def form_valid(self, form): + """ + When a user joins a team, the user is automatically subscribed to + the team mailing list,the user is invited in the team Matrix room. + """ + self.object = form.instance + ret = super().form_valid(form) + + # Join the team + user = self.request.user + registration = user.registration + registration.team = form.instance + registration.save() + + # Subscribe to the team mailing list + get_sympa_client().subscribe(user.email, f"equipe-{form.instance.trigram.lower()}", False, + f"{user.first_name} {user.last_name}") + + # Invite the user in the team Matrix room + Matrix.invite(f"#equipe-{form.instance.trigram.lower()}:correspondances-maths.fr", + f"@{user.registration.matrix_username}:correspondances-maths.fr") + return ret + + def get_success_url(self): + return reverse_lazy("participation:team_detail", args=(self.object.pk,)) + + +class MyTeamDetailView(LoginRequiredMixin, RedirectView): + """ + Redirect to the detail of the team in which the user is. + """ + + def get_redirect_url(self, *args, **kwargs): + user = self.request.user + registration = user.registration + if registration.participates: + if registration.team: + return reverse_lazy("participation:team_detail", args=(registration.team_id,)) + raise PermissionDenied(_("You are not in a team.")) + raise PermissionDenied(_("You don't participate, so you don't have any team.")) + + +class TeamDetailView(LoginRequiredMixin, FormMixin, ProcessFormView, DetailView): + """ + Display the detail of a team. + """ + model = Team + + def get(self, request, *args, **kwargs): + user = request.user + self.object = self.get_object() + # Ensure that the user is an admin or a member of the team + if user.registration.is_admin or user.registration.participates and user.registration.team.pk == kwargs["pk"]: + return super().get(request, *args, **kwargs) + raise PermissionDenied + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + + team = self.get_object() + context["title"] = _("Detail of team {trigram}").format(trigram=self.object.trigram) + context["request_validation_form"] = RequestValidationForm(self.request.POST or None) + context["validation_form"] = ValidateParticipationForm(self.request.POST or None) + # A team is complete when there are at least 3 members that have sent their photo authorization + # and confirmed their email address + context["can_validate"] = team.students.count() >= 3 and \ + all(r.email_confirmed for r in team.students.all()) and \ + all(r.photo_authorization for r in team.students.all()) and \ + team.participation.problem + + return context + + def get_form_class(self): + if not self.request.POST: + return RequestValidationForm + elif self.request.POST["_form_type"] == "RequestValidationForm": + return RequestValidationForm + elif self.request.POST["_form_type"] == "ValidateParticipationForm": + return ValidateParticipationForm + return None + + def form_valid(self, form): + self.object = self.get_object() + if isinstance(form, RequestValidationForm): + if not self.request.user.registration.participates: + form.add_error(None, _("You don't participate, so you can't request the validation of the team.")) + return self.form_invalid(form) + if self.object.participation.valid is not None: + form.add_error(None, _("The validation of the team is already done or pending.")) + return self.form_invalid(form) + + self.object.participation.valid = False + self.object.participation.save() + + for admin in AdminRegistration.objects.all(): + mail_context = dict(user=admin.user, team=self.object) + mail_plain = render_to_string("participation/mails/request_validation.txt", mail_context) + mail_html = render_to_string("participation/mails/request_validation.html", mail_context) + admin.user.email_user("[Corres2math] Validation d'équipe", mail_plain, html_message=mail_html) + elif isinstance(form, ValidateParticipationForm): + if not self.request.user.registration.is_admin: + form.add_error(None, _("You are not an administrator.")) + return self.form_invalid(form) + elif self.object.participation.valid is not False: + form.add_error(None, _("This team has no pending validation.")) + return self.form_invalid(form) + + if "validate" in self.request.POST: + self.object.participation.valid = True + self.object.participation.save() + mail_context = dict(team=self.object, message=form.cleaned_data["message"]) + mail_plain = render_to_string("participation/mails/team_validated.txt", mail_context) + mail_html = render_to_string("participation/mails/team_validated.html", mail_context) + send_mail("[Corres2math] Équipe validée", mail_plain, None, [self.object.email], html_message=mail_html) + elif "invalidate" in self.request.POST: + self.object.participation.valid = None + self.object.participation.save() + mail_context = dict(team=self.object, message=form.cleaned_data["message"]) + mail_plain = render_to_string("participation/mails/team_not_validated.txt", mail_context) + mail_html = render_to_string("participation/mails/team_not_validated.html", mail_context) + send_mail("[Corres2math] Équipe non validée", mail_plain, None, [self.object.email], + html_message=mail_html) + else: + form.add_error(None, _("You must specify if you validate the registration or not.")) + return self.form_invalid(form) + + return super().form_invalid(form) + + def get_success_url(self): + return self.request.path + + +class TeamUpdateView(LoginRequiredMixin, UpdateView): + """ + Update the detail of a team + """ + model = Team + form_class = TeamForm + template_name = "participation/update_team.html" + + def dispatch(self, request, *args, **kwargs): + user = request.user + if user.registration.is_admin or user.registration.participates and user.registration.team.pk == kwargs["pk"]: + return super().dispatch(request, *args, **kwargs) + raise PermissionDenied + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + context["participation_form"] = ParticipationForm(data=self.request.POST or None, + instance=self.object.participation) + context["title"] = _("Update team {trigram}").format(trigram=self.object.trigram) + return context + + @transaction.atomic + def form_valid(self, form): + participation_form = ParticipationForm(data=self.request.POST or None, instance=self.object.participation) + if not participation_form.is_valid(): + return self.form_invalid(form) + + participation_form.save() + return super().form_valid(form) + + def get_success_url(self): + return reverse_lazy("participation:team_detail", args=(self.object.pk,)) + + +class TeamAuthorizationsView(LoginRequiredMixin, DetailView): + """ + Get as a ZIP archive all the authorizations that are sent + """ + model = Team + + def dispatch(self, request, *args, **kwargs): + user = request.user + if user.registration.is_admin or user.registration.participates and user.registration.team.pk == kwargs["pk"]: + return super().dispatch(request, *args, **kwargs) + raise PermissionDenied + + def get(self, request, *args, **kwargs): + team = self.get_object() + output = BytesIO() + zf = ZipFile(output, "w") + for student in team.students.all(): + magic = Magic(mime=True) + mime_type = magic.from_file("media/" + student.photo_authorization.name) + ext = mime_type.split("/")[1].replace("jpeg", "jpg") + zf.write("media/" + student.photo_authorization.name, + _("Photo authorization of {student}.{ext}").format(student=str(student), ext=ext)) + zf.close() + response = HttpResponse(content_type="application/zip") + response["Content-Disposition"] = "attachment; filename=\"{filename}\"" \ + .format(filename=_("Photo authorizations of team {trigram}.zip").format(trigram=team.trigram)) + response.write(output.getvalue()) + return response + + +class TeamLeaveView(LoginRequiredMixin, TemplateView): + """ + A team member leaves a team + """ + template_name = "participation/team_leave.html" + extra_context = dict(title=_("Leave team")) + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return self.handle_no_permission() + if not request.user.registration.team: + raise PermissionDenied(_("You are not in a team.")) + if request.user.registration.team.participation.valid is not None: + raise PermissionDenied(_("The team is already validated or the validation is pending.")) + return super().dispatch(request, *args, **kwargs) + + @transaction.atomic() + def post(self, request, *args, **kwargs): + """ + When the team is left, the user is unsubscribed from the team mailing list + and kicked from the team room. + """ + team = request.user.registration.team + request.user.registration.team = None + request.user.registration.save() + get_sympa_client().unsubscribe(request.user.email, f"equipe-{team.trigram.lower()}", False) + Matrix.kick(f"#equipe-{team.trigram.lower()}:correspondances-maths.fr", + f"@{request.user.registration.matrix_username}:correspondances-maths.fr", + "Équipe quittée") + if team.students.count() + team.coachs.count() == 0: + team.delete() + return redirect(reverse_lazy("index")) + + +class MyParticipationDetailView(LoginRequiredMixin, RedirectView): + """ + Redirects to the detail view of the participation of the team. + """ + def get_redirect_url(self, *args, **kwargs): + user = self.request.user + registration = user.registration + if registration.participates: + if registration.team: + return reverse_lazy("participation:participation_detail", args=(registration.team.participation.id,)) + raise PermissionDenied(_("You are not in a team.")) + raise PermissionDenied(_("You don't participate, so you don't have any team.")) + + +class ParticipationDetailView(LoginRequiredMixin, DetailView): + """ + Display detail about the participation of a team, and manage the video submission. + """ + model = Participation + + def dispatch(self, request, *args, **kwargs): + user = request.user + if not self.get_object().valid: + raise PermissionDenied(_("The team is not validated yet.")) + if user.registration.is_admin or user.registration.participates \ + and user.registration.team.participation.pk == kwargs["pk"]: + return super().dispatch(request, *args, **kwargs) + raise PermissionDenied + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + + context["title"] = lambda: _("Participation of team {trigram}").format(trigram=self.object.team.trigram) + context["current_phase"] = Phase.current_phase() + + return context + + +class SetParticipationReceiveParticipationView(AdminMixin, UpdateView): + """ + Define the solution that a team will receive. + """ + model = Participation + form_class = ReceiveParticipationForm + template_name = "participation/receive_participation_form.html" + + def get_success_url(self): + return reverse_lazy("participation:participation_detail", args=(self.object.pk,)) + + +class SetParticipationSendParticipationView(AdminMixin, UpdateView): + """ + Define the team where the solution will be sent. + """ + model = Participation + form_class = SendParticipationForm + template_name = "participation/send_participation_form.html" + + def get_success_url(self): + return reverse_lazy("participation:participation_detail", args=(self.object.pk,)) + + +class CreateQuestionView(LoginRequiredMixin, CreateView): + """ + Ask a question to another team. + """ + participation: Participation + model = Question + form_class = QuestionForm + extra_context = dict(title=_("Create question")) + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return self.handle_no_permission() + self.participation = Participation.objects.get(pk=kwargs["pk"]) + if request.user.registration.is_admin or \ + request.user.registration.participates and \ + request.user.registration.team.pk == self.participation.team_id: + return super().dispatch(request, *args, **kwargs) + raise PermissionDenied + + def form_valid(self, form): + form.instance.participation = self.participation + return super().form_valid(form) + + def get_success_url(self): + return reverse_lazy("participation:participation_detail", args=(self.participation.pk,)) + + +class UpdateQuestionView(LoginRequiredMixin, UpdateView): + """ + Edit a question. + """ + model = Question + form_class = QuestionForm + + def dispatch(self, request, *args, **kwargs): + self.object = self.get_object() + if not request.user.is_authenticated: + return self.handle_no_permission() + if request.user.registration.is_admin or \ + request.user.registration.participates and \ + request.user.registration.team.pk == self.object.participation.team_id: + return super().dispatch(request, *args, **kwargs) + raise PermissionDenied + + def get_success_url(self): + return reverse_lazy("participation:participation_detail", args=(self.object.participation.pk,)) + + +class DeleteQuestionView(LoginRequiredMixin, DeleteView): + """ + Remove a question. + """ + model = Question + extra_context = dict(title=_("Delete question")) + + def dispatch(self, request, *args, **kwargs): + self.object = self.get_object() + if not request.user.is_authenticated: + return self.handle_no_permission() + if request.user.registration.is_admin or \ + request.user.registration.participates and \ + request.user.registration.team.pk == self.object.participation.team_id: + return super().dispatch(request, *args, **kwargs) + raise PermissionDenied + + def get_success_url(self): + return reverse_lazy("participation:participation_detail", args=(self.object.participation.pk,)) + + +class UploadVideoView(LoginRequiredMixin, UpdateView): + """ + Upload a solution video for a team. + """ + model = Video + form_class = UploadVideoForm + template_name = "participation/upload_video.html" + extra_context = dict(title=_("Upload video")) + + def dispatch(self, request, *args, **kwargs): + user = request.user + if user.registration.is_admin or user.registration.participates \ + and user.registration.team.participation.pk == self.get_object().participation.pk: + return super().dispatch(request, *args, **kwargs) + raise PermissionDenied + + def get_success_url(self): + return reverse_lazy("participation:participation_detail", args=(self.object.participation.pk,)) + + +class CalendarView(SingleTableView): + """ + Display the calendar of the action. + """ + table_class = CalendarTable + model = Phase + extra_context = dict(title=_("Calendar")) + + +class PhaseUpdateView(AdminMixin, UpdateView): + """ + Update a phase of the calendar, if we have sufficient rights. + """ + model = Phase + form_class = PhaseForm + extra_context = dict(title=_("Calendar update")) + + def get_success_url(self): + return reverse_lazy("participation:calendar") diff --git a/apps/registration/__init__.py b/apps/registration/__init__.py new file mode 100644 index 0000000..7e6a996 --- /dev/null +++ b/apps/registration/__init__.py @@ -0,0 +1 @@ +default_app_config = 'registration.apps.RegistrationConfig' diff --git a/apps/registration/admin.py b/apps/registration/admin.py new file mode 100644 index 0000000..edc257a --- /dev/null +++ b/apps/registration/admin.py @@ -0,0 +1,26 @@ +from django.contrib import admin +from polymorphic.admin import PolymorphicChildModelAdmin, PolymorphicParentModelAdmin + +from .models import AdminRegistration, CoachRegistration, Registration, StudentRegistration + + +@admin.register(Registration) +class RegistrationAdmin(PolymorphicParentModelAdmin): + child_models = (StudentRegistration, CoachRegistration, AdminRegistration,) + list_display = ("user", "type", "email_confirmed",) + polymorphic_list = True + + +@admin.register(StudentRegistration) +class StudentRegistrationAdmin(PolymorphicChildModelAdmin): + pass + + +@admin.register(CoachRegistration) +class CoachRegistrationAdmin(PolymorphicChildModelAdmin): + pass + + +@admin.register(AdminRegistration) +class AdminRegistrationAdmin(PolymorphicChildModelAdmin): + pass diff --git a/apps/registration/apps.py b/apps/registration/apps.py new file mode 100644 index 0000000..4c681a5 --- /dev/null +++ b/apps/registration/apps.py @@ -0,0 +1,17 @@ +from django.apps import AppConfig +from django.db.models.signals import post_save, pre_save + + +class RegistrationConfig(AppConfig): + """ + Registration app contains the detail about users only. + """ + name = 'registration' + + def ready(self): + from registration.signals import create_admin_registration, invite_to_public_rooms, \ + set_username, send_email_link + pre_save.connect(set_username, "auth.User") + pre_save.connect(send_email_link, "auth.User") + post_save.connect(create_admin_registration, "auth.User") + post_save.connect(invite_to_public_rooms, "registration.Registration") diff --git a/apps/registration/auth.py b/apps/registration/auth.py new file mode 100644 index 0000000..d2febf4 --- /dev/null +++ b/apps/registration/auth.py @@ -0,0 +1,14 @@ +from cas_server.auth import DjangoAuthUser + + +class CustomAuthUser(DjangoAuthUser): + """ + Override Django Auth User model to define a custom Matrix username. + """ + + def attributs(self): + d = super().attributs() + if self.user: + d["matrix_username"] = self.user.registration.matrix_username + d["display_name"] = str(self.user.registration) + return d diff --git a/apps/registration/fixtures/initial.json b/apps/registration/fixtures/initial.json new file mode 100644 index 0000000..40afb61 --- /dev/null +++ b/apps/registration/fixtures/initial.json @@ -0,0 +1,17 @@ +[ + { + "model": "cas_server.servicepattern", + "pk": 1, + "fields": { + "pos": 100, + "name": "Plateforme des Correspondances", + "pattern": "^https://correspondances-maths.fr:8448/.*$", + "user_field": "matrix_username", + "restrict_users": false, + "proxy": true, + "proxy_callback": true, + "single_log_out": true, + "single_log_out_callback": "" + } + } +] diff --git a/apps/registration/forms.py b/apps/registration/forms.py new file mode 100644 index 0000000..18d76eb --- /dev/null +++ b/apps/registration/forms.py @@ -0,0 +1,95 @@ +from django import forms +from django.contrib.auth.forms import UserCreationForm +from django.contrib.auth.models import User +from django.core.exceptions import ValidationError +from django.forms import FileInput +from django.utils.translation import gettext_lazy as _ + +from .models import AdminRegistration, CoachRegistration, StudentRegistration + + +class SignupForm(UserCreationForm): + """ + Signup form to registers participants and coaches + They can choose the role at the registration. + """ + + role = forms.ChoiceField( + label=lambda: _("role").capitalize(), + choices=lambda: [ + ("participant", _("participant").capitalize()), + ("coach", _("coach").capitalize()), + ], + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["first_name"].required = True + self.fields["last_name"].required = True + self.fields["email"].required = True + + class Meta: + model = User + fields = ('first_name', 'last_name', 'email', 'password1', 'password2', 'role',) + + +class UserForm(forms.ModelForm): + """ + Replace the default user form to require the first name, last name and the email. + The username is always equal to the email. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["first_name"].required = True + self.fields["last_name"].required = True + self.fields["email"].required = True + + class Meta: + model = User + fields = ('first_name', 'last_name', 'email',) + + +class StudentRegistrationForm(forms.ModelForm): + """ + A student can update its class, its school and if it allows Animath to contact him/her later. + """ + class Meta: + model = StudentRegistration + fields = ('student_class', 'school', 'give_contact_to_animath',) + + +class PhotoAuthorizationForm(forms.ModelForm): + """ + Form to send a photo authorization. + """ + def clean_photo_authorization(self): + file = self.files["photo_authorization"] + if file.content_type not in ["application/pdf", "image/png", "image/jpeg"]: + raise ValidationError(_("The uploaded file must be a PDF, PNG of JPEG file.")) + return self.cleaned_data["photo_authorization"] + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["photo_authorization"].widget = FileInput() + + class Meta: + model = StudentRegistration + fields = ('photo_authorization',) + + +class CoachRegistrationForm(forms.ModelForm): + """ + A coach can tell its professional activity. + """ + class Meta: + model = CoachRegistration + fields = ('professional_activity', 'give_contact_to_animath',) + + +class AdminRegistrationForm(forms.ModelForm): + """ + Admins can tell everything they want. + """ + class Meta: + model = AdminRegistration + fields = ('role', 'give_contact_to_animath',) diff --git a/apps/registration/migrations/0001_initial.py b/apps/registration/migrations/0001_initial.py new file mode 100644 index 0000000..0ea8266 --- /dev/null +++ b/apps/registration/migrations/0001_initial.py @@ -0,0 +1,70 @@ +# Generated by Django 3.1.1 on 2020-09-21 15:51 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('contenttypes', '0002_remove_content_type_name'), + ('participation', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Registration', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('give_contact_to_animath', models.BooleanField(default=False, verbose_name='Grant Animath to contact me in the future about other actions')), + ('polymorphic_ctype', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='polymorphic_registration.registration_set+', to='contenttypes.contenttype')), + ('team', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.PROTECT, to='participation.team', verbose_name='team')), + ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user')), + ], + options={ + 'verbose_name': 'registration', + 'verbose_name_plural': 'registrations', + }, + ), + migrations.CreateModel( + name='AdminRegistration', + fields=[ + ('registration_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='registration.registration')), + ('role', models.TextField(verbose_name='role of the administrator')), + ], + options={ + 'verbose_name': 'admin registration', + 'verbose_name_plural': 'admin registrations', + }, + bases=('registration.registration',), + ), + migrations.CreateModel( + name='CoachRegistration', + fields=[ + ('registration_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='registration.registration')), + ('professional_activity', models.TextField(verbose_name='professional activity')), + ], + options={ + 'verbose_name': 'coach registration', + 'verbose_name_plural': 'coach registrations', + }, + bases=('registration.registration',), + ), + migrations.CreateModel( + name='StudentRegistration', + fields=[ + ('registration_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='registration.registration')), + ('student_class', models.IntegerField(choices=[(12, '12th grade'), (11, '11th grade'), (10, '10th grade or lower')], verbose_name='student class')), + ('school', models.CharField(max_length=255, verbose_name='school')), + ], + options={ + 'verbose_name': 'student registration', + 'verbose_name_plural': 'student registrations', + }, + bases=('registration.registration',), + ), + ] diff --git a/apps/registration/migrations/0002_auto_20200921_1948.py b/apps/registration/migrations/0002_auto_20200921_1948.py new file mode 100644 index 0000000..759bbac --- /dev/null +++ b/apps/registration/migrations/0002_auto_20200921_1948.py @@ -0,0 +1,29 @@ +# Generated by Django 3.1.1 on 2020-09-21 17:48 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('participation', '0001_initial'), + ('registration', '0001_initial'), + ] + + operations = [ + migrations.RemoveField( + model_name='registration', + name='team', + ), + migrations.AddField( + model_name='coachregistration', + name='team', + field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='coachs', to='participation.team', verbose_name='team'), + ), + migrations.AddField( + model_name='studentregistration', + name='team', + field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='students', to='participation.team', verbose_name='team'), + ), + ] diff --git a/apps/registration/migrations/0003_registration_email_confirmed.py b/apps/registration/migrations/0003_registration_email_confirmed.py new file mode 100644 index 0000000..a9cc7ae --- /dev/null +++ b/apps/registration/migrations/0003_registration_email_confirmed.py @@ -0,0 +1,18 @@ +# Generated by Django 3.1.1 on 2020-09-22 16:56 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('registration', '0002_auto_20200921_1948'), + ] + + operations = [ + migrations.AddField( + model_name='registration', + name='email_confirmed', + field=models.BooleanField(default=False, verbose_name='email confirmed'), + ), + ] diff --git a/apps/registration/migrations/0004_studentregistration_photo_authorization.py b/apps/registration/migrations/0004_studentregistration_photo_authorization.py new file mode 100644 index 0000000..c6477ee --- /dev/null +++ b/apps/registration/migrations/0004_studentregistration_photo_authorization.py @@ -0,0 +1,19 @@ +# Generated by Django 3.1.1 on 2020-09-24 20:36 + +from django.db import migrations, models +import registration.models + + +class Migration(migrations.Migration): + + dependencies = [ + ('registration', '0003_registration_email_confirmed'), + ] + + operations = [ + migrations.AddField( + model_name='studentregistration', + name='photo_authorization', + field=models.FileField(blank=True, default='', upload_to=registration.models.get_random_filename, verbose_name='photo authorization'), + ), + ] diff --git a/apps/registration/migrations/__init__.py b/apps/registration/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/registration/models.py b/apps/registration/models.py new file mode 100644 index 0000000..7fe7292 --- /dev/null +++ b/apps/registration/models.py @@ -0,0 +1,196 @@ +from corres2math.tokens import email_validation_token +from django.contrib.sites.models import Site +from django.db import models +from django.template import loader +from django.urls import reverse_lazy +from django.utils.crypto import get_random_string +from django.utils.encoding import force_bytes +from django.utils.http import urlsafe_base64_encode +from django.utils.translation import gettext_lazy as _ +from polymorphic.models import PolymorphicModel + + +class Registration(PolymorphicModel): + """ + Registrations store extra content that are not asked in the User Model. + This is specific to the role of the user, see StudentRegistration, + ClassRegistration or AdminRegistration.. + """ + user = models.OneToOneField( + "auth.User", + on_delete=models.CASCADE, + verbose_name=_("user"), + ) + + give_contact_to_animath = models.BooleanField( + default=False, + verbose_name=_("Grant Animath to contact me in the future about other actions"), + ) + + email_confirmed = models.BooleanField( + default=False, + verbose_name=_("email confirmed"), + ) + + def send_email_validation_link(self): + """ + The account got created or the email got changed. + Send an email that contains a link to validate the address. + """ + subject = "[Corres2math] " + str(_("Activate your Correspondances account")) + token = email_validation_token.make_token(self.user) + uid = urlsafe_base64_encode(force_bytes(self.user.pk)) + site = Site.objects.first() + message = loader.render_to_string('registration/mails/email_validation_email.txt', + { + 'user': self.user, + 'domain': site.domain, + 'token': token, + 'uid': uid, + }) + html = loader.render_to_string('registration/mails/email_validation_email.html', + { + 'user': self.user, + 'domain': site.domain, + 'token': token, + 'uid': uid, + }) + self.user.email_user(subject, message, html_message=html) + + @property + def type(self): + raise NotImplementedError + + @property + def form_class(self): + raise NotImplementedError + + @property + def participates(self): + return isinstance(self, StudentRegistration) or isinstance(self, CoachRegistration) + + @property + def is_admin(self): + return isinstance(self, AdminRegistration) or self.user.is_superuser + + @property + def matrix_username(self): + return f"corres2math_{self.user.pk}" + + def get_absolute_url(self): + return reverse_lazy("registration:user_detail", args=(self.user_id,)) + + def __str__(self): + return f"{self.user.first_name} {self.user.last_name}" + + class Meta: + verbose_name = _("registration") + verbose_name_plural = _("registrations") + + +def get_random_filename(instance, filename): + return "authorization/photo/" + get_random_string(64) + + +class StudentRegistration(Registration): + """ + Specific registration for students. + They have a team, a student class and a school. + """ + team = models.ForeignKey( + "participation.Team", + related_name="students", + on_delete=models.PROTECT, + null=True, + default=None, + verbose_name=_("team"), + ) + + student_class = models.IntegerField( + choices=[ + (12, _("12th grade")), + (11, _("11th grade")), + (10, _("10th grade or lower")), + ], + verbose_name=_("student class"), + ) + + school = models.CharField( + max_length=255, + verbose_name=_("school"), + ) + + photo_authorization = models.FileField( + verbose_name=_("photo authorization"), + upload_to=get_random_filename, + blank=True, + default="", + ) + + @property + def type(self): + return _("student") + + @property + def form_class(self): + from registration.forms import StudentRegistrationForm + return StudentRegistrationForm + + class Meta: + verbose_name = _("student registration") + verbose_name_plural = _("student registrations") + + +class CoachRegistration(Registration): + """ + Specific registration for coaches. + They have a team and a professional activity. + """ + team = models.ForeignKey( + "participation.Team", + related_name="coachs", + on_delete=models.PROTECT, + null=True, + default=None, + verbose_name=_("team"), + ) + + professional_activity = models.TextField( + verbose_name=_("professional activity"), + ) + + @property + def type(self): + return _("coach") + + @property + def form_class(self): + from registration.forms import CoachRegistrationForm + return CoachRegistrationForm + + class Meta: + verbose_name = _("coach registration") + verbose_name_plural = _("coach registrations") + + +class AdminRegistration(Registration): + """ + Specific registration for admins. + They have a field to justify they status. + """ + role = models.TextField( + verbose_name=_("role of the administrator"), + ) + + @property + def type(self): + return _("admin") + + @property + def form_class(self): + from registration.forms import AdminRegistrationForm + return AdminRegistrationForm + + class Meta: + verbose_name = _("admin registration") + verbose_name_plural = _("admin registrations") diff --git a/apps/registration/search_indexes.py b/apps/registration/search_indexes.py new file mode 100644 index 0000000..d52ce87 --- /dev/null +++ b/apps/registration/search_indexes.py @@ -0,0 +1,13 @@ +from haystack import indexes + +from .models import Registration + + +class RegistrationIndex(indexes.ModelSearchIndex, indexes.Indexable): + """ + Registrations are indexed by the user detail. + """ + text = indexes.NgramField(document=True, use_template=True) + + class Meta: + model = Registration diff --git a/apps/registration/signals.py b/apps/registration/signals.py new file mode 100644 index 0000000..ff89f65 --- /dev/null +++ b/apps/registration/signals.py @@ -0,0 +1,52 @@ +from corres2math.lists import get_sympa_client +from corres2math.matrix import Matrix +from django.contrib.auth.models import User + +from .models import AdminRegistration, Registration + + +def set_username(instance, **_): + """ + Ensure that the user username is always equal to the user email address. + """ + instance.username = instance.email + + +def send_email_link(instance, **_): + """ + If the email address got changed, send a new validation link + and update the registration status in the team mailing list. + """ + if instance.pk: + old_instance = User.objects.get(pk=instance.pk) + if old_instance.email != instance.email: + registration = Registration.objects.get(user=instance) + registration.email_confirmed = False + registration.save() + registration.user = instance + registration.send_email_validation_link() + + if registration.participates and registration.team: + get_sympa_client().unsubscribe(old_instance.email, f"equipe-{registration.team.trigram.lower()}", False) + get_sympa_client().subscribe(instance.email, f"equipe-{registration.team.trigram.lower()}", False, + f"{instance.first_name} {instance.last_name}") + + +def create_admin_registration(instance, **_): + """ + When a super user got created through console, + ensure that an admin registration is created. + """ + if instance.is_superuser: + AdminRegistration.objects.get_or_create(user=instance) + + +def invite_to_public_rooms(instance: Registration, **_): + """ + When a user got registered, automatically invite the Matrix user into public rooms. + """ + if not instance.pk: + Matrix.invite("#annonces:correspondances-maths.fr", f"@{instance.matrix_username}:correspondances-maths.fr") + Matrix.invite("#faq:correspondances-maths.fr", f"@{instance.matrix_username}:correspondances-maths.fr") + Matrix.invite("#je-cherche-une-equip:correspondances-maths.fr", + f"@{instance.matrix_username}:correspondances-maths.fr") diff --git a/apps/registration/tables.py b/apps/registration/tables.py new file mode 100644 index 0000000..7995ade --- /dev/null +++ b/apps/registration/tables.py @@ -0,0 +1,24 @@ +from django.utils.translation import gettext_lazy as _ +import django_tables2 as tables + +from .models import Registration + + +class RegistrationTable(tables.Table): + """ + Table of all registrations. + """ + last_name = tables.LinkColumn( + 'registration:user_detail', + args=[tables.A("user_id")], + verbose_name=lambda: _("last name").capitalize(), + accessor="user__last_name", + ) + + class Meta: + attrs = { + 'class': 'table table condensed table-striped', + } + model = Registration + fields = ('last_name', 'user__first_name', 'user__email', 'type',) + template_name = 'django_tables2/bootstrap4.html' diff --git a/apps/registration/templates/registration/email_validation_complete.html b/apps/registration/templates/registration/email_validation_complete.html new file mode 100644 index 0000000..f58a7e5 --- /dev/null +++ b/apps/registration/templates/registration/email_validation_complete.html @@ -0,0 +1,27 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-3.0-or-later +{% endcomment %} +{% load i18n %} + +{% block content %} +
+

+ {{ title }} +

+
+ {% if validlink %} +

+ {% trans "Your email have successfully been validated." %} +

+

+ {% blocktrans %}You can now log in.{% endblocktrans %} +

+ {% else %} +

+ {% trans "The link was invalid. The token may have expired. Please send us an email to activate your account." %} +

+ {% endif %} +
+
+{% endblock %} diff --git a/apps/registration/templates/registration/email_validation_email_sent.html b/apps/registration/templates/registration/email_validation_email_sent.html new file mode 100644 index 0000000..adc0c02 --- /dev/null +++ b/apps/registration/templates/registration/email_validation_email_sent.html @@ -0,0 +1,18 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-3.0-or-later +{% endcomment %} +{% load i18n %} + +{% block content %} +
+

+ {% trans "Account activation" %} +

+
+

+ {% trans "An email has been sent. Please click on the link to activate your account." %} +

+
+
+{% endblock %} diff --git a/apps/registration/templates/registration/mails/email_validation_email.html b/apps/registration/templates/registration/mails/email_validation_email.html new file mode 100644 index 0000000..416c496 --- /dev/null +++ b/apps/registration/templates/registration/mails/email_validation_email.html @@ -0,0 +1,36 @@ +{% load i18n %} + + + + + + + + + +

+ {% trans "Hi" %} {{ user.username }}, +

+ +

+ {% trans "You recently registered on the Correspondances platform. Please click on the link below to confirm your registration." %} +

+ +

+ + https://{{ domain }}{% url 'registration:email_validation' uidb64=uid token=token %} + +

+ +

+ {% trans "This link is only valid for a couple of days, after that you will need to contact us to validate your email." %} +

+ +

+ {% trans "Thanks" %}, +

+ +-- +

+ {% trans "The Correspondances team." %}
+

diff --git a/apps/registration/templates/registration/mails/email_validation_email.txt b/apps/registration/templates/registration/mails/email_validation_email.txt new file mode 100644 index 0000000..e9219c4 --- /dev/null +++ b/apps/registration/templates/registration/mails/email_validation_email.txt @@ -0,0 +1,13 @@ +{% load i18n %} + +{% trans "Hi" %} {{ user.username }}, + +{% trans "You recently registered on the Correspondances platform. Please click on the link below to confirm your registration." %} + +https://{{ domain }}{% url 'registration:email_validation' uidb64=uid token=token %} + +{% trans "This link is only valid for a couple of days, after that you will need to contact us to validate your email." %} + +{% trans "Thanks" %}, + +{% trans "The Correspondances team." %} diff --git a/apps/registration/templates/registration/password_change_done.html b/apps/registration/templates/registration/password_change_done.html new file mode 100644 index 0000000..150a00e --- /dev/null +++ b/apps/registration/templates/registration/password_change_done.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-3.0-or-later +{% endcomment %} +{% load i18n %} + +{% block content %} +

{% trans 'Your password was changed.' %}

+{% endblock %} diff --git a/apps/registration/templates/registration/password_change_form.html b/apps/registration/templates/registration/password_change_form.html new file mode 100644 index 0000000..01133e4 --- /dev/null +++ b/apps/registration/templates/registration/password_change_form.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-3.0-or-later +{% endcomment %} +{% load i18n crispy_forms_tags %} + +{% block content %} +
{% csrf_token %} +

{% trans "Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly." %}

+ {{ form | crispy }} + +
+{% endblock %} \ No newline at end of file diff --git a/apps/registration/templates/registration/password_reset_complete.html b/apps/registration/templates/registration/password_reset_complete.html new file mode 100644 index 0000000..dec34f6 --- /dev/null +++ b/apps/registration/templates/registration/password_reset_complete.html @@ -0,0 +1,12 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-3.0-or-later +{% endcomment %} +{% load i18n %} + +{% block content %} +

{% trans "Your password has been set. You may go ahead and log in now." %}

+

+ {% trans 'Log in' %} +

+{% endblock %} diff --git a/apps/registration/templates/registration/password_reset_confirm.html b/apps/registration/templates/registration/password_reset_confirm.html new file mode 100644 index 0000000..6432872 --- /dev/null +++ b/apps/registration/templates/registration/password_reset_confirm.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-3.0-or-later +{% endcomment %} +{% load i18n crispy_forms_tags %} + +{% block content %} + {% if validlink %} +

{% trans "Please enter your new password twice so we can verify you typed it in correctly." %}

+
{% csrf_token %} + {{ form | crispy }} + +
+ {% else %} +

{% trans "The password reset link was invalid, possibly because it has already been used. Please request a new password reset." %}

+ {% endif %} +{% endblock %} diff --git a/apps/registration/templates/registration/password_reset_done.html b/apps/registration/templates/registration/password_reset_done.html new file mode 100644 index 0000000..a215ab9 --- /dev/null +++ b/apps/registration/templates/registration/password_reset_done.html @@ -0,0 +1,10 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-3.0-or-later +{% endcomment %} +{% load i18n %} + +{% block content %} +

{% trans "We've emailed you instructions for setting your password, if an account exists with the email you entered. You should receive them shortly." %}

+

{% trans "If you don't receive an email, please make sure you've entered the address you registered with, and check your spam folder." %}

+{% endblock %} diff --git a/apps/registration/templates/registration/password_reset_form.html b/apps/registration/templates/registration/password_reset_form.html new file mode 100644 index 0000000..61adaa9 --- /dev/null +++ b/apps/registration/templates/registration/password_reset_form.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-3.0-or-later +{% endcomment %} +{% load i18n crispy_forms_tags %} + +{% block content %} +

{% trans "Forgotten your password? Enter your email address below, and we'll email instructions for setting a new one." %}

+
{% csrf_token %} + {{ form | crispy }} + +
+{% endblock %} diff --git a/apps/registration/templates/registration/signup.html b/apps/registration/templates/registration/signup.html new file mode 100644 index 0000000..82a9431 --- /dev/null +++ b/apps/registration/templates/registration/signup.html @@ -0,0 +1,44 @@ + +{% extends 'base.html' %} +{% load crispy_forms_filters %} +{% load i18n %} +{% block title %}{% trans "Sign up" %}{% endblock %} + +{% block content %} +

{% trans "Sign up" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} +
+ {{ student_registration_form|crispy }} +
+
+ {{ coach_registration_form|crispy }} +
+ +
+{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/registration/templates/registration/update_user.html b/apps/registration/templates/registration/update_user.html new file mode 100644 index 0000000..7e282d5 --- /dev/null +++ b/apps/registration/templates/registration/update_user.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} + {{ registration_form|crispy }} +
+ +
+{% endblock content %} + diff --git a/apps/registration/templates/registration/upload_photo_authorization.html b/apps/registration/templates/registration/upload_photo_authorization.html new file mode 100644 index 0000000..9a5a1c5 --- /dev/null +++ b/apps/registration/templates/registration/upload_photo_authorization.html @@ -0,0 +1,20 @@ +{% extends "base.html" %} + +{% load i18n static crispy_forms_filters %} + +{% block content %} + {% trans "Back to the user detail" %} +
+
+
+
+ {% trans "Authorzation templates:" %} + {% trans "Adult" %} — + {% trans "Child" %} +
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock %} diff --git a/apps/registration/templates/registration/user_detail.html b/apps/registration/templates/registration/user_detail.html new file mode 100644 index 0000000..710cf48 --- /dev/null +++ b/apps/registration/templates/registration/user_detail.html @@ -0,0 +1,98 @@ +{% extends "base.html" %} + +{% load i18n %} + +{% block content %} +{% trans "any" as any %} + +
+
+

{{ user_object.first_name }} {{ user_object.last_name }}

+
+
+
+
{% trans "Last name:" %}
+
{{ user_object.last_name }}
+ +
{% trans "First name:" %}
+
{{ user_object.first_name }}
+ +
{% trans "Email:" %}
+
{{ user_object.email }} + {% if not user_object.registration.email_confirmed %} ({% trans "Not confirmed" %}, {% trans "resend the validation link" %}){% endif %}
+ + {% if user_object.registration.participates or True %} +
{% trans "Team:" %}
+ {% trans "any" as any %} +
+ + {{ user_object.registration.team|default:any }} + +
+ {% endif %} + + {% if user_object.registration.studentregistration %} +
{% trans "Student class:" %}
+
{{ user_object.registration.get_student_class_display }}
+ +
{% trans "School:" %}
+
{{ user_object.registration.school }}
+ +
{% trans "Photo authorization:" %}
+
+ {% if user_object.registration.photo_authorization %} + {% trans "Download" %} + {% endif %} + {% if user_object.pk == user.pk %} + + {% endif %} +
+ {% elif user_object.registration.coachregistration %} +
{% trans "Profesional activity:" %}
+
{{ user_object.registration.professional_activity }}
+ {% elif user_object.registration.adminregistration %} +
{% trans "Role:" %}
+
{{ user_object.registration.role }}
+ {% endif %} + +
{% trans "Grant Animath to contact me in the future about other actions:" %}
+
{{ user_object.registration.give_contact_to_animath|yesno }}
+
+
+ {% if user.pk == user_object.pk or user.registration.is_admin %} + + {% endif %} +
+ + {% trans "Update user" as modal_title %} + {% trans "Update" as modal_button %} + {% url "registration:update_user" pk=user_object.pk as modal_action %} + {% include "base_modal.html" with modal_id="updateUser" %} + + {% trans "Upload photo authorization" as modal_title %} + {% trans "Upload" as modal_button %} + {% url "registration:upload_user_photo_authorization" pk=user_object.registration.pk as modal_action %} + {% include "base_modal.html" with modal_id="uploadPhotoAuthorization" modal_enctype="multipart/form-data" %} +{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/registration/templates/search/indexes/registration/adminregistration_text.txt b/apps/registration/templates/search/indexes/registration/adminregistration_text.txt new file mode 100644 index 0000000..a5077ab --- /dev/null +++ b/apps/registration/templates/search/indexes/registration/adminregistration_text.txt @@ -0,0 +1,5 @@ +{{ object.user.last_name }} +{{ object.user.first_name }} +{{ object.user.email }} +{{ object.type }} +{{ object.role }} diff --git a/apps/registration/templates/search/indexes/registration/coachregistration_text.txt b/apps/registration/templates/search/indexes/registration/coachregistration_text.txt new file mode 100644 index 0000000..e7e53e5 --- /dev/null +++ b/apps/registration/templates/search/indexes/registration/coachregistration_text.txt @@ -0,0 +1,7 @@ +{{ object.user.first_name }} +{{ object.user.last_name }} +{{ object.user.email }} +{{ object.type }} +{{ object.professional_activity }} +{{ object.team.name }} +{{ object.team.trigram }} diff --git a/apps/registration/templates/search/indexes/registration/studentregistration_text.txt b/apps/registration/templates/search/indexes/registration/studentregistration_text.txt new file mode 100644 index 0000000..f103c7f --- /dev/null +++ b/apps/registration/templates/search/indexes/registration/studentregistration_text.txt @@ -0,0 +1,8 @@ +{{ object.user.first_name }} +{{ object.user.last_name }} +{{ object.user.email }} +{{ object.type }} +{{ object.get_student_class_display }} +{{ object.school }} +{{ object.team.name }} +{{ object.team.trigram }} diff --git a/apps/registration/templatetags/__init__.py b/apps/registration/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/registration/templatetags/search_results_tables.py b/apps/registration/templatetags/search_results_tables.py new file mode 100644 index 0000000..840ebac --- /dev/null +++ b/apps/registration/templatetags/search_results_tables.py @@ -0,0 +1,26 @@ +from django import template +from django_tables2 import Table +from participation.models import Participation, Team, Video +from participation.tables import ParticipationTable, TeamTable, VideoTable + +from ..models import Registration +from ..tables import RegistrationTable + + +def search_table(results): + model_class = results[0].object.__class__ + if issubclass(model_class, Registration): + table_class = RegistrationTable + elif issubclass(model_class, Team): + table_class = TeamTable + elif issubclass(model_class, Participation): + table_class = ParticipationTable + elif issubclass(model_class, Video): + table_class = VideoTable + else: + table_class = Table + return table_class([result.object for result in results], prefix=model_class._meta.model_name) + + +register = template.Library() +register.filter("search_table", search_table) diff --git a/apps/registration/tests.py b/apps/registration/tests.py new file mode 100644 index 0000000..18e5ff4 --- /dev/null +++ b/apps/registration/tests.py @@ -0,0 +1,223 @@ +from corres2math.tokens import email_validation_token +from django.contrib.auth.models import User +from django.test import TestCase +from django.urls import reverse +from django.utils.encoding import force_bytes +from django.utils.http import urlsafe_base64_encode + +from .models import CoachRegistration, Registration, StudentRegistration + + +class TestIndexPage(TestCase): + def test_index(self) -> None: + """ + Display the index page, without any right. + """ + response = self.client.get(reverse("index")) + self.assertEqual(response.status_code, 200) + + +class TestRegistration(TestCase): + def setUp(self) -> None: + self.user = User.objects.create_superuser( + username="admin", + password="admin", + email="admin@example.com", + ) + self.client.force_login(self.user) + + self.student = User.objects.create(email="student@example.com") + StudentRegistration.objects.create(user=self.student, student_class=11, school="Earth") + self.coach = User.objects.create(email="coach@example.com") + CoachRegistration.objects.create(user=self.coach, professional_activity="Teacher") + + def test_admin_pages(self): + """ + Check that admin pages are rendering successfully. + """ + response = self.client.get(reverse("admin:index") + "registration/registration/") + self.assertEqual(response.status_code, 200) + + response = self.client.get(reverse("admin:index") + + f"registration/registration/{self.user.registration.pk}/change/") + self.assertEqual(response.status_code, 200) + + response = self.client.get(reverse("admin:index") + + f"registration/registration/{self.student.registration.pk}/change/") + self.assertEqual(response.status_code, 200) + + response = self.client.get(reverse("admin:index") + + f"registration/registration/{self.coach.registration.pk}/change/") + self.assertEqual(response.status_code, 200) + + def test_registration(self): + """ + Ensure that the signup form is working successfully. + """ + response = self.client.get(reverse("registration:signup")) + self.assertEqual(response.status_code, 200) + + # Incomplete form + response = self.client.post(reverse("registration:signup"), data=dict( + last_name="Toto", + first_name="Toto", + email="toto@example.com", + password1="azertyuiopazertyuiop", + password2="azertyuiopazertyuiop", + role="participant", + )) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("registration:signup"), data=dict( + last_name="Toto", + first_name="Toto", + email="toto@example.com", + password1="azertyuiopazertyuiop", + password2="azertyuiopazertyuiop", + role="participant", + student_class=12, + school="God", + give_contact_to_animath=False, + )) + self.assertRedirects(response, reverse("registration:email_validation_sent"), 302, 200) + self.assertTrue(User.objects.filter(email="toto@example.com").exists()) + + response = self.client.get(reverse("registration:email_validation_sent")) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("registration:signup"), data=dict( + last_name="Toto", + first_name="Coach", + email="coachtoto@example.com", + password1="azertyuiopazertyuiop", + password2="azertyuiopazertyuiop", + role="coach", + professional_activity="God", + give_contact_to_animath=True, + )) + self.assertRedirects(response, reverse("registration:email_validation_sent"), 302, 200) + self.assertTrue(User.objects.filter(email="coachtoto@example.com").exists()) + + user = User.objects.get(email="coachtoto@example.com") + token = email_validation_token.make_token(user) + uid = urlsafe_base64_encode(force_bytes(user.pk)) + response = self.client.get(reverse("registration:email_validation", kwargs=dict(uidb64=uid, token=token))) + self.assertEqual(response.status_code, 200) + user.registration.refresh_from_db() + self.assertTrue(user.registration.email_confirmed) + + # Token has expired + response = self.client.get(reverse("registration:email_validation", kwargs=dict(uidb64=uid, token=token))) + self.assertEqual(response.status_code, 400) + + # Uid does not exist + response = self.client.get(reverse("registration:email_validation", kwargs=dict(uidb64=0, token="toto"))) + self.assertEqual(response.status_code, 400) + + response = self.client.get(reverse("registration:email_validation_resend", args=(user.pk,))) + self.assertRedirects(response, reverse("registration:email_validation_sent"), 302, 200) + + def test_login(self): + """ + With a registered user, try to log in + """ + response = self.client.get(reverse("login")) + self.assertEqual(response.status_code, 200) + + self.client.logout() + + response = self.client.post(reverse("login"), data=dict( + username="admin", + password="toto", + )) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("login"), data=dict( + username="admin@example.com", + password="admin", + )) + self.assertRedirects(response, reverse("index"), 302, 200) + + def test_user_detail(self): + """ + Load a user detail page. + """ + response = self.client.get(reverse("registration:my_account_detail")) + self.assertRedirects(response, reverse("registration:user_detail", args=(self.user.pk,))) + + response = self.client.get(reverse("registration:user_detail", args=(self.user.pk,))) + self.assertEqual(response.status_code, 200) + + def test_update_user(self): + """ + Update the user information, for each type of user. + """ + for user, data in [(self.user, dict(role="Bot")), + (self.student, dict(student_class=11, school="Sky")), + (self.coach, dict(professional_activity="God"))]: + response = self.client.get(reverse("registration:update_user", args=(user.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("registration:update_user", args=(user.pk,)), data=dict( + first_name="Changed", + last_name="Name", + email="new_" + user.email, + give_contact_to_animath=True, + )) + self.assertEqual(response.status_code, 200) + + data.update( + first_name="Changed", + last_name="Name", + email="new_" + user.email, + give_contact_to_animath=True, + ) + response = self.client.post(reverse("registration:update_user", args=(user.pk,)), data=data) + self.assertRedirects(response, reverse("registration:user_detail", args=(user.pk,)), 302, 200) + user.refresh_from_db() + self.assertEqual(user.email, user.username) + self.assertFalse(user.registration.email_confirmed) + self.assertEqual(user.first_name, "Changed") + + def test_upload_photo_authorization(self): + """ + Try to upload a photo authorization. + """ + response = self.client.get(reverse("registration:upload_user_photo_authorization", + args=(self.student.registration.pk,))) + self.assertEqual(response.status_code, 200) + + # README is not a valid PDF file + response = self.client.post(reverse("registration:upload_user_photo_authorization", + args=(self.student.registration.pk,)), data=dict( + photo_authorization=open("README.md", "rb"), + )) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("registration:upload_user_photo_authorization", + args=(self.student.registration.pk,)), data=dict( + photo_authorization=open("corres2math/static/Autorisation de droit à l'image - majeur.pdf", "rb"), + )) + self.assertRedirects(response, reverse("registration:user_detail", args=(self.student.pk,)), 302, 200) + + self.student.registration.refresh_from_db() + self.assertTrue(self.student.registration.photo_authorization) + + response = self.client.get(reverse("photo_authorization", + args=(self.student.registration.photo_authorization.name.split('/')[-1],))) + self.assertEqual(response.status_code, 200) + + from participation.models import Team + team = Team.objects.create(name="Test", trigram="TES") + self.student.registration.team = team + self.student.registration.save() + response = self.client.get(reverse("participation:team_authorizations", args=(team.pk,))) + self.assertEqual(response.status_code, 200) + self.assertEqual(response["content-type"], "application/zip") + + self.student.registration.photo_authorization.delete() + + def test_string_render(self): + # TODO These string field tests will be removed when used in a template + self.assertRaises(NotImplementedError, lambda: Registration().type) + self.assertRaises(NotImplementedError, lambda: Registration().form_class) diff --git a/apps/registration/urls.py b/apps/registration/urls.py new file mode 100644 index 0000000..bce8aa8 --- /dev/null +++ b/apps/registration/urls.py @@ -0,0 +1,22 @@ +from django.urls import path + +from .views import MyAccountDetailView, ResetAdminView, SignupView, UserDetailView, UserImpersonateView, \ + UserResendValidationEmailView, UserUpdateView, UserUploadPhotoAuthorizationView, UserValidateView, \ + UserValidationEmailSentView + +app_name = "registration" + +urlpatterns = [ + path("signup/", SignupView.as_view(), name="signup"), + path('validate_email/sent/', UserValidationEmailSentView.as_view(), name='email_validation_sent'), + path('validate_email/resend//', UserResendValidationEmailView.as_view(), + name='email_validation_resend'), + path('validate_email///', UserValidateView.as_view(), name='email_validation'), + path("user/", MyAccountDetailView.as_view(), name="my_account_detail"), + path("user//", UserDetailView.as_view(), name="user_detail"), + path("user//update/", UserUpdateView.as_view(), name="update_user"), + path("user//upload-photo-authorization/", UserUploadPhotoAuthorizationView.as_view(), + name="upload_user_photo_authorization"), + path("user//impersonate/", UserImpersonateView.as_view(), name="user_impersonate"), + path("reset-admin/", ResetAdminView.as_view(), name="reset_admin"), +] diff --git a/apps/registration/views.py b/apps/registration/views.py new file mode 100644 index 0000000..9195b86 --- /dev/null +++ b/apps/registration/views.py @@ -0,0 +1,277 @@ +import os + +from corres2math.tokens import email_validation_token +from django.conf import settings +from django.contrib.auth.mixins import LoginRequiredMixin +from django.contrib.auth.models import User +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import transaction +from django.http import FileResponse, Http404 +from django.shortcuts import redirect, resolve_url +from django.urls import reverse_lazy +from django.utils.http import urlsafe_base64_decode +from django.utils.translation import gettext_lazy as _ +from django.views.generic import CreateView, DetailView, RedirectView, TemplateView, UpdateView, View +from magic import Magic + +from .forms import CoachRegistrationForm, PhotoAuthorizationForm, SignupForm, StudentRegistrationForm, UserForm +from .models import StudentRegistration + + +class SignupView(CreateView): + """ + Signup, as a participant or a coach. + """ + model = User + form_class = SignupForm + template_name = "registration/signup.html" + extra_context = dict(title=_("Sign up")) + + def get_context_data(self, **kwargs): + context = super().get_context_data() + + context["student_registration_form"] = StudentRegistrationForm(self.request.POST or None) + context["coach_registration_form"] = CoachRegistrationForm(self.request.POST or None) + + return context + + @transaction.atomic + def form_valid(self, form): + role = form.cleaned_data["role"] + if role == "participant": + registration_form = StudentRegistrationForm(self.request.POST) + else: + registration_form = CoachRegistrationForm(self.request.POST) + + if not registration_form.is_valid(): + return self.form_invalid(form) + + ret = super().form_valid(form) + registration = registration_form.instance + registration.user = form.instance + registration.save() + + return ret + + def get_success_url(self): + return reverse_lazy("registration:email_validation_sent") + + +class UserValidateView(TemplateView): + """ + A view to validate the email address. + """ + title = _("Email validation") + template_name = 'registration/email_validation_complete.html' + extra_context = dict(title=_("Validate email")) + + def get(self, *args, **kwargs): + """ + With a given token and user id (in params), validate the email address. + """ + assert 'uidb64' in kwargs and 'token' in kwargs + + self.validlink = False + user = self.get_user(kwargs['uidb64']) + token = kwargs['token'] + + # Validate the token + if user is not None and email_validation_token.check_token(user, token): + self.validlink = True + user.registration.email_confirmed = True + user.registration.save() + return self.render_to_response(self.get_context_data(), status=200 if self.validlink else 400) + + def get_user(self, uidb64): + """ + Get user from the base64-encoded string. + """ + try: + # urlsafe_base64_decode() decodes to bytestring + uid = urlsafe_base64_decode(uidb64).decode() + user = User.objects.get(pk=uid) + except (TypeError, ValueError, OverflowError, User.DoesNotExist, ValidationError): + user = None + return user + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + context['user_object'] = self.get_user(self.kwargs["uidb64"]) + context['login_url'] = resolve_url(settings.LOGIN_URL) + if self.validlink: + context['validlink'] = True + else: + context.update({ + 'title': _('Email validation unsuccessful'), + 'validlink': False, + }) + return context + + +class UserValidationEmailSentView(TemplateView): + """ + Display the information that the validation link has been sent. + """ + template_name = 'registration/email_validation_email_sent.html' + extra_context = dict(title=_('Email validation email sent')) + + +class UserResendValidationEmailView(LoginRequiredMixin, DetailView): + """ + Rensend the email validation link. + """ + model = User + extra_context = dict(title=_("Resend email validation link")) + + def get(self, request, *args, **kwargs): + user = self.get_object() + user.registration.send_email_validation_link() + return redirect('registration:email_validation_sent') + + +class MyAccountDetailView(LoginRequiredMixin, RedirectView): + """ + Redirect to our own profile detail page. + """ + def get_redirect_url(self, *args, **kwargs): + return reverse_lazy("registration:user_detail", args=(self.request.user.pk,)) + + +class UserDetailView(LoginRequiredMixin, DetailView): + """ + Display the detail about a user. + """ + + model = User + context_object_name = "user_object" + template_name = "registration/user_detail.html" + + def dispatch(self, request, *args, **kwargs): + user = request.user + # Only an admin or the concerned user can see the information + if not user.registration.is_admin and user.pk != kwargs["pk"]: + raise PermissionDenied + return super().dispatch(request, *args, **kwargs) + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + context["title"] = _("Detail of user {user}").format(user=str(self.object.registration)) + return context + + +class UserUpdateView(LoginRequiredMixin, UpdateView): + """ + Update the detail about a user and its registration. + """ + model = User + form_class = UserForm + template_name = "registration/update_user.html" + + def dispatch(self, request, *args, **kwargs): + user = request.user + if not user.registration.is_admin and user.pk != kwargs["pk"]: + raise PermissionDenied + return super().dispatch(request, *args, **kwargs) + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + user = self.get_object() + context["title"] = _("Update user {user}").format(user=str(self.object.registration)) + context["registration_form"] = user.registration.form_class(data=self.request.POST or None, + instance=self.object.registration) + return context + + @transaction.atomic + def form_valid(self, form): + user = form.instance + registration_form = user.registration.form_class(data=self.request.POST or None, + instance=self.object.registration) + if not registration_form.is_valid(): + return self.form_invalid(form) + + registration_form.save() + return super().form_valid(form) + + def get_success_url(self): + return reverse_lazy("registration:user_detail", args=(self.object.pk,)) + + +class UserUploadPhotoAuthorizationView(LoginRequiredMixin, UpdateView): + """ + A participant can send its photo authorization. + """ + model = StudentRegistration + form_class = PhotoAuthorizationForm + template_name = "registration/upload_photo_authorization.html" + extra_context = dict(title=_("Upload photo authorization")) + + def dispatch(self, request, *args, **kwargs): + user = request.user + if not user.registration.is_admin and user.registration.pk != kwargs["pk"]: + raise PermissionDenied + return super().dispatch(request, *args, **kwargs) + + @transaction.atomic + def form_valid(self, form): + old_instance = StudentRegistration.objects.get(pk=self.object.pk) + if old_instance.photo_authorization: + old_instance.photo_authorization.delete() + return super().form_valid(form) + + def get_success_url(self): + return reverse_lazy("registration:user_detail", args=(self.object.user.pk,)) + + +class PhotoAuthorizationView(LoginRequiredMixin, View): + """ + Display the sent photo authorization. + """ + def get(self, request, *args, **kwargs): + filename = kwargs["filename"] + path = f"media/authorization/photo/{filename}" + if not os.path.exists(path): + raise Http404 + student = StudentRegistration.objects.get(photo_authorization__endswith=filename) + user = request.user + if not user.registration.is_admin and user.pk != student.user.pk: + raise PermissionDenied + # Guess mime type of the file + mime = Magic(mime=True) + mime_type = mime.from_file(path) + ext = mime_type.split("/")[1].replace("jpeg", "jpg") + # Replace file name + true_file_name = _("Photo authorization of {student}.{ext}").format(student=str(student), ext=ext) + return FileResponse(open(path, "rb"), content_type=mime_type, filename=true_file_name) + + +class UserImpersonateView(LoginRequiredMixin, RedirectView): + """ + An administrator can log in through this page as someone else, and act as this other person. + """ + + def dispatch(self, request, *args, **kwargs): + if self.request.user.registration.is_admin: + if not User.objects.filter(pk=kwargs["pk"]).exists(): + raise Http404 + session = request.session + session["admin"] = request.user.pk + session["_fake_user_id"] = kwargs["pk"] + return redirect(request.path) + return super().dispatch(request, *args, **kwargs) + + def get_redirect_url(self, *args, **kwargs): + return reverse_lazy("registration:user_detail", args=(kwargs["pk"],)) + + +class ResetAdminView(LoginRequiredMixin, View): + """ + Return to admin view, clear the session field that let an administrator to log in as someone else. + """ + + def dispatch(self, request, *args, **kwargs): + user = request.user + if not user.is_authenticated: + return self.handle_no_permission() + if "_fake_user_id" in request.session: + del request.session["_fake_user_id"] + return redirect(request.GET.get("path", "/")) diff --git a/assets/favicon.ico b/assets/favicon.ico deleted file mode 100644 index 8f01ebb..0000000 Binary files a/assets/favicon.ico and /dev/null differ diff --git a/assets/style.css b/assets/style.css deleted file mode 100644 index 5c8d3ff..0000000 --- a/assets/style.css +++ /dev/null @@ -1,47 +0,0 @@ -html, body { - height: 100%; - margin: 0; -} - -:root { - --navbar-height: 32px; -} - -.container { - min-height: 78%; -} - -.inner { - margin: 20px; -} - -.alert { - text-align: justify; -} - - -footer .alert { - text-align: center; -} - -#navbar-logo { - height: var(--navbar-height); - display: block; -} - -ul .deroule { - display: none; - position: absolute; - background: #f8f9fa !important; - list-style-type: none; - padding: 20px; - z-index: 42; -} - -li:hover ul.deroule { - display:block; -} - -a.nav-link:hover { - background-color: #d8d9da; -} diff --git a/corres2math.cron b/corres2math.cron new file mode 100644 index 0000000..1e07e98 --- /dev/null +++ b/corres2math.cron @@ -0,0 +1,5 @@ +# min hour day month weekday command +# Envoyer les mails en attente +* * * * * cd /code && python manage.py send_mail -c 1 +* * * * * cd /code && python manage.py retry_deferred -c 1 +0 0 * * * cd /code && python manage.py purge_mail_log 7 -c 1 diff --git a/corres2math/__init__.py b/corres2math/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/corres2math/asgi.py b/corres2math/asgi.py new file mode 100644 index 0000000..949b8bb --- /dev/null +++ b/corres2math/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for corres2math project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'corres2math.settings') + +application = get_asgi_application() diff --git a/corres2math/lists.py b/corres2math/lists.py new file mode 100644 index 0000000..a8cbac2 --- /dev/null +++ b/corres2math/lists.py @@ -0,0 +1,23 @@ +import os + +_client = None + + +def get_sympa_client(): + global _client + if _client is None: + if os.getenv("SYMPA_PASSWORD", None) is not None: + from sympasoap import Client + _client = Client("https://" + os.getenv("SYMPA_URL")) + _client.login(os.getenv("SYMPA_EMAIL"), os.getenv("SYMPA_PASSWORD")) + else: + _client = FakeSympaSoapClient() + return _client + + +class FakeSympaSoapClient: + """ + Simulate a Sympa Soap client to run tests, if no Sympa instance is connected. + """ + def __getattribute__(self, item): + return lambda *args, **kwargs: None diff --git a/corres2math/matrix.py b/corres2math/matrix.py new file mode 100644 index 0000000..ddf76c6 --- /dev/null +++ b/corres2math/matrix.py @@ -0,0 +1,373 @@ +import os +from typing import Tuple + +from asgiref.sync import async_to_sync +from nio import * + + +class Matrix: + """ + Utility class to manage interaction with the Matrix homeserver. + This log in the @corres2mathbot account (must be created before). + The access token is then stored. + All is done with this bot account, that is a server administrator. + Tasks are normally asynchronous, but for compatibility we make + them synchronous. + """ + _token: str = None + _device_id: str = None + + @classmethod + async def _get_client(cls) -> Union[AsyncClient, "FakeMatrixClient"]: + """ + Retrieve the bot account. + If not logged, log in and store access token. + """ + if not os.getenv("SYNAPSE_PASSWORD"): + return FakeMatrixClient() + + client = AsyncClient("https://correspondances-maths.fr", "@corres2mathbot:correspondances-maths.fr") + client.user_id = "@corres2mathbot:correspondances-maths.fr" + + if os.path.isfile(".matrix_token"): + with open(".matrix_device", "r") as f: + cls._device_id = f.read().rstrip(" \t\r\n") + client.device_id = cls._device_id + with open(".matrix_token", "r") as f: + cls._token = f.read().rstrip(" \t\r\n") + client.access_token = cls._token + return client + + await client.login(password=os.getenv("SYNAPSE_PASSWORD"), device_name="Plateforme") + cls._token = client.access_token + cls._device_id = client.device_id + with open(".matrix_token", "w") as f: + f.write(cls._token) + with open(".matrix_device", "w") as f: + f.write(cls._device_id) + return client + + @classmethod + @async_to_sync + async def set_display_name(cls, name: str) -> Union[ProfileSetDisplayNameResponse, ProfileSetDisplayNameError]: + """ + Set the display name of the bot account. + """ + client = await cls._get_client() + return await client.set_displayname(name) + + @classmethod + @async_to_sync + async def set_avatar(cls, avatar_url: str) -> Union[ProfileSetAvatarResponse, ProfileSetAvatarError]: + """ + Set the display avatar of the bot account. + """ + client = await cls._get_client() + return await client.set_avatar(avatar_url) + + @classmethod + @async_to_sync + async def upload( + cls, + data_provider: DataProvider, + content_type: str = "application/octet-stream", + filename: Optional[str] = None, + encrypt: bool = False, + monitor: Optional[TransferMonitor] = None, + filesize: Optional[int] = None, + ) -> Tuple[Union[UploadResponse, UploadError], Optional[Dict[str, Any]]]: + """ + Upload a file to the content repository. + + Returns a tuple containing: + + - Either a `UploadResponse` if the request was successful, or a + `UploadError` if there was an error with the request + + - A dict with file decryption info if encrypt is ``True``, + else ``None``. + Args: + data_provider (Callable, SynchronousFile, AsyncFile): A function + returning the data to upload or a file object. File objects + must be opened in binary mode (``mode="r+b"``). Callables + returning a path string, Path, async iterable or aiofiles + open binary file object allow the file data to be read in an + asynchronous and lazy way (without reading the entire file + into memory). Returning a synchronous iterable or standard + open binary file object will still allow the data to be read + lazily, but not asynchronously. + + The function will be called again if the upload fails + due to a server timeout, in which case it must restart + from the beginning. + Callables receive two arguments: the total number of + 429 "Too many request" errors that occured, and the total + number of server timeout exceptions that occured, thus + cleanup operations can be performed for retries if necessary. + + content_type (str): The content MIME type of the file, + e.g. "image/png". + Defaults to "application/octet-stream", corresponding to a + generic binary file. + Custom values are ignored if encrypt is ``True``. + + filename (str, optional): The file's original name. + + encrypt (bool): If the file's content should be encrypted, + necessary for files that will be sent to encrypted rooms. + Defaults to ``False``. + + monitor (TransferMonitor, optional): If a ``TransferMonitor`` + object is passed, it will be updated by this function while + uploading. + From this object, statistics such as currently + transferred bytes or estimated remaining time can be gathered + while the upload is running as a task; it also allows + for pausing and cancelling. + + filesize (int, optional): Size in bytes for the file to transfer. + If left as ``None``, some servers might refuse the upload. + """ + client = await cls._get_client() + return await client.upload(data_provider, content_type, filename, encrypt, monitor, filesize) + + @classmethod + @async_to_sync + async def create_room( + cls, + visibility: RoomVisibility = RoomVisibility.private, + alias: Optional[str] = None, + name: Optional[str] = None, + topic: Optional[str] = None, + room_version: Optional[str] = None, + federate: bool = True, + is_direct: bool = False, + preset: Optional[RoomPreset] = None, + invite=(), + initial_state=(), + power_level_override: Optional[Dict[str, Any]] = None, + ) -> Union[RoomCreateResponse, RoomCreateError]: + """ + Create a new room. + + Returns either a `RoomCreateResponse` if the request was successful or + a `RoomCreateError` if there was an error with the request. + + Args: + visibility (RoomVisibility): whether to have the room published in + the server's room directory or not. + Defaults to ``RoomVisibility.private``. + + alias (str, optional): The desired canonical alias local part. + For example, if set to "foo" and the room is created on the + "example.com" server, the room alias will be + "#foo:example.com". + + name (str, optional): A name to set for the room. + + topic (str, optional): A topic to set for the room. + + room_version (str, optional): The room version to set. + If not specified, the homeserver will use its default setting. + If a version not supported by the homeserver is specified, + a 400 ``M_UNSUPPORTED_ROOM_VERSION`` error will be returned. + + federate (bool): Whether to allow users from other homeservers from + joining the room. Defaults to ``True``. + Cannot be changed later. + + is_direct (bool): If this should be considered a + direct messaging room. + If ``True``, the server will set the ``is_direct`` flag on + ``m.room.member events`` sent to the users in ``invite``. + Defaults to ``False``. + + preset (RoomPreset, optional): The selected preset will set various + rules for the room. + If unspecified, the server will choose a preset from the + ``visibility``: ``RoomVisibility.public`` equates to + ``RoomPreset.public_chat``, and + ``RoomVisibility.private`` equates to a + ``RoomPreset.private_chat``. + + invite (list): A list of user id to invite to the room. + + initial_state (list): A list of state event dicts to send when + the room is created. + For example, a room could be made encrypted immediatly by + having a ``m.room.encryption`` event dict. + + power_level_override (dict): A ``m.room.power_levels content`` dict + to override the default. + The dict will be applied on top of the generated + ``m.room.power_levels`` event before it is sent to the room. + """ + client = await cls._get_client() + return await client.room_create( + visibility, alias, name, topic, room_version, federate, is_direct, preset, invite, initial_state, + power_level_override) + + @classmethod + async def resolve_room_alias(cls, room_alias: str) -> Optional[str]: + """ + Resolve a room alias to a room ID. + Return None if the alias does not exist. + """ + client = await cls._get_client() + resp: RoomResolveAliasResponse = await client.room_resolve_alias(room_alias) + if isinstance(resp, RoomResolveAliasResponse): + return resp.room_id + return None + + @classmethod + @async_to_sync + async def invite(cls, room_id: str, user_id: str) -> Union[RoomInviteResponse, RoomInviteError]: + """ + Invite a user to a room. + + Returns either a `RoomInviteResponse` if the request was successful or + a `RoomInviteError` if there was an error with the request. + + Args: + room_id (str): The room id of the room that the user will be + invited to. + user_id (str): The user id of the user that should be invited. + """ + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + return await client.room_invite(room_id, user_id) + + @classmethod + @async_to_sync + async def send_message(cls, room_id: str, body: str, formatted_body: str = None, + msgtype: str = "m.text", html: bool = True): + """ + Send a message to a room. + """ + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + content = { + "msgtype": msgtype, + "body": body, + "formatted_body": formatted_body or body, + } + if html: + content["format"] = "org.matrix.custom.html" + return await client.room_send( + room_id=room_id, + message_type="m.room.message", + content=content, + ) + + @classmethod + @async_to_sync + async def kick(cls, room_id: str, user_id: str, reason: str = None) -> Union[RoomKickResponse, RoomInviteError]: + """ + Kick a user from a room, or withdraw their invitation. + + Kicking a user adjusts their membership to "leave" with an optional + reason. + + Returns either a `RoomKickResponse` if the request was successful or + a `RoomKickError` if there was an error with the request. + + Args: + room_id (str): The room id of the room that the user will be + kicked from. + user_id (str): The user_id of the user that should be kicked. + reason (str, optional): A reason for which the user is kicked. + """ + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + return await client.room_kick(room_id, user_id, reason) + + @classmethod + @async_to_sync + async def set_room_power_level(cls, room_id: str, user_id: str, power_level: int)\ + -> Union[RoomPutStateResponse, RoomPutStateError]: + """ + Put a given power level to a user in a certain room. + + Returns either a `RoomPutStateResponse` if the request was successful or + a `RoomPutStateError` if there was an error with the request. + + Args: + room_id (str): The room id of the room where the power level + of the user should be updated. + user_id (str): The user_id of the user which power level should + be updated. + power_level (int): The target power level to give. + """ + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + resp = await client.room_get_state_event(room_id, "m.room.power_levels") + content = resp.content + content["users"][user_id] = power_level + return await client.room_put_state(room_id, "m.room.power_levels", content=content, state_key=resp.state_key) + + @classmethod + @async_to_sync + async def set_room_power_level_event(cls, room_id: str, event: str, power_level: int)\ + -> Union[RoomPutStateResponse, RoomPutStateError]: + """ + Define the minimal power level to have to send a certain event type + in a given room. + + Returns either a `RoomPutStateResponse` if the request was successful or + a `RoomPutStateError` if there was an error with the request. + + Args: + room_id (str): The room id of the room where the power level + of the event should be updated. + event (str): The event name which minimal power level should + be updated. + power_level (int): The target power level to give. + """ + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + resp = await client.room_get_state_event(room_id, "m.room.power_levels") + content = resp.content + if event.startswith("m."): + content["events"][event] = power_level + else: + content[event] = power_level + return await client.room_put_state(room_id, "m.room.power_levels", content=content, state_key=resp.state_key) + + @classmethod + @async_to_sync + async def set_room_avatar(cls, room_id: str, avatar_uri: str)\ + -> Union[RoomPutStateResponse, RoomPutStateError]: + """ + Define the avatar of a room. + + Returns either a `RoomPutStateResponse` if the request was successful or + a `RoomPutStateError` if there was an error with the request. + + Args: + room_id (str): The room id of the room where the avatar + should be changed. + avatar_uri (str): The internal avatar URI to apply. + """ + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + return await client.room_put_state(room_id, "m.room.avatar", content={ + "url": avatar_uri + }, state_key="") + + +class FakeMatrixClient: + """ + Simulate a Matrix client to run tests, if no Matrix homeserver is connected. + """ + + def __getattribute__(self, item): + async def func(*_, **_2): + return None + return func + diff --git a/corres2math/middlewares.py b/corres2math/middlewares.py new file mode 100644 index 0000000..185eda9 --- /dev/null +++ b/corres2math/middlewares.py @@ -0,0 +1,93 @@ +from django.conf import settings +from django.contrib.auth.models import AnonymousUser, User + +from threading import local + +from django.contrib.sessions.backends.db import SessionStore + +USER_ATTR_NAME = getattr(settings, 'LOCAL_USER_ATTR_NAME', '_current_user') +SESSION_ATTR_NAME = getattr(settings, 'LOCAL_SESSION_ATTR_NAME', '_current_session') +IP_ATTR_NAME = getattr(settings, 'LOCAL_IP_ATTR_NAME', '_current_ip') + +_thread_locals = local() + + +def _set_current_user_and_ip(user=None, session=None, ip=None): + setattr(_thread_locals, USER_ATTR_NAME, user) + setattr(_thread_locals, SESSION_ATTR_NAME, session) + setattr(_thread_locals, IP_ATTR_NAME, ip) + + +def get_current_user() -> User: + return getattr(_thread_locals, USER_ATTR_NAME, None) + + +def get_current_session() -> SessionStore: + return getattr(_thread_locals, SESSION_ATTR_NAME, None) + + +def get_current_ip() -> str: + return getattr(_thread_locals, IP_ATTR_NAME, None) + + +def get_current_authenticated_user(): + current_user = get_current_user() + if isinstance(current_user, AnonymousUser): + return None + return current_user + + +class SessionMiddleware(object): + """ + This middleware get the current user with his or her IP address on each request. + """ + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + if "_fake_user_id" in request.session: + request.user = User.objects.get(pk=request.session["_fake_user_id"]) + + user = request.user + if 'HTTP_X_REAL_IP' in request.META: + ip = request.META.get('HTTP_X_REAL_IP') + else: + ip = request.META.get('REMOTE_ADDR') + + _set_current_user_and_ip(user, request.session, ip) + response = self.get_response(request) + _set_current_user_and_ip(None, None, None) + + return response + + +class TurbolinksMiddleware(object): + """ + Send the `Turbolinks-Location` header in response to a visit that was redirected, + and Turbolinks will replace the browser's topmost history entry. + """ + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + response = self.get_response(request) + + is_turbolinks = request.META.get('HTTP_TURBOLINKS_REFERRER') + is_response_redirect = response.has_header('Location') + + if is_turbolinks: + if is_response_redirect: + location = response['Location'] + prev_location = request.session.pop('_turbolinks_redirect_to', None) + if prev_location is not None: + # relative subsequent redirect + if location.startswith('.'): + location = prev_location.split('?')[0] + location + request.session['_turbolinks_redirect_to'] = location + else: + if request.session.get('_turbolinks_redirect_to'): + location = request.session.pop('_turbolinks_redirect_to') + response['Turbolinks-Location'] = location + return response diff --git a/corres2math/settings.py b/corres2math/settings.py new file mode 100644 index 0000000..1424f6f --- /dev/null +++ b/corres2math/settings.py @@ -0,0 +1,221 @@ +""" +Django settings for corres2math project. + +Generated by 'django-admin startproject' using Django 3.0.5. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.0/ref/settings/ +""" + +import os +import sys + +from django.utils.translation import gettext_lazy as _ + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +APPS_DIR = os.path.realpath(os.path.join(BASE_DIR, "apps")) +sys.path.append(APPS_DIR) + +ADMINS = [("Yohann D'ANELLO", "yohann.danello@animath.fr")] + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = '6$wl1=ehfoiymin3m3i-wyx5d3t=1h7g4(j2izn*my)*yiq#he' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +SITE_ID = 1 + +ALLOWED_HOSTS = ['*'] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.sites', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'django.forms', + + 'bootstrap_datepicker_plus', + 'crispy_forms', + 'django_extensions', + 'django_tables2', + 'haystack', + 'logs', + 'mailer', + 'polymorphic', + 'rest_framework', + 'rest_framework.authtoken', + 'cas_server', + + 'api', + 'eastereggs', + 'registration', + 'participation', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'django.middleware.locale.LocaleMiddleware', + 'django.contrib.sites.middleware.CurrentSiteMiddleware', + 'corres2math.middlewares.SessionMiddleware', + 'corres2math.middlewares.TurbolinksMiddleware', +] + +ROOT_URLCONF = 'corres2math.urls' + +LOGIN_REDIRECT_URL = "index" + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [os.path.join(BASE_DIR, 'corres2math/templates')] + , + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' + +WSGI_APPLICATION = 'corres2math.wsgi.application' + + +# Password validation +# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + +PASSWORD_HASHERS = [ + 'django.contrib.auth.hashers.PBKDF2PasswordHasher', + 'django.contrib.auth.hashers.BCryptPasswordHasher', +] + +CAS_AUTH_CLASS = 'registration.auth.CustomAuthUser' + +REST_FRAMEWORK = { + 'DEFAULT_PERMISSION_CLASSES': [ + 'rest_framework.permissions.IsAdminUser' + ], + 'DEFAULT_AUTHENTICATION_CLASSES': [ + 'rest_framework.authentication.SessionAuthentication', + 'rest_framework.authentication.TokenAuthentication', + ], + 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', + 'PAGE_SIZE': 50, +} + +# Internationalization +# https://docs.djangoproject.com/en/3.0/topics/i18n/ + +LANGUAGE_CODE = 'en' + +LANGUAGES = [ + ('en', _('English')), + ('fr', _('French')), +] + +TIME_ZONE = 'Europe/Paris' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + +LOCALE_PATHS = [os.path.join(BASE_DIR, "locale")] + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.0/howto/static-files/ + +STATIC_URL = '/static/' + +STATICFILES_DIRS = [ + os.path.join(BASE_DIR, "corres2math/static"), +] + +STATIC_ROOT = os.path.join(BASE_DIR, "static") + +MEDIA_URL = '/media/' + +MEDIA_ROOT = os.path.join(BASE_DIR, "media") + +CRISPY_TEMPLATE_PACK = 'bootstrap4' + +DJANGO_TABLES2_TEMPLATE = 'django_tables2/bootstrap4.html' + +HAYSTACK_CONNECTIONS = { + 'default': { + 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', + 'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'), + } +} + +HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' + +_db_type = os.getenv('DJANGO_DB_TYPE', 'sqlite').lower() + +if _db_type == 'mysql' or _db_type.startswith('postgres') or _db_type == 'psql': + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.mysql' if _db_type == 'mysql' else 'django.db.backends.postgresql_psycopg2', + 'NAME': os.environ.get('DJANGO_DB_NAME', 'corres2math'), + 'USER': os.environ.get('DJANGO_DB_USER', 'corres2math'), + 'PASSWORD': os.environ.get('DJANGO_DB_PASSWORD', 'CHANGE_ME_IN_ENV_SETTINGS'), + 'HOST': os.environ.get('DJANGO_DB_HOST', 'localhost'), + 'PORT': os.environ.get('DJANGO_DB_PORT', ''), # Use default port + } + } +else: + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, os.getenv('DJANGO_DB_HOST', 'db.sqlite3')), + } + } + +if os.getenv("CORRES2MATH_STAGE", "dev") == "prod": + from .settings_prod import * +else: + from .settings_dev import * diff --git a/corres2math/settings_dev.py b/corres2math/settings_dev.py new file mode 100644 index 0000000..bf6e856 --- /dev/null +++ b/corres2math/settings_dev.py @@ -0,0 +1,4 @@ +# Database +# https://docs.djangoproject.com/en/3.0/ref/settings/#databases + +EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' diff --git a/corres2math/settings_prod.py b/corres2math/settings_prod.py new file mode 100644 index 0000000..539eb41 --- /dev/null +++ b/corres2math/settings_prod.py @@ -0,0 +1,30 @@ +import os + +# Break it, fix it! +DEBUG = False + +# Mandatory ! +ALLOWED_HOSTS = ['inscription.correspondances-maths.fr', 'plateforme.correspondances-maths.fr'] + +SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'CHANGE_ME_IN_ENV_SETTINGS') + +# Emails +EMAIL_BACKEND = 'mailer.backend.DbBackend' +MAILER_EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' +EMAIL_USE_SSL = True +EMAIL_HOST = os.getenv("SMTP_HOST") +EMAIL_PORT = os.getenv("SMTP_PORT") +EMAIL_HOST_USER = os.getenv("SMTP_HOST_USER") +EMAIL_HOST_PASSWORD = os.getenv("SMTP_HOST_PASSWORD") + +DEFAULT_FROM_EMAIL = os.getenv('FROM_EMAIL', 'Contact Correspondances ') +SERVER_EMAIL = os.getenv('SERVER_EMAIL', 'contact@correspondances-maths.fr') + +# Security settings +SECURE_CONTENT_TYPE_NOSNIFF = False +SECURE_BROWSER_XSS_FILTER = False +SESSION_COOKIE_SECURE = False +CSRF_COOKIE_SECURE = False +CSRF_COOKIE_HTTPONLY = False +X_FRAME_OPTIONS = 'DENY' +SESSION_COOKIE_AGE = 60 * 60 * 3 diff --git a/assets/Autorisation de droit à l'image - majeur.pdf b/corres2math/static/Autorisation de droit à l'image - majeur.pdf similarity index 100% rename from assets/Autorisation de droit à l'image - majeur.pdf rename to corres2math/static/Autorisation de droit à l'image - majeur.pdf diff --git a/assets/Autorisation de droit à l'image - mineur.pdf b/corres2math/static/Autorisation de droit à l'image - mineur.pdf similarity index 100% rename from assets/Autorisation de droit à l'image - mineur.pdf rename to corres2math/static/Autorisation de droit à l'image - mineur.pdf diff --git a/corres2math/static/favicon.ico b/corres2math/static/favicon.ico new file mode 100644 index 0000000..69e1a32 Binary files /dev/null and b/corres2math/static/favicon.ico differ diff --git a/assets/logo.png b/corres2math/static/logo.png similarity index 100% rename from assets/logo.png rename to corres2math/static/logo.png diff --git a/corres2math/templates/400.html b/corres2math/templates/400.html new file mode 100644 index 0000000..0734a85 --- /dev/null +++ b/corres2math/templates/400.html @@ -0,0 +1,8 @@ +{% extends "base.html" %} + +{% load i18n %} + +{% block content %} +

{% trans "Bad request" %}

+ {% blocktrans %}Sorry, your request was bad. Don't know what could be wrong. An email has been sent to webmasters with the details of the error. You can now watch some videos.{% endblocktrans %} +{% endblock %} \ No newline at end of file diff --git a/corres2math/templates/403.html b/corres2math/templates/403.html new file mode 100644 index 0000000..317865f --- /dev/null +++ b/corres2math/templates/403.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load i18n %} + +{% block content %} +

{% trans "Permission denied" %}

+ {% blocktrans %}You don't have the right to perform this request.{% endblocktrans %} + {% if exception %} +
+ {% trans "Exception message:" %} {{ exception }} +
+ {% endif %} +{% endblock %} \ No newline at end of file diff --git a/corres2math/templates/404.html b/corres2math/templates/404.html new file mode 100644 index 0000000..8477f91 --- /dev/null +++ b/corres2math/templates/404.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load i18n %} + +{% block content %} +

{% trans "Page not found" %}

+ {% blocktrans %}The requested path {{ request_path }} was not found on the server.{% endblocktrans %} + {% if exception != "Resolver404" %} +
+ {% trans "Exception message:" %} {{ exception }} +
+ {% endif %} +{% endblock %} \ No newline at end of file diff --git a/corres2math/templates/500.html b/corres2math/templates/500.html new file mode 100644 index 0000000..38d12e4 --- /dev/null +++ b/corres2math/templates/500.html @@ -0,0 +1,8 @@ +{% extends "base.html" %} + +{% load i18n %} + +{% block content %} +

{% trans "Server error" %}

+ {% blocktrans %}Sorry, an error occurred when processing your request. An email has been sent to webmasters with the detail of the error, and this will be fixed soon. You can now watch some videos.{% endblocktrans %} +{% endblock %} diff --git a/corres2math/templates/amount_input.html b/corres2math/templates/amount_input.html new file mode 100644 index 0000000..6ef4a53 --- /dev/null +++ b/corres2math/templates/amount_input.html @@ -0,0 +1,11 @@ +
+ +
+ +
+
\ No newline at end of file diff --git a/corres2math/templates/autocomplete_model.html b/corres2math/templates/autocomplete_model.html new file mode 100644 index 0000000..2236c6e --- /dev/null +++ b/corres2math/templates/autocomplete_model.html @@ -0,0 +1,9 @@ + + +
    +
diff --git a/corres2math/templates/base.html b/corres2math/templates/base.html new file mode 100644 index 0000000..8cd6fc7 --- /dev/null +++ b/corres2math/templates/base.html @@ -0,0 +1,271 @@ +{% load static i18n static %} + + +{% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} + + + + + + {% block title %}{{ title }}{% endblock title %} - Plateforme des Correspondances + + + + {# Favicon #} + + + {% if no_cache %} + + {% endif %} + + {# Bootstrap CSS #} + + + + + {# JQuery, Bootstrap and Turbolinks JavaScript #} + + + + + + {# Si un formulaire requiert des données supplémentaires (notamment JS), les données sont chargées #} + {% if form.media %} + {{ form.media }} + {% endif %} + + {% block extracss %}{% endblock %} + + +
+ + {% block fullcontent %} +
+ {% block contenttitle %}{% endblock %} + {% if user.is_authenticated and not user.registration.email_confirmed %} +
+ + {% url "registration:email_validation_resend" pk=user.pk as send_email_url %} + {% blocktrans trimmed %} + Your email address is not validated. Please click on the link you received by email. + You can resend a mail by clicking on this link. + {% endblocktrans %} +
+ {% endif %} +
+
+ {% block content %} +

Default content...

+ {% endblock content %} +
+
+ {% endblock %} +
+ +
+
+
+
+
+ + {% trans "Contact us" %} — + + {% csrf_token %} + + +
+
+
+ + + +
+
+
+
+ + +{% trans "Calendar" as modal_title %} +{% include "base_modal.html" with modal_id="calendar" modal_additional_class="modal-lg" %} +{% trans "Search results" as modal_title %} +{% include "base_modal.html" with modal_id="search" modal_form_method="get" modal_additional_class="modal-lg" %} +{% trans "Log in" as modal_title %} +{% trans "Log in" as modal_button %} +{% url "login" as modal_action %} +{% include "base_modal.html" with modal_id="login" %} +{% if user.is_authenticated %} + {% trans "Join team" as modal_title %} + {% trans "Join" as modal_button %} + {% url "participation:join_team" as modal_action %} + {% include "base_modal.html" with modal_id="joinTeam" %} + {% trans "Create team" as modal_title %} + {% trans "Create" as modal_button %} + {% url "participation:create_team" as modal_action %} + {% include "base_modal.html" with modal_id="createTeam" modal_button_type="success" %} +{% endif %} + + + +{% block extrajavascript %}{% endblock %} + + diff --git a/corres2math/templates/base_modal.html b/corres2math/templates/base_modal.html new file mode 100644 index 0000000..ab9cf2a --- /dev/null +++ b/corres2math/templates/base_modal.html @@ -0,0 +1,24 @@ +{% load i18n %} + + \ No newline at end of file diff --git a/corres2math/templates/index.html b/corres2math/templates/index.html new file mode 100644 index 0000000..f3d997a --- /dev/null +++ b/corres2math/templates/index.html @@ -0,0 +1,75 @@ +{% extends "base.html" %} + +{% block content %} +
+ +
+
+

+ Bienvenue sur le site d'inscription aux + Correspondances des Jeunes Mathématicien·ne·s ! +

+
+
+
+
+

+ Tu souhaites participer aux Correspondances ? +
+ Ton équipe est déjà formée ? +

+
+ +
+ +
+
Comment ça marche ?
+

+ Pour participer aux Correspondances, il suffit de créer un compte sur la rubrique Inscription. + Vous devrez ensuite confirmer votre adresse e-mail. +

+ +

+ Vous pouvez accéder à votre compte via la rubrique Connexion. + Une fois connecté, vous pourrez créer une équipe ou en rejoindre une déjà créée par l'un de vos camarades + via un code d'accès qui vous aura été transmis. Vous serez ensuite invité à soumettre une autorisation de droit à l'image, + indispensable au bon déroulement des Correspondances. Une fois que votre équipe comporte au moins 3 participants (maximum 5) + et un encadrant, vous pourrez demander à valider votre équipe pour être apte à travailler sur le problème de votre choix. +

+ +

Je ne trouve pas d'équipe, aidez-moi !

+ +

+ En ayant créé un compte sur cette plateforme, vous créez également un compte sur la plateforme de chat dédiée + aux Correspondances, basée sur le protocole Matrix et le client + Element. Cette interface de chat vous permet de communiquer avec les membres + de votre équipe, mais surtout de pouvoir échanger durant la troisième phase des Correspondances, et + également de poser vos questions en cas de besoin. +

+ +

+ Ce chat contient également un salon #je-cherche-une-equipe où vous pouvez crier à l'aide pour trouver + une équipe, ou compléter la votre s'il vous manque des participants. C'est un petit coin auprès du feu, un parc à + jeu où vous pouvez descendre en toboggan (en le désinfectant après utilisation), ne cherchez pas à être trop formel. +

+ +

J'ai une question

+ +

+ Pour toute question, vous pouvez soit la poser dans #faq dans l'onglet chat comme indiqué ci-dessus, soit nous + contacter par mail à l'adresse contact@correspondances-maths.fr. +

+ +
+ Attention aux dates ! Si vous ne finalisez pas votre inscription dans le délai indiqué, vous + ne pourrez malheureusement pas participer aux Correspondances. +
+
+ +
+{% endblock %} diff --git a/corres2math/templates/registration/logged_out.html b/corres2math/templates/registration/logged_out.html new file mode 100644 index 0000000..3b044b7 --- /dev/null +++ b/corres2math/templates/registration/logged_out.html @@ -0,0 +1,10 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-3.0-or-later +{% endcomment %} +{% load i18n %} + +{% block content %} +

{% trans "Thanks for spending some quality time with the Web site today." %}

+

{% trans 'Log in again' %}

+{% endblock %} diff --git a/corres2math/templates/registration/login.html b/corres2math/templates/registration/login.html new file mode 100644 index 0000000..db50a06 --- /dev/null +++ b/corres2math/templates/registration/login.html @@ -0,0 +1,27 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-2.0-or-later +{% endcomment %} +{% load i18n crispy_forms_filters %} + +{% block title %}{% trans "Log in" %}{% endblock %} +{% block contenttitle %}

{% trans "Log in" %}

{% endblock %} + +{% block content %} + {% if user.is_authenticated %} +

+ {% blocktrans trimmed %} + You are authenticated as {{ user }}, but are not authorized to + access this page. Would you like to login to a different account? + {% endblocktrans %} +

+ {% endif %} +
+
+ {% csrf_token %} + {{ form | crispy }} + {% trans 'Forgotten your password or username?' %} +
+ +
+{% endblock %} diff --git a/corres2math/templates/search/search.html b/corres2math/templates/search/search.html new file mode 100644 index 0000000..e510d01 --- /dev/null +++ b/corres2math/templates/search/search.html @@ -0,0 +1,29 @@ +{% extends 'base.html' %} + +{% load crispy_forms_filters highlight i18n search_results_tables django_tables2 %} + +{% block content %} +

{% trans "Search" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+ +
+ +

{% trans "Results" %}

+ +
+ {% regroup object_list by model_name as categories %} + {% for category in categories %} +

{% trans category.grouper|capfirst %}

+ {% with table=category.list|search_table %} + {% render_table table %} + {% endwith %} + {% empty %} +

{% trans "No results found." %}

+ {% endfor %} +
+{% endblock %} \ No newline at end of file diff --git a/corres2math/tokens.py b/corres2math/tokens.py new file mode 100644 index 0000000..a945253 --- /dev/null +++ b/corres2math/tokens.py @@ -0,0 +1,27 @@ +from django.contrib.auth.tokens import PasswordResetTokenGenerator + + +class AccountActivationTokenGenerator(PasswordResetTokenGenerator): + """ + Create a unique token generator to confirm email addresses. + """ + def _make_hash_value(self, user, timestamp): + """ + Hash the user's primary key and some user state that's sure to change + after an account validation to produce a token that invalidated when + it's used: + 1. The user.profile.email_confirmed field will change upon an account + validation. + 2. The last_login field will usually be updated very shortly after + an account validation. + Failing those things, settings.PASSWORD_RESET_TIMEOUT_DAYS eventually + invalidates the token. + """ + # Truncate microseconds so that tokens are consistent even if the + # database doesn't support microseconds. + login_timestamp = '' if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None) + return str(user.pk) + str(user.email) + str(user.registration.email_confirmed)\ + + str(login_timestamp) + str(timestamp) + + +email_validation_token = AccountActivationTokenGenerator() diff --git a/corres2math/urls.py b/corres2math/urls.py new file mode 100644 index 0000000..ae1e0bb --- /dev/null +++ b/corres2math/urls.py @@ -0,0 +1,46 @@ +"""corres2math URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path, include +from django.views.defaults import bad_request, permission_denied, page_not_found, server_error +from django.views.generic import TemplateView +from registration.views import PhotoAuthorizationView + +from .views import AdminSearchView + +urlpatterns = [ + path('', TemplateView.as_view(template_name="index.html", extra_context=dict(title="Accueil")), name='index'), + path('i18n/', include('django.conf.urls.i18n')), + path('admin/doc/', include('django.contrib.admindocs.urls')), + path('admin/', admin.site.urls, name="admin"), + path('accounts/', include('django.contrib.auth.urls')), + path('search/', AdminSearchView.as_view(), name="haystack_search"), + + path('api/', include('api.urls')), + path('participation/', include('participation.urls')), + path('registration/', include('registration.urls')), + + path('media/authorization/photo//', PhotoAuthorizationView.as_view(), name='photo_authorization'), + + path('cas/', include('cas_server.urls', namespace="cas_server")), + + path('', include('eastereggs.urls')), +] + +handler400 = bad_request +handler403 = permission_denied +handler404 = page_not_found +handler500 = server_error diff --git a/corres2math/views.py b/corres2math/views.py new file mode 100644 index 0000000..c777822 --- /dev/null +++ b/corres2math/views.py @@ -0,0 +1,16 @@ +from django.contrib.auth.mixins import LoginRequiredMixin +from django.core.exceptions import PermissionDenied +from haystack.generic_views import SearchView + + +class AdminMixin(LoginRequiredMixin): + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return self.handle_no_permission() + if not request.user.registration.is_admin: + raise PermissionDenied + return super().dispatch(request, *args, **kwargs) + + +class AdminSearchView(AdminMixin, SearchView): + pass diff --git a/corres2math/wsgi.py b/corres2math/wsgi.py new file mode 100644 index 0000000..0cae477 --- /dev/null +++ b/corres2math/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for corres2math project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'corres2math.settings') + +application = get_wsgi_application() diff --git a/dispatcher.php b/dispatcher.php deleted file mode 100644 index b6cf0f3..0000000 --- a/dispatcher.php +++ /dev/null @@ -1,95 +0,0 @@ - $file) { - if (preg_match('#' . $route . '#', $path, $matches)) { - for ($i = 1; $i < sizeof($file); ++$i) - $_GET[$file[$i]] = $matches[$i]; - - if (!preg_match("#php$#", $file[0])) { - header("Content-Type: " . $file[1]); - readfile($file[0]); - exit(); - } - - /** @noinspection PhpIncludeInspection */ - require $file[0]; - exit(); - } -} - -require_once "server_files/404.php"; diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100755 index 0000000..044f92e --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +crond -l 0 + +nginx + +if [ "$CORRES2MATH_STAGE" = "prod" ]; then + gunicorn -b 0.0.0.0:8000 --workers=2 --threads=4 --worker-class=gthread corres2math.wsgi --access-logfile '-' --error-logfile '-'; +else + ./manage.py runserver 0.0.0.0:8000; +fi diff --git a/locale/fr/LC_MESSAGES/django.po b/locale/fr/LC_MESSAGES/django.po new file mode 100644 index 0000000..3411a2a --- /dev/null +++ b/locale/fr/LC_MESSAGES/django.po @@ -0,0 +1,1228 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# Yohann D'ANELLO , 2020. +# +msgid "" +msgstr "" +"Project-Id-Version: Corres2math\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2020-11-02 10:56+0100\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: Yohann D'ANELLO \n" +"Language-Team: LANGUAGE \n" +"Language: fr\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: apps/api/apps.py:10 +msgid "API" +msgstr "API" + +#: apps/eastereggs/templates/eastereggs/xp_modal.html:7 +msgid "Error" +msgstr "Erreur" + +#: apps/eastereggs/templates/eastereggs/xp_modal.html:13 +msgid "This task failed successfully." +msgstr "Cette tâche a échoué avec succès." + +#: apps/eastereggs/templates/eastereggs/xp_modal.html:16 +#: templates/base_modal.html:19 +msgid "Close" +msgstr "Fermer" + +#: apps/logs/apps.py:11 +msgid "Logs" +msgstr "Logs" + +#: apps/logs/models.py:22 apps/registration/models.py:22 +msgid "user" +msgstr "utilisateur" + +#: apps/logs/models.py:28 +msgid "IP Address" +msgstr "Adresse IP" + +#: apps/logs/models.py:36 +msgid "model" +msgstr "modèle" + +#: apps/logs/models.py:43 +msgid "identifier" +msgstr "identifiant" + +#: apps/logs/models.py:49 +msgid "previous data" +msgstr "données précédentes" + +#: apps/logs/models.py:55 +msgid "new data" +msgstr "nouvelles données" + +#: apps/logs/models.py:63 +msgid "create" +msgstr "créer" + +#: apps/logs/models.py:64 +msgid "edit" +msgstr "modifier" + +#: apps/logs/models.py:65 +msgid "delete" +msgstr "supprimer" + +#: apps/logs/models.py:68 +msgid "action" +msgstr "action" + +#: apps/logs/models.py:76 +msgid "timestamp" +msgstr "date" + +#: apps/logs/models.py:80 +msgid "Logs cannot be destroyed." +msgstr "Les logs ne peuvent pas être détruits." + +#: apps/logs/models.py:83 +msgid "changelog" +msgstr "changelog" + +#: apps/logs/models.py:84 +msgid "changelogs" +msgstr "changelogs" + +#: apps/logs/models.py:87 +#, python-brace-format +msgid "Changelog of type \"{action}\" for model {model} at {timestamp}" +msgstr "Changelog de type \"{action}\" pour le modèle {model} le {timestamp}" + +#: apps/participation/forms.py:20 apps/participation/models.py:33 +msgid "The trigram must be composed of three uppercase letters." +msgstr "Le trigramme doit être composé de trois lettres majuscules." + +#: apps/participation/forms.py:35 +msgid "No team was found with this access code." +msgstr "Aucune équipe n'a été trouvée avec ce code d'accès." + +#: apps/participation/forms.py:69 +msgid "I engage myself to participate to the whole \"Correspondances\"." +msgstr "Je m'engage à participer à l'intégralité des Correspondances." + +#: apps/participation/forms.py:84 +msgid "Message to address to the team:" +msgstr "Message à adresser à l'équipe :" + +#: apps/participation/forms.py:99 +msgid "You can't upload your video after the deadline." +msgstr "Vous ne pouvez pas envoyer de vidéo après la date limite." + +#: apps/participation/forms.py:124 +msgid "Send to team" +msgstr "Envoyer à l'équipe" + +#: apps/participation/forms.py:152 +msgid "How did you get the idea to ...?" +msgstr "Comment avez-vous eu l'idée de ... ?" + +#: apps/participation/forms.py:175 +msgid "Start date must be before the end date." +msgstr "La date de début doit être avant la date de fin." + +#: apps/participation/forms.py:177 +msgid "This phase must start after the previous phases." +msgstr "Cette phase doit commencer après les phases précédentes." + +#: apps/participation/forms.py:179 +msgid "This phase must end after the next phases." +msgstr "Cette phase doit finir avant les phases suivantes." + +#: apps/participation/models.py:26 apps/participation/tables.py:30 +#: apps/participation/tables.py:52 apps/participation/tables.py:78 +msgid "name" +msgstr "nom" + +#: apps/participation/models.py:32 apps/participation/tables.py:57 +msgid "trigram" +msgstr "trigramme" + +#: apps/participation/models.py:40 +msgid "access code" +msgstr "code d'accès" + +#: apps/participation/models.py:41 +msgid "The access code let other people to join the team." +msgstr "Le code d'accès permet aux autres participants de rejoindre l'équipe." + +#: apps/participation/models.py:45 +msgid "Grant Animath to publish my video" +msgstr "Autoriser Animath à publier ma vidéo" + +#: apps/participation/models.py:46 +msgid "" +"Give the authorisation to publish the video on the main website to promote " +"the action." +msgstr "" +"Donner l'autorisation de publier la vidéo sur le site principal pour " +"promouvoir les Correspondances." + +#: apps/participation/models.py:97 +#, python-brace-format +msgid "Team {name} ({trigram})" +msgstr "Équipe {name} ({trigram})" + +#: apps/participation/models.py:100 apps/participation/models.py:115 +#: apps/registration/models.py:106 apps/registration/models.py:155 +msgid "team" +msgstr "équipe" + +#: apps/participation/models.py:101 +msgid "teams" +msgstr "équipes" + +#: apps/participation/models.py:119 +#, python-brace-format +msgid "Problem #{problem:d}" +msgstr "Problème n°{problem:d}" + +#: apps/participation/models.py:122 apps/participation/tables.py:35 +#: apps/participation/tables.py:62 +msgid "problem number" +msgstr "numéro de problème" + +#: apps/participation/models.py:128 apps/participation/models.py:182 +msgid "valid" +msgstr "valide" + +#: apps/participation/models.py:129 apps/participation/models.py:183 +msgid "The video got the validation of the administrators." +msgstr "La vidéo a été validée par les administrateurs." + +#: apps/participation/models.py:138 +msgid "solution video" +msgstr "vidéo de solution" + +#: apps/participation/models.py:147 +msgid "received participation" +msgstr "participation reçue" + +#: apps/participation/models.py:156 +msgid "synthesis video" +msgstr "vidéo de synthèse" + +#: apps/participation/models.py:163 +#, python-brace-format +msgid "Participation of the team {name} ({trigram})" +msgstr "Participation de l'équipe {name} ({trigram})" + +#: apps/participation/models.py:166 apps/participation/models.py:240 +msgid "participation" +msgstr "participation" + +#: apps/participation/models.py:167 +msgid "participations" +msgstr "participations" + +#: apps/participation/models.py:175 +msgid "link" +msgstr "lien" + +#: apps/participation/models.py:176 +msgid "The full video link." +msgstr "Le lien complet de la vidéo." + +#: apps/participation/models.py:225 +#, python-brace-format +msgid "Video of team {name} ({trigram})" +msgstr "Vidéo de l'équipe {name} ({trigram})" + +#: apps/participation/models.py:229 +msgid "video" +msgstr "vidéo" + +#: apps/participation/models.py:230 +msgid "videos" +msgstr "vidéos" + +#: apps/participation/models.py:245 +msgid "question" +msgstr "question" + +#: apps/participation/models.py:259 +msgid "phase number" +msgstr "phase" + +#: apps/participation/models.py:264 +msgid "phase description" +msgstr "description" + +#: apps/participation/models.py:268 +msgid "start date of the given phase" +msgstr "début de la phase" + +#: apps/participation/models.py:273 +msgid "end date of the given phase" +msgstr "fin de la phase" + +#: apps/participation/models.py:291 +msgid "" +"Phase {phase_number:d} starts on {start:%Y-%m-%d %H:%M} and ends on {end:%Y-" +"%m-%d %H:%M}" +msgstr "" +"Phase {phase_number:d} démarrant le {start:%d/%m/%Y %H:%M} et finissant le " +"{end:%d/%m/%Y %H:%M}" + +#: apps/participation/models.py:295 +msgid "phase" +msgstr "phase" + +#: apps/participation/models.py:296 +msgid "phases" +msgstr "phases" + +#: apps/participation/templates/participation/create_team.html:11 +#: templates/base.html:231 +msgid "Create" +msgstr "Créer" + +#: apps/participation/templates/participation/join_team.html:11 +#: templates/base.html:227 +msgid "Join" +msgstr "Rejoindre" + +#: apps/participation/templates/participation/participation_detail.html:6 +#: apps/participation/templates/participation/team_detail.html:31 +#: apps/participation/templates/participation/team_detail.html:40 +#: apps/participation/templates/participation/team_detail.html:45 +#: apps/registration/templates/registration/user_detail.html:6 +#: apps/registration/templates/registration/user_detail.html:26 +msgid "any" +msgstr "aucun·e" + +#: apps/participation/templates/participation/participation_detail.html:9 +msgid "Participation of team" +msgstr "Participation de l'équipe" + +#: apps/participation/templates/participation/participation_detail.html:13 +#: apps/registration/templates/registration/user_detail.html:25 +msgid "Team:" +msgstr "Équipe :" + +#: apps/participation/templates/participation/participation_detail.html:16 +#: apps/participation/templates/participation/team_detail.html:44 +msgid "Chosen problem:" +msgstr "Problème choisi :" + +#: apps/participation/templates/participation/participation_detail.html:22 +#: apps/participation/templates/participation/participation_detail.html:150 +msgid "No video sent" +msgstr "Pas de vidéo envoyée" + +#: apps/participation/templates/participation/participation_detail.html:23 +#: apps/participation/templates/participation/participation_detail.html:106 +msgid "Proposed solution:" +msgstr "Solution proposée :" + +#: apps/participation/templates/participation/participation_detail.html:27 +#: apps/participation/templates/participation/participation_detail.html:154 +#: apps/participation/templates/participation/participation_detail.html:182 +#: apps/participation/templates/participation/participation_detail.html:234 +#: apps/participation/templates/participation/upload_video.html:11 +#: apps/registration/templates/registration/upload_photo_authorization.html:18 +#: apps/registration/templates/registration/user_detail.html:78 +msgid "Upload" +msgstr "Téléverser" + +#: apps/participation/templates/participation/participation_detail.html:30 +#: apps/participation/templates/participation/participation_detail.html:83 +#: apps/participation/templates/participation/participation_detail.html:110 +#: apps/participation/templates/participation/participation_detail.html:156 +msgid "Display" +msgstr "Afficher" + +#: apps/participation/templates/participation/participation_detail.html:45 +msgid "Sent solution" +msgstr "Solution envoyée" + +#: apps/participation/templates/participation/participation_detail.html:49 +msgid "Team that received your solution:" +msgstr "Équipe qui a reçu votre solution :" + +#: apps/participation/templates/participation/participation_detail.html:53 +#: apps/participation/templates/participation/participation_detail.html:102 +#: apps/participation/templates/participation/participation_detail.html:126 +msgid "Change" +msgstr "Modifier" + +#: apps/participation/templates/participation/participation_detail.html:60 +msgid "" +"The mentioned team received your video. They are now watching your video, " +"and formulating questions. You would be able to exchange with the other " +"phase during the next phase." +msgstr "" +"L'équipe mentionnée a reçu votre vidéo. Ils sont actuellement en train de la " +"visionner, et de formuler des questions. Lors de la prochaine phase, vous " +"serez invités à répondre aux questions et échanger avec l'autre équipe." + +#: apps/participation/templates/participation/participation_detail.html:68 +#, python-format +msgid "" +"The other team sent you questions about your solution. Your are now able to " +"answer them, then to exchange freely with the other team. You can click on " +"the Chat button, or to connect to your dedicated Matrix account: " +"@corres2math_%(user_id)s:correspondances-maths.fr. You can use " +"your own Matrix client, or use the dedicated Element client: element.correpondances-maths." +"fr" +msgstr "" +"L'autre équipe vous a envoyé leurs questions à propos de votre solution. " +"Vous pouvez désormais leur répondre, puis échanger librement avec l'autre " +"équipe. Vous pouvez cliquer sur le bouton de chat, ou vous connecter à votre " +"compte Matrix dédié : @corres2math_%(user_id)s:correspondances-maths." +"fr. Vous pouvez utiliser votre propre client Matrix, ou utiliser le " +"client Element dédié : element.correpondances-maths.fr" + +#: apps/participation/templates/participation/participation_detail.html:79 +msgid "Synthesis from the other team:" +msgstr "Synthèse de l'autre équipe :" + +#: apps/participation/templates/participation/participation_detail.html:94 +msgid "Received solution" +msgstr "Solution reçue" + +#: apps/participation/templates/participation/participation_detail.html:98 +msgid "Team that sent you their solution:" +msgstr "Équipe qui vous a envoyé leur solution :" + +#: apps/participation/templates/participation/participation_detail.html:116 +msgid "" +"You received a solution about the same problem that you treated from another " +"team. You are now encouraged to see the video, then to ask from 3 to 6 " +"questions about the video. After that, you will be invited to exchange with " +"the other team about the solution." +msgstr "" +"Vous avez reçu une vidéo à propos du même problème que vous avez traité de " +"la part d'une autre équipe. Vous êtes désormais encouragés à visionner la " +"vidéo, puis à poser 3 à 6 questions à propos de la vidéo. Après cela, vous " +"serez invités à échanger avec l'autre équipe à propos de la solution." + +#: apps/participation/templates/participation/participation_detail.html:133 +msgid "Add a question" +msgstr "Ajouter une question" + +#: apps/participation/templates/participation/participation_detail.html:138 +#, python-format +msgid "" +"You sent your questions to the other team about their solution. When they " +"answer to your questions, you will be able to exchange freely with the other " +"team. You can click on the Chat button, or to connect to your dedicated " +"Matrix account: @corres2math_%(user_id)s:correspondances-maths.fr. You can use your own Matrix client, or use the dedicated Element " +"client: element." +"correpondances-maths.fr" +msgstr "" +"Vous avez envoyé vos questions à l'autre équipe à propos de leur solution. " +"Lorsqu'ils auront répondu, vous pourrez échanger librement avec l'autre " +"équipe. Vous pouvez cliquer sur le bouton de chat, ou vous connecter à votre " +"compte Matrix dédié : @corres2math_%(user_id)s:correspondances-maths." +"fr. Vous pouvez utiliser votre propre client Matrix, ou utiliser le " +"client Element dédié : element.correpondances-maths.fr" + +#: apps/participation/templates/participation/participation_detail.html:151 +msgid "Your synthesis of the exchange:" +msgstr "Votre synthèse de l'échange :" + +#: apps/participation/templates/participation/participation_detail.html:170 +msgid "Define received video" +msgstr "Définir la vidéo reçue" + +#: apps/participation/templates/participation/participation_detail.html:171 +#: apps/participation/templates/participation/participation_detail.html:176 +#: apps/participation/templates/participation/participation_detail.html:210 +#: apps/participation/templates/participation/phase_form.html:11 +#: apps/participation/templates/participation/phase_list.html:18 +#: apps/participation/templates/participation/receive_participation_form.html:11 +#: apps/participation/templates/participation/send_participation_form.html:11 +#: apps/participation/templates/participation/team_detail.html:64 +#: apps/participation/templates/participation/team_detail.html:123 +#: apps/participation/templates/participation/update_team.html:12 +#: apps/registration/templates/registration/update_user.html:12 +#: apps/registration/templates/registration/user_detail.html:64 +#: apps/registration/templates/registration/user_detail.html:73 +msgid "Update" +msgstr "Modifier" + +#: apps/participation/templates/participation/participation_detail.html:175 +msgid "Define team that receives your video" +msgstr "Définir l'équipe qui recevra votre vidéo" + +#: apps/participation/templates/participation/participation_detail.html:181 +#: apps/participation/templates/participation/participation_detail.html:233 +#: apps/participation/views.py:463 +msgid "Upload video" +msgstr "Envoyer la vidéo" + +#: apps/participation/templates/participation/participation_detail.html:186 +#: apps/participation/templates/participation/participation_detail.html:193 +msgid "Display solution" +msgstr "Afficher la solution" + +#: apps/participation/templates/participation/participation_detail.html:187 +#: apps/participation/templates/participation/participation_detail.html:194 +#: apps/participation/templates/participation/participation_detail.html:229 +#: apps/participation/templates/participation/participation_detail.html:240 +msgid "This video platform is not supported yet." +msgstr "La plateforme de cette vidéo n'est pas encore supportée." + +#: apps/participation/templates/participation/participation_detail.html:200 +msgid "Add question" +msgstr "Ajouter une question" + +#: apps/participation/templates/participation/participation_detail.html:201 +msgid "Add" +msgstr "Ajouter" + +#: apps/participation/templates/participation/participation_detail.html:207 +#: apps/participation/templates/participation/participation_detail.html:218 +#: apps/participation/templates/participation/question_confirm_delete.html:14 +msgid "Delete" +msgstr "Supprimer" + +#: apps/participation/templates/participation/participation_detail.html:209 +msgid "Update question" +msgstr "Modifier la question" + +#: apps/participation/templates/participation/participation_detail.html:217 +#: apps/participation/views.py:440 +msgid "Delete question" +msgstr "Supprimer la question" + +#: apps/participation/templates/participation/participation_detail.html:228 +#: apps/participation/templates/participation/participation_detail.html:239 +msgid "Display synthesis" +msgstr "Afficher la synthèse" + +#: apps/participation/templates/participation/phase_list.html:10 +#: apps/participation/views.py:482 templates/base.html:68 +#: templates/base.html:70 templates/base.html:217 +msgid "Calendar" +msgstr "Calendrier" + +#: apps/participation/templates/participation/phase_list.html:17 +msgid "Update phase" +msgstr "Modifier la phase" + +#: apps/participation/templates/participation/question_confirm_delete.html:9 +msgid "Are you sure you want to delete this question?" +msgstr "Êtes-vous sûr·e de vouloir supprimer cette question ?" + +#: apps/participation/templates/participation/question_form.html:11 +msgid "Send" +msgstr "Envoyer" + +#: apps/participation/templates/participation/team_detail.html:14 +msgid "Name:" +msgstr "Nom :" + +#: apps/participation/templates/participation/team_detail.html:17 +msgid "Trigram:" +msgstr "Trigramme :" + +#: apps/participation/templates/participation/team_detail.html:20 +#: apps/registration/templates/registration/user_detail.html:20 +msgid "Email:" +msgstr "Adresse e-mail :" + +#: apps/participation/templates/participation/team_detail.html:23 +msgid "Access code:" +msgstr "Code d'accès :" + +#: apps/participation/templates/participation/team_detail.html:26 +msgid "Coachs:" +msgstr "Encadrants :" + +#: apps/participation/templates/participation/team_detail.html:35 +msgid "Participants:" +msgstr "Participants :" + +#: apps/participation/templates/participation/team_detail.html:48 +msgid "Grant Animath to publish our video:" +msgstr "Autoriser Animath à publier notre vidéo :" + +#: apps/participation/templates/participation/team_detail.html:51 +msgid "Authorizations:" +msgstr "Autorisations :" + +#: apps/participation/templates/participation/team_detail.html:57 +msgid "Not uploaded yet" +msgstr "Pas encore envoyée" + +#: apps/participation/templates/participation/team_detail.html:66 +#: apps/participation/templates/participation/team_detail.html:128 +#: apps/participation/templates/participation/team_leave.html:11 +msgid "Leave" +msgstr "Quitter" + +#: apps/participation/templates/participation/team_detail.html:76 +msgid "Access to team participation" +msgstr "Accéder à la participation de l'équipe" + +#: apps/participation/templates/participation/team_detail.html:83 +msgid "" +"Your team has at least 3 members and all photo authorizations were given: " +"the team can be validated." +msgstr "" +"Votre équipe contient au moins 3 personnes et toutes les autorisations de " +"droit à l'image ont été données : l'équipe peut être validée." + +#: apps/participation/templates/participation/team_detail.html:88 +msgid "Submit my team to validation" +msgstr "Soumettre mon équipe à validation" + +#: apps/participation/templates/participation/team_detail.html:94 +msgid "" +"Your team must be composed of 3 members and each member must upload its " +"photo authorization and confirm its email address." +msgstr "" +"Votre équipe doit être composée de 3 membres et chaque membre doit envoyer " +"son autorisation de droit à l'image et confirmé son adresse e-mail." + +#: apps/participation/templates/participation/team_detail.html:99 +msgid "This team didn't ask for validation yet." +msgstr "L'équipe n'a pas encore demandé à être validée." + +#: apps/participation/templates/participation/team_detail.html:105 +msgid "Your validation is pending." +msgstr "Votre validation est en attente." + +#: apps/participation/templates/participation/team_detail.html:109 +msgid "" +"The team requested to be validated. You may now control the authorizations " +"and confirm that they can participate." +msgstr "" +"L'équipe a demandé à être validée. Vous pouvez désormais contrôler les " +"différentes autorisations et confirmer qu'elle peut participer." + +#: apps/participation/templates/participation/team_detail.html:115 +msgid "Validate" +msgstr "Valider" + +#: apps/participation/templates/participation/team_detail.html:116 +msgid "Invalidate" +msgstr "Invalider" + +#: apps/participation/templates/participation/team_detail.html:122 +msgid "Update team" +msgstr "Modifier l'équipe" + +#: apps/participation/templates/participation/team_detail.html:127 +#: apps/participation/views.py:296 +msgid "Leave team" +msgstr "Quitter l'équipe" + +#: apps/participation/templates/participation/team_leave.html:9 +msgid "Are you sure that you want to leave this team?" +msgstr "Êtes-vous sûr·e de vouloir quitter cette équipe ?" + +#: apps/participation/views.py:36 templates/base.html:77 +#: templates/base.html:230 +msgid "Create team" +msgstr "Créer une équipe" + +#: apps/participation/views.py:43 apps/participation/views.py:89 +msgid "You don't participate, so you can't create a team." +msgstr "Vous ne participez pas, vous ne pouvez pas créer d'équipe." + +#: apps/participation/views.py:45 apps/participation/views.py:91 +msgid "You are already in a team." +msgstr "Vous êtes déjà dans une équipe." + +#: apps/participation/views.py:82 templates/base.html:82 +#: templates/base.html:226 +msgid "Join team" +msgstr "Rejoindre une équipe" + +#: apps/participation/views.py:133 apps/participation/views.py:302 +#: apps/participation/views.py:335 +msgid "You are not in a team." +msgstr "Vous n'êtes pas dans une équipe." + +#: apps/participation/views.py:134 apps/participation/views.py:336 +msgid "You don't participate, so you don't have any team." +msgstr "Vous ne participez pas, vous n'avez donc pas d'équipe." + +#: apps/participation/views.py:155 +#, python-brace-format +msgid "Detail of team {trigram}" +msgstr "Détails de l'équipe {trigram}" + +#: apps/participation/views.py:180 +msgid "You don't participate, so you can't request the validation of the team." +msgstr "" +"Vous ne participez pas, vous ne pouvez pas demander la validation de " +"l'équipe." + +#: apps/participation/views.py:183 +msgid "The validation of the team is already done or pending." +msgstr "La validation de l'équipe est déjà faite ou en cours." + +#: apps/participation/views.py:196 +msgid "You are not an administrator." +msgstr "Vous n'êtes pas administrateur." + +#: apps/participation/views.py:199 +msgid "This team has no pending validation." +msgstr "L'équipe n'a pas de validation en attente." + +#: apps/participation/views.py:218 +msgid "You must specify if you validate the registration or not." +msgstr "Vous devez spécifier si vous validez l'inscription ou non." + +#: apps/participation/views.py:245 +#, python-brace-format +msgid "Update team {trigram}" +msgstr "Mise à jour de l'équipe {trigram}" + +#: apps/participation/views.py:282 apps/registration/views.py:243 +#, python-brace-format +msgid "Photo authorization of {student}.{ext}" +msgstr "Autorisation de droit à l'image de {student}.{ext}" + +#: apps/participation/views.py:286 +#, python-brace-format +msgid "Photo authorizations of team {trigram}.zip" +msgstr "Autorisations de droit à l'image de l'équipe {trigram}.zip" + +#: apps/participation/views.py:304 +msgid "The team is already validated or the validation is pending." +msgstr "La validation de l'équipe est déjà faite ou en cours." + +#: apps/participation/views.py:348 +msgid "The team is not validated yet." +msgstr "L'équipe n'est pas encore validée." + +#: apps/participation/views.py:357 +#, python-brace-format +msgid "Participation of team {trigram}" +msgstr "Participation de l'équipe {trigram}" + +#: apps/participation/views.py:394 +msgid "Create question" +msgstr "Créer une question" + +#: apps/participation/views.py:491 +msgid "Calendar update" +msgstr "Mise à jour du calendrier" + +#: apps/registration/forms.py:18 +msgid "role" +msgstr "rôle" + +#: apps/registration/forms.py:20 +msgid "participant" +msgstr "participant" + +#: apps/registration/forms.py:21 apps/registration/models.py:164 +msgid "coach" +msgstr "encadrant" + +#: apps/registration/forms.py:68 +msgid "The uploaded file must be a PDF, PNG of JPEG file." +msgstr "Le fichier envoyé doit être au format PDF, PNG ou JPEG." + +#: apps/registration/models.py:27 +msgid "Grant Animath to contact me in the future about other actions" +msgstr "" +"Autoriser Animath à me recontacter à l'avenir à propos d'autres actions" + +#: apps/registration/models.py:32 +msgid "email confirmed" +msgstr "email confirmé" + +#: apps/registration/models.py:40 +msgid "Activate your Correspondances account" +msgstr "Activez votre compte des Correspondances" + +#: apps/registration/models.py:87 +msgid "registration" +msgstr "inscription" + +#: apps/registration/models.py:88 +msgid "registrations" +msgstr "inscriptions" + +#: apps/registration/models.py:111 +msgid "12th grade" +msgstr "Terminale" + +#: apps/registration/models.py:112 +msgid "11th grade" +msgstr "Première" + +#: apps/registration/models.py:113 +msgid "10th grade or lower" +msgstr "Seconde ou inférieur" + +#: apps/registration/models.py:115 +msgid "student class" +msgstr "classe" + +#: apps/registration/models.py:120 +msgid "school" +msgstr "école" + +#: apps/registration/models.py:124 +msgid "photo authorization" +msgstr "autorisation de droit à l'image" + +#: apps/registration/models.py:132 +msgid "student" +msgstr "étudiant" + +#: apps/registration/models.py:140 +msgid "student registration" +msgstr "inscription d'élève" + +#: apps/registration/models.py:141 +msgid "student registrations" +msgstr "inscriptions d'élève" + +#: apps/registration/models.py:159 +msgid "professional activity" +msgstr "activité professionnelle" + +#: apps/registration/models.py:172 +msgid "coach registration" +msgstr "inscription d'encadrant" + +#: apps/registration/models.py:173 +msgid "coach registrations" +msgstr "inscriptions d'encadrants" + +#: apps/registration/models.py:182 +msgid "role of the administrator" +msgstr "rôle de l'administrateur" + +#: apps/registration/models.py:187 +msgid "admin" +msgstr "admin" + +#: apps/registration/models.py:195 +msgid "admin registration" +msgstr "inscription d'administrateur" + +#: apps/registration/models.py:196 +msgid "admin registrations" +msgstr "inscriptions d'administrateur" + +#: apps/registration/tables.py:14 +msgid "last name" +msgstr "nom de famille" + +#: apps/registration/templates/registration/email_validation_complete.html:15 +msgid "Your email have successfully been validated." +msgstr "Votre email a été validé avec succès." + +#: apps/registration/templates/registration/email_validation_complete.html:18 +#, python-format +msgid "You can now log in." +msgstr "Vous pouvez désormais vous connecter." + +#: apps/registration/templates/registration/email_validation_complete.html:22 +msgid "" +"The link was invalid. The token may have expired. Please send us an email to " +"activate your account." +msgstr "" +"Le lien est invalide. Le jeton a peut-être expiré. Merci de nous envoyer un " +"mail pour activer votre compte." + +#: apps/registration/templates/registration/email_validation_email_sent.html:10 +msgid "Account activation" +msgstr "Activation du compte" + +#: apps/registration/templates/registration/email_validation_email_sent.html:14 +msgid "" +"An email has been sent. Please click on the link to activate your account." +msgstr "" +"Un email a été envoyé. Merci de cliquer sur le lien pour activer votre " +"compte." + +#: apps/registration/templates/registration/mails/email_validation_email.html:12 +#: apps/registration/templates/registration/mails/email_validation_email.txt:3 +msgid "Hi" +msgstr "Bonjour" + +#: apps/registration/templates/registration/mails/email_validation_email.html:16 +#: apps/registration/templates/registration/mails/email_validation_email.txt:5 +msgid "" +"You recently registered on the Correspondances platform. Please click on the " +"link below to confirm your registration." +msgstr "" +"Vous vous êtes inscrits sur la plateforme des Correspondances. Merci de " +"cliquer sur le lien ci-dessous pour confirmer votre inscription." + +#: apps/registration/templates/registration/mails/email_validation_email.html:26 +#: apps/registration/templates/registration/mails/email_validation_email.txt:9 +msgid "" +"This link is only valid for a couple of days, after that you will need to " +"contact us to validate your email." +msgstr "" +"Ce lien n'est valide que pendant quelques jours, après cela vous devrez nous " +"contacter pour valider votre email." + +#: apps/registration/templates/registration/mails/email_validation_email.html:30 +#: apps/registration/templates/registration/mails/email_validation_email.txt:11 +msgid "Thanks" +msgstr "Merci" + +#: apps/registration/templates/registration/mails/email_validation_email.html:35 +#: apps/registration/templates/registration/mails/email_validation_email.txt:13 +msgid "The Correspondances team." +msgstr "L'équipe des Correspondances" + +#: apps/registration/templates/registration/password_change_done.html:8 +msgid "Your password was changed." +msgstr "Votre mot de passe a été changé." + +#: apps/registration/templates/registration/password_change_form.html:9 +msgid "" +"Please enter your old password, for security's sake, and then enter your new " +"password twice so we can verify you typed it in correctly." +msgstr "" +"Merci d'entrer votre ancien mot de passe pour des raisons de sécurité, et " +"d'entrer votre nouveau mot de passe deux fois afin de s'assurer que vous " +"l'ayez tapé correctement." + +#: apps/registration/templates/registration/password_change_form.html:11 +#: apps/registration/templates/registration/password_reset_confirm.html:12 +msgid "Change my password" +msgstr "Changer mon mot de passe" + +#: apps/registration/templates/registration/password_reset_complete.html:8 +msgid "Your password has been set. You may go ahead and log in now." +msgstr "Votre mot de passe a été changé. Vous pouvez désormais vous connecter." + +#: apps/registration/templates/registration/password_reset_complete.html:10 +#: templates/base.html:130 templates/base.html:221 templates/base.html:222 +#: templates/registration/login.html:7 templates/registration/login.html:8 +#: templates/registration/login.html:25 +msgid "Log in" +msgstr "Connexion" + +#: apps/registration/templates/registration/password_reset_confirm.html:9 +msgid "" +"Please enter your new password twice so we can verify you typed it in " +"correctly." +msgstr "" +"Merci d'entrer votre nouveau mot de passe deux fois afin de vérifier que " +"vous l'ayez tapé correctement." + +#: apps/registration/templates/registration/password_reset_confirm.html:15 +msgid "" +"The password reset link was invalid, possibly because it has already been " +"used. Please request a new password reset." +msgstr "" +"Le lien de réinitialisation du mot de passe est invalide, probablement parce " +"qu'il a déjà été utilisé. Merci de demander une nouvelle réinitialisation du " +"mot de passe." + +#: apps/registration/templates/registration/password_reset_done.html:8 +msgid "" +"We've emailed you instructions for setting your password, if an account " +"exists with the email you entered. You should receive them shortly." +msgstr "" +"Nous vous avons envoyé un email contenant des instructions pour définir " +"votre mot de passe, si un compte existe avec l'adresse mail que vous avez " +"entrée. Vous devriez le recevoir très rapidement." + +#: apps/registration/templates/registration/password_reset_done.html:9 +msgid "" +"If you don't receive an email, please make sure you've entered the address " +"you registered with, and check your spam folder." +msgstr "" +"Si vous ne recevez pas de mail, merci de vous assurer que vous avez entré " +"l'adresse mail avec laquelle vous êtes inscrits, et de vérifier vos " +"courriers indésirables." + +#: apps/registration/templates/registration/password_reset_form.html:8 +msgid "" +"Forgotten your password? Enter your email address below, and we'll email " +"instructions for setting a new one." +msgstr "" +"Mot de passe oublié ? Entrez votre adresse mail ci-dessous, et nous vous " +"enverrons un mail avec les instructions pour en définir un nouveau." + +#: apps/registration/templates/registration/password_reset_form.html:11 +msgid "Reset my password" +msgstr "Réinitialiser mon mot de passe" + +#: apps/registration/templates/registration/signup.html:5 +#: apps/registration/templates/registration/signup.html:8 +#: apps/registration/templates/registration/signup.html:20 +#: apps/registration/views.py:28 +msgid "Sign up" +msgstr "Inscription" + +#: apps/registration/templates/registration/upload_photo_authorization.html:6 +msgid "Back to the user detail" +msgstr "Retour aux détails de l'utilisateur" + +#: apps/registration/templates/registration/upload_photo_authorization.html:11 +msgid "Authorzation templates:" +msgstr "Modèles d'autorisation :" + +#: apps/registration/templates/registration/upload_photo_authorization.html:12 +msgid "Adult" +msgstr "Majeur" + +#: apps/registration/templates/registration/upload_photo_authorization.html:13 +msgid "Child" +msgstr "Mineur" + +#: apps/registration/templates/registration/user_detail.html:14 +msgid "Last name:" +msgstr "Nom de famille :" + +#: apps/registration/templates/registration/user_detail.html:17 +msgid "First name:" +msgstr "Prénom :" + +#: apps/registration/templates/registration/user_detail.html:22 +msgid "Not confirmed" +msgstr "Non confirmée" + +#: apps/registration/templates/registration/user_detail.html:22 +msgid "resend the validation link" +msgstr "Renvoyer le lien de validation" + +#: apps/registration/templates/registration/user_detail.html:35 +msgid "Student class:" +msgstr "Classe :" + +#: apps/registration/templates/registration/user_detail.html:38 +msgid "School:" +msgstr "École :" + +#: apps/registration/templates/registration/user_detail.html:41 +msgid "Photo authorization:" +msgstr "Autorisation de droit à l'image" + +#: apps/registration/templates/registration/user_detail.html:44 +msgid "Download" +msgstr "Télécharger" + +#: apps/registration/templates/registration/user_detail.html:47 +msgid "Replace" +msgstr "Remplacer" + +#: apps/registration/templates/registration/user_detail.html:51 +msgid "Profesional activity:" +msgstr "Activité professionnelle :" + +#: apps/registration/templates/registration/user_detail.html:54 +msgid "Role:" +msgstr "Rôle :" + +#: apps/registration/templates/registration/user_detail.html:58 +msgid "Grant Animath to contact me in the future about other actions:" +msgstr "Autorise Animath à recontacter à propos d'autres actions :" + +#: apps/registration/templates/registration/user_detail.html:66 +msgid "Impersonate" +msgstr "Impersonifier" + +#: apps/registration/templates/registration/user_detail.html:72 +msgid "Update user" +msgstr "Modifier l'utilisateur" + +#: apps/registration/templates/registration/user_detail.html:77 +#: apps/registration/views.py:206 +msgid "Upload photo authorization" +msgstr "Téléverser l'autorisation de droit à l'image" + +#: apps/registration/views.py:64 +msgid "Email validation" +msgstr "Validation de l'adresse mail" + +#: apps/registration/views.py:66 +msgid "Validate email" +msgstr "Valider l'adresse mail" + +#: apps/registration/views.py:105 +msgid "Email validation unsuccessful" +msgstr "Échec de la validation de l'adresse mail" + +#: apps/registration/views.py:116 +msgid "Email validation email sent" +msgstr "Mail de confirmation de l'adresse mail envoyé" + +#: apps/registration/views.py:124 +msgid "Resend email validation link" +msgstr "Renvoyé le lien de validation de l'adresse mail" + +#: apps/registration/views.py:158 +#, python-brace-format +msgid "Detail of user {user}" +msgstr "Détails de l'utilisateur {user}" + +#: apps/registration/views.py:179 +#, python-brace-format +msgid "Update user {user}" +msgstr "Mise à jour de l'utilisateur {user}" + +#: corres2math/settings.py:154 +msgid "English" +msgstr "Anglais" + +#: corres2math/settings.py:155 +msgid "French" +msgstr "Français" + +#: templates/400.html:6 +msgid "Bad request" +msgstr "Requête invalide" + +#: templates/400.html:7 +msgid "" +"Sorry, your request was bad. Don't know what could be wrong. An email has " +"been sent to webmasters with the details of the error. You can now watch " +"some videos." +msgstr "" +"Désolé, votre requête est invalide. Aucune idée de ce qui a pu se passer. Un " +"email a été envoyé aux administrateurs avec les détails de l'erreur. Vous " +"pouvez désormais retourner voir des vidéos." + +#: templates/403.html:6 +msgid "Permission denied" +msgstr "Permission refusée" + +#: templates/403.html:7 +msgid "You don't have the right to perform this request." +msgstr "Vous n'avez pas le droit d'effectuer cette requête." + +#: templates/403.html:10 templates/404.html:10 +msgid "Exception message:" +msgstr "Message d'erreur :" + +#: templates/404.html:6 +msgid "Page not found" +msgstr "Page non trouvée" + +#: templates/404.html:7 +#, python-format +msgid "" +"The requested path %(request_path)s was not found on the server." +msgstr "" +"Le chemin demandé %(request_path)s n'a pas été trouvé sur le " +"serveur." + +#: templates/500.html:6 +msgid "Server error" +msgstr "Erreur du serveur" + +#: templates/500.html:7 +msgid "" +"Sorry, an error occurred when processing your request. An email has been " +"sent to webmasters with the detail of the error, and this will be fixed " +"soon. You can now watch some videos." +msgstr "" +"Désolé, une erreur est survenue lors du traitement de votre requête. Aucune " +"idée de ce qui a pu se passer. Un email a été envoyé aux administrateurs " +"avec les détails de l'erreur. Vous pouvez désormais retourner voir des " +"vidéos." + +#: templates/base.html:64 +msgid "Home" +msgstr "Accueil" + +#: templates/base.html:88 +msgid "My team" +msgstr "Mon équipe" + +#: templates/base.html:93 +msgid "My participation" +msgstr "Ma participation" + +#: templates/base.html:100 +msgid "Chat" +msgstr "Chat" + +#: templates/base.html:104 +msgid "Administration" +msgstr "Administration" + +#: templates/base.html:112 +msgid "Search..." +msgstr "Chercher ..." + +#: templates/base.html:121 +msgid "Return to admin view" +msgstr "Retourner à l'interface administrateur" + +#: templates/base.html:126 +msgid "Register" +msgstr "S'inscrire" + +#: templates/base.html:142 +msgid "My account" +msgstr "Mon compte" + +#: templates/base.html:145 +msgid "Log out" +msgstr "Déconnexion" + +#: templates/base.html:162 +#, python-format +msgid "" +"Your email address is not validated. Please click on the link you received " +"by email. You can resend a mail by clicking on this link." +msgstr "" +"Votre adresse mail n'est pas validée. Merci de cliquer sur le lien que vous " +"avez reçu par mail. Vous pouvez renvoyer un mail en cliquant sur ce lien." + +#: templates/base.html:186 +msgid "Contact us" +msgstr "Nous contacter" + +#: templates/base.html:219 +msgid "Search results" +msgstr "Résultats de la recherche" + +#: templates/registration/logged_out.html:8 +msgid "Thanks for spending some quality time with the Web site today." +msgstr "Merci d'avoir utilisé la plateforme des Correspondances." + +#: templates/registration/logged_out.html:9 +msgid "Log in again" +msgstr "Se reconnecter" + +#: templates/registration/login.html:13 +#, python-format +msgid "" +"You are authenticated as %(user)s, but are not authorized to access this " +"page. Would you like to login to a different account?" +msgstr "" +"Vous êtes connectés en tant que %(user)s, mais n'êtes pas autorisés à " +"accéder à cette page. Voulez-vous vous reconnecter avec un autre compte ?" + +#: templates/registration/login.html:23 +msgid "Forgotten your password or username?" +msgstr "Mot de passe oublié ?" + +#: templates/search/search.html:6 templates/search/search.html:11 +msgid "Search" +msgstr "Chercher" + +#: templates/search/search.html:16 +msgid "Results" +msgstr "Résultats" + +#: templates/search/search.html:26 +msgid "No results found." +msgstr "Aucun résultat." diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..c481888 --- /dev/null +++ b/manage.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'corres2math.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/nginx_corres2math.conf b/nginx_corres2math.conf new file mode 100644 index 0000000..e4b01f0 --- /dev/null +++ b/nginx_corres2math.conf @@ -0,0 +1,19 @@ +upstream corres2math { + server 127.0.0.1:8000; +} + +server { + listen 80; + server_name corres2math; + + location / { + proxy_pass http://corres2math; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header Host $host; + proxy_redirect off; + } + + location /static { + alias /code/static/; + } +} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..fe4e57a --- /dev/null +++ b/requirements.txt @@ -0,0 +1,17 @@ +Django~=3.0 +django-bootstrap-datepicker-plus +django-cas-server +django-crispy-forms +django-extensions +django-filter~=2.3.0 +django-haystack~=3.0 +django-mailer +django-polymorphic +django-tables2 +djangorestframework~=3.11.1 +django-rest-polymorphic +matrix-nio +ptpython +python-magic~=0.4.18 +gunicorn +whoosh \ No newline at end of file diff --git a/server_files/403.php b/server_files/403.php deleted file mode 100644 index 72127d0..0000000 --- a/server_files/403.php +++ /dev/null @@ -1,16 +0,0 @@ - - -
-

- Vous n'êtes pas autorisé à accéder à cette page. -

-
- - - -
-

- Cette page n'existe pas. -

-
- -prepare("SELECT * FROM `documents` WHERE `file_id` = ?;"); - $req->execute([htmlspecialchars($id)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - return self::fromData($data); - } - - public static function fromData($data) - { - $doc = new Document(); - $doc->fill($data); - return $doc; - } - - private function fill($data) - { - $this->file_id = $data["file_id"]; - $this->user_id = $data["user"]; - $this->team_id = $data["team"]; - $this->problem = $data["problem"]; - $this->uploaded_at = $data["uploaded_at"]; - $this->version = isset($data["version"]) ? $data["version"] : 1; - } - - public function getFileId() - { - return $this->file_id; - } - - public function getUserId() - { - return $this->user_id; - } - - public function getTeamId() - { - return $this->team_id; - } - - public function getProblem() - { - return $this->problem; - } - - public function getUploadedAt() - { - return $this->uploaded_at; - } - - public function getVersion() - { - return $this->version; - } - - - - public static function getAllDocuments($problem, $team_id = -1) - { - global $DB; - $req = $DB->query("SELECT * FROM `documents` AS `t1` " - . "INNER JOIN (SELECT `user`, `problem`, MAX(`uploaded_at`) AS `last_upload`, COUNT(`team`) AS `version` FROM `documents` GROUP BY `problem`, `user`) `t2` " - . "ON `t1`.`user` = `t2`.`user` AND `t1`.`problem` = `t2`.`problem` " - . "WHERE `t1`.`uploaded_at` = `t2`.`last_upload` AND `t1`.`problem` = $problem " . ($team_id >= 0 ? "AND `team` = $team_id" : "") . " ORDER BY `t1`.`user`;"); - - $docs = []; - - while (($data = $req->fetch()) !== false) - $docs[] = Document::fromData($data); - - return $docs; - } -} diff --git a/server_files/classes/Phase.php b/server_files/classes/Phase.php deleted file mode 100644 index 7cb6669..0000000 --- a/server_files/classes/Phase.php +++ /dev/null @@ -1,68 +0,0 @@ -getStartPhase1Date()) - return self::INSCRIPTION; - - if ($date < $CONFIG->getEndPhase1Date()) - return self::PHASE1; - - if ($date < $CONFIG->getStartPhase2Date()) - return self::PHASE12; - - if ($date < $CONFIG->getEndPhase2Date()) - return self::PHASE2; - - if ($date < $CONFIG->getStartPhase3Date()) - return self::PHASE23; - - if ($date < $CONFIG->getEndPhase3Date()) - return self::PHASE3; - - if ($date < $CONFIG->getStartPhase4Date()) - return self::PHASE34; - - if ($date < $CONFIG->getEndPhase4Date()) - return self::PHASE4; - - return self::END; - } - - public static function getTranslatedName($phase) - { - switch ($phase) - { - case self::INSCRIPTION: - return "Inscription"; - case self::PHASE1: - return "Phase 1 (soumission des vidéos)"; - case self::PHASE2: - return "Phase 2 (questions)"; - case self::PHASE3: - return "Phase 3 (réponses)"; - case self::PHASE4: - return "Phase 4 (vidéo de réponse)"; - case self::END: - return "Les Correspondances sont terminées"; - default: - return "Entre deux phases"; - } - } -} \ No newline at end of file diff --git a/server_files/classes/Question.php b/server_files/classes/Question.php deleted file mode 100644 index f31fe3c..0000000 --- a/server_files/classes/Question.php +++ /dev/null @@ -1,185 +0,0 @@ -prepare("SELECT * FROM `questions` WHERE `id` = ?;"); - $req->execute(htmlspecialchars($id)); - $data = $req->fetch(); - - if ($data === false) - return null; - - $question = new Question(); - $question->fill($data); - return $question; - } - - public static function fromAttachedFile($attached_file) - { - global $DB; - - $req = $DB->prepare("SELECT * FROM `questions` WHERE `attached_file` = ? OR `attached_file_answer` = ?;"); - $req->execute([htmlspecialchars($attached_file), htmlspecialchars($attached_file)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $question = new Question(); - $question->fill($data); - return $question; - } - - public function fill($data) - { - foreach ($data as $key => $value) - $this->$key = $value; - } - - public static function getQuestions(Team $from, Team $to) - { - global $DB; - - ensure($from->getProblem() == $to->getProblem(), "Les deux équipes doivent travailler sur le même problème."); - - $req = $DB->prepare("SELECT * FROM `questions` WHERE `from` = ? AND `to` = ? ORDER BY `from`, `number`;"); - $req->execute([$from->getId(), $to->getId()]); - - $questions = []; - - while (($data = $req->fetch()) !== false) { - $question = new Question(); - $question->fill($data); - $questions[] = $question; - } - - if (sizeof($questions) == 0) { - $req = $DB->prepare("INSERT INTO `questions`(`from`, `to`, `problem`, `number`, `question`) VALUES (?, ?, ?, ?, ?);"); - $req->execute([$from->getId(), $to->getId(), $from->getProblem(), 0, ""]); - for ($i = 1; $i <= 6; ++$i) { - $req = $DB->prepare("INSERT INTO `questions`(`from`, `to`, `problem`, `number`, `question`) VALUES (?, ?, ?, ?, ?);"); - $req->execute([$from->getId(), $to->getId(), $from->getProblem(), $i, self::DEFAULT_QUESTIONS[$i - 1]]); - } - return self::getQuestions($from, $to); - } - - return $questions; - } - - public static function getQuestionsTo(Team $to) - { - global $DB, $YEAR; - $id = $to->getId(); - $req = $DB->query("SELECT `id` from `teams` WHERE (`video_team1` = $id OR `video_team2` = $id) AND `year` = $YEAR;"); - - $questions = []; - - while (($data = $req->fetch()) !== false) - $questions[] = self::getQuestions(Team::fromId($data["id"]), $to); - - return $questions; - } - - public function getId() - { - return $this->id; - } - - public function getFrom() - { - return $this->from; - } - - public function getTo() - { - return $this->to; - } - - public function getProblem() - { - return $this->problem; - } - - public function getNumber() - { - return $this->number; - } - - public function getQuestion() - { - return $this->question; - } - - public function setQuestion($question) - { - global $DB; - $this->question = $question; - $req = $DB->prepare("UPDATE `questions` SET `question` = ? WHERE `id` = ?;"); - $req->execute([$question, $this->id]); - } - - public function getAttachedFile() - { - return $this->attached_file; - } - - public function setAttachedFile($attached_file) - { - global $DB; - $this->attached_file = $attached_file; - $req = $DB->prepare("UPDATE `questions` SET `attached_file` = ? WHERE `id` = ?;"); - $req->execute([$attached_file, $this->id]); - } - - public function getAnswer() - { - return $this->answer; - } - - public function setAnswer($answer) - { - global $DB; - $this->answer = $answer; - $req = $DB->prepare("UPDATE `questions` SET `answer` = ? WHERE `id` = ?;"); - $req->execute([$answer, $this->id]); - } - - public function getAttachedFileAnswer() - { - return $this->attached_file_answer; - } - - public function setAttachedFileAnswer($attached_file) - { - global $DB; - $this->attached_file_answer = $attached_file; - $req = $DB->prepare("UPDATE `questions` SET `attached_file_answer` = ? WHERE `id` = ?;"); - $req->execute([$attached_file, $this->id]); - } -} \ No newline at end of file diff --git a/server_files/classes/Reason.php b/server_files/classes/Reason.php deleted file mode 100644 index dece59f..0000000 --- a/server_files/classes/Reason.php +++ /dev/null @@ -1,41 +0,0 @@ -prepare("SELECT * FROM `teams` WHERE `id` = ?;"); - $req->execute([htmlspecialchars($id)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $team = new Team(); - $team->fill($data); - return $team; - } - - /** - * @param $trigram - * @return Team|null - */ - public static function fromTrigram($trigram) - { - global $DB, $YEAR; - $req = $DB->prepare("SELECT * FROM `teams` WHERE `trigram` = ? AND `year` = $YEAR;"); - $req->execute([htmlspecialchars($trigram)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $team = new Team(); - $team->fill($data); - return $team; - } - - public static function fromAccessCode($access_code) - { - global $DB, $YEAR; - $req = $DB->prepare("SELECT * FROM `teams` WHERE `access_code` = ? AND `year` = $YEAR;"); - $req->execute([htmlspecialchars($access_code)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $team = new Team(); - $team->fill($data); - return $team; - } - - public static function getAllTeams($problem = -1, $only_validated = false, $only_with_solutions = true) - { - global $DB, $YEAR; - $req = $DB->prepare("SELECT * FROM `teams` WHERE " . ($problem < 0 ? "" : "`problem` = ? AND ") . ($only_validated ? "`validation_status` = 'VALIDATED' AND " : "") . "`year` = $YEAR;"); - $req->execute([htmlspecialchars($problem)]); - - $teams = []; - - while (($data = $req->fetch()) != false) { - $team = new Team(); - $team->fill($data); - $sol = $team->getSolution(); - if ($sol != null && $sol->getValidation() == ValidationStatus::VALIDATED - 1) - $teams[] = $team; - } - - return $teams; - } - - private function fill($data) - { - $this->id = $data["id"]; - $this->name = $data["name"]; - $this->trigram = $data["trigram"]; - $this->problem = $data["problem"]; - $this->encadrant = $data["encadrant"]; - $this->participants = [$data["participant_1"], $data["participant_2"], $data["participant_3"], $data["participant_4"], $data["participant_5"]]; - $this->inscription_date = $data["inscription_date"]; - $this->allow_publish = $data["allow_publish"] ? 1 : 0; - $this->validation_status = ValidationStatus::fromName($data["validation_status"]); - $this->video_team_ids = [$data["video_team1"], $data["video_team2"]]; - $this->access_code = $data["access_code"]; - $this->year = $data["year"]; - } - - public function getId() - { - return $this->id; - } - - public function getName() - { - return $this->name; - } - - public function setName($name) - { - global $DB; - $this->name = $name; - $DB->prepare("UPDATE `teams` SET `name` = ? WHERE `id` = ?;")->execute([$name, $this->id]); - } - - public function getTrigram() - { - return $this->trigram; - } - - public function setTrigram($trigram) - { - global $DB; - $this->trigram = $trigram; - $DB->prepare("UPDATE `teams` SET `trigram` = ? WHERE `id` = ?;")->execute([$trigram, $this->id]); - } - - public function getProblem() - { - return $this->problem; - } - - public function setProblem($problem) - { - global $DB; - $this->problem = $problem; - $DB->prepare("UPDATE `teams` SET `problem` = ? WHERE `id` = ?;")->execute([$problem, $this->id]); - } - - public function getEncadrantId() - { - return $this->encadrant; - } - - public function setEncadrant($encadrant) - { - global $DB; - $this->encadrant = $encadrant; - /** @noinspection SqlResolve */ - $DB->prepare("UPDATE `teams` SET `encadrant` = ? WHERE `id` = ?;")->execute([$encadrant, $this->id]); - } - - public function getParticipants() - { - return $this->participants; - } - - public function setParticipant($i, $participant) - { - global $DB; - $this->participants[$i - 1] = $participant; - /** @noinspection SqlResolve */ - $DB->prepare("UPDATE `teams` SET `participant_$i` = ? WHERE `id` = ?;")->execute([$participant, $this->id]); - } - - public function getInscriptionDate() - { - return $this->inscription_date; - } - - public function allowPublish() - { - return $this->allow_publish; - } - - public function setAllowPublish($allow_publish) - { - global $DB; - $this->allow_publish = $allow_publish; - $DB->prepare("UPDATE `teams` SET `allow_publish` = ? WHERE `id` = ?;")->execute([$allow_publish ? 1 : 0, $this->id]); - } - - public function getValidationStatus() - { - return $this->validation_status; - } - - public function setValidationStatus($status) - { - global $DB; - $this->validation_status = $status; - $DB->prepare("UPDATE `teams` SET `validation_status` = ? WHERE `id` = ?;")->execute([ValidationStatus::getName($status), $this->id]); - } - - public function getSolution() - { - return Video::getVideo(Reason::SOLUTION, $this); - } - - public function getVideoTeamIds() - { - return $this->video_team_ids; - } - - public function setVideoTeamIds($video_team_ids) - { - global $DB; - ensure(sizeof($video_team_ids) == 2, "Une équipe doit recevoir exactement deux vidéos."); - $this->video_team_ids = $video_team_ids; - $DB->prepare("UPDATE `teams` SET `video_team1` = ?, `video_team2` = ? WHERE `id` = ?;")->execute([$video_team_ids[0], $video_team_ids[1], $this->id]); - } - - public function getAccessCode() - { - return $this->access_code; - } - - public function getYear() - { - return $this->year; - } - - public function getAllDocuments() - { - global $DB; - $req = $DB->query("SELECT * FROM `documents` AS `t1` " - . "INNER JOIN (SELECT `team`, MAX(`uploaded_at`) AS `last_upload`, COUNT(`user`) AS `version` FROM `documents` GROUP BY `problem`, `user`, `team`) `t2` " - . "ON `t1`.`team` = `t2`.`team` " - . "WHERE `t1`.`uploaded_at` = `t2`.`last_upload` AND `t1`.`team` = $this->id;"); - - $docs = []; - - while (($data = $req->fetch()) !== false) - $docs[] = Document::fromData($data); - - return $docs; - } - - public function getAllEmails() - { - $emails = []; - if ($this->getEncadrantId() != null) - $emails[] = User::fromId($this->getEncadrantId())->getEmail(); - - foreach ($this->getParticipants() as $participantId) { - if ($participantId != 0) - $emails[] = User::fromId($participantId)->getEmail(); - } - - return $emails; - } -} diff --git a/server_files/classes/User.php b/server_files/classes/User.php deleted file mode 100644 index b81bd99..0000000 --- a/server_files/classes/User.php +++ /dev/null @@ -1,335 +0,0 @@ -prepare("SELECT * FROM `users` WHERE `id` = ?;"); - $req->execute([htmlspecialchars($id)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $user = new User(); - $user->fill($data); - return $user; - } - - public static function fromEmail($email) - { - global $DB, $YEAR; - $req = $DB->prepare("SELECT * FROM `users` WHERE `email` = ? AND `year` = $YEAR;"); - $req->execute([htmlspecialchars($email)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $user = new User(); - $user->fill($data); - return $user; - } - - public static function getAdmins() - { - global $DB, $YEAR; - $admins = []; - $req = $DB->query("SELECT * FROM `users` WHERE `role` = 'ADMIN' AND `year` = $YEAR;"); - - while (($data = $req->fetch()) !== false) { - $admin = new User(); - $admin->fill($data); - $admins[] = $admin; - } - - return $admins; - } - - public static function getAllUsers() - { - global $DB, $YEAR; - $orphans = []; - $req = $DB->query("SELECT * FROM `users` WHERE `role` != 'ADMIN' AND `year` = $YEAR ORDER BY `role`, `inscription_date`;"); - - while (($data = $req->fetch()) !== false) { - $orphan = new User(); - $orphan->fill($data); - $orphans[] = $orphan; - } - - return $orphans; - } - - public static function getOrphanUsers() - { - global $DB, $YEAR; - $orphans = []; - $req = $DB->query("SELECT * FROM `users` WHERE `role` != 'ADMIN' AND `team_id` IS NULL " - . "AND NOT EXISTS (SELECT 1 FROM `teams` WHERE `encadrant` = `users`.`id`) " - . "AND `year` = $YEAR ORDER BY `role`, `inscription_date`;"); - - while (($data = $req->fetch()) !== false) { - $orphan = new User(); - $orphan->fill($data); - $orphans[] = $orphan; - } - - return $orphans; - } - - private function fill($data) - { - $this->id = $data["id"]; - $this->email = $data["email"]; - $this->pwd_hash = $data["pwd_hash"]; - $this->surname = $data["surname"]; - $this->first_name = $data["first_name"]; - $this->school = $data["school"]; - $this->city = $data["city"]; - $this->country = $data["country"]; - $this->class = SchoolClass::fromName($data["class"]); - $this->description = $data["description"]; - $this->role = Role::fromName($data["role"]); - $this->team_id = $data["team_id"]; - $this->year = $data["year"]; - $this->confirm_email = $data["confirm_email"]; - $this->forgotten_password = $data["forgotten_password"]; - $this->inscription_date = $data["inscription_date"]; - $this->receive_animath_mails = $data["receive_animath_mails"]; - } - - public function getEmail() - { - return $this->email; - } - - public function setEmail($email) - { - global $DB; - $this->email = $email; - $DB->prepare("UPDATE `users` SET `email` = ? WHERE `id` = ?;")->execute([$email, $this->getId()]); - } - - public function getId() - { - return $this->id; - } - - public function checkPassword($password) - { - return password_verify($password, $this->pwd_hash); - } - - public function setPassword($password) - { - $this->setPasswordHash(password_hash($password, PASSWORD_BCRYPT)); - } - - private function setPasswordHash($password_hash) - { - global $DB; - $this->pwd_hash = $password_hash; - $DB->prepare("UPDATE `users` SET `pwd_hash` = ? WHERE `id` = ?;")->execute([$password_hash, $this->getId()]); - } - - public function getSurname() - { - return $this->surname; - } - - public function setSurname($surname) - { - global $DB; - $this->surname = $surname; - $DB->prepare("UPDATE `users` SET `surname` = ? WHERE `id` = ?;")->execute([$surname, $this->getId()]); - } - - public function getFirstName() - { - return $this->first_name; - } - - public function setFirstName($first_name) - { - global $DB; - $this->first_name = $first_name; - $DB->prepare("UPDATE `users` SET `first_name` = ? WHERE `id` = ?;")->execute([$first_name, $this->getId()]); - } - - public function getSchool() - { - return $this->school; - } - - public function setSchool($school) - { - global $DB; - $this->school = $school; - $DB->prepare("UPDATE `users` SET `school` = ? WHERE `id` = ?;")->execute([$school, $this->getId()]); - } - - public function getCity() - { - return $this->city; - } - - public function setCity($city) - { - global $DB; - $this->city = $city; - $DB->prepare("UPDATE `users` SET `city` = ? WHERE `id` = ?;")->execute([$city, $this->getId()]); - } - - public function getCountry() - { - return $this->country; - } - - public function setCountry($country) - { - global $DB; - $this->country = $country; - $DB->prepare("UPDATE `users` SET `country` = ? WHERE `id` = ?;")->execute([$country, $this->getId()]); - } - - public function getClass() - { - return $this->class; - } - - public function setClass($class) - { - global $DB; - $this->class = $class; - $DB->prepare("UPDATE `users` SET `class` = ? WHERE `id` = ?;")->execute([SchoolClass::getName($class), $this->getId()]); - } - - public function getDescription() - { - return $this->description; - } - - public function setDescription($desc) - { - global $DB; - $this->description = $desc; - $DB->prepare("UPDATE `users` SET `description` = ? WHERE `id` = ?;")->execute([$desc, $this->getId()]); - } - - public function getRole() - { - return $this->role; - } - - public function setRole($role) - { - global $DB; - $this->role = $role; - $DB->prepare("UPDATE `users` SET `role` = ? WHERE `id` = ?;")->execute([Role::getName($role), $this->getId()]); - } - - public function getTeamId() - { - return $this->team_id; - } - - public function setTeamId($team_id) - { - global $DB; - $this->team_id = $team_id; - $DB->prepare("UPDATE `users` SET `team_id` = ? WHERE `id` = ?;")->execute([$team_id, $this->getId()]); - } - - public function getConfirmEmailToken() - { - return $this->confirm_email; - } - - public function setConfirmEmailToken($token) - { - global $DB; - $this->confirm_email = $token; - $DB->prepare("UPDATE `users` SET `confirm_email` = ? WHERE `id` = ?;")->execute([$token, $this->getId()]); - } - - public function getForgottenPasswordToken() - { - return $this->forgotten_password; - } - - public function setForgottenPasswordToken($token) - { - global $DB; - $this->forgotten_password = $token; - $DB->prepare("UPDATE `users` SET `forgotten_password` = ? WHERE `id` = ?;")->execute([$token, $this->getId()]); - } - - public function getInscriptionDate() - { - return $this->inscription_date; - } - - public function doReceiveAnimathMails() - { - return $this->receive_animath_mails; - } - - public function setReceiveAnimathMails($receive_animath_mails) - { - global $DB; - $this->receive_animath_mails = $receive_animath_mails; - $DB->prepare("UPDATE `users` SET `receive_animath_mails` = ? WHERE `id` = ?;")->execute([$receive_animath_mails ? 1 : 0, $this->getId()]); - } - - public function getAllDocuments() - { - global $DB; - $req = $DB->query("SELECT * FROM `documents` AS `t1` " - . "INNER JOIN (SELECT `user`, MAX(`uploaded_at`) AS `last_upload`, COUNT(`team`) AS `version` FROM `documents` GROUP BY `problem`, `user`) `t2` " - . "ON `t1`.`user` = `t2`.`user` " - . "WHERE `t1`.`uploaded_at` = `t2`.`last_upload` AND `t1`.`user` = $this->id;"); - - $docs = []; - - while (($data = $req->fetch()) !== false) - $docs[] = Document::fromData($data); - - return $docs; - } - - // Seulement pour les encadrants - public function getTeams() - { - global $DB; - $req = $DB->query("SELECT `id` FROM `teams` WHERE `encadrant` = $this->id OR `participant_1` = $this->id OR `participant_2` = $this->id OR `participant_3` = $this->id OR `participant_4` = $this->id OR `participant_5` = $this->id;"); - - $teams = []; - - while (($data =$req->fetch()) !== false) - $teams[] = Team::fromId($data["id"]); - - return $teams; - } -} \ No newline at end of file diff --git a/server_files/classes/ValidationStatus.php b/server_files/classes/ValidationStatus.php deleted file mode 100644 index 459d7ad..0000000 --- a/server_files/classes/ValidationStatus.php +++ /dev/null @@ -1,41 +0,0 @@ -prepare("SELECT * FROM `videos` WHERE `id` = ?;"); - $req->execute([htmlspecialchars($id)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $video = new Video(); - $video->fill($data); - return $video; - } - - public static function getVideos($reason, $problem, $validation_min = -1, $team_id = -1) - { - global $DB, $YEAR; - $req = $DB->query("SELECT * FROM `videos` AS `t1` " - . "INNER JOIN (SELECT `team`, `problem`, `reason`, MAX(`uploaded_at`) AS `last_upload`, COUNT(`team`) AS `version` FROM `videos` " - . "WHERE `validation` >= $validation_min AND `year` = $YEAR GROUP BY `problem`, `reason`, `team`) `t2` " - . "ON `t1`.`team` = `t2`.`team` AND `t1`.`reason` = `t2`.`reason` AND `t1`.`problem` = `t2`.`problem` " - . "WHERE `t1`.`uploaded_at` = `t2`.`last_upload` AND `t1`.`problem` = $problem AND `t1`.`reason` = '" . Reason::getName($reason) . "'" - . ($team_id >= 0 ? " AND `t1`.`team` = $team_id" : "") - . " AND `validation` >= $validation_min AND `year` = $YEAR ORDER BY `t1`.`problem`, `t1`.`reason`;"); - - $videos = []; - - while (($data = $req->fetch()) !== false) { - $video = new Video(); - $video->fill($data); - $videos[] = $video; - } - - return $videos; - } - - /** - * @param int $reason - * @param Team $team - * @param int $validation_min - * @return Video|null - */ - public static function getVideo($reason, Team $team, $validation_min = -1) { - $videos = self::getVideos($reason, $team->getProblem(), $validation_min, $team->getId()); - if (sizeof($videos) == 0) - return null; - else - return $videos[0]; - } - - private function fill($data) - { - foreach ($data as $key => $value) - $this->$key = $value; - - $this->reason = Reason::fromName($this->reason); - } - - public function getId() - { - return $this->id; - } - - public function getTeam() - { - return $this->team; - } - - public function getProblem() - { - return $this->problem; - } - - public function getLink() - { - return $this->link; - } - - public function getReason() - { - return $this->reason; - } - - public function getValidation() - { - return $this->validation; - } - - public function setValidation($validation) - { - global $DB; - $this->validation = $validation; - $DB->exec("UPDATE `videos` SET `validation` = $validation WHERE `id` = $this->id;"); - } - - public function getUploadedAt() - { - return $this->uploaded_at; - } - - public function getYear() - { - return $this->year; - } - - public function getVersion() - { - return $this->version; - } -} \ No newline at end of file diff --git a/server_files/config.php b/server_files/config.php deleted file mode 100644 index 155f878..0000000 --- a/server_files/config.php +++ /dev/null @@ -1,227 +0,0 @@ - PDO::ERRMODE_EXCEPTION)); -} -catch (Exception $ex) { - die("Erreur lors de la connexion à la base de données : " . $ex->getMessage()); -} - -$CONFIG = new Config(); -$CONFIG->initDB(); -$CONFIG->loadConfigValues(); - -class Config -{ - private $inscription_date; - private $start_phase1_date; - private $end_phase1_date; - private $start_phase2_date; - private $end_phase2_date; - private $start_phase3_date; - private $end_phase3_date; - private $start_phase4_date; - private $end_phase4_date; - private $index_page; - private $views; - - public function initDB() - { - global $DB, $LOCAL_PATH, $YEAR; - - $index_template_page = htmlspecialchars(file_get_contents($LOCAL_PATH . "/server_files/views/index.html")); - - $DB->exec("SET GLOBAL time_zone = 'Europe/Paris';"); - $DB->prepare("INSERT IGNORE INTO `config`(`key`, `value`) - VALUES ('inscription_date_$YEAR', CURRENT_TIMESTAMP + INTERVAL 2 DAY), - ('start_phase1_date_$YEAR', CURRENT_TIMESTAMP + INTERVAL 1 DAY), - ('end_phase1_date_$YEAR', CURRENT_TIMESTAMP + INTERVAL 3 DAY), - ('start_phase2_date_$YEAR', CURRENT_TIMESTAMP + INTERVAL 4 DAY), - ('end_phase2_date_$YEAR', CURRENT_TIMESTAMP + INTERVAL 5 DAY), - ('start_phase3_date_$YEAR', CURRENT_TIMESTAMP + INTERVAL 6 DAY), - ('end_phase3_date_$YEAR', CURRENT_TIMESTAMP + INTERVAL 7 DAY), - ('start_phase4_date_$YEAR', CURRENT_TIMESTAMP + INTERVAL 8 DAY), - ('end_phase4_date_$YEAR', CURRENT_TIMESTAMP + INTERVAL 9 DAY), - ('index_page_$YEAR', ?), - ('views_$YEAR', 0);")->execute([$index_template_page]); - } - - public function loadConfigValues() - { - global $DB, $YEAR; - - $req = $DB->query("SELECT * FROM `config` WHERE `key` REGEXP '$YEAR';"); - - while (($data = $req->fetch()) !== false) { - $key = substr($data["key"], 0, -5); - $this->$key = $data["value"]; - } - } - - public function getInscriptionDate() - { - return $this->inscription_date; - } - - public function setInscriptionDate($inscription_date) - { - global $DB, $YEAR; - $DB->exec("UPDATE `config` SET `value` = '$inscription_date' WHERE `key` = 'inscription_date_$YEAR'"); - - $this->inscription_date = $inscription_date; - } - - public function getStartPhase1Date() - { - return $this->start_phase1_date; - } - - public function setStartPhase1Date($start_phase1_date) - { - global $DB, $YEAR; - $DB->exec("UPDATE `config` SET `value` = '$start_phase1_date' WHERE `key` = 'start_phase1_date_$YEAR'"); - - $this->start_phase1_date = $start_phase1_date; - } - - public function getEndPhase1Date() - { - return $this->end_phase1_date; - } - - public function setEndPhase1Date($end_phase1_date) - { - global $DB, $YEAR; - $DB->exec("UPDATE `config` SET `value` = '$end_phase1_date' WHERE `key` = 'end_phase1_date_$YEAR'"); - - $this->end_phase1_date = $end_phase1_date; - } - - public function getStartPhase2Date() - { - return $this->start_phase2_date; - } - - public function setStartPhase2Date($start_phase2_date) - { - global $DB, $YEAR; - $DB->exec("UPDATE `config` SET `value` = '$start_phase2_date' WHERE `key` = 'start_phase2_date_$YEAR'"); - - $this->start_phase2_date = $start_phase2_date; - } - - public function getEndPhase2Date() - { - return $this->end_phase2_date; - } - - public function setEndPhase2Date($end_phase2_date) - { - global $DB, $YEAR; - $DB->exec("UPDATE `config` SET `value` = '$end_phase2_date' WHERE `key` = 'end_phase2_date_$YEAR'"); - - $this->end_phase2_date = $end_phase2_date; - } - - public function getStartPhase3Date() - { - return $this->start_phase3_date; - } - - public function setStartPhase3Date($start_phase3_date) - { - global $DB, $YEAR; - $DB->exec("UPDATE `config` SET `value` = '$start_phase3_date' WHERE `key` = 'start_phase3_date_$YEAR'"); - - $this->start_phase3_date = $start_phase3_date; - } - - public function getEndPhase3Date() - { - return $this->end_phase3_date; - } - - public function setEndPhase3Date($end_phase3_date) - { - global $DB, $YEAR; - $DB->exec("UPDATE `config` SET `value` = '$end_phase3_date' WHERE `key` = 'end_phase3_date_$YEAR'"); - - $this->end_phase3_date = $end_phase3_date; - } - - public function getStartPhase4Date() - { - return $this->start_phase4_date; - } - - public function setStartPhase4Date($start_phase4_date) - { - global $DB, $YEAR; - $DB->exec("UPDATE `config` SET `value` = '$start_phase4_date' WHERE `key` = 'start_phase4_date_$YEAR'"); - - $this->start_phase4_date = $start_phase4_date; - } - - public function getEndPhase4Date() - { - return $this->end_phase4_date; - } - - public function setEndPhase4Date($end_phase4_date) - { - global $DB, $YEAR; - $DB->exec("UPDATE `config` SET `value` = '$end_phase4_date' WHERE `key` = 'end_phase4_date_$YEAR'"); - - $this->end_phase4_date = $end_phase4_date; - } - - public function getIndexPage() - { - return $this->index_page; - } - - public function setIndexPage($index_page) - { - global $DB, $YEAR; - $DB->prepare("UPDATE `config` SET `value` = ? WHERE `key` = 'index_page_$YEAR'")->execute([$index_page]); - - $this->index_page = $index_page; - } - - public function getViews() - { - return $this->views; - } - - public function incrViews() - { - global $DB, $YEAR; - - if (isset($_SESSION["user_id"]) && $_SESSION["role"] == Role::ADMIN || isset($_SESSION["admin"])) - return; - - $DB->exec("UPDATE `config` SET `value` = " . ($this->views + 1) . " WHERE `key` = 'views_$YEAR';"); - $this->views++; - } -} - -session_start(); -setlocale(LC_ALL, "fr_FR.utf8"); -date_default_timezone_set("Europe/Paris"); diff --git a/server_files/controllers/admins.php b/server_files/controllers/admins.php deleted file mode 100644 index 23ece61..0000000 --- a/server_files/controllers/admins.php +++ /dev/null @@ -1,8 +0,0 @@ -makeVerifications(); - $admin->register(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class NewAdmin { - public $surname; - public $first_name; - public $email; - public $password; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - } - - public function makeVerifications() - { - ensure($this->surname != null && $this->surname != "", "Le nom est invalide."); - ensure($this->first_name != null && $this->first_name != "", "Le prénom est invalide."); - ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse e-mail est invalide."); - $this->email = strtolower($this->email); - ensure(!userExists($this->email), "Cette adresse e-mail est déjà utilisée."); - } - - public function register() { - global $DB, $YEAR; - - $this->password = genRandomPhrase(16, true); - - $req = $DB->prepare("INSERT INTO `users`(`email`, `pwd_hash`, `surname`, `first_name`, `class`, `role`, `year`) - VALUES (?, ?, ?, ?, ?, ?, ?);"); - $req->execute([$this->email, password_hash($this->password, PASSWORD_BCRYPT), $this->surname, - $this->first_name, "ADULT", "ADMIN", $YEAR]); - - Mailer::sendAddAdminMail($this); - } -} - -require_once "server_files/views/ajouter_admin.php"; \ No newline at end of file diff --git a/server_files/controllers/ajouter_equipe.php b/server_files/controllers/ajouter_equipe.php deleted file mode 100644 index 234d341..0000000 --- a/server_files/controllers/ajouter_equipe.php +++ /dev/null @@ -1,75 +0,0 @@ -makeVerifications(); - $new_team->register(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class NewTeam { - public $name; - public $trigram; - public $problem; - public $allow_other_teams; - public $allow_publish; - public $access_code; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - - $this->trigram = strtoupper($this->trigram); - - $this->allow_other_teams = $this->allow_other_teams == "on" ? 1 : 0; - $this->allow_publish = $this->allow_publish == "on" ? 1 : 0; - } - - public function makeVerifications() { - global $CONFIG; - - ensure(date("Y-m-d H:i:s") < $CONFIG->getInscriptionDate(), "La date limite d'inscription est dépassée."); - ensure($_SESSION["team"] == null || $_SESSION["role"] == Role::ENCADRANT, "Vous êtes déjà dans une équipe."); - ensure($this->name != null && $this->name != "", "Vous devez spécifier un nom d'équipe."); - ensure(preg_match("#^[\p{L} ]+$#ui", $this->name), "Le nom de l'équipe ne doit pas comporter de caractères spéciaux."); - ensure(preg_match("#^[A-Z]{3}$#", $this->trigram), "Le trigramme entré n'est pas valide."); - ensure(!teamExists($this->name), "Une équipe existe déjà avec ce nom."); - ensure(!trigramExists($this->trigram), "Une équipe a déjà choisi ce trigramme."); - ensure(preg_match("#[0-4]#", $this->problem), "Le problème choisi n'a pas été reconnu."); - ensure($this->allow_other_teams, "Vous devez autoriser de diffuser vos vidéos aux autres équipes participantes pour pouvoir participer."); - } - - public function register() { - global $DB, $YEAR; - - $this->access_code = genRandomPhrase(6); - - $req = $DB->prepare("INSERT INTO `teams` (`name`, `trigram`, `problem`, `encadrant`, `participant_1`, `allow_publish`, `validation_status`, `access_code`, `year`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"); - $req->execute([$this->name, $this->trigram, $this->problem, $_SESSION["role"] == Role::ENCADRANT ? $_SESSION["user_id"] : NULL, - $_SESSION["role"] == Role::PARTICIPANT ? $_SESSION["user_id"] : NULL, $this->allow_publish, ValidationStatus::getName(ValidationStatus::NOT_READY), $this->access_code, $YEAR]); - - $_SESSION["teams"] = $_SESSION["user"]->getTeams(); - $team = Team::fromTrigram($this->trigram); - if ($_SESSION["role"] == Role::PARTICIPANT) { - $_SESSION["team"] = $team; - $_SESSION["user"]->setTeamId($_SESSION["team"]->getId()); - } - - Mailer::sendAddTeamMail($_SESSION["user"], $team); - } -} - -require_once "server_files/views/ajouter_equipe.php"; diff --git a/server_files/controllers/calendrier.php b/server_files/controllers/calendrier.php deleted file mode 100644 index 1db0176..0000000 --- a/server_files/controllers/calendrier.php +++ /dev/null @@ -1,76 +0,0 @@ -makeVerifications(); - $update_calendar->updateCalendar(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class UpdateCalendar -{ - private $date_inscription; - private $time_inscription; - private $date_start_phase1; - private $time_start_phase1; - private $date_end_phase1; - private $time_end_phase1; - private $date_start_phase2; - private $time_start_phase2; - private $date_end_phase2; - private $time_end_phase2; - private $date_start_phase3; - private $time_start_phase3; - private $date_end_phase3; - private $time_end_phase3; - private $date_start_phase4; - private $time_start_phase4; - private $date_end_phase4; - private $time_end_phase4; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - } - - public function makeVerifications() - { - ensure(dateWellFormed($this->date_inscription . " " . $this->time_inscription), "La date d'inscription n'est pas bien formée."); - ensure(dateWellFormed($this->date_start_phase1 . " " . $this->time_start_phase1), "La date de début de la phase 1 n'est pas bien formée."); - ensure(dateWellFormed($this->date_end_phase1 . " " . $this->time_end_phase1), "La date de fin de la phase 1 n'est pas bien formée."); - ensure(dateWellFormed($this->date_start_phase2 . " " . $this->time_start_phase2), "La date de début de la phase 2 n'est pas bien formée."); - ensure(dateWellFormed($this->date_end_phase2 . " " . $this->time_end_phase2), "La date de fin de la phase 2 n'est pas bien formée."); - ensure(dateWellFormed($this->date_start_phase3 . " " . $this->time_start_phase3), "La date de début de la phase 3 n'est pas bien formée."); - ensure(dateWellFormed($this->date_end_phase3 . " " . $this->time_end_phase3), "La date de fin de la phase 3 n'est pas bien formée."); - ensure(dateWellFormed($this->date_start_phase4 . " " . $this->time_start_phase4), "La date de début de la phase 4 n'est pas bien formée."); - ensure(dateWellFormed($this->date_end_phase4 . " " . $this->time_end_phase4), "La date de fin de la phase 4 n'est pas bien formée."); - } - - public function updateCalendar() - { - global $CONFIG, $URL_BASE; - - $CONFIG->setInscriptionDate($this->date_inscription . " " . $this->time_inscription); - $CONFIG->setStartPhase1Date($this->date_start_phase1 . " " . $this->time_start_phase1); - $CONFIG->setEndPhase1Date($this->date_end_phase1 . " " . $this->time_end_phase1); - $CONFIG->setStartPhase2Date($this->date_start_phase2 . " " . $this->time_start_phase2); - $CONFIG->setEndPhase2Date($this->date_end_phase2 . " " . $this->time_end_phase2); - $CONFIG->setStartPhase3Date($this->date_start_phase3 . " " . $this->time_start_phase3); - $CONFIG->setEndPhase3Date($this->date_end_phase3 . " " . $this->time_end_phase3); - $CONFIG->setStartPhase4Date($this->date_start_phase4 . " " . $this->time_start_phase4); - $CONFIG->setEndPhase4Date($this->date_end_phase4 . " " . $this->time_end_phase4); - - header("Location: $URL_BASE/calendrier"); - exit(); - } -} - -require_once "server_files/views/calendrier.php"; \ No newline at end of file diff --git a/server_files/controllers/commenter_echange.php b/server_files/controllers/commenter_echange.php deleted file mode 100644 index b1f3e92..0000000 --- a/server_files/controllers/commenter_echange.php +++ /dev/null @@ -1,77 +0,0 @@ -getRole() == Role::PARTICIPANT ? $_SESSION["team"] : Team::fromTrigram($_GET["trigram"]); - -if ($team == null) - require_once "server_files/404.php"; - -if ($user->getRole() == Role::ENCADRANT && $team->getEncadrantId() != $user->getId() || $team->getValidationStatus() != ValidationStatus::VALIDATED) - require_once "server_files/403.php"; - -if (isset($_POST["upload_answer"])) { - $new_answer = new NewAnswer($_POST); - try { - $new_answer->makeVerifications(); - $new_answer->uploadVideo(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class NewAnswer -{ - public $link; - public $team; - private $valid_link; - private $no_change; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = $value; - } - - public function makeVerifications() - { - ensure(preg_match("#(https?\:\/\/|)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?#", $this->link), "Ce n'est pas une URL valide."); - $this->link = preg_replace('/^(?!https?:\/\/)/', 'https://', $this->link); - ensure(preg_match("#[1|2]#", $this->team), "L'équipe n'a pas été trouvée."); - ensure($this->valid_link != null, "Vous devez confirmer que le lien est valide."); - ensure($this->no_change != null, "Vous devez vous engager à ne pas changer le contenu du lien et de la vidéo."); - } - - public function uploadVideo() - { - global $DB, $YEAR, $team; - - $req = $DB->prepare("INSERT INTO `videos`(`team`, `problem`, `link`, `reason`, `year`) VALUES (?, ?, ?, ?, ?)"); - $req->execute([$team->getId(), $team->getProblem(), $this->link, "ANSWER" . $this->team, $YEAR]); - - Mailer::sendNewAnswer($this, $team); - } -} - -$team1 = Team::fromId($team->getVideoTeamIds()[0]); -$sol1 = Video::getVideo(Reason::SOLUTION, $team1); -$answer1 = Video::getVideo(Reason::ANSWER1, $team); -$answer1_validated = Video::getVideo(Reason::ANSWER1, $team, Video::ACCEPTED); -$team2 = Team::fromId($team->getVideoTeamIds()[1]); -$sol2 = Video::getVideo(Reason::SOLUTION, $team2); -$answer2 = Video::getVideo(Reason::ANSWER2, $team); -$answer2_validated = Video::getVideo(Reason::ANSWER2, $team, Video::ACCEPTED); - -$teams = [$team1, $team2]; -$sols = [$sol1, $sol2]; -$answers = [$answer1, $answer2]; -$answers_validated = [$answer1_validated, $answer2_validated]; - -require_once "server_files/views/commenter_echange.php"; \ No newline at end of file diff --git a/server_files/controllers/confirmer_mail.php b/server_files/controllers/confirmer_mail.php deleted file mode 100644 index ea06f20..0000000 --- a/server_files/controllers/confirmer_mail.php +++ /dev/null @@ -1,25 +0,0 @@ -query("SELECT `email` FROM `users` WHERE `confirm_email` = '$token' AND `year` = '$YEAR';"); - if (($data = $result->fetch()) === FALSE) { - $has_error = true; - $error_message = "Le jeton est invalide. Votre compte est peut-être déjà validé ?"; - } - else { - $DB->exec("UPDATE `users` SET `confirm_email` = NULL WHERE `confirm_email` = '$token';"); - $error_message = "Votre adresse mail a été validée ! Vous pouvez désormais vous connecter."; - } -} -else { - $has_error = true; - $error_message = "Il n'y a pas de compte à valider !"; -} -require_once "server_files/views/header.php"; -if (!$has_error) -echo "
$error_message
"; -require_once "server_files/views/footer.php"; diff --git a/server_files/controllers/connexion.php b/server_files/controllers/connexion.php deleted file mode 100644 index 9a441c8..0000000 --- a/server_files/controllers/connexion.php +++ /dev/null @@ -1,170 +0,0 @@ -makeVerifications(); - $logging_in_user->login(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_POST["forgotten_password"]) && !isset($_SESSION["user_id"])) { - $recuperate_account = new RecuperateAccount($_POST); - try { - $recuperate_account->makeVerifications(); - $recuperate_account->recuperateAccount(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_GET["reset_password"]) && isset($_GET["token"]) && !isset($_SESSION["user_id"])) { - $reset_password = new ResetPassword($_GET, $_POST); - try { - $reset_password->makeVerifications(); - if (isset($_POST["password"])) - $reset_password->resetPassword(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_GET["confirmation-mail"]) && !isset($_SESSION["user_id"])) - sendConfirmEmail(); - -class LoggingInUser -{ - public $email; - /** @var User $user */ - public $user; - private $password; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - } - - public function makeVerifications() - { - ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse email est invalide."); - $this->user = User::fromEmail($this->email); - ensure($this->user != null, "Le compte n'existe pas."); - ensure($this->user->checkPassword($this->password), "Le mot de passe est incorrect."); - if ($this->user->getConfirmEmailToken() != null) { - $_SESSION["confirm_email"] = $this->email; - /** @noinspection HtmlUnknownTarget */ - throw new AssertionError("L'adresse mail n'a pas été validée. Veuillez vérifier votre boîte mail (surtout vos spams). " - . "Cliquez ici pour renvoyer le mail de confirmation."); - } - } - - public function login() - { - $_SESSION["user_id"] = $this->user->getId(); - $this->user->setForgottenPasswordToken(null); - loadUserValues(); - } -} - -class RecuperateAccount -{ - public $email; - /** @var User $user */ - public $user; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - } - - public function makeVerifications() - { - ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse email est invalide."); - $this->user = User::fromEmail($this->email); - ensure($this->user != null, "Le compte n'existe pas."); - } - - public function recuperateAccount() - { - $token = genRandomPhrase(64); - $this->user->setForgottenPasswordToken($token); - Mailer::sendForgottenPasswordProcedureMail($this->user); - } -} - -class ResetPassword -{ - public $token; - /** @var User $user */ - public $user; - private $password; - private $confirm_password; - - public function __construct($data, $data2) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - foreach ($data2 as $key => $value) - $this->$key = htmlspecialchars($value); - } - - public function makeVerifications() - { - global $DB; - $data = $DB->query("SELECT `id` FROM `users` WHERE `forgotten_password` = '" . $this->token . "';")->fetch(); - ensure($data !== false, "Il n'y a pas de compte à récupérer avec ce jeton."); - $this->user = User::fromId($data["id"]); - - if (!isset($_POST["password"])) - return; - - ensure($this->password == $this->confirm_password, "Les deux mots de passe sont différents."); - ensure(strlen($this->password) >= 8, "Le mot de passe doit comporter au moins 8 caractères."); - } - - public function resetPassword() - { - $this->user->setForgottenPasswordToken(null); - $this->user->setPassword($this->password); - - Mailer::sendChangePasswordMail($this->user); - - return false; - } -} - -function sendConfirmEmail() -{ - global $URL_BASE; - - $email = htmlspecialchars($_SESSION["confirm_email"]); - - if (!isset($email)) { - header("Location: $URL_BASE/connexion"); - exit(); - } - - $user = User::fromEmail($email); - - if ($user === null) { - unset($_SESSION["confirm_email"]); - header("Location: $URL_BASE/connexion"); - exit(); - } - - Mailer::sendConfirmEmail($user); - - return false; -} - -require_once "server_files/views/connexion.php"; diff --git a/server_files/controllers/deconnexion.php b/server_files/controllers/deconnexion.php deleted file mode 100644 index 20e215e..0000000 --- a/server_files/controllers/deconnexion.php +++ /dev/null @@ -1,14 +0,0 @@ - - -
- Déconnexion réussie ! -
- -getRole() == Role::PARTICIPANT ? $_SESSION["team"] : Team::fromTrigram($_GET["trigram"]); - -if ($team == null) - require_once "server_files/404.php"; - -if ($user->getRole() == Role::ENCADRANT && $team->getEncadrantId() != $user->getId() || $team->getValidationStatus() != ValidationStatus::VALIDATED) - require_once "server_files/403.php"; - -if (Phase::getCurrentPhase() != Phase::PHASE1) { - if (!(Phase::getCurrentPhase() == Phase::PHASE12 && Video::getVideo(Reason::SOLUTION, $team) != NULL && (Video::getVideo(Reason::SOLUTION, $team, ValidationStatus::WAITING) == NULL || isset($_POST["upload"])))) - require_once "server_files/403.php"; -} - -$has_error = false; -$error_message = null; - -if (isset($_POST["upload"])) { - $new_video = new NewVideo($_POST); - try { - $new_video->makeVerifications(); - $new_video->uploadVideo(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class NewVideo -{ - public $link; - private $valid_link; - private $no_change; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = $value; - } - - public function makeVerifications() - { - ensure(preg_match("#(https?\:\/\/|)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?#", $this->link), "Ce n'est pas une URL valide."); - $this->link = preg_replace('/^(?!https?:\/\/)/', 'https://', $this->link); - ensure($this->valid_link != null, "Vous devez confirmer que le lien est valide."); - ensure($this->no_change != null, "Vous devez vous engager à ne pas changer le contenu du lien et de la vidéo."); - } - - public function uploadVideo() - { - global $DB, $YEAR, $team; - - $req = $DB->prepare("INSERT INTO `videos`(`team`, `problem`, `link`, `reason`, `year`) VALUES (?, ?, ?, ?, ?)"); - $req->execute([$team->getId(), $team->getProblem(), $this->link, Reason::getName(Reason::SOLUTION), $YEAR]); - - Mailer::sendNewVideo($this, $team); - } -} - -$video = Video::getVideo(Reason::SOLUTION, $team); -$video_validated = Video::getVideo(Reason::SOLUTION, $team, Video::ACCEPTED); - -require_once "server_files/views/envoyer_video.php"; \ No newline at end of file diff --git a/server_files/controllers/equipe.php b/server_files/controllers/equipe.php deleted file mode 100644 index 2f226b1..0000000 --- a/server_files/controllers/equipe.php +++ /dev/null @@ -1,112 +0,0 @@ -setValidationStatus(ValidationStatus::VALIDATED); - Mailer::sendValidateTeam($team, $_POST["message"]); -} -elseif (isset($_POST["unvalidate"])) { - $team->setValidationStatus(ValidationStatus::NOT_READY); - Mailer::sendUnvalidateTeam($team, $_POST["message"]); -} -elseif (isset($_POST["select_problem"])) { - if ($team->getValidationStatus() == ValidationStatus::NOT_READY) { - $problem = $_POST["select_problem"]; - if (preg_match("#[0-4]#", $problem)) { - $team->setProblem($problem); - $DB->prepare("UPDATE `documents` SET `problem` = ? WHERE `team` = ?;")->execute([$problem, $team->getId()]); - } - else { - $has_error = true; - $error_message = "Le problème indiqué n'existe pas."; - } - } - else { - $has_error = true; - $error_message = "Cette équipe est déjà validée ou en cours de validation."; - } -} -elseif (isset($_POST["delete_team"])) { - if ($team->getValidationStatus() == ValidationStatus::NOT_READY) { - $documents = Document::getAllDocuments($team->getProblem(), $team->getId()); - /** @var Document $doc */ - foreach ($documents as $doc) - unlink($LOCAL_PATH . "/files/" . $doc->getFileId()); - $DB->prepare("DELETE FROM `documents` WHERE `team` = ?;")->execute([$team->getId()]); - $DB->prepare("DELETE FROM `teams` WHERE `id` = ?;")->execute([$team->getId()]); - $DB->prepare("UPDATE `users` SET `team_id` = NULL WHERE `team_id` = ?;")->execute([$team->getId()]); - header("Location: /"); - exit(0); - } - else { - $has_error = true; - $error_message = "Cette équipe est déjà validée ou en cours de validation."; - } -} - -if (isset($_POST["download_zip"])) { - $file_name = getZipFile($team->getProblem(), $team->getId()); - - header("Content-Type: application/zip"); - header("Content-Disposition: attachment; filename=\"Documents de l'équipe " . $team->getTrigram() . ".zip\""); - header("Content-Length: " . strval(filesize($file_name))); - - readfile($file_name); - - exit(); -} - -if (isset($_POST["update_video_teams"])) { - $update_video_teams = new UpdateVideoTeams($_POST); - try { - $update_video_teams->makeVerifications(); - $update_video_teams->update(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class UpdateVideoTeams -{ - private $other_teams; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = $value; - } - - public function makeVerifications() - { - global $team; - - ensure(Phase::getCurrentPhase() <= Phase::PHASE2, "Il est trop tard pour réaffecter les vidéos aux équipes."); - ensure($team->getSolution() != null, "L'équipe doit avoir soumis une vidéo."); - ensure($team->getSolution()->getValidation() == ValidationStatus::VALIDATED - 1, "L'équipe doit avoir soumis une vidéo validée."); - ensure(sizeof($this->other_teams) == 2, "L'équipe doit recevoir exactement deux vidéos."); - ensure(Team::fromId($this->other_teams[0]) != null, "La première équipe n'existe pas."); - ensure(Team::fromId($this->other_teams[1]) != null, "La seconde équipe n'existe pas."); - } - - public function update() - { - global $team; - - $team->setVideoTeamIds($this->other_teams); - } -} - -$other_teams = Team::getAllTeams($team->getProblem(), true, true); -$documents = Document::getAllDocuments($team->getProblem(), $team->getId()); - -require_once "server_files/views/equipe.php"; diff --git a/server_files/controllers/exporter_donnees.php b/server_files/controllers/exporter_donnees.php deleted file mode 100644 index 71b786d..0000000 --- a/server_files/controllers/exporter_donnees.php +++ /dev/null @@ -1,42 +0,0 @@ -setIndexPage(htmlspecialchars($content)); - header("Location: /"); - exit(0); - } -} - -require_once "server_files/views/index.php"; diff --git a/server_files/controllers/informations.php b/server_files/controllers/informations.php deleted file mode 100644 index 370cfcf..0000000 --- a/server_files/controllers/informations.php +++ /dev/null @@ -1,117 +0,0 @@ -getId() != $_SESSION["user_id"]) - require_once "server_files/403.php"; -} - -if ($user === null) - require_once "server_files/404.php"; - -$teams = $user->getTeams(); -if ($user->getRole() == Role::PARTICIPANT) - $team = sizeof($teams) == 0 ? null : $teams[0]; - -$has_error = false; -$error_message = null; - -if (isset($_POST["kick"])) { - if (sizeof($teams) == null) { - $has_error = true; - $error_message = "La personne à expulser n'est dans aucune équipe."; - } - else { - quitTeam($id); - $team = null; - } -} - -if (isset($_POST["attribute_team"])) { - $attribute_team = new AttributeTeam($_POST); - try { - $attribute_team->makeVerifications(); - $attribute_team->attribute(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_POST["view_as"]) && $_SESSION["role"] == Role::ADMIN) { - if (!isset($_SESSION["admin"])) - $_SESSION["admin"] = $_SESSION["user_id"]; - $_SESSION["user_id"] = $user->getId(); - header("Location: /"); - exit(); -} - -if (isset($_POST["delete_account"]) && $team == null && $_SESSION["role"] == Role::ADMIN) { - /** @var Document $document */ - foreach ($user->getAllDocuments() as $document) - unlink($LOCAL_PATH . "/files/" . $document->getFileId()); - $DB->prepare("DELETE FROM `documents` WHERE `user` = ?;")->execute([$user->getId()]); - $DB->prepare("DELETE FROM `users` WHERE `id` = ?;")->execute([$user->getId()]); - header("Location: /"); - exit(); -} - -class AttributeTeam -{ - private $team_id; - private $team; - private $min_null_index; - - public function __construct($data) - { - $this->team_id = $data["team"]; - $this->team = Team::fromId($this->team_id); - } - - public function makeVerifications() - { - global $user; - - ensure($user->getConfirmEmailToken() == null, "Ce participant n'a pas encore validé son adresse e-mail."); - ensure($this->team_id != "no_team", "Vous n'avez pas choisi d'équipe."); - ensure($this->team != null, "Cette équipe n'existe pas."); - ensure($this->team->getValidationStatus() == ValidationStatus::NOT_READY, "Cette équipe est déjà validée ou en cours de validation."); - - $role = $user->getRole(); - for ($i = 1; $i <= $role == Role::ENCADRANT ? 1 : 5; ++$i) { - if (($role == Role::PARTICIPANT ? $this->team->getParticipants()[$i - 1] : $this->team->getEncadrantId()) == NULL) - break; - } - - $this->min_null_index = $i; - - ensure($role == Role::PARTICIPANT && $this->min_null_index <= 5 || $role == Role::ENCADRANT && $this->min_null_index <= 2, - "Il n'y a plus de place pour vous dans l'équipe."); - } - - public function attribute() - { - global $user, $team; - - $user->setTeamId($this->team->getId()); - - if ($user->getRole() == Role::ENCADRANT) - $this->team->setEncadrant($user->getId()); - else - $this->team->setParticipant($this->min_null_index, $user->getId()); - - Mailer::sendJoinTeamMail($user, $this->team); - - $team = $this->team; - } -} - -if ($teams != null) - $documents = $user->getAllDocuments(); - -require_once "server_files/views/informations.php"; diff --git a/server_files/controllers/inscription.php b/server_files/controllers/inscription.php deleted file mode 100644 index 6a51fe0..0000000 --- a/server_files/controllers/inscription.php +++ /dev/null @@ -1,84 +0,0 @@ -makeVerifications(); - $user->register(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class NewUser -{ - public $email; - public $first_name; - public $surname; - public $role; - public $school; - public $city; - public $country; - public $class; - public $receive_animath_mails; - - public $description; - public $confirm_email_token; - private $password; - private $confirm_password; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - - $this->receive_animath_mails = $this->receive_animath_mails ? 1 : 0; - } - - public function makeVerifications() - { - global $CONFIG; - - ensure(date("Y-m-d H:i:s") < $CONFIG->getInscriptionDate(), "Les inscriptions sont terminées."); - ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse e-mail entrée est invalide."); - $this->email = strtolower($this->email); - ensure(!userExists($this->email), "Un compte existe déjà avec cette adresse e-mail."); - ensure(strlen($this->password) >= 8, "Le mot de passe doit comporter au moins 8 caractères."); - ensure($this->password == $this->confirm_password, "Les deux mots de passe sont différents."); - ensure($this->surname != "", "Le nom de famille est obligatoire."); - ensure($this->first_name != "", "Le prénom est obligatoire."); - $this->role = Role::fromName(strtoupper($this->role)); - ensure($this->role == Role::PARTICIPANT || $this->role == Role::ENCADRANT, "Vous devez être participant ou encadrant."); - - if ($this->role == Role::PARTICIPANT) - $this->class = SchoolClass::fromName(strtoupper($this->class)); - else - $this->class = SchoolClass::ADULT; - - $this->confirm_email_token = genRandomPhrase(64); - } - - public function register() - { - global $DB, $YEAR; - - if (!$DB->query("SELECT `id` FROM `users` WHERE `year` = $YEAR;")->fetch()) - $this->role = Role::ADMIN; - - $req = $DB->prepare("INSERT INTO `users`(`email`, `pwd_hash`, `confirm_email`, `surname`, `first_name`, - `school`, `city`, `country`, `class`, `role`, `description`, `receive_animath_mails`, `year`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); - $req->execute([$this->email, password_hash($this->password, PASSWORD_BCRYPT), $this->confirm_email_token, - $this->surname, $this->first_name, $this->school, $this->city, $this->country, SchoolClass::getName($this->class), - Role::getName($this->role), $this->description, $this->receive_animath_mails, $YEAR]); - - Mailer::sendRegisterMail($this); - } -} - -require_once "server_files/views/inscription.php"; diff --git a/server_files/controllers/ma_participation.php b/server_files/controllers/ma_participation.php deleted file mode 100644 index 6452ed1..0000000 --- a/server_files/controllers/ma_participation.php +++ /dev/null @@ -1,23 +0,0 @@ - 0) { - /** - * @var User $user - * @var Team team - */ - $user = $_SESSION["user"]; - $team = $user->getRole() == Role::PARTICIPANT ? $_SESSION["team"] : Team::fromTrigram($_GET["trigram"]); - - if ($team == null) - require_once "server_files/404.php"; - - if ($user->getRole() == Role::ENCADRANT && $team->getEncadrantId() != $user->getId()) - require_once "server_files/403.php"; - - $video = Video::getVideo(Reason::SOLUTION, $team); - $questions_received = Question::getQuestionsTo($team); -} -else - require_once "server_files/403.php"; - -require_once "server_files/views/ma_participation.php"; \ No newline at end of file diff --git a/server_files/controllers/mon_compte.php b/server_files/controllers/mon_compte.php deleted file mode 100644 index dc944e4..0000000 --- a/server_files/controllers/mon_compte.php +++ /dev/null @@ -1,177 +0,0 @@ -makeVerifications(); - $my_account->updateAccount(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_POST["update_password"])) { - $new_password = new NewPassword($_POST); - try { - $new_password->makeVerifications(); - $new_password->updatePassword(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_POST["send_document"])) { - $send_document = new SendDocument(); - try { - $send_document->makeVerifications(); - $send_document->sendDocument(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class MyAccount -{ - public $email; - public $surname; - public $first_name; - public $school; - public $city; - public $country; - public $class; - public $description; - public $receive_animath_mails; - /** @var User */ - private $user; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - - $this->user = $_SESSION["user"]; - - $keys = ["email", "surname", "first_name", "school", "class", "description"]; - - if ($this->user->getRole() == Role::PARTICIPANT) - $this->class = SchoolClass::fromName($this->class); - - foreach ($keys as $key) - $this->$key = $this->$key != null && $this->$key != "" ? $this->$key : $this->user->$key; - - $this->receive_animath_mails = $this->receive_animath_mails == "on"; - } - - public function makeVerifications() - { - ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse e-mail entrée est invalide."); - $this->email = strtolower($this->email); - ensure($this->email == $this->user->getEmail() || !userExists($this->email), "Un compte existe déjà avec cette adresse e-mail."); - $this->receive_animath_mails = $this->receive_animath_mails != false; - } - - public function updateAccount() - { - $this->user->setSurname($this->surname); - $this->user->setFirstName($this->first_name); - $this->user->setSchool($this->school); - $this->user->setCity($this->city); - $this->user->setCountry($this->country); - $this->user->setClass($this->class); - $this->user->setDescription($this->description); - $this->user->setReceiveAnimathMails($this->receive_animath_mails); - - if ($this->email != $this->user->getEmail()) { - $this->user->setEmail($this->email); - $this->user->setConfirmEmailToken(genRandomPhrase(64)); - - Mailer::sendChangeEmailAddressMail($this->user); - } - } -} - -class NewPassword -{ - private $user; - private $old_password; - private $new_password; - private $confirm_password; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - - $this->user = $_SESSION["user"]; - } - - public function makeVerifications() - { - ensure($this->user->checkPassword($this->old_password), "L'ancien mot de passe est incorrect."); - ensure(strlen($this->new_password) >= 8, "Le mot de passe doit comporter au moins 8 caractères."); - ensure($this->new_password == $this->confirm_password, "Les deux mots de passe sont différents."); - } - - public function updatePassword() - { - $this->user->setPassword($this->new_password); - - Mailer::sendChangePasswordMail($this->user); - } -} - -class SendDocument -{ - private $file; - - public function __construct() - { - $this->file = $_FILES["document"]; - } - - public function makeVerifications() - { - global $LOCAL_PATH; - - ensure($this->file["size"] <= 2e6, "Le fichier doit peser moins que 2 Mo."); - ensure(!$this->file["error"], "Une erreur est survenue."); - $mime_type = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->file["tmp_name"]); - ensure($mime_type == "application/pdf" || $mime_type == "image/png" || $mime_type == "image/jpeg", "Le fichier doit être au format PDF."); - ensure(is_dir("$LOCAL_PATH/files") || mkdir("$LOCAL_PATH/files"), "Un problème est survenu dans l'envoi du fichier. Veuillez vérifier que le fichier pèse moins de 2 Mo. Merci de compresser votre fichier si tel n'est pas le cas. En cas de problème, merci de contacter l'administrateur du serveur."); - } - - public function sendDocument() - { - global $LOCAL_PATH, $DB; - - do - $id = genRandomPhrase(64); - while (file_exists("$LOCAL_PATH/files/$id")); - - if (!rename($this->file["tmp_name"], "$LOCAL_PATH/files/$id")) - throw new AssertionError("Une erreur est survenue lors de l'envoi du fichier."); - - $req = $DB->prepare("INSERT INTO `documents`(`file_id`, `user`, `team`, `problem`) - VALUES (?, ?, ?, ?);"); - $req->execute([$id, $_SESSION["user_id"], $_SESSION["team"]->getId(), $_SESSION["team"]->getProblem()]); - } -} - -$documents = $user->getAllDocuments(); - -require_once "server_files/views/mon_compte.php"; diff --git a/server_files/controllers/mon_equipe.php b/server_files/controllers/mon_equipe.php deleted file mode 100644 index cde263d..0000000 --- a/server_files/controllers/mon_equipe.php +++ /dev/null @@ -1,112 +0,0 @@ -makeVerifications(); - $my_team->updateTeam(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -/** - * @var User $user - * @var Team $team - */ -$user = $_SESSION["user"]; -$team = $user->getRole() == Role::PARTICIPANT ? $_SESSION["team"] : Team::fromTrigram($_GET["trigram"]); - -if (isset($_POST["request_validation"])) { - if (!canValidate($team)) { - $has_error = true; - $error_message = "Votre équipe ne peut pas demander la validation : il manque soit des participants, soit des documents."; - } - else if (!isset($_POST["engage"])) { - $has_error = true; - $error_message = "Vous devez cocher la case qui vous engage à participer à l'intégralité des Correspondances."; - } - else { - $team->setValidationStatus(ValidationStatus::WAITING); - Mailer::sendRequestValidationMail($team); - } -} - -/** @var Question[][] $questions_received */ -$questions_received = []; - -if (isset($_SESSION["user_id"]) && isset($_SESSION["teams"]) && sizeof($_SESSION["teams"]) > 0) { - if ($team == null) - require_once "server_files/404.php"; - - if ($user->getRole() == Role::ENCADRANT && $team->getEncadrantId() != $user->getId()) - require_once "server_files/403.php"; - - $documents = $team->getAllDocuments(); -} -else - require_once "server_files/403.php"; - -if (isset($_GET["publish_videos"])) { - $team->setAllowPublish(!$team->allowPublish()); - header("Location: /mon-equipe"); - exit(); -} - -class MyTeam -{ - public $name; - public $trigram; - public $problem; - /** @var Team */ - private $team; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - - $this->trigram = strtoupper($this->trigram); - $this->team = $_SESSION["team"]; - } - - public function makeVerifications() - { - global $CONFIG; - - ensure($this->name != "" && $this->name != null, "Veuillez spécifier un nom d'équipe."); - ensure($this->name == $this->team->getName() || !teamExists($this->name), "Une équipe existe déjà avec ce nom."); - ensure(preg_match("#^[\p{L} ]+$#ui", $this->name), "Le nom de l'équipe ne doit pas comporter de caractères spéciaux."); - ensure(preg_match("#^[A-Z]{3}$#", $this->trigram), "Le trigramme n'est pas valide."); - ensure($this->trigram == $this->team->getTrigram() || !trigramExists($this->trigram), "Une équipe a déjà choisi ce trigramme."); - ensure(preg_match("#^[0-4]$#", $this->problem), "Le problème indiqué n'existe pas."); - ensure(date("Y-m-d H:i:s") <= $CONFIG->getInscriptionDate(), "Les inscriptions sont terminées."); - ensure($this->team->getValidationStatus() == ValidationStatus::NOT_READY, "Votre équipe est déjà validée ou en cours de validation."); - } - - public function updateTeam() - { - global $DB, $URL_BASE; - - $this->team->setName($this->name); - $this->team->setTrigram($this->trigram); - $this->team->setProblem($this->problem); - - $DB->exec("UPDATE `teams` SET `problem` = " . $this->problem . " WHERE `id` = " . $this->team->getId() . ";"); - $DB->exec("UPDATE `documents` SET `problem` = " . $this->problem . " WHERE `team` = " . $this->team->getId() . ";"); - - header("Location: $URL_BASE/mon-equipe"); - } -} - -require_once "server_files/views/mon_equipe.php"; diff --git a/server_files/controllers/poser_questions.php b/server_files/controllers/poser_questions.php deleted file mode 100644 index 7aa3ee8..0000000 --- a/server_files/controllers/poser_questions.php +++ /dev/null @@ -1,137 +0,0 @@ -getRole() == Role::PARTICIPANT ? $_SESSION["team"] : Team::fromTrigram($_GET["trigram"]); - -if ($team == null) - require_once "server_files/404.php"; - -if ($user->getRole() == Role::ENCADRANT && $team->getEncadrantId() != $user->getId() || $team->getValidationStatus() != ValidationStatus::VALIDATED) - require_once "server_files/403.php"; - -$has_error = false; -$error_message = null; - -if (isset($_POST["give_questions"])) { - $give_questions = new GiveQuestions($_POST, $_FILES); - try { - $give_questions->makeVerifications(); - $give_questions->giveQuestions(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class GiveQuestions -{ - private $to; - /** - * @var Team $to_team - */ - private $to_team; - private $question_0; - private $question_1; - private $question_2; - private $question_3; - private $question_4; - private $question_5; - private $question_6; - private $questions; - private $no_drawing; - private $has_files; - private $files; - - public function __construct($data, $files) - { - foreach ($data as $key => $value) { - $this->$key = $value; - } - - $this->files = []; - $this->has_files = false; - - for ($i = 0; $i <= 6; ++$i) { - if (strlen($files["file_$i"]["name"]) > 0) { - $this->files[] = $files["file_$i"]; - $this->has_files = true; - } - else - $this->files[] = null; - } - - $this->questions = [$this->question_0, $this->question_1, $this->question_2, $this->question_3, $this->question_4, $this->question_5, $this->question_6]; - } - - public function makeVerifications() - { - global $LOCAL_PATH, $team; - - $this->to_team = Team::fromTrigram($this->to); - ensure($this->to_team, "L'équipe indiquée n'existe pas."); - ensure($team->getProblem() == $this->to_team->getProblem(), "Les équipes ne travaillent pas sur le même problème."); - ensure($this->question_1 != null && $this->question_1 != "" && $this->question_2 != null && $this->question_2 != "" && $this->question_3 != null && $this->question_3 != "", - "Vous devez poser au moins 3 questions."); - ensure(!$this->has_files || $this->no_drawing, "Vous devez confirmer ne pas avoir inclus de texte dans vos pièces jointes."); - - for ($i = 4; $i <= 6; ++$i) { - if ($this->questions[$i] == "") - $this->questions[$i] = null; - } - - for ($i = 0; $i <= 6; ++$i) { - ensure($this->files[$i]["size"] <= 2e6, "Le fichier doit peser moins que 2 Mo."); - ensure(!$this->files[$i]["error"], "Une erreur est survenue. Veuillez vérifier vos pièces jointes. Elles ne doivent pas peser plus de 2 Mo chacune."); - } - - ensure(is_dir("$LOCAL_PATH/files") || mkdir("$LOCAL_PATH/files"), "Un problème est survenue dans l'envoi du fichier. Veuillez contacter l'administrateur du serveur."); - } - - public function giveQuestions() - { - global $LOCAL_PATH, $team; - - /** @var Question[] $questions */ - $questions = Question::getQuestions($team, $this->to_team); - for ($i = 0; $i <= 6; ++$i) { - $question = $questions[$i]; - if ($question->getQuestion() != $this->questions[$i] && $question->getAttachedFile() != null) { - unlink("$LOCAL_PATH/files/" . $question->getAttachedFile()); - $question->setAttachedFile(null); - } - - $question->setQuestion($this->questions[$i]); - - if ($this->files[$i] != null) { - do - $file_id = genRandomPhrase(64); - while (file_exists("$LOCAL_PATH/files/$file_id")); - - if (!rename($this->files[$i]["tmp_name"], "$LOCAL_PATH/files/$file_id")) - throw new AssertionError("Une erreur est survenue lors de l'envoi du fichier."); - - $question->setAttachedFile($file_id); - } - } - } -} - -/** - * @var Team[] $receivers - * @var Video[] $videos - * @var Question[][] $questions - */ -$receivers = [Team::fromId($team->getVideoTeamIds()[0]), Team::fromId($team->getVideoTeamIds()[1])]; -$videos = [Video::getVideo(Reason::SOLUTION, $receivers[0], Video::ACCEPTED), - Video::getVideo(Reason::SOLUTION, $receivers[1], Video::ACCEPTED)]; -$questions = [Question::getQuestions($team, $receivers[0]), - Question::getQuestions($team, $receivers[1])]; - -require_once "server_files/views/poser_questions.php"; \ No newline at end of file diff --git a/server_files/controllers/probleme.php b/server_files/controllers/probleme.php deleted file mode 100644 index 59130b8..0000000 --- a/server_files/controllers/probleme.php +++ /dev/null @@ -1,26 +0,0 @@ -getValidationStatus() == ValidationStatus::VALIDATED) - $validated_emails = array_merge($validated_emails, $team->getAllEmails()); - else - $not_validated_emails = array_merge($not_validated_emails, $team->getAllEmails()); -} - -require_once "server_files/views/probleme.php"; diff --git a/server_files/controllers/profiles.php b/server_files/controllers/profiles.php deleted file mode 100644 index cf4d789..0000000 --- a/server_files/controllers/profiles.php +++ /dev/null @@ -1,9 +0,0 @@ -makeVerifications(); - $join_team->joinTeam(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class JoinTeam -{ - private $access_code; - private $team; - private $min_null_index; - - public function __construct($data) - { - $this->access_code = strtolower(htmlspecialchars($data["access_code"])); - $this->team = Team::fromAccessCode($this->access_code); - } - - public function makeVerifications() - { - global $CONFIG; - - ensure(date("Y-m-d H:i:s") < $CONFIG->getInscriptionDate(), "La date limite d'inscription est dépassée."); - ensure($_SESSION["team"] == null || $_SESSION["role"] == Role::ENCADRANT, "Vous êtes déjà dans une équipe."); - ensure(preg_match("#[a-z0-9]{6}#", $this->access_code), "Le code d'accès doit comporter 6 caractères alphanumériques."); - ensure($this->team != null, "Ce code d'accès est invalide."); - ensure($this->team->getValidationStatus() == ValidationStatus::NOT_READY, "Cette équipe est déjà validée ou en cours de validation, vous ne pouvez pas la rejoindre."); - - for ($i = 1; $i <= ($_SESSION["role"] == Role::PARTICIPANT ? 5 : 1); ++$i) { - if (($_SESSION["role"] == Role::PARTICIPANT ? $this->team->getParticipants()[$i - 1] : $this->team->getEncadrantId()) == NULL) - break; - } - - $this->min_null_index = $i; - - ensure($_SESSION["role"] == Role::PARTICIPANT && $this->min_null_index <= 5 || $_SESSION["role"] == Role::ENCADRANT && $this->min_null_index <= 1, "Il n'y a plus de place pour vous dans l'équipe."); - } - - public function joinTeam() - { - global $team; - - $user = $_SESSION["user"]; - - $user->setTeamId($this->team->getId()); - - if ($_SESSION["role"] == Role::ENCADRANT) - $this->team->setEncadrant($user->getId()); - else - $this->team->setParticipant($this->min_null_index, $user->getId()); - - $team = $_SESSION["team"] = $this->team; - - Mailer::sendJoinTeamMail($user, $this->team); - } -} - -require_once "server_files/views/rejoindre_equipe.php"; diff --git a/server_files/controllers/repondre_questions.php b/server_files/controllers/repondre_questions.php deleted file mode 100644 index 924171b..0000000 --- a/server_files/controllers/repondre_questions.php +++ /dev/null @@ -1,126 +0,0 @@ -getRole() == Role::PARTICIPANT ? $_SESSION["team"] : Team::fromTrigram($_GET["trigram"]); - -if ($team == null) - require_once "server_files/404.php"; - -if ($user->getRole() == Role::ENCADRANT && $team->getEncadrantId() != $user->getId() || $team->getValidationStatus() != ValidationStatus::VALIDATED) - require_once "server_files/403.php"; - -$has_error = false; -$error_message = null; - -if (isset($_POST["answer"])) { - $answer_questions = new AnswerQuestions($_POST, $_FILES); - try { - $answer_questions->makeVerifications(); - $answer_questions->answerQuestions(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class AnswerQuestions -{ - private $from; - /** - * @var Team $to_team - */ - private $from_team; - private $answer_0; - private $answer_1; - private $answer_2; - private $answer_3; - private $answer_4; - private $answer_5; - private $answer_6; - private $answers; - private $no_drawing; - private $has_files; - private $files; - - public function __construct($data, $files) - { - foreach ($data as $key => $value) { - $this->$key = $value; - } - - $this->files = []; - $this->has_files = false; - - for ($i = 0; $i <= 6; ++$i) { - if (strlen($files["file_$i"]["name"]) > 0) { - $this->files[] = $files["file_$i"]; - $this->has_files = true; - } - else - $this->files[] = null; - } - - $this->answers = [$this->answer_0, $this->answer_1, $this->answer_2, $this->answer_3, $this->answer_4, $this->answer_5, $this->answer_6]; - } - - public function makeVerifications() - { - global $LOCAL_PATH, $team; - - $this->from_team = Team::fromTrigram($this->from); - ensure($this->from_team != null, "L'équipe indiquée n'existe pas."); - ensure($team->getProblem() == $this->from_team->getProblem(), "Les équipes ne travaillent pas sur le même problème."); - ensure(!$this->has_files || $this->no_drawing, "Vous devez confirmer ne pas avoir inclus de texte dans vos pièces jointes."); - - for ($i = 1; $i <= 6; ++$i) { - if ($this->answers[$i] == "") - $this->answers[$i] = null; - } - - for ($i = 0; $i <= 6; ++$i) { - ensure($this->files[$i]["size"] <= 2e6, "Le fichier doit peser moins que 2 Mo."); - ensure(!$this->files[$i]["error"], "Une erreur est survenue. Veuillez vérifier vos pièces jointes. Elles ne doivent pas peser plus de 2 Mo chacune."); - } - - ensure(is_dir("$LOCAL_PATH/files") || mkdir("$LOCAL_PATH/files"), "Un problème est survenue dans l'envoi du fichier. Veuillez contacter l'administrateur du serveur."); - } - - public function answerQuestions() - { - global $LOCAL_PATH, $team; - - /** @var Question[] $questions */ - $questions = Question::getQuestions($this->from_team, $team); - for ($i = 0; $i <= 6; ++$i) { - $question = $questions[$i]; - if ($question->getAnswer() != $this->answers[$i] && $question->getAttachedFileAnswer() != null) { - unlink("$LOCAL_PATH/files/" . $question->getAttachedFileAnswer()); - $question->setAttachedFileAnswer(null); - } - - $question->setAnswer($this->answers[$i]); - - if ($this->files[$i] != null) { - do - $file_id = genRandomPhrase(64); - while (file_exists("$LOCAL_PATH/files/$file_id")); - - if (!rename($this->files[$i]["tmp_name"], "$LOCAL_PATH/files/$file_id")) - throw new AssertionError("Une erreur est survenue lors de l'envoi du fichier."); - - $question->setAttachedFileAnswer($file_id); - } - } - } -} - -$questions = Question::getQuestionsTo($team); -$video = Video::getVideo(Reason::SOLUTION, $team); - -require_once "server_files/views/repondre_questions.php"; \ No newline at end of file diff --git a/server_files/controllers/suivi_correspondances.php b/server_files/controllers/suivi_correspondances.php deleted file mode 100644 index 522fabd..0000000 --- a/server_files/controllers/suivi_correspondances.php +++ /dev/null @@ -1,141 +0,0 @@ -makeVerifications(); - $validate_video->validate(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class ValidateVideo -{ - private $video_id; - private $accept; - private $reject; - /** @var Video */ - private $video; - private $message; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = $value; - } - - public function makeVerifications() - { - $this->video = Video::fromId($this->video_id); - ensure($this->video != null, "La vidéo n'existe pas."); - ensure($this->video->getValidation() != 1, "La vidéo est déjà validée / rejetée."); - ensure(($this->accept == null || $this->reject == null) && $this->accept != $this->reject, "Impossible de déterminer s'il faut accepter ou non la vidéo."); - } - - public function validate() - { - $this->video->setValidation($this->accept ? 1 : -1); - Mailer::validateVideo($this->video, $this->message); - } -} - -$videos = []; - -if (!isset($_GET["problem"])) { - for ($problem = 1; $problem <= 4; ++$problem) - $videos[] = Video::getVideos(Reason::SOLUTION, $problem); -} -else { - $videos = [[], [], [], []]; - $videos[intval($_GET["problem"]) - 1] = Video::getVideos(Reason::SOLUTION, intval($_GET["problem"])); -} - -$waiting_teams = []; -$waiting_emails = []; - -switch (Phase::getCurrentPhase()) { - case Phase::PHASE1: - case Phase::PHASE12: - $req = $DB->query("SELECT DISTINCT `teams`.`id`, `teams`.`problem`, `teams`.`trigram` FROM `teams` WHERE `validation_status` = '" . ValidationStatus::getName(ValidationStatus::VALIDATED) . "'" - . " AND `id` NOT IN (SELECT DISTINCT `team` FROM `videos` WHERE `reason` = 'SOLUTION' AND `validation` = " . Video::ACCEPTED . ")" - . " AND `year` = $YEAR ORDER BY `problem`, `trigram`;"); - break; - case Phase::PHASE2: - case Phase::PHASE23: - $req = $DB->query("SELECT DISTINCT `teams`.`id`, `teams`.`problem`, `teams`.`trigram` FROM `teams`" - . " WHERE `id` NOT IN (SELECT `q1`.`from` FROM `questions` AS `q1`" - . " JOIN `questions` AS `q2` ON `q2`.`from` = `q1`.`from` AND `q2`.`number` = 2" - . " JOIN `questions` AS `q3` ON `q3`.`from` = `q1`.`from` AND `q3`.`number` = 3" - . " JOIN `questions` AS `q4` ON `q4`.`from` = `q1`.`from` AND `q4`.`number` = 4" - . " JOIN `questions` AS `q5` ON `q5`.`from` = `q1`.`from` AND `q5`.`number` = 5" - . " JOIN `questions` AS `q6` ON `q6`.`from` = `q1`.`from` AND `q6`.`number` = 6" - . " WHERE `q1`.`number` = 1" - . " AND (`q1`.`question` != '" . Question::DEFAULT_QUESTIONS[0] . "'" - . " OR `q2`.`question` != '" . Question::DEFAULT_QUESTIONS[1] . "'" - . " OR `q3`.`question` != '" . Question::DEFAULT_QUESTIONS[2] . "'" - . " OR `q4`.`question` IS NOT NULL" - . " OR `q5`.`question` IS NOT NULL" - . " OR `q6`.`question` IS NOT NULL))" - . " AND `validation_status` = '" . ValidationStatus::getName(ValidationStatus::VALIDATED) . "'" - . " AND `year` = $YEAR ORDER BY `problem`, `trigram`;"); - break; - case Phase::PHASE3: - case Phase::PHASE34: - $req = $DB->query("SELECT DISTINCT `teams`.`id`, `teams`.`problem`, `teams`.`trigram` FROM `teams`" - . " WHERE `id` NOT IN (SELECT `q1`.`to` FROM `questions` AS `q1`" - . " JOIN `questions` AS `q2` ON `q2`.`to` = `q1`.`to` AND `q2`.`number` = 2" - . " JOIN `questions` AS `q3` ON `q3`.`to` = `q1`.`to` AND `q3`.`number` = 3" - . " JOIN `questions` AS `q4` ON `q4`.`to` = `q1`.`to` AND `q4`.`number` = 4" - . " JOIN `questions` AS `q5` ON `q5`.`to` = `q1`.`to` AND `q5`.`number` = 5" - . " JOIN `questions` AS `q6` ON `q6`.`to` = `q1`.`to` AND `q6`.`number` = 6" - . " WHERE `q1`.`number` = 1" - . " AND (`q1`.`answer` IS NOT NULL" - . " OR `q2`.`answer` IS NOT NULL" - . " OR `q3`.`answer` IS NOT NULL" - . " OR `q4`.`answer` IS NOT NULL" - . " OR `q5`.`answer` IS NOT NULL" - . " OR `q6`.`answer` IS NOT NULL))" - . " AND `validation_status` = '" . ValidationStatus::getName(ValidationStatus::VALIDATED) . "'" - . " AND `year` = $YEAR ORDER BY `problem`, `trigram`;"); - break; - case Phase::PHASE4: - case Phase::END: - $req = $DB->query("SELECT DISTINCT `teams`.`id`, `teams`.`problem`, `teams`.`trigram` FROM `teams` WHERE `validation_status` = '" . ValidationStatus::getName(ValidationStatus::VALIDATED) . "'" - . " AND (`id` NOT IN (SELECT DISTINCT `team` FROM `videos` WHERE `reason` = 'ANSWER1' AND `validation` = " . Video::ACCEPTED . ")" - . " OR `id` NOT IN (SELECT DISTINCT `team` FROM `videos` WHERE `reason` = 'ANSWER2' AND `validation` = " . Video::ACCEPTED . "))" - . " AND `year` = $YEAR ORDER BY `problem`, `trigram`;"); - break; -} - -if (isset($req)) { - $waiting_emails = []; - while (($data = $req->fetch()) !== false) { - $team = Team::fromId($data["id"]); - if (Phase::getCurrentPhase() >= Phase::PHASE12 && $team->getSolution() == null) - continue; - if (isset($_GET["problem"]) && intval($_GET["problem"]) != $team->getProblem()) - continue; - $waiting_teams[] = $team; - $waiting_emails = array_merge($waiting_emails, $team->getAllEmails()); - } -} - -$all_emails = []; -foreach (Team::getAllTeams() as $team) { - if (Phase::getCurrentPhase() >= Phase::PHASE12 && $team->getSolution() == null) - continue; - if (isset($_GET["problem"]) && intval($_GET["problem"]) != $team->getProblem()) - continue; - $all_emails = array_merge($all_emails, $team->getAllEmails()); -} - -require_once "server_files/views/suivi_correspondances.php"; \ No newline at end of file diff --git a/server_files/controllers/view_file.php b/server_files/controllers/view_file.php deleted file mode 100644 index f54e827..0000000 --- a/server_files/controllers/view_file.php +++ /dev/null @@ -1,51 +0,0 @@ -getTeamId());; - $trigram = $team->getTrigram(); - - $user = User::fromId($file->getUserId()); - - if (($_SESSION["role"] == Role::PARTICIPANT || $_SESSION["role"] == Role::ENCADRANT) && $user->getId() != $_SESSION["user_id"]) - require_once "server_files/403.php"; - - $surname = $user->getSurname(); - $first_name = $user->getFirstName(); - $mime_type = finfo_file(finfo_open(FILEINFO_MIME_TYPE), "$LOCAL_PATH/files/$id"); - $ext = $mime_type == "application/pdf" ? "pdf" : ($mime_type == "image/png" ? "png" : "jpg"); - $name = "Autorisation de droit à l'image de $first_name $surname.$ext"; - - header("Content-Type: " . $mime_type); -} -else { - $question = Question::fromAttachedFile($id); - if ($question != null) - { - $from = Team::fromId($question->getFrom()); - $to = Team::fromId($question->getTo()); - $mime_type = finfo_file(finfo_open(FILEINFO_MIME_TYPE), "$LOCAL_PATH/files/$id"); - $name = "Pièce jointe n°" . $question->getNumber() . " de l'équipe " . $from->getTrigram() . " pour l'équipe " . $from->getTrigram() . " (problème " . $question->getProblem() . ")"; - $name .= getExtFromMimeType($mime_type); - header("Content-Type: " . $mime_type); - } - else - require_once "server_files/404.php"; -} - -header("Content-Disposition: inline; filename=\"$name\""); - -readfile("$LOCAL_PATH/files/$id"); - -exit(); \ No newline at end of file diff --git a/server_files/model.php b/server_files/model.php deleted file mode 100644 index aa4fb2d..0000000 --- a/server_files/model.php +++ /dev/null @@ -1,326 +0,0 @@ -getRole(); - - $_SESSION["teams"] = $user->getTeams(); - - if ($user->getRole() == Role::PARTICIPANT) - $_SESSION["team"] = sizeof($_SESSION["teams"]) > 0 ? $_SESSION["teams"][0] : null; - } - - if (isset($_GET["view-as-admin"])) { - if (isset($_SESSION["admin"])) { - $_SESSION["user_id"] = $_SESSION["admin"]; - unset($_SESSION["admin"]); - } - header("Location: /"); - exit(); - } -} - -function quitTeam($user_id = -1) -{ - global $DB, $URL_BASE; - - if ($user_id == -1) - header("Location: $URL_BASE"); - - $user_id = $user_id >= 0 ? $user_id : $_SESSION["user_id"]; - /** @var User $user */ - $user = User::fromId($user_id); - $role = $user->getRole(); - - if ($role == Role::ADMIN) - return; - - if ($role == Role::PARTICIPANT) - for ($i = 1; $i <= 5; ++$i) - /** @noinspection SqlResolve */ - $DB->exec("UPDATE `teams` SET `participant_$i` = NULL WHERE `participant_$i` = $user_id;"); - else - $DB->exec("UPDATE `teams` SET `encadrant` = NULL WHERE `encadrant` = $user_id;"); - $user->setTeamId(null); - for ($i = 1; $i <= 4; ++$i) { - /** @noinspection SqlResolve */ - $DB->exec("UPDATE `teams` SET `participant_$i` = `participant_" . strval($i + 1) . "`, `participant_" . strval($i + 1) . "` = NULL WHERE `participant_$i` IS NULL;"); - } - - $DB->exec("DELETE FROM `teams` WHERE `encadrant` IS NULL AND `participant_1` IS NULL;"); - $req = $DB->query("SELECT `file_id` FROM `documents` WHERE `user` = $user_id;"); - while (($data = $req->fetch()) !== false) - unlink("$URL_BASE/files/" . $data["file_id"]); - $DB->exec("DELETE FROM `documents` WHERE `user` = $user_id;"); - - $_SESSION["team"] = null; - unset($_SESSION["team"]); - - $_SESSION["teams"] = $user->getTeams(); -} - -function userExists($email) -{ - global $DB, $YEAR; - - $req = $DB->prepare("SELECT `id` FROM `users` WHERE `email` = ? AND `year` = '$YEAR';"); - $req->execute([$email]); - return $req->fetch(); -} - -function teamExists($name) -{ - global $DB, $YEAR; - - $req = $DB->prepare("SELECT `id` FROM `teams` WHERE `name` = ? AND `year` = '$YEAR';"); - $req->execute([$name]); - return $req->fetch(); -} - -function trigramExists($trigram) -{ - global $DB, $YEAR; - - $req = $DB->prepare("SELECT `id` FROM `teams` WHERE `trigram` = ? AND `year` = '$YEAR';"); - $req->execute([$trigram]); - return $req->fetch(); -} - -function canValidate(Team $team) -{ - global $DB, $CONFIG; - - $can_validate = date("Y-m-d H:i:s") < $CONFIG->getInscriptionDate(); - $can_validate &= $team->getValidationStatus() == ValidationStatus::NOT_READY; - $can_validate &= $team->getEncadrantId() != null; - $can_validate &= $team->getParticipants()[2] != null; - $can_validate &= preg_match("#[1-4]#", $team->getProblem()); - - for ($i = 0; $i < 5; ++$i) { - if ($team->getParticipants()[$i] === NULL) - continue; - - $req = $DB->prepare("SELECT COUNT(*) AS `version` FROM `documents` WHERE `user` = ? AND `problem` = ?;"); - $req->execute([$team->getParticipants()[$i], $team->getProblem()]); - $d = $req->fetch(); - $can_validate &= $d["version"] > 0; - } - - return $can_validate; -} - -function printDocuments($documents) -{ - if (sizeof($documents) == 0) { - echo "
\nPas de document envoyé pour le moment.\n
\n"; - return; - } - - echo "
\n"; - foreach ($documents as $document) { - $file_id = $document->getFileId(); - $user = User::fromId($document->getUserId()); - $surname = $user->getSurname(); - $first_name = $user->getFirstName(); - $name = "Autorisation de droit à l'image"; - $version = $document->getVersion(); - echo "$name de $first_name $surname (version $version) : Télécharger
\n"; - } - echo "
\n"; -} - -function getZipFile($problem, $team_id = -1) -{ - global $LOCAL_PATH; - - $zip = new ZipArchive(); - - $file_name = tempnam("tmp", "corres2math-"); - - if ($zip->open($file_name, ZipArchive::CREATE) !== true) { - die("Impossible de créer le fichier zip."); - } - - $data = Document::getAllDocuments($problem, $team_id); - - /** @var Document $file */ - foreach ($data as $file) { - $file_id = $file->getFileId(); - $user = User::fromId($file->getUserId()); - $mime_type = finfo_file(finfo_open(FILEINFO_MIME_TYPE), "$LOCAL_PATH/files/$file_id"); - $ext = $mime_type == "application/pdf" ? "pdf" : ($mime_type == "image/png" ? "png" : "jpg"); - $name = "Autorisation de droit à l'image de " . $user->getFirstName() . " " . $user->getSurname() . "." . $ext; - - $zip->addFile("$LOCAL_PATH/files/$file_id", $name); - } - - $zip->close(); - - return $file_name; -} - -function exportUserData() { - global $DB, $YEAR; - - $file_name = tempnam("tmp", "corres2math-"); - - $csv = "Identifiant,Nom,Prénom,E-mail,École,Ville,Pays,Classe,Description,Rôle,Équipe,Autorise l'envoi de mails,Date d'inscription\n"; - - $req = $DB->query("SELECT `id` FROM `users` WHERE `year` = $YEAR;"); - while (($data = $req->fetch()) !== false) { - $user = User::fromId($data["id"]); - - $csv .= $user->getId() . ","; - $csv .= $user->getSurname() . ","; - $csv .= $user->getFirstName() . ","; - $csv .= $user->getEmail() . ","; - $csv .= $user->getSchool() . ","; - $csv .= $user->getCity() . ","; - $csv .= $user->getCountry() . ","; - $csv .= SchoolClass::getTranslatedName($user->getClass()) . ","; - $csv .= $user->getDescription() . ","; - $csv .= Role::getTranslatedName($user->getRole()) . ","; - $csv .= ($user->getTeamId() == null ? "" : Team::fromId($user->getTeamId())->getTrigram()) . ","; - $csv .= ($user->doReceiveAnimathMails() ? "oui" : "non") . ","; - $csv .= $user->getInscriptionDate() . "\n"; - } - file_put_contents($file_name, $csv, FILE_APPEND); - - return $file_name; -} - -function exportTeamData() { - global $DB, $YEAR; - - $file_name = tempnam("tmp", "corres2math-"); - - $csv = "Identifiant,Nom,Trigramme,Problème,Encadrant,Participant 1,Participant 2,Participant 3,Participant 4,Participant 5," - . "Date d'inscription,Autorise la publication,État de validation,Code d'accès\n"; - - $req = $DB->query("SELECT `id` FROM `teams` WHERE `year` = $YEAR ORDER BY `problem`;"); - while (($data = $req->fetch()) !== false) { - $team = Team::fromId($data["id"]); - - $csv .= $team->getId() . ","; - $csv .= $team->getName() . ","; - $csv .= $team->getTrigram() . ","; - $csv .= $team->getProblem() . ","; - $csv .= $team->getEncadrantId() . ","; - $csv .= $team->getParticipants()[0] . ","; - $csv .= $team->getParticipants()[1] . ","; - $csv .= $team->getParticipants()[2] . ","; - $csv .= $team->getParticipants()[3] . ","; - $csv .= $team->getParticipants()[4] . ","; - $csv .= $team->getInscriptionDate() . ","; - $csv .= $team->allowPublish() . ","; - $csv .= ValidationStatus::getTranslatedName($team->getValidationStatus()) . ","; - $csv .= $team->getAccessCode() . "\n"; - } - file_put_contents($file_name, $csv, FILE_APPEND); - - return $file_name; -} - -function exportProblemsData() { - global $DB, $URL_BASE, $YEAR; - - $file_name = tempnam("tmp", "corres2math-"); - - $csv = "Équipe,Problème,Lien,Équipe 1 ayant reçu la vidéo," - . "Question 1,Pièce jointe,Réponse,Pièce jointe," - . "Question 2,Pièce jointe,Réponse,Pièce jointe," - . "Question 3,Pièce jointe,Réponse,Pièce jointe," - . "Question 4,Pièce jointe,Réponse,Pièce jointe," - . "Question 5,Pièce jointe,Réponse,Pièce jointe," - . "Question 6,Pièce jointe,Réponse,Pièce jointe," - . "Vidéo de réponse," - . "Équipe 2 ayant reçu la vidéo," - . "Question 1,Pièce jointe,Réponse,Pièce jointe," - . "Question 2,Pièce jointe,Réponse,Pièce jointe," - . "Question 3,Pièce jointe,Réponse,Pièce jointe," - . "Question 4,Pièce jointe,Réponse,Pièce jointe," - . "Question 5,Pièce jointe,Réponse,Pièce jointe," - . "Question 6,Pièce jointe,Réponse,Pièce jointe," - . "Vidéo de réponse\n"; - - $req = $DB->query("SELECT `id` FROM `teams` WHERE `validation_status` = 'VALIDATED' AND `year` = $YEAR ORDER BY `problem`;"); - while (($data = $req->fetch()) !== false) { - $team = Team::fromId($data["id"]); - $video = Video::getVideo(Reason::SOLUTION, $team); - $questions_received = Question::getQuestionsTo($team); - - $csv .= $team->getTrigram() . ","; - $csv .= $team->getProblem() . ","; - $csv .= ($video == null ? "" : $video->getLink()) . ","; - for ($i = 0; $i < 2; ++$i) { - /** @var Question[] $questions */ - $questions = $questions_received[$i]; - $asker = Team::fromId($questions[0]->getFrom()); - $csv .= $asker->getTrigram() . ","; - - for ($j = 0; $j < 6; ++$j) { - $question = $questions[$j]; - - if ($question == null) { - $csv .= ",,,,"; - continue; - } - - $csv .= $question->getQuestion() . ","; - $csv .= ($question->getAttachedFile() == null ? "" : $URL_BASE . "/file/" . $question->getAttachedFile()) . ','; - $csv .= $question->getAnswer() . ","; - $csv .= ($question->getAttachedFileAnswer() == null ? "" : $URL_BASE . "/file/" . $question->getAttachedFileAnswer()) . ','; - } - - $answer = Video::getVideo($asker->getVideoTeamIds()[0] == $team->getId() ? Reason::ANSWER1 : Reason::ANSWER2, - $asker, Video::ACCEPTED); - $csv .= $answer == null ? "" : $answer->getLink(); - $csv .= ($i == 0 ? "," : "\n"); - } - } - file_put_contents($file_name, $csv, FILE_APPEND); - - return $file_name; -} - -function displayVideo($link) -{ - if (preg_match("#(https?://|)(www\.|)(youtube\.com/watch\?v=|youtu.be/)([a-zA-Z0-9,\-,_]*)?.*?#", $link, $matches)) { - $code = $matches[4]; - /** @noinspection HtmlDeprecatedAttribute */ - /** @noinspection HtmlDeprecatedTag */ - echo "

\n"; - } - elseif (preg_match("#(https?://|)drive\.google\.com/(file/d/|open\?id=)([a-zA-Z0-9\-_]*)/?.*?#", $link, $matches)) { - $code = $matches[3]; - /** @noinspection HtmlDeprecatedAttribute */ - /** @noinspection HtmlDeprecatedTag */ - echo "

\n"; - } - elseif (preg_match("#(https?://|)(www\.|)vimeo\.com/([0-9]*)#", $link, $matches)) { - $code = $matches[3]; - /** @noinspection HtmlDeprecatedAttribute */ - /** @noinspection HtmlDeprecatedTag */ - echo "
"; - - } - elseif (preg_match("#(https?://|)(www\.|)dailymotion\.com/video/(.*)#", $link, $matches)) { - $code = $matches[3]; - /** @noinspection HtmlDeprecatedAttribute */ - /** @noinspection HtmlDeprecatedTag */ - echo "
"; - } -} \ No newline at end of file diff --git a/server_files/services/mail.php b/server_files/services/mail.php deleted file mode 100644 index f3963eb..0000000 --- a/server_files/services/mail.php +++ /dev/null @@ -1,256 +0,0 @@ -\r\n"; - $headers .= "Reply-To: \"Contact corres2Math\" \r\n"; - $headers .= "Content-Type: text/html; charset=UTF-8\r\n"; - - ensure(mail($email, $subject, $content, $headers), "Un problème est survenu dans l'envoi d'un mail. Veuiller contacter votre administrateur."); - } - - private static function broadcastToTeam(Team $team, $subject, $content, $from = "contact") - { - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - - $encadrant = User::fromId($team->getEncadrantId()); - - if ($encadrant != null) { - $c = preg_replace("#{FIRST_NAME}#", $encadrant->getFirstName(), $content); - $c = preg_replace("#{SURNAME}#", $encadrant->getSurname(), $c); - self::sendMail($encadrant->getEmail(), $subject, $c, $from); - } - - foreach ($team->getParticipants() as $participant_id) { - $participant = User::fromId($participant_id); - if ($participant == null) - continue; - - $c = preg_replace("#{FIRST_NAME}#", $participant->getFirstName(), $content); - $c = preg_replace("#{SURNAME}#", $participant->getSurname(), $c); - self::sendMail($participant->getEmail(), $subject, $c, $from); - } - } - - private static function broadcastToAdmins($subject, $content, $from = "contact") - { - /** @var User $admin */ - foreach (User::getAdmins() as $admin) { - if (!$admin->doReceiveAnimathMails()) - continue; - - $c = preg_replace("#{FIRST_NAME}#", $admin->getFirstName(), $content); - $c = preg_replace("#{SURNAME}#", $admin->getSurname(), $c); - self::sendMail($admin->getEmail(), $subject, $c, $from); - } - } - - private static function getTemplate($name) - { - global $LOCAL_PATH; - return file_get_contents("$LOCAL_PATH/server_files/services/mail_templates/$name.html"); - } - - public static function sendRegisterMail(NewUser $new_user) - { - global $YEAR; - - $content = self::getTemplate("register"); - $content = preg_replace("#{FIRST_NAME}#", $new_user->first_name, $content); - $content = preg_replace("#{SURNAME}#", $new_user->surname, $content); - $content = preg_replace("#{TOKEN}#", $new_user->confirm_email_token, $content); - - self::sendMail($new_user->email, "Inscription aux Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendConfirmEmail(User $user) - { - global $YEAR; - - $content = self::getTemplate("confirm_email"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{TOKEN}#", $user->getConfirmEmailToken(), $content); - - self::sendMail($user->getEmail(), "Confirmation d'adresse e-mail – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendChangeEmailAddressMail(User $user) - { - global $YEAR; - - $content = self::getTemplate("change_email_address"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{TOKEN}#", $user->getConfirmEmailToken(), $content); - - self::sendMail($user->getEmail(), "Changement d'adresse e-mail – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendForgottenPasswordProcedureMail(User $user) - { - global $YEAR; - - $content = self::getTemplate("forgotten_password"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{TOKEN}#", $user->getForgottenPasswordToken(), $content); - - self::sendMail($user->getEmail(), "Mot de passe oublié – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendChangePasswordMail(User $user) - { - global $YEAR; - - $content = self::getTemplate("change_password"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - - self::sendMail($user->getEmail(), "Mot de passe changé – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendAddAdminMail(NewAdmin $new_admin) - { - global $YEAR; - - $content = self::getTemplate("add_admin"); - $content = preg_replace("#{FIRST_NAME}#", $new_admin->first_name, $content); - $content = preg_replace("#{SURNAME}#", $new_admin->surname, $content); - $content = preg_replace("#{PASSWORD}#", $new_admin->password, $content); - - self::sendMail($new_admin->email, "Ajout d'un administrateur – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendAddTeamMail(User $user, Team $team) - { - global $YEAR; - - $content = self::getTemplate("add_team"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - $content = preg_replace("#{ACCESS_CODE}#", $team->getAccessCode(), $content); - if ($team->getProblem() > 0) - $content = preg_replace("#{PROBLEM}#", "pour le problème" . $team->getProblem(), $content); - else - $content = preg_replace("#{PROBLEM}#", "", $content); - - self::sendMail($user->getEmail(), "Ajout d'une équipe – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendJoinTeamMail(User $user, Team $team) - { - global $YEAR; - - $content = self::getTemplate("join_team"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - if ($team->getProblem() > 0) - $content = preg_replace("#{PROBLEM}#", "pour le problème" . $team->getProblem(), $content); - else - $content = preg_replace("#{PROBLEM}#", "", $content); - - self::sendMail($user->getEmail(), "Équipe rejointe – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendRequestValidationMail(Team $team) - { - global $YEAR; - - $content = self::getTemplate("request_validation"); - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - $content = preg_replace("#{PROBLEM}#", $team->getProblem(), $content); - $content = preg_replace("#{ACCESS_CODE}#", $team->getAccessCode(), $content); - - self::broadcastToAdmins("Demande de validation – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendValidateTeam($team, $message) - { - global $YEAR; - - $content = self::getTemplate("validate_team"); - if (strlen($message) > 0) - $message = " L'équipe d'organisation vous transmet le message suivant :\n\n" . $message; - $message = preg_replace("#\n#", "
\n", $message); - $content = preg_replace("#{MESSAGE}#", $message, $content); - - self::broadcastToTeam($team, "Équipe validée – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendUnvalidateTeam($team, $message) - { - global $YEAR; - - $content = self::getTemplate("unvalidate_team"); - if (strlen($message) > 0) - $message = " L'équipe d'organisation vous transmet le message suivant :\n\n" . $message; - $message = preg_replace("#\n#", "
\n", $message); - $content = preg_replace("#{MESSAGE}#", $message, $content); - - self::broadcastToTeam($team, "Équipe non validée – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendNewVideo(NewVideo $video, Team $team) - { - global $YEAR; - - $content = self::getTemplate("new_video"); - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - $content = preg_replace("#{PROBLEM}#", $team->getProblem(), $content); - $content = preg_replace("#{VIDEO_LINK}#", $video->link, $content); - self::broadcastToAdmins("Nouvelle vidéo – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function sendNewAnswer(NewAnswer $video, Team $team) - { - global $YEAR; - - $content = self::getTemplate("new_answer"); - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - $dest = Team::fromId($team->getVideoTeamIds()[$video->team - 1]); - $content = preg_replace("#{DEST_TEAM_NAME}#", $dest->getName(), $content); - $content = preg_replace("#{DEST_TRIGRAM}#", $dest->getTrigram(), $content); - $content = preg_replace("#{PROBLEM}#", $team->getProblem(), $content); - $content = preg_replace("#{VIDEO_LINK}#", $video->link, $content); - - self::broadcastToAdmins("Nouvelle vidéo de réponse – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } - - public static function validateVideo(Video $video, $message) - { - global $YEAR; - - $team = Team::fromId($video->getTeam()); - - $template = "video_"; - $template .= $video->getValidation() == Video::ACCEPTED ? "accepted" : "rejected"; - $template .= $video->getReason() == Reason::SOLUTION ? "_solution" : "_answer"; - $content = self::getTemplate($template); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - $content = preg_replace("#{PROBLEM}#", $team->getProblem(), $content); - $content = preg_replace("#{VIDEO_LINK}#", $video->getLink(), $content); - if (strlen($message) > 0) - $message = " L'équipe d'organisation vous transmet le message suivant :\n\n" . $message . "\n\n"; - $message = preg_replace("#\n#", "
\n", $message); - $content = preg_replace("#{MESSAGE}#", $message, $content); - - self::broadcastToTeam($team, ($video->getValidation() == Video::REJECTED ? "Vidéo refusée " : "Vidéo acceptée ") - . $team->getTrigram() . " – Correspondances des Jeunes Mathématicien·ne·s $YEAR - " . ($YEAR + 1), $content); - } -} diff --git a/server_files/services/mail_templates/add_admin.html b/server_files/services/mail_templates/add_admin.html deleted file mode 100644 index 1f4745d..0000000 --- a/server_files/services/mail_templates/add_admin.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - Administrateur des Correspondances des Jeunes Mathématicien·ne·s - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous recevez ce message (envoyé automatiquement) car vous êtes administrateur pour les Correspondances des Jeunes Mathématicien·ne·s. -Veuillez trouver ci-dessous vos informations d'utilisateur pour le site officiel des inscriptions. Elles vous permettront de gérer les inscriptions des équipes.
-
-Votre mot de passe est : {PASSWORD}
-Vous pouvez vous connecter ici : {URL_BASE}/connexion
-
-Notez bien que ce mot de passe est temporaire, et pour des raisons de sécurité vous devrez le changer lors de votre prochaine connexion sur le site.
-
-Merci beaucoup pour votre aide !
-
-L'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/add_team.html b/server_files/services/mail_templates/add_team.html deleted file mode 100644 index 0b2b0a6..0000000 --- a/server_files/services/mail_templates/add_team.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - Nouvelle équipe Correspondances des Jeunes Mathématicien·ne·s {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de créer l'équipe « {TEAM_NAME} » ({TRIGRAM}) pour les Correspondances des Jeunes Mathématicien·ne·s -{PROBLEM} et nous vous en remercions.
-Afin de permettre aux autres membres de votre équipe de vous rejoindre, veuillez leur transmettre le code d'accès : -{ACCESS_CODE}
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/change_email_address.html b/server_files/services/mail_templates/change_email_address.html deleted file mode 100644 index b61c801..0000000 --- a/server_files/services/mail_templates/change_email_address.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - Changement d'adresse e-mail – Correspondances des Jeunes Mathématicien·ne·s - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de changer votre adresse e-mail. Veuillez désormais la confirmer en cliquant ici : {URL_BASE}/confirmer-mail/{TOKEN}
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/change_password.html b/server_files/services/mail_templates/change_password.html deleted file mode 100644 index f659999..0000000 --- a/server_files/services/mail_templates/change_password.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - Mot de passe changé – Correspondances des Jeunes Mathématicien·ne·s - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Nous vous informons que votre mot de passe vient d'être modifié. Si vous n'êtes pas à l'origine de cette manipulation, -veuillez immédiatement vérifier vos accès à votre boîte mail et changer votre mot de passe sur la plateforme -d'inscription.
-
-Cordialement,
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/confirm_email.html b/server_files/services/mail_templates/confirm_email.html deleted file mode 100644 index 471323f..0000000 --- a/server_files/services/mail_templates/confirm_email.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - Inscription aux Correspondances des Jeunes Mathématicien·ne·s {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous êtes inscrit aux Correspondances des Jeunes Mathématicien·ne·s {YEAR} et nous vous en remercions.
-Pour valider votre adresse e-mail, veuillez cliquer sur le lien : {URL_BASE}/confirmer-mail/{TOKEN}
-
-Cordialement,
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/forgotten_password.html b/server_files/services/mail_templates/forgotten_password.html deleted file mode 100644 index a5aa18a..0000000 --- a/server_files/services/mail_templates/forgotten_password.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - Mot de passe oublié – Correspondances des Jeunes Mathématicien·ne·s - - -Bonjour,
-
-Vous avez indiqué avoir oublié votre mot de passe. Veuillez cliquer ici pour le réinitialiser : {URL_BASE}/connexion/reinitialiser_mdp/{TOKEN}
-
-Si vous n'êtes pas à l'origine de cette manipulation, vous pouvez ignorer ce message.
-
-Cordialement,
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/join_team.html b/server_files/services/mail_templates/join_team.html deleted file mode 100644 index aa63d65..0000000 --- a/server_files/services/mail_templates/join_team.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - Équipe rejointe – Correspondances des Jeunes Mathématicien·ne·s {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de rejoindre l'équipe « {TEAM_NAME} » ({TRIGRAM}) pour les Correspondances des Jeunes Mathématicien·ne·s -{PROBLEM} et nous vous en remercions.
-
-Cordialement,
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/new_answer.html b/server_files/services/mail_templates/new_answer.html deleted file mode 100644 index 3f9fb3c..0000000 --- a/server_files/services/mail_templates/new_answer.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - Nouvelle vidéo – Correspondances des Jeunes Mathématicien·ne·s {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-L'équipe « {TEAM_NAME} » ({TRIGRAM}) vient d'ajouter une vidéo de réponse destinée à l'équipe « {DEST_TEAM_NAME} » ({DEST_TRIGRAM}) -pour le problème {PROBLEM} des Correspondances des Jeunes Mathématicien·ne·s : {VIDEO_LINK}. -Vous êtes désormais invité avant que quelqu'un d'autre ne le fasse à accepter ou refuser cette vidéo via la plateforme d'inscription (accessible après connexion) : -{URL_BASE}/suivi-correspondances
-
-Cordialement,
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/new_video.html b/server_files/services/mail_templates/new_video.html deleted file mode 100644 index b98d2d1..0000000 --- a/server_files/services/mail_templates/new_video.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - Nouvelle vidéo – Correspondances des Jeunes Mathématicien·ne·s {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-L'équipe « {TEAM_NAME} » ({TRIGRAM}) vient d'ajouter une vidéo pour le problème {PROBLEM} des Correspondances des Jeunes Mathématicien·ne·s : {VIDEO_LINK}. -Vous êtes désormais invité avant que quelqu'un d'autre ne le fasse à accepter ou refuser cette vidéo via la plateforme d'inscription (accessible après connexion) : -{URL_BASE}/suivi-correspondances
-
-Cordialement,
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/register.html b/server_files/services/mail_templates/register.html deleted file mode 100644 index ab699c9..0000000 --- a/server_files/services/mail_templates/register.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - Inscription aux Correspondances des Jeunes Mathématicien·ne·s {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de vous inscrire aux Correspondances des Jeunes Mathématicien·ne·s {YEAR} et nous vous en remercions.
-Pour valider votre adresse e-mail, veuillez cliquer sur le lien : {URL_BASE}/confirmer-mail/{TOKEN}
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/request_validation.html b/server_files/services/mail_templates/request_validation.html deleted file mode 100644 index 137166e..0000000 --- a/server_files/services/mail_templates/request_validation.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - Demande de validation - Correspondances des Jeunes Mathématicien·ne·s - - -Bonjour {FIRST_NAME} {SURNAME},
-
-L'équipe « {TEAM_NAME} » ({TRIGRAM}) vient de demander à valider son équipe pour participer au problème n°{PROBLEM} des -Correspondances des Jeunes Mathématicien·ne·s. Vous pouvez décider d'accepter ou de refuser l'équipe en vous rendant sur -la page de l'équipe : {URL_BASE}/equipe/{TRIGRAM}
-
-Cordialement,
-
-L'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/unvalidate_team.html b/server_files/services/mail_templates/unvalidate_team.html deleted file mode 100644 index 3c80990..0000000 --- a/server_files/services/mail_templates/unvalidate_team.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - Équipe non validée – Correspondances des Jeunes Mathématicien·ne·s {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Maleureusement, votre équipe « {TEAM_NAME} » ({TRIGRAM}) n'a pas été validée. Veuillez vérifier que vos autorisations -de droit à l'image sont correctes. -{MESSAGE}
-
-N'hésitez pas à nous contacter à l'adresse contact@correspondances-maths.fr -pour plus d'informations. -
-Cordialement,
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/video_accepted_answer.html b/server_files/services/mail_templates/video_accepted_answer.html deleted file mode 100644 index a3bfe08..0000000 --- a/server_files/services/mail_templates/video_accepted_answer.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - Vidéo acceptée – Correspondances des Jeunes Mathématicien·ne·s {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Félicitations, votre vidéo de réponse pour le problème {PROBLEM} a été validée ! Pour rappel, vous aviez soumis ce lien : {VIDEO_LINK}.
-Vous avez à présent terminé l'aventure des Correspondances. Bravo à vous ! Nous vous recontacterons dans les prochains jours pour vous tenir au courant des résultats.
-Si toutefois vous le souhaitez, vous pouvez à nouveau soumettre une vidéo avant la fin de la phase. Cette nouvelle vidéo ne remplacera l'actuelle qu'au moment de la validation de celle-ci.
-
-N'oubliez pas de contrôler que les paramètres de diffusion de vidéo sont cohérents avec ce que vous souhaitez : {URL_BASE}/mon-equipe
-
-{MESSAGE} -Cordialement,
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/video_accepted_solution.html b/server_files/services/mail_templates/video_accepted_solution.html deleted file mode 100644 index 4c62be8..0000000 --- a/server_files/services/mail_templates/video_accepted_solution.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - Vidéo acceptée – Correspondances des Jeunes Mathématicien·ne·s {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Félicitations, votre vidéo pour le problème {PROBLEM} a été validée ! Pour rappel, vous aviez soumis ce lien : {VIDEO_LINK}.
-Votre travail est à présent terminé, et vous pouvez attendre les prochaines phases. Bravo à vous !
-Si toutefois vous le souhaitez, vous pouvez à nouveau soumettre une vidéo avant la fin de la phase. Cette nouvelle vidéo ne remplacera l'actuelle qu'au moment de la validation de celle-ci.
-
-N'oubliez pas de contrôler que les paramètres de diffusion de vidéo sont cohérents avec ce que vous souhaitez : {URL_BASE}/mon-equipe
-
-{MESSAGE} -Cordialement,
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/video_rejected_answer.html b/server_files/services/mail_templates/video_rejected_answer.html deleted file mode 100644 index fdf4700..0000000 --- a/server_files/services/mail_templates/video_rejected_answer.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - Vidéo refusée – Correspondances des Jeunes Mathématicien·ne·s {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Malheureusement, votre vidéo de réponse pour le problème {PROBLEM} n'a pas été validée. Pour rappel, vous aviez soumis -ce lien : {VIDEO_LINK}.
-Si vous aviez soumis une précédente vidéo qui a été validée, elle reste conservée. -Vous êtes désormais invités à retravailler vos réponses ou votre présentation orale afin que votre prestation soit -validée par les organisateurs. N'hésitez pas à nous contacter à -contact@correspondances-maths.fr si vous souhaitez avoir plus -d'informations ou contester ce refus.
-
-{MESSAGE} -Cordialement,
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/services/mail_templates/video_rejected_solution.html b/server_files/services/mail_templates/video_rejected_solution.html deleted file mode 100644 index 3fe16da..0000000 --- a/server_files/services/mail_templates/video_rejected_solution.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - Vidéo refusée – Correspondances des Jeunes Mathématicien·ne·s {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Malheureusement, votre vidéo pour le problème {PROBLEM} n'a pas été validée. Pour rappel, vous aviez soumis ce lien : -{VIDEO_LINK}.
-Si vous aviez soumis une précédente vidéo qui a été validée, elle reste conservée. -Vous êtes désormais invités à retravailler vos résultats ou votre présentation orale afin que votre prestation soit -validée par les organisateurs. N'hésitez pas à nous contacter à -contact@correspondances-maths.fr si vous souhaitez avoir plus -d'informations ou contester ce refus.
-
-{MESSAGE} -Cordialement,
-
-Le comité d'organisation des Correspondances des Jeunes Mathématicien·ne·s - - \ No newline at end of file diff --git a/server_files/utils.php b/server_files/utils.php deleted file mode 100644 index 6363e82..0000000 --- a/server_files/utils.php +++ /dev/null @@ -1,48 +0,0 @@ - - -
-

Liste des administrateurs

-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
- Nom - - Prénom - - Adresse e-mail -
- getSurname() ?>"> - getSurname() ?> - - - getSurname() ?>"> - getFirstName() ?> - - - - getEmail() ?> - -
- Nom - - Prénom - - Adresse e-mail -
- - - -
-

Ajouter un administrateur

-
- - -
- Administrateur ajouté avec succès ! Ses identifiants ont été transmis par mail. -
- - -
-
-
- - -
- -
- - -
-
- -
-
- - -
-
- -
- -
-
- - diff --git a/server_files/views/ajouter_equipe.php b/server_files/views/ajouter_equipe.php deleted file mode 100644 index df1618a..0000000 --- a/server_files/views/ajouter_equipe.php +++ /dev/null @@ -1,78 +0,0 @@ - - -
-

Ajouter une équipe

-
- - -
- Votre équipe a bien été créée ! Voici le code d'accès à transmettre aux autres membres de votre équipe : - access_code ?> -
- -
- Vous êtes déjà dans une équipe. -
-= $CONFIG->getInscriptionDate()) { ?> -
- La date limite d'inscription est dépassée. -
- - - 0) { ?> -
- Vous êtes déjà inscrit dans une équipe. Vous pouvez toutefois encadrer plusieurs équipes. -
- - -
- Chacune des informations pourra être modifiée avant que l'équipe tant que l'équipe n'est pas validée. -
- -
-
-
- - -
- -
- - -
-
- -
- - -
- - - allow_other_teams ? "checked" : "" ?> required/>
- - - allow_publish ? "checked" : "" ?> /> - -
- Cette dernière option est modifiable à tout moment, et permet à Animath de diffuser les vidéos primées. -
- -
- -
-
- - - diff --git a/server_files/views/calendrier.php b/server_files/views/calendrier.php deleted file mode 100644 index 995eed9..0000000 --- a/server_files/views/calendrier.php +++ /dev/null @@ -1,138 +0,0 @@ - - -
-

Calendrier

-
- - - -
-
- -
- - -
-
- -
- -
- - -
-
- - -
-
- -
- -
- - -
-
- - -
-
- -
- -
- - -
-
- - -
-
- -
- -
- - -
-
- - -
-
- -
- -
-
- - - -
getInscriptionDate() ? "warning" : "success" ?>"> - : - getInscriptionDate(), true) ?> -
- -
"> - : - Du getStartPhase1Date(), true) ?> au - getEndPhase1Date(), true) ?> -
- -
"> - : - Du getStartPhase2Date(), true) ?> au - getEndPhase2Date(), true) ?> -
- -
"> - : - Du getStartPhase3Date(), true) ?> au - getEndPhase3Date(), true) ?> -
- -
"> - : - Du getStartPhase4Date(), true) ?> au - getEndPhase4Date(), true) ?> -
- - - - - - - - -
- - - - - - - -
-

Répondre aux questions

-
- - -
- Votre vidéo a bien été envoyée ! -
- - -
- Pour clore vos Correspondances, vous devez produire, pour chaque vidéo reçue d'une autre équipe, une vidéo de - synthèse d'au plus 4 minutes. - Cette vidéo doit mettre en perspective de la vidéo initiale en tenant compte de l'échange qui a eu lieu. - Vous devez mettre en valeur l’échange questions/réponses, et montrer l'évolution de la résolution au problème. -
- -
- Date limite de soumission : getEndPhase4Date(), true) ?> -
- - -
-

Vidéo de l'équipe getName() ?> (getTrigram() ?>) :

-
- Lien de la vidéo de présentation de la solution au problème : - getLink() ?> -
- getLink()) ?> - -
Questions échangées :
- getQuestion(), Question::DEFAULT_QUESTIONS[0]) - && !strcmp($questions[2]->getQuestion(), Question::DEFAULT_QUESTIONS[1]) - && !strcmp($questions[3]->getQuestion(), Question::DEFAULT_QUESTIONS[2])) { ?> -
- L'équipe n'a malheureusement transmis aucune question. Vous n'avez donc pas de réponse à donner. -
- 0 && $question->getQuestion() === null) - continue; - ?> -
- getNumber() . " :" ?> - getQuestion() ?>
- getAttachedFile() !== null) { ?> - Pièce jointe attachée : - Télécharger
- - Réponse : getAnswer() ?>
- getAttachedFileAnswer() !== null) { ?> - Pièce jointe attachée : - Télécharger
- -
- -
-
Vidéo de réponse :
- - getLink(); - echo "
Lien de la vidéo déjà envoyée : $link (version " . $answer->getVersion() . ")
\n"; - displayVideo($link); - switch ($answer->getValidation()) { - case 0: - echo "
La vidéo n'a pas encore été vérifiée par l'équipe d'organisation.
"; - break; - case 1: - echo "
La vidéo a été acceptée par l'équipe d'organisation.
"; - break; - case -1: - echo "
La vidéo a été rejetée par l'équipe d'organisation.
"; - break; - } - } - if ($answer_validated != null && $answer_validated->getId() != $answer->getId()) { - $link = $answer_validated->getLink(); - echo "
\n
Lien de la dernière vidéo validée : $link
\n"; - displayVideo($link); - } - ?> - -
- -
-
- - -
-
- -
- - - - -
-
- Le mail de récupération de mot de passe a bien été envoyé."; - elseif (isset($reset_password) && isset($_POST["password"])) - echo "
Le mot de passe a bien été changé. Vous pouvez désormais vous connecter.
"; - elseif (isset($_GET["confirmation-mail"])) - echo "
Le mail a bien été renvoyé.
"; - else if (isset($logging_in_user)) { - echo "
Connexion réussie !
"; - require_once "footer.php"; - } else if (isset($_SESSION["user_id"])) { - echo "
Vous êtes déjà connecté !
"; - require_once "footer.php"; - } -} - -if (isset($_GET["mdp_oublie"])) { ?> -
-

Réinitialisation du mot de passe

- - - -
-user != null && ($has_error || !isset($_POST["password"]))) { ?> -
-

Connexion

- "/> -
- - -
-
- - -
- -
- - -
-

Connexion

-
-
- - -
-
- - -
- -
- - - - diff --git a/server_files/views/envoyer_video.php b/server_files/views/envoyer_video.php deleted file mode 100644 index dfa8b23..0000000 --- a/server_files/views/envoyer_video.php +++ /dev/null @@ -1,87 +0,0 @@ - - -
-

Envoyer la vidéo de solution

-
- - -
- Votre vidéo a bien été envoyée ! -
- - -
-
    -
  • Une fois vos travaux sur votre problème terminés, vous êtes invités dans le cadre des Correspondances à tourner - une vidéo dans laquelle vous présentez vos résultats.
  • -
  • La vidéo doit durer au maximum 8 minutes.
  • -
  • Un travail de recherche, en équipe sur les problèmes, supervisé par l'encadrant·e, est attendu.
  • -
  • Au début de la vidéo, une brève présentation de l'énoncé est appréciée.
  • -
  • L'équipe doit présenter ses réponses trouvées aux questions de l'énoncé.
  • -
  • Toutes les plateformes d'hébergement vidéo sont supportées. Néanmoins, les plateformes - Viméo, YouTube - et Dailymotion permettent une prévisualisation de la vidéo. - Cette liste pourra être étendue si besoin est.
  • -
  • Les liens de vos vidéos sont soumis à validation à l'équipe d'organisation.
  • -
-
- -
- Date limite de soumission : getEndPhase1Date(), true) ?> -
- - -
- Vous avez soumis précédemment une vidéo, qui a été refusée par l'équipe d'organisation. Les détails ont du vous être transmis par mail. - Vous êtes désormais invités à poster une nouvelle vidéo, conforme aux attentes. En particulier, vérifiez que votre vidéo n'excède pas - la durée limite de 8 minutes. -
- - -getLink(); - echo "
Lien de la vidéo déjà envoyée : $link (version " . $video->getVersion() . ")
\n"; - displayVideo($link); - switch ($video->getValidation()) { - case 0: - echo "
La vidéo n'a pas encore été vérifiée par l'équipe d'organisation.
"; - break; - case 1: - echo "
La vidéo a été acceptée par l'équipe d'organisation.
"; - break; - case -1: - echo "
La vidéo a été rejetée par l'équipe d'organisation.
"; - break; - } -} -if ($video_validated != null && $video_validated->getId() != $video->getId()) { - $link = $video_validated->getLink(); - echo "
\n
Lien de la dernière vidéo validée : $link
\n"; - displayVideo($link); -} -?> - -
- -
-
-
- - -
-
- -
- - - - -
- - - -
-

Informations sur l'équipe

-
- -
- Nom de l'équipe : getName() ?> -
-
- Trigramme : getTrigram() ?> -
-
- getInscriptionDate() && $team->getValidationStatus() == ValidationStatus::NOT_READY) { ?> - -
- -
- - Problème : - getProblem() == 0 ? "Pas de problème choisi" : $team->getProblem() ?> - - -
-
getValidationStatus() == ValidationStatus::WAITING ? "warning" : "danger") ?>"> - Validation de l'équipe - : getValidationStatus()) ?> -
-
- getEncadrantId() !== null) { - $encadrant = User::fromId($team->getEncadrantId()); - $id = $encadrant->getId(); - echo "Encadrant : getFirstName() . " " . $encadrant->getSurname() . "\">" . $encadrant->getFirstName() . " " . $encadrant->getSurname() . "
"; - } - for ($i = 1; $i <= 5; ++$i) { - if ($team->getParticipants()[$i - 1] == NULL) - continue; - $participant = User::fromId($team->getParticipants()[$i - 1]); - $id = $participant->getId(); - echo "Participant $i : getFirstName() . " " . $participant->getSurname() . "\">" . $participant->getFirstName() . " " . $participant->getSurname() . "
"; - } - ?> -
-
- Autorise Animath à diffuser les vidéos : allowPublish() ? "oui" : "non" ?> -
- - - -getValidationStatus() == ValidationStatus::VALIDATED && $team->getSolution() != null && $team->getSolution()->getValidation() == ValidationStatus::VALIDATED - 1) { ?> -
- - - -
-
-
-
- - -
-
-
- - - -
-
- - -
- -

Autorisations de droit à l'image

- - - -
- -
- -getValidationStatus() == ValidationStatus::WAITING) { ?> -
-
-
- - -
- -
-
- - -
-
-
- getValidationStatus() == ValidationStatus::NOT_READY) { ?> -
-
- -
- \ No newline at end of file diff --git a/server_files/views/exporter_donnees.php b/server_files/views/exporter_donnees.php deleted file mode 100644 index 597f711..0000000 --- a/server_files/views/exporter_donnees.php +++ /dev/null @@ -1,33 +0,0 @@ - - -
-

Exporter les données

-
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -

Ce site a enregistré getViews() ?> visites.

- - - - - -
-
-
-
- Ce site a été conçu pour Animath, avec amour et passion. Il est récent et il est possible que - certaines pages ne fonctionnent pas correctement. Si vous remarquez des bugs, merci de les signaler à - l'adresse contact@correspondances-maths.fr.
- © Correspondances de Jeunes Mathématicien·ne·s -
-
-
- - - diff --git a/server_files/views/header.php b/server_files/views/header.php deleted file mode 100644 index 57b78b8..0000000 --- a/server_files/views/header.php +++ /dev/null @@ -1,177 +0,0 @@ -incrViews() ?> - - - - - - !"> - - - - - Site d'inscription pour les Correspondances des Jeunes Mathématicien·ne·s <?= $YEAR . " - " . ($YEAR + 1) ?> - - - - - - - - - - -
-
-
- - -
- Erreur : -
- -
- Le site est actuellement en maintenance. Veuillez réessayer ultérieurement. -
- - -
-
-

- Bienvenue sur le site d'inscription aux - Correspondances des Jeunes Mathématicien·ne·s ! -

-
-
-
-
-

- Tu souhaites participer aux Correspondances ? -
- Ton équipe est déjà formée ? -

-
- -
- -
-
Comment ça marche ?
-

- Pour participer aux Correspondances, il suffit de créer un compte sur la rubrique Inscription. - Vous devrez ensuite confirmer votre adresse e-mail. -

- -

- Vous pouvez accéder à votre compte via la rubrique Connexion. Une fois connecté, vous pourrez créer une équipe - ou en rejoindre une déjà créée par l'un de vos camarades via un code d'accès qui vous aura été transmis. Vous serez ensuite - invité à soumettre une autorisation de droit à l'image, indispensable au bon déroulement des Correspondances. Une fois que votre équipe - comporte au moins 3 participants (maximum 5) et un encadrant, vous pourrez demander à valider votre équipe pour - être apte à travailler sur le problème de votre choix. -

- -
- Attention aux dates ! Si vous ne finalisez pas votre inscription dans le délai indiqué, vous - ne pourrez malheureusement pas participer aux Correspondances. -
- -
- Si votre équipe est déjà formée mais que vous peinez à trouver un encadrant, n'hésitez pas à nous contacter à l'adresse - contact@correspondances-maths.fr pour que nous vous aidions à - vous mettre éventuellement en contact avec un encadrant de votre région. -
-
- -
\ No newline at end of file diff --git a/server_files/views/index.php b/server_files/views/index.php deleted file mode 100644 index 129d4e5..0000000 --- a/server_files/views/index.php +++ /dev/null @@ -1,76 +0,0 @@ - -
- - - -
- -
- -
-
-getInscriptionDate()) { - if ($_SESSION["teams"] == null || sizeof($_SESSION["teams"]) == 0) { ?> -
- Pour participer aux Correspondances, vous devez rejoindre une équipe. Cliquez ici - pour rejoindre une équipe, et ici pour en créer une. -
- getParticipants()[2] == null || $_SESSION["team"]->getEncadrantId() == null) { ?> -
- Votre équipe doit comporter au moins 3 personnes et un encadrant pour pouvoir participer. Pensez - à transmettre - le code d'accès aux autres membres de votre équipe, qui doivent elles aussi s'inscrire sur la - plateforme : - getAccessCode() ?> -
- getProblem() == 0) { ?> -
- Vous devez indiquer problème pour participer. Pensez à le spécifier dans la page Mon équipe. -
- getValidationStatus() == ValidationStatus::NOT_READY) { ?> -
- Pensez à demander la validation de votre équipe pour pouvoir participer aux Correspondances. - Chaque membre de votre - équipe doit pour cela avoir soumis son autorisation de droit à l'image sur la page Mon compte. - Les encadrants ne sont pas concernés. -
- -
- Vous avez soumis précédemment une vidéo pour l'équipe getName() ?>, qui a été refusée par - l'équipe d'organisation. Les détails ont du vous être transmis par mail. - Vous êtes désormais invités à poster une nouvelle vidéo sur la page dédiée, conforme aux - attentes. En particulier, vérifiez - que votre vidéo n'excède pas la durée limite de 8 minutes. -
- getIndexPage()); - - if (isset($_SESSION["user_id"]) && $_SESSION["role"] == Role::ADMIN) { ?> -
- - Modifier la page - - - -
-

getFirstName() . " " . $user->getSurname() ?>

-
- - -
- La personne a bien été exclue de l'équipe ! -
- -
- La personne a bien rejoint l'équipe ! -
- - -
- Rôle : getRole()) ?> -
- -getRole() == Role::PARTICIPANT || $user->getRole() == Role::ENCADRANT) { ?> -
- Équipe - : getTrigram() . "\">" - . $team->getName() . " (" . $team->getTrigram() . ")" ?> - -
-
-
- - -
-
-
- - - -
-
- getValidationStatus() == ValidationStatus::NOT_READY) { ?> -
- - Virer de l'équipe -
- -
- - -getRole() == Role::PARTICIPANT) { ?> -
- Lycée : getSchool() ?>
- Ville : getCity() ?>
- Pays : getCountry() ?>
- Classe : getClass()) ?> -
-getDescription() != "") { ?> -
- Activité professionnelle : getDescription() ?> -
- - -
- Adresse e-mail : getEmail() ?> - getConfirmEmailToken() == null ? "" : "(non validée)" ?> -
- -
- getRole() == Role::ADMIN ? "Reçoit des notifications par mail :" - : "Autorise Animath à envoyer des mails :" ?> doReceiveAnimathMails() ? "oui" : "non" ?> -
- -getRole() == Role::PARTICIPANT) { ?> -
- -
-

Autorisation de droit à l'image :

-
- getId()) { - if ($user->getRole() != Role::ADMIN && $team == null) { ?> -
- -
- -
- - -
- -
- getSurname() ?>"/> -
- - -
-

Formulaire d'inscription

-
- - -
- Vous êtes bien inscrit ! Merci désormais de confirmer votre boîte mail pour valider votre adresse. Pensez à vérifier - vos courriers indésirables. -
- -
- Vous êtes déjà connecté ! -
-= $CONFIG->getInscriptionDate()) { ?> -
- La date limite d'inscription est dépassée. -
- - -
-
- - -
- -
-
- - -
- -
- - -
-
- -
- L'adresse mail sert uniquement à recevoir les informations de déroulement des Correspondances. -
- -
-
- - -
-
- -
-
- - -
-
- - -
-
- -
-
- - -
-
- - -
-
-
-
- - "/> -
-
- - -
-
- -
- - - -
- - - receive_animath_mails ? "checked" : "" ?> />

- -
- -
-
- - - - - - \ No newline at end of file diff --git a/server_files/views/ma_participation.php b/server_files/views/ma_participation.php deleted file mode 100644 index 3084198..0000000 --- a/server_files/views/ma_participation.php +++ /dev/null @@ -1,132 +0,0 @@ - -= Phase::PHASE1) { ?> -
-

Ma participation

-
- -
-

Vidéo de solution proposée :

-
- Lien de la vidéo : getLink() ?> -
- getLink()) ?> -
- = Phase::PHASE3) { ?> -

Questions reçues :

- getFrom()); - $answer = Video::getVideo($asker->getVideoTeamIds()[0] == $team->getId() ? Reason::ANSWER1 : Reason::ANSWER2, - $asker, Video::ACCEPTED); - ?> -
Questions de l'équipe getName() ?> (getTrigram() ?>) :
- getQuestion() === null) - continue; - ?> -
- - getQuestion() ?> -
- getAttachedFile() !== null) { ?> - Pièce jointe attachée : - Télécharger -
- - Réponse : getAnswer() ?>
- getAttachedFileAnswer() !== null) { ?> - Pièce jointe attachée : - Télécharger -
- -
- -
- Phase::PHASE4 && $answer != null) { ?> -
Vidéo de réponse proposée par l'équipe :
-
- Lien de la vidéo : getLink() ?> -
- getLink()) ?> - " : "" ?> - - - - -
- - = Phase::PHASE2) { ?> -
-
- getVideoTeamIds()[$i]); - if ($defender == null) - continue; - $sol = Video::getVideo(Reason::SOLUTION, $defender, Video::ACCEPTED); - $answer = Video::getVideo($i == 0 ? Reason::ANSWER1 : Reason::ANSWER2, $team, Video::ACCEPTED); - $questions = Question::getQuestions($team, $defender); - ?> -

Vidéo de solution proposée par l'équipe getName() ?> - (getTrigram() ?>) :

-
- Lien de la vidéo : getLink() ?> -
- getLink()) ?> -
-
Vos questions :
-
- getQuestion() === null) - continue; - ?> -
- getNumber() ? "Question " . $question->getNumber() : "Remarques générales" ?> : \n", $question->getQuestion()) ?> -
- getAttachedFile() !== null) { ?> - Pièce jointe attachée : - Télécharger -
- - = Phase::PHASE4) { ?> - Réponse : \n", $question->getAnswer()) ?>
- getAttachedFile() !== null) { ?> - Pièce jointe attachée : - Télécharger -
- - -
- -
- = Phase::PHASE4 && $answer != null) { ?> -
Votre vidéo de réponse :
-
- Lien de la vidéo : getLink() ?> -
- getLink()) ?> - - " : "" ?> - - - - - - -
-

Mon compte

-
- - -
- Le fichier a été correctement envoyé ! -
- - - -
- Votre compte a bien été mis à jour ! -
- getEmail() != $my_account->email) { ?> -
- Votre adresse mail a bien été changée. Veuillez vérifier votre boîte mail pour valider votre nouvelle - adresse, vous en aurez besoin pour vous reconnecter. -
- - - -
- -
-
- - -
- -
- - -
-
- -
-
- - -
-
- - - doReceiveAnimathMails() ? "checked" : "" ?> /> - - getRole() == Role::PARTICIPANT) { ?> -
-
- - -
-
- - -
-
- -
-
- - -
-
- - -
-
- - getRole() == Role::ENCADRANT) { ?> - -
- - -
- - - -
- -
-
- -
- -
- -
-
- - -
- -
- - -
- -
- - -
-
- -
- -
-
- -getRole() == Role::PARTICIPANT) { - $not_validated = $_SESSION["team"]->getValidationStatus() == ValidationStatus::NOT_READY - && date("Y-m-d H:i:s") < $CONFIG->getInscriptionDate(); - ?> -
-
-

Autorisation de droit à l'image

-
- - Ce document peut être modifié tant que l'équipe n'est pas validée. - -
- Modèle d'autorisation de droit à l'image : - majeur - mineur -
- - - -
- Le fichier doit être au format PDF, PNG ou JPEG et doit peser moins de 2 Mo. -
-
- -
-
- - -
-
- -
- -
-
- - - - \ No newline at end of file diff --git a/server_files/views/mon_equipe.php b/server_files/views/mon_equipe.php deleted file mode 100644 index 3c58e77..0000000 --- a/server_files/views/mon_equipe.php +++ /dev/null @@ -1,135 +0,0 @@ - - -
-

Mon équipe

-
- -
- Nom de l'équipe : getName() ?> -
-
- Trigramme : getTrigram() ?> -
-
- Problème : - getProblem() == 0 ? "Pas de problème choisi" : $team->getProblem() ?> -
-
- getEncadrantId() !== null) { - $encadrant = User::fromId($team->getEncadrantId()); - $id = $encadrant->getId(); - echo "Encadrant : " . $encadrant->getFirstName() . " " . $encadrant->getSurname() . "
"; - } - for ($i = 1; $i <= 5; ++$i) { - if ($team->getParticipants()[$i - 1] == NULL) - continue; - $participant = User::fromId($team->getParticipants()[$i - 1]); - $id = $participant->getId(); - echo "Participant $i : " . $participant->getFirstName() . " " . $participant->getSurname() . "
"; - } - - ?> -
-
- Code d'accès : getAccessCode() ?> -
-
- - Autorise Animath à diffuser mes vidéos à la fin des Correspondances : - allowPublish() ? "oui" : "non" ?> (changer) -
- -= $CONFIG->getInscriptionDate() && $team->getValidationStatus() == ValidationStatus::NOT_READY) { ?> -
- La date limite d'inscription est dépassée, vous ne pouvez plus demander la validation de votre équipe. -
-getValidationStatus() == ValidationStatus::NOT_READY) { ?> - -
-
-
- - -
- -
- - -
-
- -
- - -
- -
- -
-
- - - - getValidationStatus() == ValidationStatus::NOT_READY && date("Y-m-d H:i:s") <= $CONFIG->getInscriptionDate()) { ?> - - - - - - getValidationStatus() == ValidationStatus::NOT_READY) { ?> -
- -
- -
- - -
-
- - -
- Attention ! Une fois votre équipe validée, vous ne pourrez plus modifier le nom - de l'équipe, le trigramme, le problème sur lequel vous souhaitez travailler ou la composition de l'équipe. -
- -
- -
-
- Pour demander à valider votre équipe, vous devez avoir au moins un encadrant, trois participants, - choisi un problème et soumis une autorisation de droit à l'image par participant. -
- - getValidationStatus() == ValidationStatus::WAITING) { ?> -
- Votre équipe est en attente de validation. -
- - -
- -

Autorisations de l'équipe

- - - - - \ No newline at end of file diff --git a/server_files/views/poser_questions.php b/server_files/views/poser_questions.php deleted file mode 100644 index 013d788..0000000 --- a/server_files/views/poser_questions.php +++ /dev/null @@ -1,98 +0,0 @@ - - -
-

Poser des questions

-
- - -
- Vos questions ont bien été mises à jour ! -
- - -
- Pour cette deuxième phase des Correspondances, vous êtes invités à visionner les vidéos de solution de deux autres - équipes, qui ont travaillé sur le même problème que vous. Vous devez désormais poser entre 3 et 6 questions, portant - sur la présentation de l'équipe. Chaque question peut-être accompagnée d'une pièce jointe (dessin, schéma, ...) - sous toute forme (PDF, image, archive, ...) tant que le poids ne dépasse pas 2 Mo. Si vous le souhaitez, vous pouvez - adresser aux équipes des remarques plus générales. -
- -
- Date limite de soumission des questions : getEndPhase2Date(), true) ?> -
- -
-

Veuillez toujours enregistrer votre travail ailleurs que sur la plateforme !

-
- - -
-

Questions pour l'équipe getName() ?> (getTrigram() ?>) :

-
- Lien de la vidéo : getLink() ?> -
- getLink()) ?> -
-
- - - getQuestion() == null && $j > 0) { ?> - " - onclick="addQuestion(, )">Ajouter une question -
- -
;"> -
- - -
- - getAttachedFile() != null) { ?> -
-
- Pièce jointe : Télécharger -
- - -
- - -
-
- - - - - -
-
- - - - -
-

- -

-
- -
- -

Équipes inscrites 0 ? "pour ce problème" : "sans problème choisi" ?> :

- - - - - - - - 0) { ?> - - - - - - - - - - - 0) { ?> - - - - - - - - - - - 0) { ?> - - - - -
- Équipe - - Trigramme - - Date d'inscription - - État de validation de l'inscription -
- getTrigram() . "\">" . $team->getName() . ""; - else - echo $team->getName(); - ?> - getTrigram() ?>getInscriptionDate()) ?>getValidationStatus()) ?>
- Équipe - - Trigramme - - Date d'inscription - - État de validation de l'inscription -
- - - - - diff --git a/server_files/views/profiles.php b/server_files/views/profiles.php deleted file mode 100644 index cc8f2e6..0000000 --- a/server_files/views/profiles.php +++ /dev/null @@ -1,63 +0,0 @@ - - -
-

-
- -
- Cette page recense tous les utilisateurs inscrits. -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
- Nom - - Rôle - - Inscrit le -
- getFirstName() . " " . $user->getSurname() ?>"> - getFirstName() . " " . $user->getSurname() ?> - - getRole()) ?>getInscriptionDate(), true) ?>
- Nom - - Rôle - - Inscrit le -
- - - -
-

Rejoindre une équipe

-
- - -
- Vous avez bien rejoint l'équipe getName() ?> ! -
-= $CONFIG->getInscriptionDate()) { ?> -
- La date limite d'inscription est dépassée. -
- - - 0) { ?> -
- Vous êtes déjà inscrit dans une équipe. Vous pouvez toutefois encadrer plusieurs équipes. -
- - -
-
-
- - -
-
- -
- -
-
- - - - \ No newline at end of file diff --git a/server_files/views/repondre_questions.php b/server_files/views/repondre_questions.php deleted file mode 100644 index ca578bc..0000000 --- a/server_files/views/repondre_questions.php +++ /dev/null @@ -1,93 +0,0 @@ - - -
-

Répondre aux questions

-
- - -
- Vos réponses ont bien été mises à jour ! -
- - -
- Deux autres équipes ayant travaillé sur le même problème que vous vous ont posé quelques questions. Afin de faire - avancer l'échange, vous êtes invités à répondre à leurs interrogations. Vous êtes libres d'ajouter à votre souhait - un paragraphe de remarques. -
- -
- Date limite de soumission des réponses : getEndPhase3Date(), true) ?> -
- -
- Lien de la vidéo : getLink() ?> -
- -getLink()); ?> - -getFrom()); - $remark = $questions_team[0]; - echo "

Questions de l'équipe " . $from->getName() . " (" . $from->getTrigram() . ") :

\n"; - if (!strcmp($questions_team[1]->getQuestion(), Question::DEFAULT_QUESTIONS[0]) - && !strcmp($questions_team[2]->getQuestion(), Question::DEFAULT_QUESTIONS[1]) - && !strcmp($questions_team[3]->getQuestion(), Question::DEFAULT_QUESTIONS[2])) { ?> -
- L'équipe n'a malheureusement transmis aucune question. Vous n'avez donc pas de réponse à donner. -
- -
- - - 0 && $question->getQuestion() == null) - continue; - ?> -
- getNumber() . " :" ?> - getQuestion() ?>
- getAttachedFile() != null) { ?> - Pièce jointe : - Télécharger
- -
-
- - -
-
- getAttachedFileAnswer() != null) { ?> - Pièce jointe : - Télécharger - -
-
- - -
-
-
- - - - -
-
- - - - - -
-

Suivi des Correspondances

-
- - 0) { ?> -
- pas encore - participé à la phase en cours : - pas encore participé à la phase en cours, ou leurs vidéos n'ont pas encore été validées : - - subject=Correspondances de Jeunes Mathématicien·ne·s" - target="_blank">Leur envoyer un mail -
- - -
- subject=Correspondances de Jeunes Mathématicien·ne·s" target="_blank"> - - - -
- - -
-

Vidéos pour le problème

-
- getLink(); - $team = Team::fromId($video->getTeam()); - $version = $video->getVersion(); - ?> -
-

- Équipe « getName() ?> » (getTrigram() ?>) -

-
- Lien de la vidéo (version ) : -
- getValidation() <= 0) { ?> -
- - - -
- - -
- - - getValidation() == 0) { ?> - - -
-
- getValidation() != 0) { ?> -
"> - La vidéo a été getValidation() == 1 ? "acceptée" : "refusée" ?>. -
- getValidation() != Video::ACCEPTED) { - $last_validated_video = Video::getVideo(Reason::SOLUTION, $team, Video::ACCEPTED); - if ($last_validated_video !== null) { - $link = $last_validated_video->getLink(); ?> -
- Lien de la vidéo validée de cette équipe (version ) : - -
- Phase::PHASE1) { - /** @var Question[] $from_questions */ - foreach (Question::getQuestionsTo($team) as $from_questions) { - - $from = Team::fromId($from_questions[0]->getFrom()); - echo "
Questions posées par l'équipe " . $from->getName() . " (" . $from->getTrigram() . ") :
\n"; - if (!strcmp($from_questions[1]->getQuestion(), Question::DEFAULT_QUESTIONS[0]) - && !strcmp($from_questions[2]->getQuestion(), Question::DEFAULT_QUESTIONS[1]) - && !strcmp($from_questions[3]->getQuestion(), Question::DEFAULT_QUESTIONS[2])) { ?> -
"> - Cette équipe n'a pas envoyé ses questions. -
- 0 && $question->getQuestion() == null) - continue; - - echo "
\n"; - echo "" . ($i == 0 ? "Remarques générales :" : "Question " . $i . " :") . " " . preg_replace("#\n#", "
\n", $question->getQuestion()) . "
\n"; - if ($question->getAttachedFile() != null) - echo "Pièce jointe attachée : getAttachedFile() . "\">Télécharger
\n"; - if ($question->getAnswer() != null) - echo "Réponse apportée : " . preg_replace("#\n#", "
\n", $question->getAnswer()) . "
\n"; - if ($question->getAttachedFileAnswer() != null) - echo "Pièce jointe attachée pour la réponse : getAttachedFileAnswer() . "\">Télécharger
\n"; - echo "
\n"; - } - echo "
\n"; - if (Phase::getCurrentPhase() >= Phase::PHASE4) { - $answer = Video::getVideo($from->getVideoTeamIds()[0] == $team->getId() ? Reason::ANSWER1 : Reason::ANSWER2, $from); - if ($answer == null) - continue; - $link = $answer->getLink(); - $version = $answer->getVersion(); - echo "
Vidéo de réponse :
\n"; - echo "Lien de la vidéo (version $version) : $link"; - displayVideo($link); - - if ($answer->getValidation() == 0) { ?> -
- - - -
- - -
- - - getValidation() == 0) { ?> - - -
-
- getValidation() != 0) { ?> -
"> - La vidéo a été getValidation() == 1 ? "acceptée" : "refusée" ?>. -
- getValidation() != Video::ACCEPTED) { - $last_validated_answer = Video::getVideo($from->getVideoTeamIds()[0] == $team->getId() ? Reason::ANSWER1 : Reason::ANSWER2, $team, Video::ACCEPTED); - if ($last_validated_answer !== null) { - $link = $last_validated_answer->getLink(); - echo "\n
\nLien de la dernière vidéo validée de cette équipe : $link
\n"; - displayVideo($link); - } - } - } - } - } - } ?> -
- \n"; -} - -require_once "footer.php"; \ No newline at end of file diff --git a/setup/create_database.sql b/setup/create_database.sql deleted file mode 100644 index 10aefe1..0000000 --- a/setup/create_database.sql +++ /dev/null @@ -1,146 +0,0 @@ --- phpMyAdmin SQL Dump --- version 4.7.5 --- https://www.phpmyadmin.net/ --- --- Hôte : db --- Généré le : mar. 22 oct. 2019 à 13:10 --- Version du serveur : 5.7.20 --- Version de PHP : 7.1.9 - -SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; -SET AUTOCOMMIT = 0; -START TRANSACTION; -SET time_zone = "+00:00"; - - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8mb4 */; - --- --- Base de données : `inscription_corres2math` --- - --- -------------------------------------------------------- - --- --- Structure de la table `config` --- - -CREATE TABLE IF NOT EXISTS `config` ( - `key` varchar(64) NOT NULL, - `value` varchar(8192) NOT NULL, - PRIMARY KEY (`key`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- -------------------------------------------------------- - --- --- Structure de la table `documents` --- - -CREATE TABLE IF NOT EXISTS `documents` ( - `file_id` varchar(64) NOT NULL, - `user` int(11) NOT NULL, - `team` int(11) NOT NULL, - `problem` int(11) NOT NULL, - `uploaded_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`file_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- -------------------------------------------------------- - --- --- Structure de la table `questions` --- - -CREATE TABLE IF NOT EXISTS `questions` ( - `id` int(8) NOT NULL AUTO_INCREMENT, - `from` int(8) NOT NULL, - `to` int(8) NOT NULL, - `problem` int(8) NOT NULL, - `number` int(8) NOT NULL, - `question` varchar(1024) DEFAULT NULL, - `attached_file` varchar(64) DEFAULT NULL, - `answer` varchar(1024) DEFAULT NULL, - `attached_file_answer` varchar(64) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- -------------------------------------------------------- - --- --- Structure de la table `teams` --- - -CREATE TABLE IF NOT EXISTS `teams` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `name` varchar(64) NOT NULL, - `trigram` varchar(3) NOT NULL, - `problem` int(8) NOT NULL, - `encadrant` int(8) DEFAULT NULL, - `participant_1` int(8) DEFAULT NULL, - `participant_2` int(8) DEFAULT NULL, - `participant_3` int(8) DEFAULT NULL, - `participant_4` int(8) DEFAULT NULL, - `participant_5` int(8) DEFAULT NULL, - `inscription_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `allow_publish` tinyint(1) NOT NULL DEFAULT '0', - `validation_status` varchar(64) NOT NULL, - `video_team1` int(11) DEFAULT NULL, - `video_team2` int(11) DEFAULT NULL, - `access_code` varchar(6) NOT NULL, - `year` int(4) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- -------------------------------------------------------- - --- --- Structure de la table `users` --- - -CREATE TABLE IF NOT EXISTS `users` ( - `id` int(8) NOT NULL AUTO_INCREMENT, - `email` varchar(255) NOT NULL, - `pwd_hash` varchar(64) NOT NULL, - `surname` varchar(255) NOT NULL, - `first_name` varchar(255) NOT NULL, - `school` varchar(255) DEFAULT NULL, - `city` varchar(256) DEFAULT NULL, - `country` varchar(256) DEFAULT NULL, - `class` varchar(255) DEFAULT NULL, - `description` varchar(255) DEFAULT NULL, - `role` varchar(64) NOT NULL, - `team_id` int(8) DEFAULT NULL, - `receive_animath_mails` tinyint(1) NOT NULL DEFAULT '0', - `year` int(4) NOT NULL DEFAULT '2020', - `confirm_email` varchar(64) DEFAULT NULL COMMENT 'Jeton de confirmation d''e-mail', - `forgotten_password` varchar(64) DEFAULT NULL COMMENT 'Jeton de récupération de mot de passe', - `inscription_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- -------------------------------------------------------- - --- --- Structure de la table `videos` --- - -CREATE TABLE IF NOT EXISTS `videos` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `team` int(8) NOT NULL, - `problem` int(8) NOT NULL, - `link` varchar(128) NOT NULL, - `reason` varchar(64) NOT NULL, - `validation` tinyint(1) NOT NULL DEFAULT '0', - `uploaded_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `year` int(4) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -COMMIT; - -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/setup/msmtprc b/setup/msmtprc deleted file mode 100644 index 0be3f65..0000000 --- a/setup/msmtprc +++ /dev/null @@ -1,18 +0,0 @@ -defaults -auth on -tls on -tls_starttls off -tls_trust_file /etc/ssl/certs/ca-certificates.crt -syslog on -logfile /var/log/msmtp.log - -account corres2math -host ssl0.ovh.net -auth on -port 465 -from contact@correspondances-maths.fr -user contact@correspondances-maths.fr -passwordeval "echo $CORRES2MATH_MAIL_PASSWORD" - -# Set a default account -account default : corres2math diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..bb02e3c --- /dev/null +++ b/tox.ini @@ -0,0 +1,46 @@ +[tox] +envlist = + py38 + py39 + + linters +skipsdist = True + +[testenv] +sitepackages = True +deps = + -r{toxinidir}/requirements.txt + coverage +commands = + coverage run --omit='*migrations*,apps/scripts*' --source=apps ./manage.py test apps/ + coverage report -m + +[testenv:linters] +deps = + flake8 + flake8-colors + flake8-django + flake8-import-order + flake8-typing-imports + pep8-naming + pyflakes +commands = + flake8 apps/ + +[flake8] +exclude = + .tox, + .git, + __pycache__, + build, + dist, + *.pyc, + *.egg-info, + .cache, + .eggs, + *migrations* +max-complexity = 10 +max-line-length = 160 +import-order-style = google +application-import-names = flake8 +format = ${cyan}%(path)s${reset}:${yellow_bold}%(row)d${reset}:${green_bold}%(col)d${reset}: ${red_bold}%(code)s${reset} %(text)s