diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml old mode 100644 new mode 100755 diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 index 084cd0b..6284f95 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ -actions/database.php .vscode/ .idea/ .last_log_cleanup \ No newline at end of file diff --git a/.htaccess b/.htaccess old mode 100644 new mode 100755 index bd15835..d00e7d7 --- a/.htaccess +++ b/.htaccess @@ -2,7 +2,10 @@ DirectoryIndex index.php RewriteEngine On +# Force HTTPS en production, mais pas en local (localhost / LAN privé) RewriteCond %{HTTPS} !=on +RewriteCond %{HTTP_HOST} !^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$ +RewriteCond %{REMOTE_ADDR} !^(127\.0\.0\.1|::1|10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.) RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] ErrorDocument 403 /errors/403.php diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md old mode 100644 new mode 100755 index d08588f..378fccc --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,42 +1,42 @@ -# Code de Conduite - BookFind - -Nous vous remercions de l'intérêt que vous portez à **BookFind**. Afin de créer un environnement respectueux et accueillant, ce Code de Conduite décrit les comportements attendus de la part de chaque contributeur au projet. - ---- - -## Comportement attendu - -Tous les contributeurs doivent : - -- Faire preuve de respect et de bienveillance envers les autres membres de la communauté. -- Maintenir une attitude constructive, même en cas de désaccord. -- Respecter le travail et les décisions des autres. -- Éviter les propos ou comportements offensants, abusifs, ou discriminatoires. - -## Propriété et Licence - -Ce projet **BookFind** est sous licence [MIT](LICENSE), propriété exclusive de **Chromared**. - -### Droits de Chromared - -- **Chromared** se réserve le droit de modifier, d'ajuster ou de refuser toute contribution qui ne serait pas conforme aux valeurs ou aux besoins du projet. -- **Chromared** conserve tous les droits d’auteur sur le code source de **BookFind**, y compris le droit de le distribuer ou de le publier. - -## Reproduction, Modification et Attribution - -- Toute modification, copie ou utilisation de ce code, en tout ou en partie, dans d’autres projets ou environnements externes, doit mentionner explicitement **Chromared** en tant que créateur et propriétaire du code. -- Si le code est réutilisé ou adapté, il est impératif de citer l’origine du code et de fournir un lien vers le dépôt source, conformément à la licence MIT. - -## Signalement de Comportements Inappropriés - -Si vous êtes témoin de comportements inappropriés ou si vous avez des questions concernant ce Code de Conduite, veuillez contacter **Chromared** via les canaux officiels du projet. - -## Modifications du Code de Conduite - -**Chromared** se réserve le droit de mettre à jour ou de modifier ce Code de Conduite à tout moment, pour répondre aux besoins évolutifs de la communauté et du projet. - -En contribuant à **BookFind**, vous acceptez de respecter ce Code de Conduite et vous engagez à collaborer dans le respect et la transparence. - ---- - -Nous apprécions votre soutien et vos contributions pour faire de **BookFind** un projet de qualité dans un environnement accueillant pour tous. +# Code of Conduct - BookFind + +Thank you for your interest in **BookFind**. In order to create a respectful and welcoming environment, this Code of Conduct describes the behavior expected from every contributor to the project. + +--- + +## Expected behavior + +All contributors must: + +- Be respectful and kind to other members of the community. +- Maintain a constructive attitude, even when disagreeing. +- Respect the work and decisions of others. +- Avoid offensive, abusive, or discriminatory remarks or behavior. + +## Ownership and License + +This **BookFind** project is licensed under [AGPL-3.0](LICENSE), exclusively owned by **Chromared**. + +### Chromared's Rights + +- **Chromared** reserves the right to modify, adjust, or reject any contribution that does not comply with the project's values or needs. +- **Chromared** retains all copyright on the **BookFind** source code, including the right to distribute or publish it. + +## Reproduction, Modification and Attribution + +- Any modification, copy or use of this code, in whole or in part, in other projects or external environments, must explicitly credit **Chromared** as the creator and owner of the code. +- If the code is reused or adapted, it is mandatory to cite the origin of the code and provide a link to the source repository, in accordance with the AGPL-3.0 license. + +## Reporting Inappropriate Behavior + +If you witness inappropriate behavior or have questions about this Code of Conduct, please contact **Chromared** through the project's official channels. + +## Changes to the Code of Conduct + +**Chromared** reserves the right to update or modify this Code of Conduct at any time, to meet the evolving needs of the community and the project. + +By contributing to **BookFind**, you agree to respect this Code of Conduct and commit to collaborating with respect and transparency. + +--- + +We appreciate your support and contributions to make **BookFind** a quality project in a welcoming environment for everyone. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md old mode 100644 new mode 100755 index 1971066..ab773ec --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,78 +1,77 @@ -# Guide de Contribution - BookFind - -Merci de vouloir contribuer à **BookFind** ! Ce guide décrit les étapes pour contribuer efficacement au projet. - -## Table des matières - -1. [Code de Conduite](#code-de-conduite) -2. [Comment Contribuer](#comment-contribuer) -3. [Configuration de l'Environnement](#configuration-de-lenvironnement) -4. [Style de Code](#style-de-code) -5. [Proposition de Fonctionnalités](#proposition-de-fonctionnalités) -6. [Signalement de Problèmes](#signalement-de-problèmes) -7. [Processus de Demande de Tirage (Pull Request)](#processus-de-demande-de-tirage-pull-request) - ---- - -## Code de Conduite - -Ce projet adhère à un [Code de Conduite](CODE_OF_CONDUCT.md) afin de garantir un environnement respectueux pour tous les contributeurs. - -## Comment Contribuer - -### Types de Contributions - -- **Corrections de bugs** : Identifiez, corrigez et signalez des erreurs. -- **Améliorations de fonctionnalités** : Proposez des améliorations pour les fonctionnalités existantes. -- **Documentation** : Aidez à améliorer la documentation en ajoutant des exemples ou en clarifiant les sections. - -### Processus de Contribution - -1. **Fork le dépôt** et clonez-le localement. -2. Créez une nouvelle branche avec un nom descriptif (ex : `feature`). -3. Effectuez vos modifications sur cette branche. -4. Testez et assurez-vous que le code est fonctionnel avant de faire une demande de tirage (pull request). - -## Configuration de l'Environnement - -1. Assurez-vous d’avoir installé les versions requises de PHP et MySQL. -2. Cloner le projet : - ```bash - git clone https://github.com/chromared/bookfind.git - ``` -3. Installez les dépendances requises et configurez votre base de données locale comme décrit dans le fichier `README.md`. -4. Vérifiez que toutes les pages fonctionnent correctement après chaque changement. - -## Style de Code - -- **Indentation** : Utilisez des espaces (4 par niveau d’indentation). -- **Nommage** : Utilisez des noms de variables et de fonctions explicites en anglais. -- **Commentaires** : Commentez les parties complexes du code pour faciliter la compréhension des autres contributeurs. - -## Proposition de Fonctionnalités - -Si vous souhaitez proposer une nouvelle fonctionnalité : - -1. **Ouvrez une issue** pour discuter de l'idée avec les mainteneurs. -2. Fournissez une description détaillée de la fonctionnalité et des raisons de son ajout. -3. Attendez les retours avant de commencer à travailler dessus. - -## Signalement de Problèmes - -Pour signaler un problème : - -1. **Ouvrez une issue** avec un titre clair et une description détaillée. -2. Fournissez les étapes pour reproduire le problème, les résultats attendus, et les résultats obtenus. -3. Joignez des captures d’écran si cela aide à mieux comprendre le problème. - -## Processus de Demande de Tirage (Pull Request) - -1. **Vérifiez que le code est testé** et respecte les directives de style. -2. **Faites une pull request** depuis votre branche vers `main`. -3. **Décrivez vos changements** dans la pull request et mentionnez l'issue concernée (si applicable). -4. **Attendez la revue** d’un mainteneur qui pourra fusionner votre contribution. - -Merci de suivre ces instructions ! Avec votre aide, nous pouvons améliorer **BookFind** pour tous les utilisateurs. - ---- - +# Contribution Guide - BookFind + +Thank you for wanting to contribute to **BookFind**! This guide describes the steps to contribute effectively to the project. + +## Table of contents + +1. [Code of Conduct](#code-of-conduct) +2. [How to Contribute](#how-to-contribute) +3. [Environment Setup](#environment-setup) +4. [Code Style](#code-style) +5. [Proposing Features](#proposing-features) +6. [Reporting Issues](#reporting-issues) +7. [Pull Request Process](#pull-request-process) + +--- + +## Code of Conduct + +This project adheres to a [Code of Conduct](CODE_OF_CONDUCT.md) to ensure a respectful environment for all contributors. + +## How to Contribute + +### Types of Contributions + +- **Bug fixes**: Identify, fix and report errors. +- **Feature improvements**: Propose improvements for existing features. +- **Documentation**: Help improve the documentation by adding examples or clarifying sections. + +### Contribution Process + +1. **Fork the repository** and clone it locally. +2. Create a new branch with a descriptive name (e.g. `feature`). +3. Make your changes on this branch. +4. Test and make sure the code works before submitting a pull request. + +## Environment Setup + +1. Make sure you have the required versions of PHP and MySQL installed. +2. Clone the project: + ```bash + git clone https://github.com/chromared/bookfind.git + ``` +3. Install the required dependencies and configure your local database as described in the `README.md` file. +4. Verify that all pages work correctly after each change. + +## Code Style + +- **Indentation**: Use spaces (4 per indentation level). +- **Naming**: Use explicit variable and function names in English. +- **Comments**: Comment complex parts of the code to make them easier for other contributors to understand. + +## Proposing Features + +If you want to propose a new feature: + +1. **Open an issue** to discuss the idea with the maintainers. +2. Provide a detailed description of the feature and the reasons for adding it. +3. Wait for feedback before starting to work on it. + +## Reporting Issues + +To report a problem: + +1. **Open an issue** with a clear title and a detailed description. +2. Provide the steps to reproduce the problem, the expected results, and the actual results. +3. Attach screenshots if it helps to better understand the problem. + +## Pull Request Process + +1. **Make sure the code is tested** and follows the style guidelines. +2. **Submit a pull request** from your branch to `main`. +3. **Describe your changes** in the pull request and mention the relevant issue (if applicable). +4. **Wait for review** by a maintainer who can merge your contribution. + +Thank you for following these instructions! With your help, we can improve **BookFind** for all users. + +--- diff --git a/LICENSE b/LICENSE index 9bc9774..0d2bc4a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,15 +1,661 @@ -Copyright (c) 2026 cheomared (BookFind) - -This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. - -You are free to: -- Share — copy and redistribute the material in any medium or format -- Adapt — remix, transform, and build upon the material - -Under the following terms: -- Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. -- NonCommercial — You may not use the material for commercial purposes. -- ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original. - -To view a copy of this license, visit: -http://creativecommons.org/licenses/by-nc-sa/4.0/ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 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 Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero 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. + + BookFind - CDI library management web application + Copyright (C) 2025 Chromared + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see +. diff --git a/README.md b/README.md old mode 100644 new mode 100755 index a7f3da5..4bca4fb --- a/README.md +++ b/README.md @@ -1,115 +1,112 @@ -# BookFind - -**BookFind** est une application web destinée aux utilisateurs d'un Centre de Documentation et d'Information (CDI). Elle permet la recherche et l'emprunt de livres via une interface intuitive et une gestion sécurisée des utilisateurs. - ---- - -## Table des matières - -1. [Aperçu du Projet](#aperçu-du-projet) -2. [Fonctionnalités](#fonctionnalités) -3. [Structure du Projet](#structure-du-projet) -4. [Installation](#installation) -5. [Configuration de la base de données](#configuration-de-la-base-de-donnée) -6. [Utilisation](#utilisation) -7. [Dépendances](#dépendances) -8. [Licence](#licence) - ---- - -## Aperçu du Projet - -Le projet **BookFind** est conçu pour simplifier la gestion des emprunts de livres au sein d’un CDI. L’application permet aux utilisateurs : -- De rechercher des ouvrages disponibles -- D'emprunter des livres -- De consulter leurs emprunts en cours -- D'accéder aux fonctionnalités protégées àils sont gradés - -Cette application offre une solution efficace pour le personnel du CDI et leurs utilisateurs. - -## Fonctionnalités - -- **Page d'accueil** : Présentation de l'application et formulaire de recherche de livres. -- **Recherche de livres** : Interface permettant aux utilisateurs de trouver des livres en fonction de leur titre. -- **Gestion des emprunts** : Permet de voir les livres empruntés et l'historique d'emprunt. -- **Connexion et profil utilisateur** : Authentification avec mot de passe crypté, accès aux fonctionnalités réservées, ainsi qu'un espace pour gérer son profil ou modifier le profil d'un utilisateur si on est gradé. Les parties modifiables varient en fonction du niveau de permission. - -## Structure du Projet - -- `index.php` : Page principale de l'application, introduisant le service de recherche de livres. -- `login.php` : Page de connexion pour authentifier les utilisateurs. -- `books.php` : Page de recherche de livres avec un formulaire pour entrer des critères de recherche. -- `profil.php` : Interface permettant aux utilisateurs de consulter et de modifier leurs informations personnelles. -- `emprunts.php` : Page où l'utilisateur peut voir les livres qu'il a empruntés. -- `pdc.php` : Page affichant les politiques de confidentialité et les conditions d'utilisation. -- `rules.php` : Page affichant le règlement. - -### Répertoires - -- `actions/` : Contient les scripts PHP et JavaScript pour les actions, comme la connexion à la base de données, l´enregistrement d'un livre et le fonctionnement du site en général. -- `includes/` : Composants inclus dans les différentes pages, comme le `header.php`, la `navbar.php` et le `footer.php` pour un affichage cohérent. Ce dossier sert à centraliser des bouts de code qui n'auront pas à être répétés et où le changement impacteront toutes les pages. -- `assets/` : Ressources telles que les fichiers CSS, images et icones. -- `temp/` : Contient les fichiers temporaires. - -## Installation - -1. **Cloner le dépôt ou télécharger le ZIP** : - ```bash - git clone https://github.com/chromared/bookfind.git - ``` -2. **Configuration du serveur local** : - - Utilisez XAMPP, WAMP, ou un autre serveur avec PHP et MySQL. -3. **Déplacer le projet** : - - Placez le dossier extrait dans le répertoire racine de votre serveur web (en général `htdocs` sur les serveurs web et XAMPP ou `www` pour WAMP et uWAMP). - -## Configurer BookFind - -1. Dans votre navigateur, rendez-vous sur le fichier `configuration.php`. -2. Suivez les actions **dans l'ordre** pour configurer la base de donnée, les classes de votre établissement... -3. Quand vous avez fini, cliquez sur le bouton qui est apparu permettant de supprimer le fichier `configuration.php`. Cette action est nécessaire pour des raisons de sécurité. Le fichier ne doit pas rester accessible après la configuration. - -## Utilisation - -### Étapes d'utilisation de l'application - -1. **Accéder à la Page d'accueil** : Rendez-vous sur `index.php` pour une vue d'ensemble et un accès rapide à la recherche de livres. -2. **Créer un compte et se connecter** : - - Allez sur `signup.php` ou `login.php` pour créer un compte ou vous connecter. -3. **Rechercher des livres** : - - Utilisez `books.php` pour explorer les livres disponibles. -4. **Voir et gérer le profil** : - - Consultez et modifiez vos informations personnelles sur `profil.php`. -5. **Suivre les emprunts** : - - Rendez-vous sur `emprunts.php` pour consulter vos livres empruntés et leur statut. -6. **Gestion** : - - Pour les gradés, un lien "Gestion" apparaît dans la barre de navigation. En fonction de vos permissions, ce lien vous permettera d'accéder à certaines options de configuration du site ou du C.D.I. - -## Environnement - -- **Serveur Web** : Apache. -- **PHP** : version 8.3 ou supérieure. -- **MySQL** : version 8.4 ou supérieure. - -## Dépendances - -- **Aucune** : Il n'y a pour l'instant pas de dépendances nécessaires au fonctionnement de BookFind. - -## Liste des contributeurs - -### Contributeurs actifs - -- [Alban Muller / @MythUp_](https://github.com/MythUp) --> Full Stack -- [@Jià N0w](https://github.com/JiaN0w) --> Gestion dépôt GitHub -- [@DawnFolk](https://github.com/DawnFolk) --> Pentest - -### Contributeurs passifs - -- [Mitali Jadhavro / Coding Artist](https://codingartistweb.com/) --> Frontend (JS = [action/fonction/title.js](https://github.com/Chromared/bookfind/blob/main/actions/functions/title.js)) - -## Licence - -Ce projet est distribué selon les termes de la license [MIT]. 2026 Chromared. - ---- - -[MIT]: https://opensource.org/licenses/MIT +# BookFind + +**BookFind** is a web application for users of a Documentation and Information Center (CDI). It allows searching for and borrowing books through an intuitive interface with secure user management. + +--- + +## Table of contents + +1. [Project overview](#project-overview) +2. [Features](#features) +3. [Project structure](#project-structure) +4. [Installation](#installation) +5. [Database configuration](#database-configuration) +6. [Usage](#usage) +7. [Dependencies](#dependencies) +8. [License](#license) + +--- + +## Project overview + +The **BookFind** project is designed to simplify the management of book loans within a CDI. The application allows users to: +- Search for available books +- Borrow books +- View their current loans +- Access protected features if they are graded + +This application offers an efficient solution for the CDI staff and their users. + +## Features + +- **Home page**: Presentation of the application and a book search form. +- **Book search**: Interface allowing users to find books by their title. +- **Loan management**: View borrowed books and loan history. +- **Login and user profile**: Authentication with hashed passwords, access to restricted features, as well as a space to manage your own profile or edit another user's profile if you are graded. The editable parts vary depending on the permission level. + +## Project structure + +- `index.php`: Main page of the application, introducing the book search service. +- `login.php`: Login page to authenticate users. +- `books.php`: Book search page with a form to enter search criteria. +- `profile.php`: Interface allowing users to view and edit their personal information. +- `loans.php`: Page where the user can see the books they have borrowed. +- `privacy.php`: Page displaying the privacy policy and terms of use. +- `rules.php`: Page displaying the rules. + +### Directories + +- `actions/`: Contains the PHP and JavaScript scripts for actions, such as the database connection, registering a book and the general operation of the site. +- `includes/`: Components included in the various pages, such as `header.php`, `navbar.php` and `footer.php`, for consistent display. This folder centralizes pieces of code that do not need to be repeated and where changes impact every page. +- `assets/`: Resources such as CSS files, images and icons. +- `temp/`: Contains temporary files. + +## Installation + +1. **Clone the repository or download the ZIP**: + ```bash + git clone https://github.com/chromared/bookfind.git + ``` +2. **Local server setup**: + - Use XAMPP, WAMP, or another server with PHP and MySQL. +3. **Move the project**: + - Place the extracted folder in the root directory of your web server (usually `htdocs` on web servers and XAMPP, or `www` for WAMP and uWAMP). + +## Configure BookFind + +1. In your browser, go to the `configuration.php` file. +2. Follow the actions **in order** to configure the database and the classes of your institution... +3. When you are done, click the button that appears to delete the `configuration.php` file. This action is required for security reasons. The file must not remain accessible after configuration. + +## Usage + +### Steps for using the application + +1. **Access the home page**: Go to `index.php` for an overview and quick access to the book search. +2. **Create an account and sign in**: + - Go to `signup.php` or `login.php` to create an account or sign in. +3. **Search for books**: + - Use `books.php` to browse the available books. +4. **View and manage the profile**: + - View and edit your personal information on `profile.php`. +5. **Track loans**: + - Go to `loans.php` to view your borrowed books and their status. +6. **Management**: + - For graded users, a "Management" link appears in the navigation bar. Depending on your permissions, this link gives you access to certain site or CDI configuration options. + +## Environment + +- **Web server**: Apache. +- **PHP**: version 8.3 or higher. +- **MySQL**: version 8.4 or higher. + +## Dependencies + +- **None**: BookFind currently has no dependencies required for its operation. + +## List of contributors + +### Active contributors + +- [Alban Muller / @MythUp_](https://github.com/MythUp) --> Full Stack +- [@Jià N0w](https://github.com/JiaN0w) --> GitHub repository management +- [@DawnFolk](https://github.com/DawnFolk) --> Pentest +- [@Sylvain Durif, le Grand Monarque, le Christ cosmique et le Messie lui-même](https://www.linkedin.com/in/sylvain-pierre-durif-26a92119/?locale=fr) --> Bénédiction Cosmique + +### Passive contributors + +- [Mitali Jadhavro / Coding Artist](https://codingartistweb.com/) --> Frontend (JS = [action/fonction/title.js](https://github.com/Chromared/bookfind/blob/main/actions/functions/title.js)) + +## License + +This project is distributed under the terms of the [AGPL-3.0](LICENSE) license. 2026 Chromared. diff --git a/actions/bookfind.sql b/actions/bookfind.sql old mode 100644 new mode 100755 index 26a9227..9540ba7 --- a/actions/bookfind.sql +++ b/actions/bookfind.sql @@ -29,26 +29,26 @@ SET time_zone = "+00:00"; CREATE TABLE `books` ( `id` int NOT NULL, - `titre` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `auteur` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `author` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, `isbn` bigint NOT NULL, - `id_unique` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, - `resume` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci, - `editeur` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `unique_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `summary` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci, + `publisher` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, `type` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `serie` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, - `tome` int DEFAULT NULL, - `statut` int NOT NULL, + `series` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL, + `volume` int DEFAULT NULL, + `status` int NOT NULL, `genre` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; -- -------------------------------------------------------- -- --- Table structure for table `censure` +-- Table structure for table `blacklist` -- -CREATE TABLE `censure` ( +CREATE TABLE `blacklist` ( `id` int NOT NULL, `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; @@ -82,19 +82,19 @@ CREATE TABLE `cookies` ( -- -------------------------------------------------------- -- --- Table structure for table `emprunts` +-- Table structure for table `loans` -- -CREATE TABLE `emprunts` ( +CREATE TABLE `loans` ( `id` int NOT NULL, - `id_book` int NOT NULL, - `titre_book` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `date_emprunt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `date_futur_retour` date NOT NULL, - `date_retour` datetime DEFAULT NULL, - `id_emprunteur` int NOT NULL, - `firstname_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `statut` int NOT NULL DEFAULT '1' + `book_id` int NOT NULL, + `book_title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `loan_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `due_date` date NOT NULL, + `return_date` datetime DEFAULT NULL, + `borrower_id` int NOT NULL, + `borrower_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `status` int NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; -- -------------------------------------------------------- @@ -124,16 +124,16 @@ CREATE TABLE `logs` ( CREATE TABLE `users` ( `id` int NOT NULL, `username` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `classe` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `nom` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `prenom` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, - `mdp` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `class_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `last_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `first_name` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `password` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, `grade` int NOT NULL DEFAULT '0', `datetime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `regles` int NOT NULL, - `pdc` int NOT NULL, - `nb_emprunt_max` int NOT NULL DEFAULT '5', - `nb_emprunt` int NOT NULL DEFAULT '0', + `rules_accepted` int NOT NULL, + `privacy_accepted` int NOT NULL, + `max_loans` int NOT NULL DEFAULT '5', + `loans_count` int NOT NULL DEFAULT '0', `theme` int NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; @@ -148,9 +148,9 @@ ALTER TABLE `books` ADD PRIMARY KEY (`id`); -- --- Indexes for table `censure` +-- Indexes for table `blacklist` -- -ALTER TABLE `censure` +ALTER TABLE `blacklist` ADD PRIMARY KEY (`id`); -- @@ -167,9 +167,9 @@ ALTER TABLE `cookies` ADD PRIMARY KEY (`id`); -- --- Indexes for table `emprunts` +-- Indexes for table `loans` -- -ALTER TABLE `emprunts` +ALTER TABLE `loans` ADD PRIMARY KEY (`id`); -- @@ -196,9 +196,9 @@ ALTER TABLE `books` MODIFY `id` int NOT NULL AUTO_INCREMENT; -- --- AUTO_INCREMENT for table `censure` +-- AUTO_INCREMENT for table `blacklist` -- -ALTER TABLE `censure` +ALTER TABLE `blacklist` MODIFY `id` int NOT NULL AUTO_INCREMENT; -- @@ -214,9 +214,9 @@ ALTER TABLE `cookies` MODIFY `id` int NOT NULL AUTO_INCREMENT; -- --- AUTO_INCREMENT for table `emprunts` +-- AUTO_INCREMENT for table `loans` -- -ALTER TABLE `emprunts` +ALTER TABLE `loans` MODIFY `id` int NOT NULL AUTO_INCREMENT; -- diff --git a/actions/books/sBooks.php b/actions/books/sBooks.php old mode 100644 new mode 100755 index 45e1d7c..0947173 --- a/actions/books/sBooks.php +++ b/actions/books/sBooks.php @@ -1,79 +1,70 @@ - - -prepare($sql); - $params = []; - foreach ($keywords as $keyword) { - $params = array_merge($params, array_fill(0, 8, "%$keyword%")); - } - $recupBooks->execute($params); - - if($recupBooks->rowCount() == 0){ ?> -
-
-
-
-

- Aucun livre trouvé avec ces critères de recherche. -

-
-
-
-
- rowCount() > 0){ - - while($books = $recupBooks->fetch()){ - - $recupEmprunts = $bdd->prepare('SELECT * FROM emprunts WHERE id_book = ? AND statut = 1'); - $recupEmprunts->execute(array($books['id'])); - $emprunts = $recupEmprunts->fetch(); ?> -
-
-
-
-
-
-

-

Tome de la série

- -
    - -
  • Emprunté par
  • -
  • Retour prévu le
  • - -
  • Cet ouvrage est actuellement emprunté
  • - -
- -
- - Modifier - - Voir - - Emprunt - -
-
-
-
-
-
- - + +prepare($sql); + $params = []; + foreach ($keywords as $keyword) { + $params = array_merge($params, array_fill(0, 8, "%$keyword%")); + } + $fetchedBooks->execute($params); + + if ($fetchedBooks->rowCount() == 0) { ?> +
+ +

No books found with these search criteria.

+
+ rowCount() > 0) { ?> +
+ fetch()) { + $fetchedLoans = $db->prepare('SELECT * FROM loans WHERE book_id = ? AND status = 1'); + $fetchedLoans->execute(array($books['id'])); + $loans = $fetchedLoans->fetch(); ?> +
+
+ + Borrowed + + +
+
+
+
+
+ + + Volume +
+ +
+ Par — retour le +
+ +
+ View + + Loan + +
+
+
+ +
+ - - -prepare('SELECT * FROM emprunts WHERE id_emprunteur = ? AND statut = 1 AND date_futur_retour < ? ORDER BY date_futur_retour'); - $selectInfosFromEmprunts1->execute(array($id, $Now)); - - $selectInfosFromEmprunts2 = $bdd->prepare('SELECT * FROM emprunts WHERE id_emprunteur = ? AND statut = 1 AND date_futur_retour = ? ORDER BY date_futur_retour'); - $selectInfosFromEmprunts2->execute(array($id, $Now)); - - $selectInfosFromEmprunts3 = $bdd->prepare('SELECT * FROM emprunts WHERE id_emprunteur = ? AND statut = 1 AND date_futur_retour > ? ORDER BY date_futur_retour'); - $selectInfosFromEmprunts3->execute(array($id, $Now)); - - $selectInfosFromEmprunts4 = $bdd->prepare('SELECT * FROM emprunts WHERE id_emprunteur = ? AND statut = 2 ORDER BY date_retour DESC'); - $selectInfosFromEmprunts4->execute(array($id)); - - if($id != $_SESSION['id']){ - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Consultation des emprunts', 'Aucun commentaire'); - - } - - } -} diff --git a/actions/books/showLoans.php b/actions/books/showLoans.php new file mode 100755 index 0000000..365b66d --- /dev/null +++ b/actions/books/showLoans.php @@ -0,0 +1,35 @@ + + + +prepare('SELECT * FROM loans WHERE borrower_id = ? AND status = 1 AND due_date < ? ORDER BY due_date'); + $selectLoans1->execute(array($id, $Now)); + + $selectLoans2 = $db->prepare('SELECT * FROM loans WHERE borrower_id = ? AND status = 1 AND due_date = ? ORDER BY due_date'); + $selectLoans2->execute(array($id, $Now)); + + $selectLoans3 = $db->prepare('SELECT * FROM loans WHERE borrower_id = ? AND status = 1 AND due_date > ? ORDER BY due_date'); + $selectLoans3->execute(array($id, $Now)); + + $selectLoans4 = $db->prepare('SELECT * FROM loans WHERE borrower_id = ? AND status = 2 ORDER BY return_date DESC'); + $selectLoans4->execute(array($id)); + + if($id != $_SESSION['id']){ + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Loans viewed', 'No comment'); + + } + + } +} diff --git a/actions/books/showOneBookAction.php b/actions/books/showOneBookAction.php old mode 100644 new mode 100755 index 1292c42..f512a5c --- a/actions/books/showOneBookAction.php +++ b/actions/books/showOneBookAction.php @@ -1,7 +1,7 @@ @@ -11,7 +11,7 @@ prepare('SELECT * FROM books WHERE id = ?'); + $selectInfosFromBooks= $db->prepare('SELECT * FROM books WHERE id = ?'); $selectInfosFromBooks->execute(array($id)); $booksInfos = $selectInfosFromBooks->fetch(); diff --git a/actions/books/showOneEmprunt.php b/actions/books/showOneEmprunt.php deleted file mode 100644 index f70dc1f..0000000 --- a/actions/books/showOneEmprunt.php +++ /dev/null @@ -1,18 +0,0 @@ - - - -prepare('SELECT * FROM emprunts WHERE id_book = ? AND statut = ?'); - $selectInfosFromEmprunts->execute(array($id, 1)); - - $emprunt = $selectInfosFromEmprunts->fetch(); - }} \ No newline at end of file diff --git a/actions/books/showOneLoan.php b/actions/books/showOneLoan.php new file mode 100755 index 0000000..f3694d9 --- /dev/null +++ b/actions/books/showOneLoan.php @@ -0,0 +1,18 @@ + + + +prepare('SELECT * FROM loans WHERE book_id = ? AND status = ?'); + $selectLoans->execute(array($id, 1)); + + $loan = $selectLoans->fetch(); + }} \ No newline at end of file diff --git a/actions/database.php b/actions/database.php old mode 100644 new mode 100755 index efc0570..aaa78fb --- a/actions/database.php +++ b/actions/database.php @@ -1,27 +1,27 @@ - - - - -setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } catch (PDOException $e) { - $bdd = null; - $db_error_message = 'Connexion impossible à la base de données.'; + + + + +setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + } catch (PDOException $e) { + $db = null; + $db_error_message = 'Unable to connect to the database.'; }} \ No newline at end of file diff --git a/actions/functions/checked.php b/actions/functions/checked.php old mode 100644 new mode 100755 index 61fccbb..124b78f --- a/actions/functions/checked.php +++ b/actions/functions/checked.php @@ -1,7 +1,7 @@ diff --git a/actions/functions/colorDateEmpruntFunction.php b/actions/functions/colorDateEmpruntFunction.php deleted file mode 100644 index c8faea1..0000000 --- a/actions/functions/colorDateEmpruntFunction.php +++ /dev/null @@ -1,26 +0,0 @@ - - - - - $Now): - echo '' . NoEchoConversionDate($Date) . ''; - break; - case ($Date == $Now): - echo '' . NoEchoConversionDate($Date) . ''; - break; - case ($Date < $Now): - echo '' . NoEchoConversionDate($Date) . ''; - break; - } -} diff --git a/actions/functions/colorLoanDateFunction.php b/actions/functions/colorLoanDateFunction.php new file mode 100755 index 0000000..5816d13 --- /dev/null +++ b/actions/functions/colorLoanDateFunction.php @@ -0,0 +1,24 @@ + + + $Now): + echo '' . NoEchoConversionDate($Date) . ''; + break; + case ($Date == $Now): + echo '' . NoEchoConversionDate($Date) . ''; + break; + case ($Date < $Now): + echo '' . NoEchoConversionDate($Date) . ''; + break; + } +} diff --git a/actions/functions/conversionDate.php b/actions/functions/conversionDate.php old mode 100644 new mode 100755 index 206b9b4..41edfd5 --- a/actions/functions/conversionDate.php +++ b/actions/functions/conversionDate.php @@ -1,32 +1,32 @@ - - - - - + + + + - - - - + + + + - - - -query('SELECT name FROM classes'); - - if(isset($usersInfos['classe'])){ - while($classes = $selectClasses->fetch()){ - echo ''; - } - }else{ - - while($classes = $selectClasses->fetch()){ - echo ''; + + + + +query('SELECT name FROM classes'); + + if(isset($usersInfos['class_name'])){ + while($classes = $selectClasses->fetch()){ + echo ''; + } + }else{ + + while($classes = $selectClasses->fetch()){ + echo ''; }} \ No newline at end of file diff --git a/actions/functions/gradeIntToText.php b/actions/functions/gradeIntToText.php new file mode 100755 index 0000000..abfa24f --- /dev/null +++ b/actions/functions/gradeIntToText.php @@ -0,0 +1,53 @@ + + +None'; + break; + + case 1: + echo 'Administrator'; + break; + + case 2: + echo 'Manager'; + break; + + case 3: + echo 'Assistant'; + break; + + default: + echo '?'; + } +} +function NoEchoGrade($grade) +{ + switch ($grade) + { + case 0: + return 'None'; + + case 1: + return 'Administrator'; + + case 2: + return 'Manager'; + + case 3: + return 'Assistant'; + + default: + return '?'; + } +} diff --git a/actions/functions/logFunction.php b/actions/functions/logFunction.php old mode 100644 new mode 100755 index a99ae03..6112ce3 --- a/actions/functions/logFunction.php +++ b/actions/functions/logFunction.php @@ -1,92 +1,92 @@ - - - tags with a secure href (http(s) or relative path) - if (empty($html)) return ''; - - $doc = new DOMDocument(); - libxml_use_internal_errors(true); - // load as an HTML fragment - $doc->loadHTML('
' . $html . '
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); - libxml_clear_errors(); - - $allowed = []; - $div = $doc->getElementsByTagName('div')->item(0); - if (!$div) return htmlspecialchars($html, ENT_QUOTES); - - // Iterate recursively and reconstruct a safe fragment - $safeFragments = []; - - foreach ($div->childNodes as $node) { - if ($node->nodeType === XML_TEXT_NODE) { - $safeFragments[] = htmlspecialchars($node->nodeValue, ENT_QUOTES); - } elseif ($node->nodeType === XML_ELEMENT_NODE && strtolower($node->nodeName) === 'a') { - $href = ''; - if ($node instanceof DOMElement) { - $href = $node->getAttribute('href'); - } - $text = ''; - foreach ($node->childNodes as $c) { - if ($c->nodeType === XML_TEXT_NODE) $text .= $c->nodeValue; - } - - // Valider le href - $valid = false; - if ($href === '') { - $valid = false; - } else { - $parts = parse_url($href); - if ($parts === false) { - $valid = false; - } else { - if (!isset($parts['scheme'])) { - // relative path -> allowed - $valid = true; - } else { - $scheme = strtolower($parts['scheme']); - if (in_array($scheme, ['http', 'https'])) $valid = true; - } - } - } - - if ($valid) { - $safeHref = htmlspecialchars($href, ENT_QUOTES); - $safeText = htmlspecialchars($text, ENT_QUOTES); - $safeFragments[] = '' . $safeText . ''; - } else { - // if href is invalid, display only the text - $safeFragments[] = htmlspecialchars($text, ENT_QUOTES); - } - } else { - // for any other element, safely extract the text - $safeFragments[] = htmlspecialchars($node->textContent ?? '', ENT_QUOTES); - } - } - - return implode('', $safeFragments); -} - -function SaveLog($bdd, $page, $type, $comment){ - - $user_id = $_SESSION['id'] ?? null; - $user_ip = $_SERVER['REMOTE_ADDR'] ?? ''; - $username = $_SESSION['username'] ?? ''; - $name = ($_SESSION['firstname'] ?? '') . ' ' . ($_SESSION['lastname'] ?? ''); - - // Sanitize the comment to allow only safe links - $safe_comment = sanitize_log_comment($comment ?? ''); - $safe_page = htmlspecialchars($page ?? '', ENT_QUOTES); - $safe_type = htmlspecialchars($type ?? '', ENT_QUOTES); - $safe_username = htmlspecialchars($username ?? '', ENT_QUOTES); - $safe_name = htmlspecialchars($name ?? '', ENT_QUOTES); - - $insertLog = $bdd->prepare('INSERT INTO logs SET page = ?, user_id = ?, user_ip = ?, username = ?, user_name = ?, type = ?, comment = ?'); - $insertLog->execute(array($safe_page, $user_id, $user_ip, $safe_username, $safe_name, $safe_type, $safe_comment)); - -} + + + tags with a secure href (http(s) or relative path) + if (empty($html)) return ''; + + $doc = new DOMDocument(); + libxml_use_internal_errors(true); + // load as an HTML fragment + $doc->loadHTML('
' . $html . '
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); + libxml_clear_errors(); + + $allowed = []; + $div = $doc->getElementsByTagName('div')->item(0); + if (!$div) return htmlspecialchars($html, ENT_QUOTES); + + // Iterate recursively and reconstruct a safe fragment + $safeFragments = []; + + foreach ($div->childNodes as $node) { + if ($node->nodeType === XML_TEXT_NODE) { + $safeFragments[] = htmlspecialchars($node->nodeValue, ENT_QUOTES); + } elseif ($node->nodeType === XML_ELEMENT_NODE && strtolower($node->nodeName) === 'a') { + $href = ''; + if ($node instanceof DOMElement) { + $href = $node->getAttribute('href'); + } + $text = ''; + foreach ($node->childNodes as $c) { + if ($c->nodeType === XML_TEXT_NODE) $text .= $c->nodeValue; + } + + // Validate the href + $valid = false; + if ($href === '') { + $valid = false; + } else { + $parts = parse_url($href); + if ($parts === false) { + $valid = false; + } else { + if (!isset($parts['scheme'])) { + // relative path -> allowed + $valid = true; + } else { + $scheme = strtolower($parts['scheme']); + if (in_array($scheme, ['http', 'https'])) $valid = true; + } + } + } + + if ($valid) { + $safeHref = htmlspecialchars($href, ENT_QUOTES); + $safeText = htmlspecialchars($text, ENT_QUOTES); + $safeFragments[] = '' . $safeText . ''; + } else { + // if href is invalid, display only the text + $safeFragments[] = htmlspecialchars($text, ENT_QUOTES); + } + } else { + // for any other element, safely extract the text + $safeFragments[] = htmlspecialchars($node->textContent ?? '', ENT_QUOTES); + } + } + + return implode('', $safeFragments); +} + +function SaveLog($db, $page, $type, $comment){ + + $user_id = $_SESSION['id'] ?? null; + $user_ip = $_SERVER['REMOTE_ADDR'] ?? ''; + $username = $_SESSION['username'] ?? ''; + $name = ($_SESSION['firstname'] ?? '') . ' ' . ($_SESSION['lastname'] ?? ''); + + // Sanitize the comment to allow only safe links + $safe_comment = sanitize_log_comment($comment ?? ''); + $safe_page = htmlspecialchars($page ?? '', ENT_QUOTES); + $safe_type = htmlspecialchars($type ?? '', ENT_QUOTES); + $safe_username = htmlspecialchars($username ?? '', ENT_QUOTES); + $safe_name = htmlspecialchars($name ?? '', ENT_QUOTES); + + $insertLog = $db->prepare('INSERT INTO logs SET page = ?, user_id = ?, user_ip = ?, username = ?, user_name = ?, type = ?, comment = ?'); + $insertLog->execute(array($safe_page, $user_id, $user_ip, $safe_username, $safe_name, $safe_type, $safe_comment)); + +} diff --git a/actions/functions/selected.php b/actions/functions/selected.php old mode 100644 new mode 100755 index 916df9f..c2c0b21 --- a/actions/functions/selected.php +++ b/actions/functions/selected.php @@ -1,24 +1,24 @@ - - - - - + + + + { - pageTitleTimeout = setInterval(function () { - document.title = document.title === pageTitle ? "BookFind" : pageTitle; - }, 1500); -}; - -window.addEventListener("load", -startPageTitleFlashing); \ No newline at end of file +//This file belongs to the BookFind project. +// +//BookFind is distributed under the terms of the GNU Affero General Public License v3.0. +// +//Copyright (C) 2025 Chromared + + +// Optional title flashing helper — no longer auto-started so tab titles stay stable. +// Call startPageTitleFlashing() from a page to alternate between its title and "BookFind". +let pageTitle = document.title; +let pageTitleTimeout; + +const startPageTitleFlashing = () => { + pageTitleTimeout = setInterval(function () { + document.title = document.title === pageTitle ? "BookFind" : pageTitle; + }, 1500); +}; \ No newline at end of file diff --git a/actions/functions/transfoGradeIntVersText.php b/actions/functions/transfoGradeIntVersText.php deleted file mode 100644 index 9ae324a..0000000 --- a/actions/functions/transfoGradeIntVersText.php +++ /dev/null @@ -1,55 +0,0 @@ - - - - -Aucun'; - break; - - case 1: - echo 'Administrateur'; - break; - - case 2: - echo 'Gérant'; - break; - - case 3: - echo 'Assistant'; - break; - - default: - echo '?'; - } -} -function NoEchoGrade($grade) -{ - switch ($grade) - { - case 0: - return 'Aucun'; - - case 1: - return 'Administrateur'; - - case 2: - return 'Gérant'; - - case 3: - return 'Assistant'; - - default: - return '?'; - } -} \ No newline at end of file diff --git a/actions/users/decodeThemeAction.php b/actions/users/decodeThemeAction.php old mode 100644 new mode 100755 index 7f4acb3..6fe702d --- a/actions/users/decodeThemeAction.php +++ b/actions/users/decodeThemeAction.php @@ -1,18 +1,6 @@ - attribute. +// 0 = dark (default), 1 = light. +$theme = $_SESSION['theme'] ?? '0'; -switch ($theme) { - case "0": - echo ""; - break; - - case "1": - echo "dark"; - break; - - default: - echo ""; -} +echo ($theme === '1') ? 'light' : 'dark'; diff --git a/actions/users/deleteAccountAction1.php b/actions/users/deleteAccountAction1.php old mode 100644 new mode 100755 index 193415f..300b574 --- a/actions/users/deleteAccountAction1.php +++ b/actions/users/deleteAccountAction1.php @@ -1,43 +1,43 @@ - - - - -prepare('SELECT mdp, nb_emprunt FROM users WHERE id = ?'); - $checkPassword->execute(array($id)); - - $InfoDelete = $checkPassword->fetch(); - - if($InfoDelete['nb_emprunt'] == '0'){ - - if (password_verify($password, $InfoDelete['mdp'])) { - - $deleteAccount = true; - - }else{ - $errorMsg4 = 'Votre mot de passe actuel n\'est pas bon.'; - } - - }else{ - $errorMsg4 = 'Vous devez avoir rendu tous vos emprunts pour supprimer votre compte. Il vous reste actuellement ' . $InfoDelete['nb_emprunt'] . ' livre(s) emprunté(s).'; - } - - }else{ - $errorMsg4 = 'Veuillez remplir tous les champs.'; - } -}else{ - $errorMsg4 = 'Tous les champs n\'existent pas. Veuillez recharger la page.'; -} + + + + +prepare('SELECT password, loans_count FROM users WHERE id = ?'); + $checkPassword->execute(array($id)); + + $InfoDelete = $checkPassword->fetch(); + + if($InfoDelete['loans_count'] == '0'){ + + if (password_verify($password, $InfoDelete['password'])) { + + $deleteAccount = true; + + }else{ + $errorMsg4 = 'Your current password is incorrect.'; + } + + }else{ + $errorMsg4 = 'You must return all your loans before deleting your account. You currently have ' . $InfoDelete['loans_count'] . ' book(s) still on loan.'; + } + + }else{ + $errorMsg4 = 'Please fill in all fields.'; + } +}else{ + $errorMsg4 = 'Not all fields exist. Please reload the page.'; +} } \ No newline at end of file diff --git a/actions/users/deleteAccountAction2.php b/actions/users/deleteAccountAction2.php old mode 100644 new mode 100755 index 372cfbe..27b0ad8 --- a/actions/users/deleteAccountAction2.php +++ b/actions/users/deleteAccountAction2.php @@ -1,19 +1,19 @@ - - - - -prepare('DELETE FROM users WHERE id = ?'); - $checkPassword->execute(array($id)); - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Suppression de compte', 'Aucun commentaire.'); - - header('Location: actions/users/logoutAction.php'); + + + + +prepare('DELETE FROM users WHERE id = ?'); + $checkPassword->execute(array($id)); + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Account deleted', 'No comment.'); + + header('Location: actions/users/logoutAction.php'); } \ No newline at end of file diff --git a/actions/users/loginAction.php b/actions/users/loginAction.php old mode 100644 new mode 100755 index 657dc26..9a6684f --- a/actions/users/loginAction.php +++ b/actions/users/loginAction.php @@ -1,170 +1,174 @@ - - - - -prepare('SELECT user_id FROM cookies WHERE token = ? AND user_ip = ?'); - $checkIfTokenIsValid->execute(array($token, $ip)); - - if ($checkIfTokenIsValid->rowCount() > 0) { - - $usersID = $checkIfTokenIsValid->fetch(); - - $updateLastUsed = $bdd->prepare('UPDATE cookies SET last_used = ? WHERE user_id = ?'); - $updateLastUsed->execute(array(date('Y-m-d H:i:s'), $usersID['user_id'])); - - $checkIfUserAlreadyExists = $bdd->prepare('SELECT * FROM users WHERE id = ?'); - $checkIfUserAlreadyExists->execute(array($usersID['user_id'])); - - $usersInfos = $checkIfUserAlreadyExists->fetch(); - - $_SESSION['auth'] = true; - $_SESSION['admin'] = false; - $_SESSION['id'] = $usersInfos['id']; - $_SESSION['lastname'] = $usersInfos['nom']; - $_SESSION['firstname'] = $usersInfos['prenom']; - $_SESSION['username'] = $usersInfos['username']; - $_SESSION['classe'] = $usersInfos['classe']; - $_SESSION['grade'] = $usersInfos['grade']; - $_SESSION['theme'] = $usersInfos['theme']; - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Connexion', 'Connexion automatique via cookie.'); - - if (isset($_GET['redirect']) and !empty($_GET['redirect'])) { - header('Location: ' . htmlspecialchars($_GET['redirect'])); - exit; - } else { - header('Location: index.php'); - exit; - } - } -} -require_once __DIR__ . '/../functions/csrfFunction.php'; - -if (isset($_POST['validate'])) { - // Verify CSRF token - csrf_verify(); - - // Anti-brute-force protections (by IP and session) - $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown'; - if (!isset($_SESSION['login_attempts'])) { - $_SESSION['login_attempts'] = []; - } - $key = 'ip_' . $ip; - if (!isset($_SESSION['login_attempts'][$key])) { - $_SESSION['login_attempts'][$key] = ['count' => 0, 'first' => time()]; - } - $attempts = &$_SESSION['login_attempts'][$key]; - // window 15 minutes, max 5 - if ($attempts['count'] >= 5 && (time() - $attempts['first']) < 900) { - $errorMsg = '
Trop de tentatives. Réessayez plus tard.
'; - } - - // reset window if expired - if ((time() - $attempts['first']) >= 900) { - $attempts = ['count' => 0, 'first' => time()]; - } - - // initializations - $rememberMe = false; - - if (isset($_POST['username']) and isset($_POST['password'])) { - if (!empty($_POST['username']) and !empty($_POST['password'])) { - - $username = $_POST['username']; - $password = $_POST['password']; - - $checkIfUserAlreadyExists = $bdd->prepare('SELECT * FROM users WHERE username = ?'); - $checkIfUserAlreadyExists->execute(array($username)); - - if ($checkIfUserAlreadyExists->rowCount() > 0) { - - $usersInfos = $checkIfUserAlreadyExists->fetch(); - - if (password_verify($password, $usersInfos['mdp'])) { - - if(isset($_POST['rememberMe']) and !empty($_POST['rememberMe'])) { - - $rememberMe = true; - - // generate a unique token - do { - $token = bin2hex(random_bytes(32)); - $checkIfTokenAlreadyExists = $bdd->prepare('SELECT id FROM cookies WHERE token = ?'); - $checkIfTokenAlreadyExists->execute(array($token)); - } while ($checkIfTokenAlreadyExists->rowCount() > 0); - $ip = $_SERVER['REMOTE_ADDR']; - $userID = $usersInfos['id']; - - $insertToken = $bdd->prepare('INSERT INTO cookies (user_id, token, user_ip, last_used) VALUES (?, ?, ?, ?)'); - $insertToken->execute(array($userID, $token, $ip, date('Y-m-d H:i:s'))); - - setcookie( - "auth_token", - $token, - [ - "expires" => time() + 60 * 60 * 24 * 30, // 30 days - "path" => "/", - "secure" => true, // HTTPS only - "httponly" => true, // not accessible in JS - "samesite" => "Strict" - ] - ); - } - - $_SESSION['auth'] = true; - $_SESSION['admin'] = false; - $_SESSION['id'] = $usersInfos['id']; - $_SESSION['lastname'] = $usersInfos['nom']; - $_SESSION['firstname'] = $usersInfos['prenom']; - $_SESSION['username'] = $usersInfos['username']; - $_SESSION['classe'] = $usersInfos['classe']; - $_SESSION['grade'] = $usersInfos['grade']; - $_SESSION['theme'] = $usersInfos['theme']; - - // Regenerate session ID to prevent fixation - session_regenerate_id(true); - - // reset attempts on success - $attempts = ['count' => 0, 'first' => time()]; - - if($rememberMe) { - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Connexion', 'Connexion manuelle avec création d\'un cookie.'); - } else { - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Connexion', 'Connexion manuelle.'); - } - - - if (isset($_POST['redirect']) and !empty($_POST['redirect'])) { - header('Location: ' . htmlspecialchars($_POST['redirect'])); - exit; - } else { - header('Location: index.php'); - exit; - } - } else { - // failure: increment counter and set generic message - $attempts['count']++; - $errorMsg = '
Identifiants incorrects.
'; - } - } else { - // failure: increment counter and set generic message - $attempts['count']++; - $errorMsg = '
Identifiants incorrects.
'; - } - } else { - $errorMsg = '
Tous les champs ne sont pas rempli.
'; - } - } else { - $errorMsg = '

Tous les champs n\'existe pas. Recharger la page en cliquant ici.

'; - } -} + + + + +prepare('SELECT user_id FROM cookies WHERE token = ? AND user_ip = ?'); + $checkIfTokenIsValid->execute(array($token, $ip)); + + if ($checkIfTokenIsValid->rowCount() > 0) { + + $usersID = $checkIfTokenIsValid->fetch(); + + $updateLastUsed = $db->prepare('UPDATE cookies SET last_used = ? WHERE user_id = ?'); + $updateLastUsed->execute(array(date('Y-m-d H:i:s'), $usersID['user_id'])); + + $checkIfUserAlreadyExists = $db->prepare('SELECT * FROM users WHERE id = ?'); + $checkIfUserAlreadyExists->execute(array($usersID['user_id'])); + + $usersInfos = $checkIfUserAlreadyExists->fetch(); + + $_SESSION['auth'] = true; + $_SESSION['admin'] = false; + $_SESSION['id'] = $usersInfos['id']; + $_SESSION['lastname'] = $usersInfos['last_name']; + $_SESSION['firstname'] = $usersInfos['first_name']; + $_SESSION['username'] = $usersInfos['username']; + $_SESSION['class_name'] = $usersInfos['class_name']; + $_SESSION['grade'] = $usersInfos['grade']; + $_SESSION['theme'] = $usersInfos['theme']; + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Login', 'Automatic login via cookie.'); + + header('Location: ' . loginRedirectTarget($_GET['redirect'] ?? '')); + exit; + } +} +require_once __DIR__ . '/../functions/csrfFunction.php'; + +if (isset($_POST['validate'])) { + // Verify CSRF token + csrf_verify(); + + // Anti-brute-force protections (by IP and session) + $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown'; + if (!isset($_SESSION['login_attempts'])) { + $_SESSION['login_attempts'] = []; + } + $key = 'ip_' . $ip; + if (!isset($_SESSION['login_attempts'][$key])) { + $_SESSION['login_attempts'][$key] = ['count' => 0, 'first' => time()]; + } + $attempts = &$_SESSION['login_attempts'][$key]; + // window 15 minutes, max 5 + if ($attempts['count'] >= 5 && (time() - $attempts['first']) < 900) { + $errorMsg = '
Too many attempts. Try again later.
'; + } + + // reset window if expired + if ((time() - $attempts['first']) >= 900) { + $attempts = ['count' => 0, 'first' => time()]; + } + + // initializations + $rememberMe = false; + + if (isset($_POST['username']) and isset($_POST['password'])) { + if (!empty($_POST['username']) and !empty($_POST['password'])) { + + $username = $_POST['username']; + $password = $_POST['password']; + + $checkIfUserAlreadyExists = $db->prepare('SELECT * FROM users WHERE username = ?'); + $checkIfUserAlreadyExists->execute(array($username)); + + if ($checkIfUserAlreadyExists->rowCount() > 0) { + + $usersInfos = $checkIfUserAlreadyExists->fetch(); + + if (password_verify($password, $usersInfos['password'])) { + + if(isset($_POST['rememberMe']) and !empty($_POST['rememberMe'])) { + + $rememberMe = true; + + // generate a unique token + do { + $token = bin2hex(random_bytes(32)); + $checkIfTokenAlreadyExists = $db->prepare('SELECT id FROM cookies WHERE token = ?'); + $checkIfTokenAlreadyExists->execute(array($token)); + } while ($checkIfTokenAlreadyExists->rowCount() > 0); + $ip = $_SERVER['REMOTE_ADDR']; + $userID = $usersInfos['id']; + + $insertToken = $db->prepare('INSERT INTO cookies (user_id, token, user_ip, last_used) VALUES (?, ?, ?, ?)'); + $insertToken->execute(array($userID, $token, $ip, date('Y-m-d H:i:s'))); + + setcookie( + "auth_token", + $token, + [ + "expires" => time() + 60 * 60 * 24 * 30, // 30 days + "path" => "/", + "secure" => true, // HTTPS only + "httponly" => true, // not accessible in JS + "samesite" => "Strict" + ] + ); + } + + $_SESSION['auth'] = true; + $_SESSION['admin'] = false; + $_SESSION['id'] = $usersInfos['id']; + $_SESSION['lastname'] = $usersInfos['last_name']; + $_SESSION['firstname'] = $usersInfos['first_name']; + $_SESSION['username'] = $usersInfos['username']; + $_SESSION['class_name'] = $usersInfos['class_name']; + $_SESSION['grade'] = $usersInfos['grade']; + $_SESSION['theme'] = $usersInfos['theme']; + + // Regenerate session ID to prevent fixation + session_regenerate_id(true); + + // reset attempts on success + $attempts = ['count' => 0, 'first' => time()]; + + if($rememberMe) { + SaveLog($db, $_SERVER['REQUEST_URI'], 'Login', 'Manual login with cookie creation.'); + } else { + SaveLog($db, $_SERVER['REQUEST_URI'], 'Login', 'Manual login.'); + } + + + header('Location: ' . loginRedirectTarget($_POST['redirect'] ?? '')); + exit; + } else { + // failure: increment counter and set generic message + $attempts['count']++; + $errorMsg = '
Incorrect credentials.
'; + } + } else { + // failure: increment counter and set generic message + $attempts['count']++; + $errorMsg = '
Incorrect credentials.
'; + } + } else { + $errorMsg = '
Not all fields are filled in.
'; + } + } else { + $errorMsg = '

Not all fields exist. Reload the page by clicking here.

'; + } +} diff --git a/actions/users/logoutAction.php b/actions/users/logoutAction.php old mode 100644 new mode 100755 index b61b7bb..f7ebef9 --- a/actions/users/logoutAction.php +++ b/actions/users/logoutAction.php @@ -1,34 +1,34 @@ - - - - -prepare('DELETE FROM cookies WHERE user_id = ?'); -$deleteCookies->execute(array($_SESSION['id'])); - -SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Déconnexion', 'Aucun commentaire.'); - -$_SESSION = []; -session_destroy(); -setcookie( - "auth_token", - "", - [ - "expires" => time() - 3600, - "path" => "/", - "secure" => true, - "httponly" => true, - "samesite" => "Strict" - ] -); - -header('Location: ../../login.php'); + + + + +prepare('DELETE FROM cookies WHERE user_id = ?'); +$deleteCookies->execute(array($_SESSION['id'])); + +SaveLog($db, $_SERVER['REQUEST_URI'], 'Logout', 'No comment.'); + +$_SESSION = []; +session_destroy(); +setcookie( + "auth_token", + "", + [ + "expires" => time() - 3600, + "path" => "/", + "secure" => true, + "httponly" => true, + "samesite" => "Strict" + ] +); + +header('Location: ../../index.php'); diff --git a/actions/users/securityAction.php b/actions/users/securityAction.php old mode 100644 new mode 100755 index 0cb535b..243cde3 --- a/actions/users/securityAction.php +++ b/actions/users/securityAction.php @@ -1,16 +1,16 @@ - - - - - + + + + - - - -prepare('SELECT * FROM users WHERE id = ?'); - $selectInfosFromUsers->execute(array($id)); - - $usersInfos = $selectInfosFromUsers->fetch(); - - if($id != $_SESSION['id'] AND $selectInfosFromUsers->rowCount() === 1){ - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Consultation de profil', 'Le profil de ' . htmlspecialchars($usersInfos['prenom']) . ' ' . htmlspecialchars($usersInfos['nom']) . ' a été consulté.'); - - } - - }else{ - die('Vous n\'avez pas les permissions nécessaires pour accéder à ce profil.'); - } \ No newline at end of file diff --git a/actions/users/showOneUserProfileAction.php b/actions/users/showOneUserProfileAction.php new file mode 100755 index 0000000..63503af --- /dev/null +++ b/actions/users/showOneUserProfileAction.php @@ -0,0 +1,28 @@ + + + + +prepare('SELECT * FROM users WHERE id = ?'); + $selectInfosFromUsers->execute(array($id)); + + $usersInfos = $selectInfosFromUsers->fetch(); + + if($id != $_SESSION['id'] AND $selectInfosFromUsers->rowCount() === 1){ + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Profile viewed', 'The profile of ' . htmlspecialchars($usersInfos['first_name']) . ' ' . htmlspecialchars($usersInfos['last_name']) . ' was viewed.'); + + } + + }else{ + die('You do not have the required permissions to view this profile.'); + } \ No newline at end of file diff --git a/actions/users/signupAction.php b/actions/users/signupAction.php old mode 100644 new mode 100755 index 3f100e0..fbe1674 --- a/actions/users/signupAction.php +++ b/actions/users/signupAction.php @@ -1,86 +1,86 @@ - - - - -prepare("SELECT COUNT(*) FROM users WHERE username LIKE ?"); - $stmt->execute([$username . '%']); - $count = $stmt->fetchColumn(); - - // If the username already exists, add a number - if ($count > 0) { - $username .= ($count + 1); // The number is based on the number of people already having this username - } - - $checkIfClasseAlreadyExists = $bdd->prepare('SELECT name FROM classes WHERE name = ?'); - $checkIfClasseAlreadyExists->execute(array($classe)); - - if ($checkIfClasseAlreadyExists->rowCount() > 0) { - - $checkIfOneUserExist = $bdd->query('SELECT id FROM users'); - - if ($checkIfOneUserExist->rowCount() == 0) { - $grade = 1; - } else { - $grade = 0; - } - - $insertUserOnWebsite = $bdd->prepare('INSERT INTO users SET username = ?, classe = ?, nom = ?, prenom = ?, mdp = ?, regles = ?, pdc = ?, grade = ?'); - $insertUserOnWebsite->execute(array($username, $classe, $lastname, $firstname, $mdp, true, true, $grade)); - - $getInfosOfThisUserReq = $bdd->prepare('SELECT * FROM users WHERE username = ?'); - $getInfosOfThisUserReq->execute(array($username)); - - $usersInfos = $getInfosOfThisUserReq->fetch(); - - $_SESSION['auth'] = true; - $_SESSION['id'] = $usersInfos['id']; - $_SESSION['lastname'] = $usersInfos['nom']; - $_SESSION['firstname'] = $usersInfos['prenom']; - $_SESSION['username'] = $usersInfos['username']; - $_SESSION['classe'] = $usersInfos['classe']; - $_SESSION['grade'] = $usersInfos['grade']; - $_SESSION['theme'] = $usersInfos['theme']; - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Inscription', 'Aucun commentaire.'); - - header('Location: index.php?signup'); - } else { - $errorMsg = 'La classe sélectionnée n\'existe pas.'; - } - } else { - $errorMsg = 'Les conditions d\'utilisation et les règles doivent être acceptées.'; - } - } else { - $errorMsg = 'Les deux mot de passe ne sont pas identique.'; - } - } else { - $errorMsg = 'Veuillez remplir tous les champs.'; - } - } else { - $errorMsg = 'Tous les champs n\'existe pas. Veuillez recharger la page.'; - } -} + + + + +prepare("SELECT COUNT(*) FROM users WHERE username LIKE ?"); + $stmt->execute([$username . '%']); + $count = $stmt->fetchColumn(); + + // If the username already exists, add a number + if ($count > 0) { + $username .= ($count + 1); // The number is based on the number of people already having this username + } + + $checkIfClassAlreadyExists = $db->prepare('SELECT name FROM classes WHERE name = ?'); + $checkIfClassAlreadyExists->execute(array($class_name)); + + if ($checkIfClassAlreadyExists->rowCount() > 0) { + + $checkIfOneUserExist = $db->query('SELECT id FROM users'); + + if ($checkIfOneUserExist->rowCount() == 0) { + $grade = 1; + } else { + $grade = 0; + } + + $insertUserOnWebsite = $db->prepare('INSERT INTO users SET username = ?, class_name = ?, last_name = ?, first_name = ?, password = ?, rules_accepted = ?, privacy_accepted = ?, grade = ?'); + $insertUserOnWebsite->execute(array($username, $class_name, $lastname, $firstname, $password, true, true, $grade)); + + $getInfosOfThisUserReq = $db->prepare('SELECT * FROM users WHERE username = ?'); + $getInfosOfThisUserReq->execute(array($username)); + + $usersInfos = $getInfosOfThisUserReq->fetch(); + + $_SESSION['auth'] = true; + $_SESSION['id'] = $usersInfos['id']; + $_SESSION['lastname'] = $usersInfos['last_name']; + $_SESSION['firstname'] = $usersInfos['first_name']; + $_SESSION['username'] = $usersInfos['username']; + $_SESSION['class_name'] = $usersInfos['class_name']; + $_SESSION['grade'] = $usersInfos['grade']; + $_SESSION['theme'] = $usersInfos['theme']; + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Sign up', 'No comment.'); + + header('Location: index.php?signup'); + } else { + $errorMsg = 'The selected class does not exist.'; + } + } else { + $errorMsg = 'The terms of use and the rules must be accepted.'; + } + } else { + $errorMsg = 'The two passwords are not identical.'; + } + } else { + $errorMsg = 'Please fill in all fields.'; + } + } else { + $errorMsg = 'Not all fields exist. Please reload the page.'; + } +} diff --git a/actions/users/updateInfoPersoAction.php b/actions/users/updateInfoPersoAction.php deleted file mode 100644 index 3c45c1f..0000000 --- a/actions/users/updateInfoPersoAction.php +++ /dev/null @@ -1,41 +0,0 @@ - - - - -prepare('UPDATE users SET nom = ?, prenom = ? WHERE id = ?'); - $updateInfoPerso->execute(array($name, $firstname, $id)); - - if($name != $_SESSION['lastname'] AND $firstname == $_SESSION['firstname']){ - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de compte', 'Le nouveau nom est ' . $name . '.'); - }elseif($name == $_SESSION['lastname'] AND $firstname != $_SESSION['firstname']){ - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de compte', 'Le nouveau prénom est ' . $firstname . '.'); - }elseif($name != $_SESSION['lastname'] AND $firstname != $_SESSION['firstname']){ - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de compte', 'Cette utilisateur se nomme maintenant ' . $name . ' ' . $firstname . '.'); - } - - $_SESSION['lastname'] = $name; - $_SESSION['firstname'] = $firstname; - - header('Location: updateProfil.php?id=' . $id .'&msg1=true'); - - }else { - $errorMsg1 = 'Veuillez remplir tous les champs.'; - } -}else{ - $errorMsg1 = 'Tous les champs n\'existent pas. Veuillez recharger la page.'; -} -} \ No newline at end of file diff --git a/actions/users/updateInfoScoAction.php b/actions/users/updateInfoScoAction.php deleted file mode 100644 index a6709f7..0000000 --- a/actions/users/updateInfoScoAction.php +++ /dev/null @@ -1,37 +0,0 @@ - - - - -prepare('SELECT name FROM classes WHERE name = ?'); - $checkIfClasseAlreadyExists->execute(array($classe)); - - if($checkIfClasseAlreadyExists->rowCount() > 0){ - - $updateInfoSco = $bdd->prepare('UPDATE users SET classe = ? WHERE id = ?'); - $updateInfoSco->execute(array($classe, $id)); - - if($classe != $_SESSION['classe']){ - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de compte', 'Modification de la classe. Ancienne classe : ' . $_SESSION['classe'] . '. Nouvelle classe : ' . $classe . '.'); - } - - $_SESSION['classe'] = $classe; - - header('Location: updateProfil.php?id=' . $id .'&msg2=true'); - - }else{ $errorMsg2 = 'La classe sélectionnée n\'existe pas.'; } - }else{ $errorMsg2 = 'Tous les champs doivent être remplis.'; } - }else{ $errorMsg2 = 'Tous les champs n\'existent pas. Recharger la page ici.'; } -} \ No newline at end of file diff --git a/actions/users/updateMdpAction.php b/actions/users/updateMdpAction.php deleted file mode 100644 index 54b0cba..0000000 --- a/actions/users/updateMdpAction.php +++ /dev/null @@ -1,50 +0,0 @@ - - - - -prepare('SELECT mdp FROM users WHERE id = ?'); - $checkPassword->execute(array($id)); - - $Password = $checkPassword->fetch(); - - if (password_verify($password, $Password['mdp'])) { - - $checkPassword->closeCursor(); - - $updateMdp = $bdd->prepare('UPDATE users SET mdp = ? WHERE id = ?'); - $updateMdp->execute(array($newPassword, $id)); - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de compte', 'Modification du mot de passe.'); - - - header('Location: updateProfil.php?id=' . $id .'&msg3=true'); - - }else{ - $errorMsg3 = 'Votre mot de passe actuel n\'est pas bon.'; -} -}else{ - $errorMsg3 = 'Les deux nouveaux mot de passe ne sont pas identiques.'; -} -}else{ - $errorMsg3 = 'Veuillez remplir tous les champs.'; -} -}else{ - $errorMsg3 = 'Tous les champs n\'existent pas. Veuillez recharger la page.'; -} -} \ No newline at end of file diff --git a/actions/users/updatePasswordAction.php b/actions/users/updatePasswordAction.php new file mode 100755 index 0000000..87b79c2 --- /dev/null +++ b/actions/users/updatePasswordAction.php @@ -0,0 +1,50 @@ + + + + +prepare('SELECT password FROM users WHERE id = ?'); + $checkPassword->execute(array($id)); + + $Password = $checkPassword->fetch(); + + if (password_verify($password, $Password['password'])) { + + $checkPassword->closeCursor(); + + $updatePassword = $db->prepare('UPDATE users SET password = ? WHERE id = ?'); + $updatePassword->execute(array($newPassword, $id)); + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Account modified', 'Password changed.'); + + + header('Location: updateProfile.php?id=' . $id .'&msg3=true'); + + }else{ + $errorMsg3 = 'Your current password is incorrect.'; +} +}else{ + $errorMsg3 = 'The two new passwords are not identical.'; +} +}else{ + $errorMsg3 = 'Please fill in all fields.'; +} +}else{ + $errorMsg3 = 'Not all fields exist. Please reload the page.'; +} +} \ No newline at end of file diff --git a/actions/users/updatePersonalInfoAction.php b/actions/users/updatePersonalInfoAction.php new file mode 100755 index 0000000..a4ec447 --- /dev/null +++ b/actions/users/updatePersonalInfoAction.php @@ -0,0 +1,41 @@ + + + + +prepare('UPDATE users SET last_name = ?, first_name = ? WHERE id = ?'); + $updatePersonalInfo->execute(array($name, $firstname, $id)); + + if($name != $_SESSION['lastname'] AND $firstname == $_SESSION['firstname']){ + SaveLog($db, $_SERVER['REQUEST_URI'], 'Account modified', 'The new last name is ' . $name . '.'); + }elseif($name == $_SESSION['lastname'] AND $firstname != $_SESSION['firstname']){ + SaveLog($db, $_SERVER['REQUEST_URI'], 'Account modified', 'The new first name is ' . $firstname . '.'); + }elseif($name != $_SESSION['lastname'] AND $firstname != $_SESSION['firstname']){ + SaveLog($db, $_SERVER['REQUEST_URI'], 'Account modified', 'This user is now named ' . $name . ' ' . $firstname . '.'); + } + + $_SESSION['lastname'] = $name; + $_SESSION['firstname'] = $firstname; + + header('Location: updateProfile.php?id=' . $id .'&msg1=true'); + + }else { + $errorMsg1 = 'Please fill in all fields.'; + } +}else{ + $errorMsg1 = 'Not all fields exist. Please reload the page.'; +} +} \ No newline at end of file diff --git a/actions/users/updateSchoolInfoAction.php b/actions/users/updateSchoolInfoAction.php new file mode 100755 index 0000000..5d09e49 --- /dev/null +++ b/actions/users/updateSchoolInfoAction.php @@ -0,0 +1,37 @@ + + + + +prepare('SELECT name FROM classes WHERE name = ?'); + $checkIfClassAlreadyExists->execute(array($class_name)); + + if($checkIfClassAlreadyExists->rowCount() > 0){ + + $updateSchoolInfo = $db->prepare('UPDATE users SET class_name = ? WHERE id = ?'); + $updateSchoolInfo->execute(array($class_name, $id)); + + if($class_name != $_SESSION['class_name']){ + SaveLog($db, $_SERVER['REQUEST_URI'], 'Account modified', 'Class changed. Old class: ' . $_SESSION['class_name'] . '. New class: ' . $class_name . '.'); + } + + $_SESSION['class_name'] = $class_name; + + header('Location: updateProfile.php?id=' . $id .'&msg2=true'); + + }else{ $errorMsg2 = 'The selected class does not exist.'; } + }else{ $errorMsg2 = 'All fields must be filled in.'; } + }else{ $errorMsg2 = 'Not all fields exist. Reload the page here.'; } +} \ No newline at end of file diff --git a/actions/users/updateThemeAction.php b/actions/users/updateThemeAction.php old mode 100644 new mode 100755 index ac1e9aa..054b04c --- a/actions/users/updateThemeAction.php +++ b/actions/users/updateThemeAction.php @@ -4,13 +4,13 @@ if($theme == '0' OR $theme == '1'){ - $updateTheme = $bdd->prepare('UPDATE users SET theme = ? WHERE id = ?'); + $updateTheme = $db->prepare('UPDATE users SET theme = ? WHERE id = ?'); $updateTheme->execute(array($theme, $id)); $_SESSION['theme'] = $theme; header('Location: settings.php?id=' . $id . '&msg1=success'); }else{ - $errorMsg1 = 'Veuillez sélectionner un thème valide.'; + $errorMsg1 = 'Please select a valid theme.'; } } \ No newline at end of file diff --git a/assets/app.js b/assets/app.js new file mode 100644 index 0000000..f468a67 --- /dev/null +++ b/assets/app.js @@ -0,0 +1,127 @@ +// BookFind — lightweight UI behaviors (no framework). +// Event delegation on document so it works regardless of load order. +(function () { + "use strict"; + + function closeOtherDropdowns(current) { + document.querySelectorAll(".dropdown.is-open").forEach(function (dd) { + if (dd !== current) dd.classList.remove("is-open"); + }); + } + + // Global click handling: nav toggle, dropdowns, tabs, modals. + document.addEventListener("click", function (e) { + // --- Navbar / sidebar mobile toggle --- + var navToggle = e.target.closest("[data-nav-toggle]"); + if (navToggle) { + var target = document.getElementById(navToggle.getAttribute("data-nav-toggle")); + if (target) { + var open = target.classList.toggle("is-open"); + navToggle.setAttribute("aria-expanded", open ? "true" : "false"); + var backdrop = document.querySelector(".sidebar__backdrop"); + if (backdrop) backdrop.classList.toggle("is-open", open); + document.body.classList.toggle("nav-open", open); + } + return; + } + + // --- Sidebar backdrop click closes it --- + if (e.target.closest("[data-sidebar-close]")) { + var sb = document.getElementById("sidebar"); + if (sb) sb.classList.remove("is-open"); + var bd = document.querySelector(".sidebar__backdrop"); + if (bd) bd.classList.remove("is-open"); + document.body.classList.remove("nav-open"); + return; + } + + // --- Dropdowns --- + var ddToggle = e.target.closest("[data-dropdown-toggle]"); + if (ddToggle) { + e.preventDefault(); + var dd = ddToggle.closest(".dropdown"); + if (dd) { + var isOpen = dd.classList.toggle("is-open"); + closeOtherDropdowns(dd); + ddToggle.setAttribute("aria-expanded", isOpen ? "true" : "false"); + } + return; + } + + // --- Tabs --- + var tab = e.target.closest("[data-tab]"); + if (tab) { + if (tab.disabled) return; + var group = tab.closest(".tabs"); + var pane = document.getElementById(tab.getAttribute("data-tab")); + if (!group || !pane) return; + group.querySelectorAll("[data-tab]").forEach(function (t) { + t.classList.toggle("is-active", t === tab); + t.setAttribute("aria-selected", t === tab ? "true" : "false"); + }); + var block = group.closest(".tabs-block"); + if (block) { + block.querySelectorAll(".tab-pane").forEach(function (p) { + p.classList.toggle("is-active", p === pane); + }); + } + return; + } + + // --- Modals --- + var opener = e.target.closest("[data-modal-open]"); + if (opener) { + var modal = document.getElementById(opener.getAttribute("data-modal-open")); + if (modal) openModal(modal); + return; + } + var closer = e.target.closest("[data-modal-close]"); + if (closer) { + var m = closer.closest(".modal"); + if (m) closeModal(m); + return; + } + var backdrop = e.target.closest(".modal__backdrop"); + if (backdrop && e.target === backdrop) { + closeModal(backdrop.closest(".modal")); + return; + } + + // Close dropdowns when clicking elsewhere + closeOtherDropdowns(null); + }); + + function openModal(m) { + m.classList.add("is-open"); + document.body.classList.add("modal-open"); + var focusEl = m.querySelector("[data-autofocus]") || m.querySelector("button, input, a"); + if (focusEl) focusEl.focus(); + } + function closeModal(m) { + if (!m) return; + m.classList.remove("is-open"); + document.body.classList.remove("modal-open"); + } + + document.addEventListener("keydown", function (e) { + if (e.key === "Escape") { + document.querySelectorAll(".modal.is-open").forEach(closeModal); + closeOtherDropdowns(null); + } + }); + + // --- Searchable select (input filters the options of a sibling select) --- + document.addEventListener("input", function (e) { + var input = e.target.closest("[data-select-search]"); + if (!input) return; + var wrap = input.closest(".select-search"); + if (!wrap) return; + var select = wrap.querySelector("select"); + if (!select) return; + var q = input.value.trim().toLowerCase(); + Array.prototype.forEach.call(select.options, function (opt) { + if (opt.value === "") return; // keep the placeholder option visible + opt.hidden = opt.textContent.toLowerCase().indexOf(q) === -1; + }); + }); +})(); diff --git a/assets/chromared.png b/assets/chromared.png old mode 100644 new mode 100755 diff --git a/assets/favicon.ico b/assets/favicon.ico old mode 100644 new mode 100755 index 07cdf07..e7b482f Binary files a/assets/favicon.ico and b/assets/favicon.ico differ diff --git a/assets/favicon.svg b/assets/favicon.svg new file mode 100644 index 0000000..4790c15 --- /dev/null +++ b/assets/favicon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/iconesite.png b/assets/iconesite.png old mode 100644 new mode 100755 diff --git a/assets/logo.svg b/assets/logo.svg new file mode 100644 index 0000000..22aae94 --- /dev/null +++ b/assets/logo.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/logopourpage.png b/assets/logopourpage.png old mode 100644 new mode 100755 diff --git a/assets/style.css b/assets/style.css old mode 100644 new mode 100755 index 9f4d5d7..c17f394 --- a/assets/style.css +++ b/assets/style.css @@ -1,13 +1,1107 @@ -:target { - scroll-margin-top: 60px; +/* ========================================================================== + BookFind — design system + Dark-first (Linear-inspired tokens) with a derived light mode, plus a real + application layout: top navbar (public), sidebar + topbar (admin), split + auth screens, landing grid, responsive book grid, structured profile/reader. + ========================================================================== */ + +/* -------------------------------------------------------------------------- + 1. TOKENS + -------------------------------------------------------------------------- */ +:root { + color-scheme: dark; + + --canvas: #010102; + --surface-1: #0f1011; + --surface-2: #141516; + --surface-3: #18191a; + --surface-4: #1d1e20; + --hairline: #23252a; + --hairline-strong: #34343a; + --hairline-tertiary: #3e3e44; + --ink: #f7f8f8; + --ink-muted: #d0d6e0; + --ink-subtle: #8a8f98; + --ink-tertiary: #62666d; + --primary: #5e6ad2; + --primary-hover: #828fff; + --primary-focus: #5e69d1; + --on-primary: #ffffff; + --success: #4ac46a; + --success-strong: #27a644; + --warning: #eab308; + --warning-strong: #b7791f; + --danger: #f2555a; + --danger-strong: #d64545; + --edge-highlight: rgba(255, 255, 255, 0.04); + --scrim: rgba(0, 0, 0, 0.62); + + /* Soft backgrounds (explicit values, no color-mix for compatibility) */ + --primary-soft: rgba(94, 106, 210, 0.16); + --primary-soft-border: rgba(94, 106, 210, 0.42); + --success-soft: rgba(74, 196, 106, 0.14); + --success-soft-border: rgba(74, 196, 106, 0.42); + --danger-soft: rgba(242, 85, 90, 0.14); + --danger-soft-border: rgba(242, 85, 90, 0.42); + --warning-soft: rgba(234, 179, 8, 0.14); + --warning-soft-border: rgba(234, 179, 8, 0.42); + --focus-ring: rgba(94, 105, 209, 0.28); + --nav-bg: rgba(1, 1, 2, 0.82); + + --font-display: "Inter Tight", "Inter", "SF Pro Display", -apple-system, + BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + --font-text: "Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, + "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + --font-mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, + monospace; + + --radius-xs: 4px; + --radius-sm: 6px; + --radius-md: 8px; + --radius-lg: 12px; + --radius-xl: 16px; + --radius-pill: 9999px; + + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-6: 24px; + --space-8: 32px; + --space-12: 48px; + --space-section: 128px; + + --nav-h: 78px; + --sidebar-w: 256px; } -.card-widget i { - font-size: 2rem; +[data-theme="light"] { + color-scheme: light; + + --canvas: #f7f8fa; + --surface-1: #ffffff; + --surface-2: #fbfbfc; + --surface-3: #f4f5f6; + --surface-4: #eef0f1; + --hairline: #e6e8eb; + --hairline-strong: #d4d7db; + --hairline-tertiary: #c5c9ce; + --ink: #181a1d; + --ink-muted: #3c4046; + --ink-subtle: #6a7078; + --ink-tertiary: #9aa0a6; + --primary-hover: #4d58c4; + --primary-focus: #5e69d1; + --success: #1a7f37; + --success-strong: #1a7f37; + --warning: #8a5a00; + --warning-strong: #c17a10; + --danger: #c22a2a; + --danger-strong: #d02a2a; + --edge-highlight: rgba(255, 255, 255, 0.6); + --scrim: rgba(24, 26, 29, 0.4); + + --primary-soft: rgba(94, 106, 210, 0.10); + --primary-soft-border: rgba(94, 106, 210, 0.35); + --success-soft: rgba(26, 127, 55, 0.10); + --success-soft-border: rgba(26, 127, 55, 0.35); + --danger-soft: rgba(194, 42, 42, 0.10); + --danger-soft-border: rgba(194, 42, 42, 0.35); + --warning-soft: rgba(138, 90, 0, 0.10); + --warning-soft-border: rgba(138, 90, 0, 0.35); + --nav-bg: rgba(247, 248, 250, 0.82); } -.card-widget .card-body { +/* -------------------------------------------------------------------------- + 2. BASE + -------------------------------------------------------------------------- */ +* { box-sizing: border-box; } + +html { -webkit-text-size-adjust: 100%; scroll-behavior: smooth; } + +body { + margin: 0; display: flex; + flex-direction: column; + min-height: 100vh; + overflow-x: clip; + font-family: var(--font-text); + font-size: 16px; + line-height: 1.55; + letter-spacing: -0.05px; + color: var(--ink); + background-color: var(--canvas); + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +h1, h2, h3, h4, h5, h6 { + margin: 0 0 12px; + font-family: var(--font-display); + font-weight: 600; + line-height: 1.2; + letter-spacing: -0.02em; + color: var(--ink); +} +h1 { font-size: 2rem; letter-spacing: -0.04em; } +h2 { font-size: 1.5rem; letter-spacing: -0.03em; } +h3 { font-size: 1.25rem; letter-spacing: -0.02em; } +h4 { font-size: 1.125rem; } +h5 { font-size: 1rem; font-weight: 500; letter-spacing: 0; } +h6 { font-size: 0.875rem; font-weight: 500; letter-spacing: 0; } + +p { margin: 0 0 12px; } +p:last-child { margin-bottom: 0; } + +a { color: var(--primary); text-decoration: none; } +a:hover { color: var(--primary-hover); } + +hr { border: 0; border-top: 1px solid var(--hairline); margin: 24px 0; } + +::selection { background: var(--primary-soft); color: var(--ink); } + +:focus-visible { outline: 2px solid var(--primary-focus); outline-offset: 2px; } + +* { scrollbar-width: thin; scrollbar-color: var(--hairline-strong) transparent; } +*::-webkit-scrollbar { width: 10px; height: 10px; } +*::-webkit-scrollbar-thumb { background: var(--hairline-strong); border-radius: 9999px; } +*::-webkit-scrollbar-track { background: transparent; } + +code, pre, .mono { font-family: var(--font-mono); font-size: 13px; } + +.icon { width: 18px; height: 18px; flex: none; display: inline-block; vertical-align: middle; } +.icon--lg { width: 22px; height: 22px; } +.icon--sm { width: 16px; height: 16px; } + +.text-muted { color: var(--ink-muted); } +.text-subtle { color: var(--ink-subtle); } +.text-success { color: var(--success); } +.text-danger { color: var(--danger); } +.text-warning { color: var(--warning); } + +/* -------------------------------------------------------------------------- + 3. LAYOUT + -------------------------------------------------------------------------- */ +.page { + flex: 1; + width: 100%; + padding-top: calc(var(--nav-h) + 48px); + padding-bottom: var(--space-section); +} +.page--flush { padding-top: 0; padding-bottom: 0; } + +.container { width: 100%; max-width: 1160px; margin-inline: auto; padding-inline: 24px; } +.container--wide { max-width: 1320px; } + +.narrow { width: 100%; max-width: 720px; margin-inline: auto; } +.narrow--sm { max-width: 480px; } + +.stack { display: flex; flex-direction: column; gap: 28px; } +.stack--lg { gap: 40px; } + +.center { text-align: center; } + +.grid { display: grid; gap: 20px; } +.grid--auto { grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); } +.grid--3 { grid-template-columns: repeat(3, 1fr); } +.grid--2 { grid-template-columns: repeat(2, 1fr); } +@media (max-width: 1024px) { .grid--3 { grid-template-columns: repeat(2, 1fr); } } +@media (max-width: 720px) { .grid--3, .grid--2 { grid-template-columns: 1fr; } } + +.split { display: grid; grid-template-columns: 1.35fr 1fr; gap: 32px; align-items: start; } +@media (max-width: 880px) { .split { grid-template-columns: 1fr; } } + +.row { display: flex; flex-wrap: wrap; gap: 16px; } +.col { flex: 1; min-width: 0; } + +.mt-1 { margin-top: var(--space-1); } +.mt-2 { margin-top: var(--space-2); } +.mt-3 { margin-top: var(--space-3); } +.mt-4 { margin-top: var(--space-4); } +.mt-5 { margin-top: var(--space-6); } +.mb-1 { margin-bottom: var(--space-1); } +.mb-2 { margin-bottom: var(--space-2); } +.mb-3 { margin-bottom: var(--space-3); } +.mb-4 { margin-bottom: var(--space-4); } +.mb-5 { margin-bottom: var(--space-6); } + +/* Page header (title + optional subtitle/actions) */ +.page-head { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 16px; margin-bottom: 24px; } +.page-head__title { margin: 0; } +.page-head__sub { margin: 4px 0 0; color: var(--ink-subtle); font-size: 15px; } +.page-head__actions { display: inline-flex; flex-wrap: wrap; gap: 8px; } + +/* -------------------------------------------------------------------------- + 4. BUTTONS + -------------------------------------------------------------------------- */ +.btn { + display: inline-flex; align-items: center; + justify-content: center; + gap: 8px; + padding: 8px 14px; + font-family: var(--font-text); + font-size: 14px; + font-weight: 500; + line-height: 1.2; + text-align: center; + white-space: nowrap; + border: 1px solid transparent; + border-radius: var(--radius-md); + cursor: pointer; + user-select: none; + transition: background-color 140ms ease, border-color 140ms ease, color 140ms ease; +} +.btn:disabled, .btn.is-disabled { opacity: 0.45; pointer-events: none; } +.btn--block { width: 100%; } +.btn--lg { padding: 10px 18px; font-size: 15px; } + +.btn--primary { background: var(--primary); border-color: var(--primary); color: var(--on-primary); } +.btn--primary:hover { background: var(--primary-hover); border-color: var(--primary-hover); color: var(--on-primary); } +.btn--primary:active { background: var(--primary-focus); border-color: var(--primary-focus); } + +.btn--secondary { background: var(--surface-1); border-color: var(--hairline-strong); color: var(--ink); } +.btn--secondary:hover { background: var(--surface-2); border-color: var(--hairline-tertiary); color: var(--ink); } +.btn--secondary:active { background: var(--surface-3); } + +.btn--outline { background: transparent; border-color: var(--hairline-strong); color: var(--ink-muted); } +.btn--outline:hover { background: var(--surface-2); border-color: var(--hairline-tertiary); color: var(--ink); } +.btn--outline:active { background: var(--surface-3); color: var(--ink); } + +.btn--ghost { background: transparent; border-color: transparent; color: var(--ink-subtle); } +.btn--ghost:hover { color: var(--ink); background: var(--surface-2); } + +.btn--success { background: var(--success-strong); border-color: var(--success-strong); color: #fff; } +.btn--success:hover { filter: brightness(1.08); color: #fff; } +.btn--success:active { filter: brightness(0.94); } + +.btn--danger { background: var(--danger-strong); border-color: var(--danger-strong); color: #fff; } +.btn--danger:hover { filter: brightness(1.08); color: #fff; } +.btn--danger:active { filter: brightness(0.94); } + +.btn--warning { background: var(--warning-strong); border-color: var(--warning-strong); color: #fff; } +.btn--warning:hover { filter: brightness(1.08); color: #fff; } +.btn--warning:active { filter: brightness(0.94); } + +.btn--link { background: none; border: none; color: var(--primary); padding: 0; } +.btn--link:hover { color: var(--primary-hover); } + +.btn-group { display: inline-flex; flex-wrap: wrap; gap: 8px; } + +/* -------------------------------------------------------------------------- + 5. CARDS + -------------------------------------------------------------------------- */ +.card { + position: relative; + display: flex; + flex-direction: column; + background: var(--surface-1); + border: 1px solid var(--hairline); + border-radius: var(--radius-lg); + box-shadow: inset 0 1px 0 var(--edge-highlight); + overflow: hidden; +} +.card__header { + display: flex; + align-items: center; + gap: 10px; + padding: 16px 24px; + font-family: var(--font-display); + font-size: 15px; + font-weight: 500; + letter-spacing: -0.2px; + color: var(--ink); + background: var(--surface-2); + border-bottom: 1px solid var(--hairline); +} +.card__header .icon { color: var(--ink-subtle); } +.card__body { padding: 28px; } +.card__title { margin-bottom: 6px; font-family: var(--font-display); font-size: 20px; font-weight: 600; letter-spacing: -0.4px; color: var(--ink); } +.card__subtitle { margin: -2px 0 8px; font-size: 14px; color: var(--ink-subtle); } +.card__text { color: var(--ink-muted); } +.card__footer { padding: 12px 20px; background: var(--surface-2); border-top: 1px solid var(--hairline); color: var(--ink-muted); font-size: 14px; } + +/* Key/value rows */ +.kv { + display: flex; justify-content: space-between; -} \ No newline at end of file + align-items: baseline; + gap: 16px; + padding: 10px 0; + border-bottom: 1px solid var(--hairline); + font-size: 14px; + text-align: left; +} +.kv:last-child { border-bottom: 0; } +.kv__k { color: var(--ink-subtle); flex: none; } +.kv__v { color: var(--ink); text-align: right; } + +/* Chips / meta pills */ +.chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 10px; + font-size: 12px; + font-weight: 500; + color: var(--ink-muted); + background: var(--surface-3); + border: 1px solid var(--hairline); + border-radius: var(--radius-pill); + white-space: nowrap; +} + +/* -------------------------------------------------------------------------- + 6. BADGES + -------------------------------------------------------------------------- */ +.badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 2px 10px; + font-size: 12px; + font-weight: 500; + line-height: 1.5; + border: 1px solid transparent; + border-radius: var(--radius-pill); + white-space: nowrap; +} +.badge--neutral { background: var(--surface-3); color: var(--ink-muted); border-color: var(--hairline); } +.badge--primary { background: var(--primary-soft); color: var(--primary); border-color: var(--primary-soft-border); } +.badge--success { background: var(--success-soft); color: var(--success); border-color: var(--success-soft-border); } +.badge--danger { background: var(--danger-soft); color: var(--danger); border-color: var(--danger-soft-border); } +.badge--warning { background: var(--warning-soft); color: var(--warning); border-color: var(--warning-soft-border); } +.badge--info { background: var(--primary-soft); color: var(--primary); border-color: var(--primary-soft-border); } + +/* -------------------------------------------------------------------------- + 7. ALERTS + -------------------------------------------------------------------------- */ +.alert { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 12px 16px; + margin-bottom: 16px; + font-size: 14px; + line-height: 1.5; + text-align: left; + color: var(--ink); + background: var(--surface-1); + border: 1px solid var(--hairline-strong); + border-radius: var(--radius-md); +} +.alert .icon { margin-top: 2px; } +.alert--info { background: var(--primary-soft); border-color: var(--primary-soft-border); } +.alert--info .icon { color: var(--primary); } +.alert--success { background: var(--success-soft); border-color: var(--success-soft-border); } +.alert--success .icon { color: var(--success); } +.alert--danger { background: var(--danger-soft); border-color: var(--danger-soft-border); } +.alert--danger .icon { color: var(--danger); } +.alert--warning { background: var(--warning-soft); border-color: var(--warning-soft-border); } +.alert--warning .icon { color: var(--warning); } + +/* -------------------------------------------------------------------------- + 8. FORMS + -------------------------------------------------------------------------- */ +.field { margin-bottom: 16px; } +.field:last-child { margin-bottom: 0; } + +.label { display: block; margin-bottom: 6px; font-size: 13px; font-weight: 500; color: var(--ink-muted); text-align: left; } + +.input, .select, .textarea { + display: block; + width: 100%; + padding: 9px 12px; + font-family: var(--font-text); + font-size: 14px; + line-height: 1.5; + color: var(--ink); + background-color: var(--surface-1); + border: 1px solid var(--hairline-strong); + border-radius: var(--radius-md); + transition: border-color 140ms ease, box-shadow 140ms ease; +} +.textarea { min-height: 96px; resize: vertical; } +.input::placeholder, .textarea::placeholder { color: var(--ink-tertiary); } + +.input:focus, .select:focus, .textarea:focus { + border-color: var(--primary-focus); + outline: 0; + box-shadow: 0 0 0 3px var(--focus-ring); +} +.input:disabled, .input[readonly] { background: var(--surface-2); color: var(--ink-tertiary); border-color: var(--hairline); } + +.select { + appearance: none; + background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238a8f98' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpath d='m6 9 6 6 6-6'/%3e%3c/svg%3e"); + background-repeat: no-repeat; + background-position: right 10px center; + background-size: 16px; + padding-right: 36px; +} + +.check { display: flex; align-items: flex-start; gap: 8px; font-size: 14px; color: var(--ink-muted); cursor: pointer; text-align: left; } +.check input[type="checkbox"], .check input[type="radio"] { width: 16px; height: 16px; accent-color: var(--primary); margin: 2px 0 0; flex: none; } +.check a { color: var(--primary); } + +.switch { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; color: var(--ink-muted); cursor: pointer; } +.switch input { position: relative; width: 34px; height: 20px; appearance: none; background: var(--surface-3); border: 1px solid var(--hairline-strong); border-radius: var(--radius-pill); cursor: pointer; transition: background 140ms ease; margin: 0; } +.switch input::after { content: ""; position: absolute; top: 2px; left: 2px; width: 14px; height: 14px; border-radius: 50%; background: var(--ink-subtle); transition: transform 140ms ease, background 140ms ease; } +.switch input:checked { background: var(--primary); border-color: var(--primary); } +.switch input:checked::after { transform: translateX(14px); background: #fff; } + +.input-group { display: flex; gap: 8px; align-items: stretch; } +.input-group .input, .input-group .select { flex: 1; min-width: 0; } + +.form-row { display: flex; flex-wrap: wrap; gap: 16px; } +.form-row > .field { flex: 1; min-width: 220px; } + +.hint { font-size: 12.5px; color: var(--ink-subtle); text-align: left; } + +.select-search .input { margin-bottom: 8px; } + +/* -------------------------------------------------------------------------- + 9. TABS + -------------------------------------------------------------------------- */ +.tabs { + display: flex; + flex-wrap: wrap; + gap: 4px; + padding: 4px; + margin: 0; + list-style: none; + background: var(--surface-1); + border: 1px solid var(--hairline); + border-radius: var(--radius-md); +} +.tabs__item { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 12px; + font-size: 14px; + font-weight: 500; + color: var(--ink-subtle); + background: transparent; + border: 0; + border-radius: var(--radius-sm); + cursor: pointer; + transition: color 140ms ease, background-color 140ms ease; +} +.tabs__item:hover:not(:disabled) { color: var(--ink); } +.tabs__item.is-active { background: var(--surface-3); color: var(--ink); } +.tabs__item:disabled { opacity: 0.45; pointer-events: none; } +.tabs__count { display: inline-flex; min-width: 18px; justify-content: center; padding: 0 5px; border-radius: var(--radius-pill); background: var(--surface-2); font-size: 11px; color: var(--ink-muted); border: 1px solid var(--hairline); } + +.tabs-block { display: flex; flex-direction: column; } +.tab-pane { display: none; width: 100%; margin-top: 24px; } +.tab-pane.is-active { display: block; } + +/* -------------------------------------------------------------------------- + 10. PUBLIC NAVBAR + -------------------------------------------------------------------------- */ +.navbar { + position: fixed; + top: 0; right: 0; left: 0; + z-index: 1000; + height: var(--nav-h); + background: var(--nav-bg); + -webkit-backdrop-filter: saturate(180%) blur(12px); + backdrop-filter: saturate(180%) blur(12px); + border-bottom: 1px solid var(--hairline); +} +.navbar__inner { display: flex; align-items: center; gap: 16px; height: 100%; max-width: 1280px; margin-inline: auto; padding-inline: 24px; } +.navbar__brand { display: inline-flex; align-items: center; gap: 11px; font-family: var(--font-display); font-size: 20px; font-weight: 600; letter-spacing: -0.4px; color: var(--ink); white-space: nowrap; } +.navbar__brand:hover { color: var(--ink); } +.navbar__mark { display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; border-radius: var(--radius-sm); color: var(--primary); transition: color 140ms ease; } +.navbar__brand:hover .navbar__mark { color: var(--primary-hover); } +.navbar__logo { width: 40px; height: 40px; flex: none; } +.navbar__link--cta { color: var(--on-primary) !important; background: var(--primary); padding: 10px 20px; } +.navbar__link--cta:hover { color: var(--on-primary) !important; background: var(--primary-hover); } + +.navbar__toggle { display: none; margin-left: auto; padding: 6px 8px; background: transparent; border: 1px solid var(--hairline-strong); border-radius: var(--radius-md); color: var(--ink); cursor: pointer; } + +.navbar__nav { display: flex; align-items: center; gap: 4px; margin-left: auto; } +.navbar__link { display: block; padding: 11px 18px; font-size: 16px; color: var(--ink-subtle); border-radius: var(--radius-md); white-space: nowrap; transition: color 140ms ease, background-color 140ms ease; } +.navbar__link:hover { color: var(--ink); background: var(--surface-2); } +.navbar__link.is-active { color: var(--ink); } +/* Smaller auth buttons (Sign in / Sign up) with a small gap between them */ +.navbar__link--auth { padding: 8px 14px; font-size: 14px; line-height: 1.2; } +.navbar__link--cta.navbar__link--auth { margin-left: 6px; } + +.dropdown { position: relative; } +.dropdown__menu { + position: absolute; + top: calc(100% + 8px); + left: 0; + min-width: 200px; + padding: 6px; + background: var(--surface-3); + border: 1px solid var(--hairline-strong); + border-radius: var(--radius-lg); + box-shadow: inset 0 1px 0 var(--edge-highlight); + opacity: 0; visibility: hidden; + transform: translateY(-4px); + transition: opacity 140ms ease, transform 140ms ease, visibility 140ms ease; + z-index: 50; +} +.dropdown.is-open .dropdown__menu { opacity: 1; visibility: visible; transform: translateY(0); } +.dropdown__item { display: block; padding: 8px 10px; font-size: 14px; color: var(--ink-muted); border-radius: var(--radius-sm); white-space: nowrap; } +.dropdown__item:hover { color: var(--ink); background: var(--surface-2); } +.dropdown__item.is-active { color: var(--ink); } +.dropdown__divider { height: 1px; margin: 6px 0; background: var(--hairline); } + +@media (max-width: 900px) { + .navbar__link--cta.navbar__link--auth { margin-left: 0; } + .navbar__toggle { display: inline-flex; } + .navbar__nav { display: none; position: absolute; top: var(--nav-h); left: 0; right: 0; flex-direction: column; align-items: stretch; gap: 0; margin: 0; padding: 12px 24px 20px; background: var(--canvas); border-bottom: 1px solid var(--hairline); } + .navbar__nav.is-open { display: flex; } + .dropdown__menu { position: static; opacity: 1; visibility: visible; transform: none; border: 0; background: transparent; box-shadow: none; padding: 0 0 0 12px; } +} + +/* -------------------------------------------------------------------------- + 11. ADMIN SIDEBAR + TOPBAR + -------------------------------------------------------------------------- */ +body.admin { padding-left: var(--sidebar-w); } +body.admin .page { padding-top: calc(var(--nav-h) + 36px); } + +.sidebar { + position: fixed; + top: 0; left: 0; bottom: 0; + width: var(--sidebar-w); + display: flex; + flex-direction: column; + background: var(--surface-1); + border-right: 1px solid var(--hairline); + z-index: 1000; +} +.sidebar__head { display: flex; align-items: center; gap: 9px; height: var(--nav-h); padding: 0 20px; border-bottom: 1px solid var(--hairline); } +.sidebar__nav { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 2px; } +.sidebar__label { margin: 16px 10px 6px; font-size: 11px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-tertiary); } +.sidebar__link { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 10px; + font-size: 14px; + color: var(--ink-muted); + border-radius: var(--radius-md); + transition: color 140ms ease, background-color 140ms ease; +} +.sidebar__link .icon { color: var(--ink-subtle); } +.sidebar__link:hover { color: var(--ink); background: var(--surface-2); } +.sidebar__link.is-active { color: var(--ink); background: var(--surface-3); } +.sidebar__link.is-active .icon { color: var(--primary); } +.sidebar__foot { padding: 12px; border-top: 1px solid var(--hairline); } + +.topbar { + position: fixed; + top: 0; left: var(--sidebar-w); right: 0; + height: var(--nav-h); + display: flex; + align-items: center; + gap: 16px; + padding: 0 24px; + background: var(--nav-bg); + -webkit-backdrop-filter: saturate(180%) blur(12px); + backdrop-filter: saturate(180%) blur(12px); + border-bottom: 1px solid var(--hairline); + z-index: 900; +} +.topbar__title { font-family: var(--font-display); font-size: 18px; font-weight: 600; letter-spacing: -0.3px; color: var(--ink); } +.topbar__right { margin-left: auto; display: inline-flex; align-items: center; gap: 12px; } +.topbar__user { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; color: var(--ink-muted); } +.topbar__toggle { display: none; padding: 6px 8px; background: transparent; border: 1px solid var(--hairline-strong); border-radius: var(--radius-md); color: var(--ink); cursor: pointer; } + +.sidebar__backdrop { display: none; position: fixed; inset: 0; background: var(--scrim); z-index: 990; } + +@media (max-width: 960px) { + body.admin { padding-left: 0; } + .sidebar { transform: translateX(-100%); transition: transform 200ms ease; } + body.admin .sidebar.is-open { transform: translateX(0); } + body.admin .sidebar.is-open + .sidebar__backdrop, .sidebar__backdrop.is-open { display: block; } + .topbar { left: 0; } + .topbar__toggle { display: inline-flex; } +} + +/* -------------------------------------------------------------------------- + 12. AUTH (split screen) + -------------------------------------------------------------------------- */ +.auth { display: grid; grid-template-columns: 1fr 1fr; min-height: 100vh; } +.auth__back { + align-self: flex-start; + display: inline-flex; + align-items: center; + justify-content: center; + width: 42px; + height: 42px; + border-radius: 50%; + color: var(--ink-muted); + background: var(--surface-1); + border: 1px solid var(--hairline-strong); + transition: color 140ms ease, background-color 140ms ease, border-color 140ms ease, transform 140ms ease; +} +.auth__back:hover { color: var(--ink); background: var(--surface-2); border-color: var(--hairline-tertiary); transform: translateX(-2px); } +.auth__back .icon { width: 20px; height: 20px; } +.auth__back--mobile { display: none; } +.auth__brand { + display: flex; + flex-direction: column; + justify-content: space-between; + gap: 40px; + padding: 48px; + background: var(--surface-1); + border-right: 1px solid var(--hairline); +} +.auth__brand-top { display: inline-flex; align-items: center; gap: 9px; font-family: var(--font-display); font-size: 18px; font-weight: 600; letter-spacing: -0.4px; color: var(--ink); } +.auth__brand-top .navbar__mark { color: var(--primary); } +.auth__brand h2 { font-size: 2rem; letter-spacing: -0.03em; max-width: 420px; } +.auth__brand p { color: var(--ink-subtle); max-width: 400px; } +.auth__points { display: flex; flex-direction: column; gap: 16px; margin-top: 8px; } +.auth__point { display: flex; gap: 12px; align-items: flex-start; } +.auth__point .icon { color: var(--primary); margin-top: 2px; } +.auth__point b { color: var(--ink); font-weight: 600; } +.auth__point span { color: var(--ink-subtle); font-size: 14px; } +.auth__foot { font-size: 13px; color: var(--ink-tertiary); } + +.auth__form { display: flex; align-items: center; justify-content: center; padding: 48px 24px; } +.auth__form-inner { width: 100%; max-width: 400px; } +.auth__form h1 { margin-bottom: 4px; } +.auth__form .card { box-shadow: none; } +.auth__foot-link { margin-top: 16px; text-align: center; font-size: 14px; color: var(--ink-subtle); } + +@media (max-width: 880px) { + .auth { grid-template-columns: 1fr; } + .auth__brand { display: none; } + .auth__back--mobile { display: inline-flex; margin-bottom: 24px; } +} + +/* -------------------------------------------------------------------------- + 13. LANDING (home) + -------------------------------------------------------------------------- */ +.hero { + position: relative; + padding: 72px 0 40px; + text-align: left; + overflow: hidden; +} +/* Fine dot-grid behind the hero */ +.hero::before { + content: ""; + position: absolute; + pointer-events: none; + z-index: 0; + inset: 0; + background-image: radial-gradient(rgba(255, 255, 255, 0.055) 1px, transparent 1.4px); + background-size: 22px 22px; + -webkit-mask-image: radial-gradient(ellipse 85% 75% at 50% 0%, #000 25%, transparent 78%); + mask-image: radial-gradient(ellipse 85% 75% at 50% 0%, #000 25%, transparent 78%); +} +[data-theme="light"] .hero::before { + background-image: radial-gradient(rgba(24, 26, 29, 0.07) 1px, transparent 1.4px); +} +.hero__content { position: relative; z-index: 1; max-width: 900px; } +.hero__title { font-size: clamp(3.25rem, 7vw, 5.5rem); letter-spacing: -0.04em; margin-bottom: 1.5rem; line-height: 1.05; } +.hero__accent { + background: linear-gradient(90deg, var(--primary-hover) 0%, var(--success) 50%, var(--primary-hover) 100%); + background-size: 200% 100%; + -webkit-background-clip: text; + background-clip: text; + color: transparent; + animation: heroAccent 6s linear infinite; +} +@keyframes heroAccent { + 0% { background-position: 0% 50%; } + 100% { background-position: 200% 50%; } +} + +/* Hero — popular links */ +.hero__popular { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-top: 32px; } +.hero__popular-label { font-size: 12px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; color: var(--ink-tertiary); } +.hero__popular-list { display: inline-flex; flex-wrap: wrap; gap: 6px; } +.chip--link { color: var(--ink-muted); text-decoration: none; transition: color 140ms ease, border-color 140ms ease, background 140ms ease, transform 140ms ease; } +.chip--link:hover { color: var(--primary); border-color: var(--primary-soft-border); background: var(--primary-soft); transform: translateY(-1px); } + +/* Landing — entrance animation (hero) */ +.hero__title, .hero__popular { + animation: heroReveal 800ms cubic-bezier(0.16, 1, 0.3, 1) both; +} +.hero__title { animation-delay: 60ms; } +.hero__popular { animation-delay: 140ms; } +@keyframes heroReveal { + from { opacity: 0; transform: translateY(20px) scale(0.985); filter: blur(6px); } + to { opacity: 1; transform: none; filter: blur(0); } +} + +/* Landing — scroll reveal */ +.reveal { opacity: 0; transform: translateY(26px); transition: opacity 650ms ease, transform 650ms ease; } +.reveal.is-visible { opacity: 1; transform: none; } +.landing-stats .reveal { transition-delay: 80ms; } +.landing-stats .reveal:nth-child(2) { transition-delay: 140ms; } +.landing-stats .reveal:nth-child(3) { transition-delay: 200ms; } +.landing-stats .reveal:nth-child(4) { transition-delay: 260ms; } +.steps .reveal { transition-delay: 80ms; } +.steps .reveal:nth-child(2) { transition-delay: 140ms; } +.steps .reveal:nth-child(3) { transition-delay: 200ms; } +@media (prefers-reduced-motion: reduce) { + .reveal { opacity: 1; transform: none; transition: none; } + .hero__title, .hero__popular, .hero__accent { animation: none; } + .hero::before { animation: none; } +} + +.section-head { text-align: center; margin-bottom: 44px; } +.section-head h2 { margin-bottom: 8px; } +.section-head p { color: var(--ink-subtle); } + +.featured { padding: 96px 0 0; } +.steps { padding: 104px 0 0; } +.step { position: relative; background: var(--surface-1); border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 28px; box-shadow: inset 0 1px 0 var(--edge-highlight); } +.step__head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; } +.step__icon { display: inline-flex; align-items: center; justify-content: center; width: 44px; height: 44px; border-radius: var(--radius-md); background: var(--primary-soft); color: var(--primary); } +.step:nth-child(2) .step__icon { background: var(--success-soft); color: var(--success); } +.step:nth-child(3) .step__icon { background: var(--warning-soft); color: var(--warning); } +.step__num { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 24px; + height: 24px; + padding: 0 6px; + border-radius: var(--radius-pill); + background: var(--surface-3); + border: 1px solid var(--hairline); + color: var(--ink-subtle); + font-family: var(--font-display); + font-size: 12.5px; + font-weight: 600; +} +.step h3 { font-size: 1.05rem; margin-bottom: 6px; } +.step p { color: var(--ink-subtle); font-size: 14.5px; } + +.cta { padding: 104px 0 0; } +.cta__inner { + position: relative; + overflow: hidden; + text-align: center; + padding: 64px 24px; + border: 0; + border-radius: var(--radius-xl); + background: linear-gradient(135deg, var(--primary) 0%, #6d5bd0 45%, var(--success-strong) 110%); + box-shadow: 0 30px 70px rgba(64, 70, 160, 0.35); +} +.cta__inner::before, +.cta__inner::after { + content: ""; + position: absolute; + border-radius: 50%; + pointer-events: none; +} +.cta__inner::before { width: 260px; height: 260px; top: -120px; left: -60px; background: rgba(255, 255, 255, 0.12); } +.cta__inner::after { width: 320px; height: 320px; bottom: -160px; right: -80px; background: rgba(0, 0, 0, 0.10); } +.cta__inner h2, .cta__inner p, .cta__inner .btn-group { position: relative; z-index: 1; } +.cta__inner h2 { color: #fff; margin-bottom: 8px; } +.cta__inner p { color: rgba(255, 255, 255, 0.85); margin-bottom: 28px; } +.cta__inner .btn-group { justify-content: center; } +.cta__inner .btn--primary { background: #fff; border-color: #fff; color: var(--primary); } +.cta__inner .btn--primary:hover { background: rgba(255, 255, 255, 0.9); border-color: rgba(255, 255, 255, 0.9); color: var(--primary); } +.cta__inner .btn--secondary { background: rgba(255, 255, 255, 0.14); border-color: rgba(255, 255, 255, 0.45); color: #fff; } +.cta__inner .btn--secondary:hover { background: rgba(255, 255, 255, 0.22); border-color: rgba(255, 255, 255, 0.6); color: #fff; } + +@media (max-width: 1024px) { + .hero { text-align: center; } + .hero__content { margin-inline: auto; } + .hero__popular, .hero__popular-list { justify-content: center; } +} + + +/* Error pages (404 / 403) */ +.error { max-width: 640px; margin: 0 auto; padding: 120px 0 80px; text-align: center; } +.error__code { + font-family: var(--font-display); + font-size: clamp(5rem, 12vw, 8rem); + font-weight: 700; + letter-spacing: -0.05em; + line-height: 1; + margin-bottom: 20px; + background: linear-gradient(135deg, var(--primary-hover), var(--success)); + -webkit-background-clip: text; + background-clip: text; + color: transparent; +} +.error__icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 56px; + height: 56px; + border-radius: 50%; + background: var(--danger-soft); + color: var(--danger); + margin-bottom: 20px; +} +.error__title { font-size: 1.6rem; margin-bottom: 8px; } +.error__text { color: var(--ink-subtle); font-size: 16px; margin-bottom: 28px; } +.error .btn-group { justify-content: center; margin-bottom: 28px; } +.error__search { max-width: 480px; margin: 0 auto; } + +/* Landing — stats band */ +.landing-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin: 80px 0 0; } +.landing-stat { + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; + padding: 24px 16px; + text-align: center; + background: var(--surface-1); + border: 1px solid var(--hairline); + border-radius: var(--radius-lg); + box-shadow: inset 0 1px 0 var(--edge-highlight); + transition: border-color 140ms ease, transform 140ms ease; +} +.landing-stat:hover { border-color: var(--hairline-strong); transform: translateY(-2px); } +.landing-stat__icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 42px; + height: 42px; + border-radius: var(--radius-md); + background: var(--primary-soft); + color: var(--primary); + margin-bottom: 8px; +} +.landing-stat:nth-child(2) .landing-stat__icon { background: var(--success-soft); color: var(--success); } +.landing-stat:nth-child(3) .landing-stat__icon { background: var(--warning-soft); color: var(--warning); } +.landing-stat:nth-child(4) .landing-stat__icon { background: var(--surface-3); color: var(--ink-muted); } +.landing-stat__value { font-family: var(--font-display); font-size: 30px; font-weight: 600; letter-spacing: -0.5px; line-height: 1; color: var(--ink); } +.landing-stat__label { font-size: 13px; color: var(--ink-subtle); } +@media (max-width: 1024px) { .landing-stats { grid-template-columns: repeat(2, 1fr); } } +@media (max-width: 560px) { .landing-stats { grid-template-columns: 1fr; } } + +.book-card { transition: border-color 140ms ease, transform 140ms ease, box-shadow 140ms ease; } +.book-card:hover { border-color: var(--hairline-strong); transform: translateY(-4px); box-shadow: 0 18px 40px rgba(0, 0, 0, 0.18); } + +/* -------------------------------------------------------------------------- + 14. BOOK GRID (search results) + -------------------------------------------------------------------------- */ +.searchband { background: var(--surface-1); border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 16px; margin-bottom: 24px; box-shadow: inset 0 1px 0 var(--edge-highlight); } +.searchband .input { height: 44px; font-size: 15px; } + +.books-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px; } +.book-card { display: flex; flex-direction: column; background: var(--surface-1); border: 1px solid var(--hairline); border-radius: var(--radius-lg); box-shadow: inset 0 1px 0 var(--edge-highlight); overflow: hidden; transition: border-color 140ms ease, transform 140ms ease; } +.book-card:hover { border-color: var(--hairline-strong); } +.book-card__cover { + position: relative; + display: flex; + align-items: center; + justify-content: center; + height: 120px; + background: var(--surface-3); + border-bottom: 1px solid var(--hairline); + color: var(--ink-tertiary); +} +.book-card__cover .icon { width: 30px; height: 30px; } +.book-card__status { position: absolute; top: 12px; right: 12px; } +.book-card__body { padding: 16px; display: flex; flex-direction: column; gap: 6px; flex: 1; } +.book-card__title { font-family: var(--font-display); font-size: 16px; font-weight: 600; letter-spacing: -0.3px; color: var(--ink); line-height: 1.25; } +.book-card__author { font-size: 13.5px; color: var(--ink-subtle); } +.book-card__meta { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; } +.book-card__foot { display: flex; gap: 8px; margin-top: auto; padding-top: 12px; } +.book-card__foot .btn { flex: 1; } + +/* -------------------------------------------------------------------------- + 15. PROFILE / READER + -------------------------------------------------------------------------- */ +.avatar { + display: inline-flex; + align-items: center; + justify-content: center; + width: 72px; + height: 72px; + border-radius: var(--radius-xl); + background: var(--surface-3); + border: 1px solid var(--hairline); + color: var(--primary); + font-family: var(--font-display); + font-size: 26px; + font-weight: 600; + letter-spacing: -1px; + flex: none; +} +.profile-head { display: flex; align-items: center; gap: 20px; flex-wrap: wrap; } +.profile-head__name { margin: 0; } +.profile-head__meta { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 6px; color: var(--ink-subtle); font-size: 14px; } + +.stat-strip { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; } +@media (max-width: 720px) { .stat-strip { grid-template-columns: 1fr; } } +.stat-strip__item { background: var(--surface-1); border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 16px 20px; } +.stat-strip__value { font-family: var(--font-display); font-size: 24px; font-weight: 600; letter-spacing: -0.5px; color: var(--ink); } +.stat-strip__label { font-size: 13px; color: var(--ink-subtle); } + +/* -------------------------------------------------------------------------- + 16. MODAL + -------------------------------------------------------------------------- */ +.modal { display: none; } +.modal.is-open { display: block; } +.modal__backdrop { position: fixed; inset: 0; z-index: 1050; display: flex; align-items: center; justify-content: center; padding: 24px; background: var(--scrim); } +.modal__dialog { width: 100%; max-width: 480px; max-height: 90vh; overflow: auto; background: var(--surface-1); border: 1px solid var(--hairline-strong); border-radius: var(--radius-xl); box-shadow: inset 0 1px 0 var(--edge-highlight); } +.modal__header { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 16px 20px; border-bottom: 1px solid var(--hairline); } +.modal__title { margin: 0; font-size: 17px; font-weight: 600; letter-spacing: -0.3px; } +.modal__close { padding: 4px; background: transparent; border: 0; color: var(--ink-subtle); cursor: pointer; border-radius: var(--radius-sm); } +.modal__close:hover { color: var(--ink); background: var(--surface-2); } +.modal__body { padding: 20px; font-size: 14px; color: var(--ink-muted); } +.modal__body ul { margin: 8px 0 0; padding-left: 20px; } +.modal__footer { display: flex; justify-content: flex-end; gap: 8px; padding: 14px 20px; border-top: 1px solid var(--hairline); } +body.modal-open { overflow: hidden; } + +/* -------------------------------------------------------------------------- + 17. TABLE + -------------------------------------------------------------------------- */ +.table-wrap { overflow-x: auto; border: 1px solid var(--hairline); border-radius: var(--radius-md); } +.table { width: 100%; border-collapse: collapse; font-size: 14px; } +.table th, .table td { padding: 10px 12px; text-align: left; border-bottom: 1px solid var(--hairline); vertical-align: top; } +.table th { background: var(--surface-2); color: var(--ink-muted); font-weight: 500; font-size: 13px; } +.table tr:last-child td { border-bottom: 0; } +.table td .label { margin: 0; } +.table .select, .table .input { min-width: 200px; } + +/* -------------------------------------------------------------------------- + 18. STAT CARDS (dashboard) + -------------------------------------------------------------------------- */ +.stat .card__body { display: flex; align-items: center; justify-content: space-between; gap: 16px; } +.stat__icon { display: inline-flex; align-items: center; justify-content: center; width: 44px; height: 44px; border-radius: var(--radius-md); background: var(--surface-3); border: 1px solid var(--hairline); color: var(--ink-muted); } +.stat--primary .stat__icon { color: var(--primary); } +.stat--success .stat__icon { color: var(--success); } +.stat--warning .stat__icon { color: var(--warning); } +.stat--info .stat__icon { color: var(--primary); } +.stat--secondary .stat__icon { color: var(--ink-subtle); } +.stat__value { font-family: var(--font-display); font-size: 32px; font-weight: 600; letter-spacing: -1px; line-height: 1; color: var(--ink); } + +/* -------------------------------------------------------------------------- + 18.5 CHARTS (dashboard) + -------------------------------------------------------------------------- */ +.charts-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; margin-top: 24px; } +@media (max-width: 1024px) { .charts-grid { grid-template-columns: 1fr; } } +.charts-grid > .chart:last-child:nth-child(odd) { grid-column: 1 / -1; } + +.chart { min-width: 0; } +.chart__body { padding: 20px 24px; } +.chart-empty { color: var(--ink-subtle); text-align: center; padding: 24px 0; margin: 0; font-size: 14px; } + +/* Vertical bars */ +.bars { display: flex; align-items: stretch; gap: 10px; height: 200px; } +.bars__col { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: center; gap: 6px; } +.bars__bar-wrap { flex: 1; width: 100%; display: flex; align-items: flex-end; justify-content: center; } +.bars__bar { width: 65%; max-width: 40px; min-height: 2px; border-radius: 6px 6px 2px 2px; background: var(--primary); transition: height 500ms ease; } +.bars__bar--muted { background: var(--hairline-strong); } +.bars__value { font-family: var(--font-display); font-size: 13px; font-weight: 600; color: var(--ink-muted); line-height: 1; } +.bars__label { font-size: 12px; color: var(--ink-subtle); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; text-transform: capitalize; } + +/* Donut */ +.donut-wrap { display: flex; align-items: center; gap: 24px; } +.donut { position: relative; width: 150px; height: 150px; border-radius: 50%; flex: none; } +.donut__hole { position: absolute; inset: 26px; border-radius: 50%; background: var(--surface-1); } +.donut__legend { flex: 1; min-width: 0; margin: 0; padding: 0 0 0 8px; list-style: none; display: flex; flex-direction: column; gap: 5px; max-height: 150px; overflow-y: auto; font-size: 13px; color: var(--ink-muted); } +.donut__legend li { display: flex; align-items: center; gap: 8px; min-width: 0; } +.donut__dot { width: 10px; height: 10px; border-radius: 3px; flex: none; } +.donut__label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.donut__pct { flex: none; font-size: 12px; color: var(--ink-subtle); } +.donut__legend b { margin-left: auto; flex: none; color: var(--ink); font-weight: 600; font-family: var(--font-display); } +@media (max-width: 560px) { .donut-wrap { flex-direction: column; align-items: flex-start; } .donut__legend { width: 100%; padding: 0; } } + +/* Split layout for pie + legend */ +.chart-split { display: flex; align-items: center; gap: 24px; } +/* Vertically center the chart content inside its card (equal-height grid rows) */ +.chart--center .card__body { flex: 1; display: flex; align-items: center; } +.chart--center .chart-split { width: 100%; } +@media (max-width: 560px) { .chart-split { flex-direction: column; align-items: flex-start; } .chart-split .donut__legend { width: 100%; padding: 0; } } + +/* Pie (SVG) */ +.pie-wrap { flex: none; position: relative; } +.pie { width: 140px; height: 140px; display: block; } + +/* Chart hover tooltip (line + pie) */ +.line-wrap { position: relative; } +.chart-tip { + position: absolute; + z-index: 5; + pointer-events: none; + opacity: 0; + visibility: hidden; + transform: translateY(4px); + transition: opacity 120ms ease, transform 120ms ease; + padding: 6px 10px; + border-radius: var(--radius-md); + background: var(--ink); + color: var(--surface-1); + font-family: var(--font-display); + font-size: 12.5px; + font-weight: 600; + white-space: nowrap; + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.28); +} +.chart-tip.is-visible { opacity: 1; visibility: visible; transform: translateY(0); } +.chart-dot { cursor: pointer; } +.chart-dot.is-active { fill: var(--primary); stroke-width: 2.6; } + +/* Horizontal bars */ +.hbars { display: flex; flex-direction: column; gap: 13px; } +.hbar { display: grid; grid-template-columns: 1fr auto; gap: 4px 12px; align-items: center; font-size: 13px; } +.hbar__label { color: var(--ink-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.hbar__value { color: var(--ink); font-weight: 600; font-family: var(--font-display); } +.hbar__track { grid-column: 1 / -1; height: 8px; border-radius: 999px; background: var(--surface-3); overflow: hidden; } +.hbar__fill { display: block; height: 100%; border-radius: 999px; background: linear-gradient(90deg, var(--primary), var(--primary-hover)); transition: width 500ms ease; } + +/* Line chart (SVG) */ +.line-wrap { width: 100%; } +.line-chart { display: block; width: 100%; height: 160px; } +.line-labels { display: flex; gap: 2px; margin-top: 4px; } +.line-labels span { flex: 1; min-width: 0; font-size: 10.5px; color: var(--ink-subtle); text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-transform: capitalize; } + +/* Gauge (SVG) */ +.gauge-wrap { position: relative; display: flex; flex-direction: column; align-items: center; gap: 6px; padding-top: 8px; } +.gauge { display: block; width: 220px; height: 120px; } +.gauge__value { position: absolute; top: 62px; font-family: var(--font-display); font-size: 34px; font-weight: 600; letter-spacing: -1px; color: var(--ink); line-height: 1; } +.gauge__meta { font-size: 13px; color: var(--ink-subtle); text-align: center; } + +/* -------------------------------------------------------------------------- + 19. FOOTER + -------------------------------------------------------------------------- */ +.footer { margin-top: auto; border-top: 1px solid var(--hairline); background: var(--surface-1); } +.footer__inner { max-width: 1280px; margin-inline: auto; padding: 56px 24px 32px; } +.footer__grid { display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 40px; margin-bottom: 40px; } +.footer__col { display: flex; flex-direction: column; gap: 10px; } +.footer__title { font-size: 13px; font-weight: 600; color: var(--ink-subtle); text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 6px; } +.footer__logo { display: inline-flex; align-items: center; gap: 10px; color: var(--ink); font-family: var(--font-display); font-weight: 600; font-size: 17px; letter-spacing: -0.3px; } +.footer__logo img { width: 28px; height: 28px; } +.footer__col p { color: var(--ink-subtle); font-size: 14px; max-width: 320px; } +.footer__link { font-size: 14px; color: var(--ink-subtle); } +.footer__link:hover { color: var(--ink); } +.footer__social { display: inline-flex; gap: 6px; margin-top: 6px; } +.footer__social a { display: inline-flex; align-items: center; justify-content: center; width: 34px; height: 34px; border-radius: var(--radius-md); color: var(--ink-subtle); border: 1px solid var(--hairline); } +.footer__social a:hover { color: var(--ink); background: var(--surface-2); } +.footer__bottom { border-top: 1px solid var(--hairline); padding-top: 24px; font-size: 13px; color: var(--ink-tertiary); } +@media (max-width: 760px) { .footer__grid { grid-template-columns: 1fr; gap: 28px; } } + +/* -------------------------------------------------------------------------- + 20. MISC + -------------------------------------------------------------------------- */ +.spinner { width: 18px; height: 18px; border: 2px solid var(--hairline-strong); border-top-color: var(--primary); border-radius: 50%; animation: spin 0.7s linear infinite; } +@keyframes spin { to { transform: rotate(360deg); } } + +.pagination { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 6px; } + +.prose { max-width: 760px; } +.prose h1 { margin-bottom: 16px; } +.prose .lead { font-size: 18px; color: var(--ink-subtle); } +.prose section { margin-bottom: 24px; } +.prose h2 { font-size: 1.125rem; margin-bottom: 6px; } + +.empty { text-align: center; padding: 48px 24px; color: var(--ink-subtle); } +.empty .icon { width: 36px; height: 36px; color: var(--ink-tertiary); margin-bottom: 12px; } + +@media (prefers-reduced-motion: reduce) { + * { animation: none !important; transition: none !important; } + html { scroll-behavior: auto; } +} diff --git a/books-reader.php b/books-reader.php old mode 100644 new mode 100755 index acf1997..2c008ad --- a/books-reader.php +++ b/books-reader.php @@ -1,71 +1,124 @@ - - - - - - - - - - Informations sur le livre - - - - - -
-
-
-
-
-
-

-
    -
  • ID n°
  • -
  • ISBN :
  • -
  • Éditeur :
  • -
  • Type :
  • - -
  • Genre :
  • - - -
  • Identifiant unique :
  • - - -
  • Tome de la série
  • - -
- -
    -
  • Emprunté par
  • -
  • Retour prévu le
  • -
- -
- - Modifier - Emprunt - -
-
-
-
-
- - - - \ No newline at end of file + + + + + + + + + + BookFind — Book information + + + + + +
+
+
+
+

+

+
+ +
+ Edit + Loan +
+ +
+ +
+
+
+ + About the book +
+
+ +

+ +

No summary available.

+ +
+
+ ID + no. +
+
+ ISBN + +
+
+ Publisher + +
+
+ Type + +
+ +
+ Genre + +
+ + +
+ Unique identifier + +
+ + +
+ Series + Volume +
+ +
+
+
+ +
+
+ + Availability +
+
+ + Currently on loan +
+
+ Borrowed by + +
+
+ Due on + +
+
+ + Available +

This book is available for loan.

+ +
+
+
+
+
+ + + + diff --git a/books.php b/books.php old mode 100644 new mode 100755 index f3c30c7..47cc06f --- a/books.php +++ b/books.php @@ -1,47 +1,57 @@ - - - - - - - - - - Rechercher un livre - - - - - -
-
-
-
- /> - -
-
-
-
- - - - - \ No newline at end of file + + + + + + + + + + BookFind — Search for a book + + + + + +
+
+
+
+

Search for a book

+

Browse the C.D.I. catalog.

+
+
+ +
+
+
+ /> + +
+
+
+ + +
+
+ + + + diff --git a/configuration.php b/configuration.php old mode 100644 new mode 100755 index 3ef2163..e620bf9 --- a/configuration.php +++ b/configuration.php @@ -1,326 +1,347 @@ - - - - - - - - - - Configuration du projet - - - - - - -
-

Bienvenue sur BookFind !

-

Fichier de configuration du site

- - - - -
-
- 1. Configurer les accès MySQL -
-
-
- -
- - -
-
- - -
-
- - -
- -
- Enregistré avec succès ! Recharger la page.
'; - } - ?> -
-
- Étape 1 validée.'; - $step1 = true; - } ?> - - - -
-
- 2. Importer la base de données -
-
-
-
- -
-
- - -
-
- - -
-
-
-
- - -
-
- setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } catch (PDOException $e) { - echo 'Connexion failed : ' . $e->getMessage(); - } - $sqlFilePath = 'actions/bookfind.sql'; - if (file_exists($sqlFilePath)) { - $sql = file_get_contents($sqlFilePath); - $sql = preg_replace('/CREATE DATABASE\s+IF NOT EXISTS.*?;|CREATE DATABASE.*?;|USE `.*?`;/is', '', $sql); - $queries = array_filter(array_map('trim', explode(';', $sql))); - foreach ($queries as $query) { - if (!empty($query)) { - try { - $bdd->exec($query); - } catch (Exception $e) { - echo '
Erreur d\'exécution SQL : ' . htmlspecialchars($e->getMessage()) . '
'; - } - } - } - echo '
Tables importées. Recharger la page.
'; - } else { - echo '
Fichier SQL introuvable.
'; - } - } else { - echo '
Identifiants MySQL manquants. Remplissez d\'abord le formulaire plus haut.
'; - } - } - - if (isset($_POST['import'])) { - if (!empty($host) && !empty($username)) { - // If the user requests to import only tables - if (!empty($_POST['onlyTables'])) { - $dbnameInput = !empty($_POST['dbname_import']) ? trim($_POST['dbname_import']) : 'bookfind'; - $filePath = 'actions/database.php'; - $fileContent = file_get_contents($filePath); - $fileContent = preg_replace_callback('/\\$dbname\s*=\s*\'[^\']*\';/', function ($m) use ($dbnameInput) { - return '$dbname = ' . var_export($dbnameInput, true) . ';'; - }, $fileContent); - file_put_contents($filePath, $fileContent); - // Reconnect to the provided database - include 'actions/database.php'; - $sqlFilePath = 'actions/bookfind.sql'; - if (file_exists($sqlFilePath)) { - $sql = file_get_contents($sqlFilePath); - $cleanSql = preg_replace('/CREATE DATABASE\\s+IF NOT EXISTS.*?;|CREATE DATABASE.*?;|USE `.*?`;/is', '', $sql); - $queries = array_filter(array_map('trim', explode(';', $cleanSql))); - foreach ($queries as $query) { - if (!empty($query)) { - try { - $bdd->exec($query); - } catch (Exception $e) { - echo '
Erreur d\'exécution SQL : ' . htmlspecialchars($e->getMessage()) . '
'; - } - } - } - echo '
Tables importées. Recharger la page.
'; - } else { - echo '
Fichier SQL introuvable.
'; - } - // End of import-only-tables flow - goto end_import; - } - - $filePath = 'actions/database.php'; - $fileContent = file_get_contents($filePath); - $fileContent = preg_replace_callback('/\\$dbname\s*=\s*\'[^\']*\';/', function ($m) { - return '$dbname = ' . var_export('bookfind', true) . ';'; - }, $fileContent); - file_put_contents($filePath, $fileContent); - $sqlFilePath = 'actions/bookfind.sql'; - if (file_exists($sqlFilePath)) { - $sql = file_get_contents($sqlFilePath); - // Create the database without connecting to a non-existent database - try { - $tmpDsn = 'mysql:host=' . $host . ';charset=utf8'; - $tmpPdo = new PDO($tmpDsn, $username, $password); - $tmpPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $tmpPdo->exec('CREATE DATABASE IF NOT EXISTS `bookfind` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci'); - } catch (Exception $e) { - echo '
Impossible de créer la base : ' . htmlspecialchars($e->getMessage()) . '
'; - // Stop here - goto end_import; - } - // Reload config to connect to the new database - include 'actions/database.php'; - // Remove any CREATE DATABASE / USE lines from the dump before execution - $cleanSql = preg_replace('/CREATE DATABASE\\s+IF NOT EXISTS.*?;|CREATE DATABASE.*?;|USE `.*?`;/is', '', $sql); - $queries = array_filter(array_map('trim', explode(';', $cleanSql))); - foreach ($queries as $query) { - if (!empty($query)) { - try { - $bdd->exec($query); - } catch (Exception $e) { - echo '
Erreur d\'exécution SQL : ' . htmlspecialchars($e->getMessage()) . '
'; - } - } - } - echo '
Base de données importée. Recharger la page.
'; - } else { - echo '
Fichier SQL introuvable.
'; - } - } else { - echo '
Identifiants MySQL manquants. Remplissez d\'abord le formulaire plus haut.
'; - } - } - end_import: - ?> -
-
- Étape 2 validée.'; - $step2 = true; - } ?> - - -
-
- 3. Créer des classes -
-
-
-
- - -
- - ' . htmlspecialchars($_POST['classe'] ?? '') . ''; ?> - - -
- prepare('SELECT name FROM classes WHERE name = ?'); - $checkIfClasseAlreadyExists->execute([$classe]); - if ($checkIfClasseAlreadyExists->rowCount() == 0) { - $addClasse = $bdd->prepare('INSERT INTO classes SET name = ?'); - $addClasse->execute([$classe]); - echo '
Classe ajoutée avec succès.
'; - } else { - echo '
Cette classe existe déjà.
'; - } - } else { - echo '
Identifiants MySQL manquants. Remplissez d\'abord le formulaire plus haut.
'; - } - } - - if (!empty($host) && !empty($dbname) && !empty($username)) { - $checkIfClasseExists = $bdd->query('SELECT name FROM classes'); - if ($checkIfClasseExists->rowCount() > 0) { - echo '
Étape 3 validée.
'; - $step3 = true; - } - } - ?> -
-
- - - query('SELECT id FROM users'); - if ($checkIfOneUserExist->rowCount() == 0) { ?> -
- 4. Créez le premier compte administrateur en vous inscrivant via la page d'inscription. -
- Étape 4 validée.'; - $step4 = true; - } ?> - - - -
-
-

Félicitations ! Configuration terminée.

-

Pour des raisons de sécurité, veuillez supprimer ce fichier.

-
- -
-
-
- Fichier supprimé avec succès. Vous pouvez maintenant accéder au site.'; - } - } ?> - - - - - \ No newline at end of file + + + + + + + + + + BookFind — Project configuration + + + + + + +
+
+
+
+

Welcome to BookFind!

+

Site configuration file

+ +
+ + + +
+
1. Configure MySQL access
+
+
+ +
+ + +
+
+ + +
+
+ + +
+ +
+
Saved successfully! Reload the page.
'; + } + ?> +
+
+
Step 1 completed.
'; + $step1 = true; + } ?> + + + +
+
2. Import the database
+
+
+ +
+ +
+ +
+ + +
+
+
+ +
+ + +
+
+ setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + } catch (PDOException $e) { + $db = null; + echo '
Cannot connect to database "' . htmlspecialchars($dbname) . '": ' . htmlspecialchars($e->getMessage()) . '
'; + } + $sqlFilePath = 'actions/bookfind.sql'; + if (file_exists($sqlFilePath) && isset($db) && $db !== null) { + $sql = file_get_contents($sqlFilePath); + $sql = preg_replace('/CREATE DATABASE\s+IF NOT EXISTS.*?;|CREATE DATABASE.*?;|USE `.*?`;/is', '', $sql); + $queries = array_filter(array_map('trim', explode(';', $sql))); + foreach ($queries as $query) { + if (!empty($query)) { + try { + $db->exec($query); + } catch (Exception $e) { + echo '
SQL execution error: ' . htmlspecialchars($e->getMessage()) . '
'; + } + } + } + echo '
Tables imported. Reload the page.
'; + } elseif (!file_exists($sqlFilePath)) { + echo '
SQL file not found.
'; + } else { + echo '
Cannot connect to database "' . htmlspecialchars($dbname) . '". Check your MySQL credentials and that the server is running.
'; + } + } else { + echo '
Missing MySQL credentials. Fill in the form above first.
'; + } + } + + if (isset($_POST['import'])) { + if (!empty($host) && !empty($username)) { + // If the user requests to import only tables + if (!empty($_POST['onlyTables'])) { + $dbnameInput = !empty($_POST['dbname_import']) ? trim($_POST['dbname_import']) : 'bookfind'; + $sqlFilePath = 'actions/bookfind.sql'; + if (!file_exists($sqlFilePath)) { + echo '
SQL file not found.
'; + goto end_import; + } + // Connect directly to the provided database + // (including database.php would serve the old version from the OPcache) + try { + $db = new PDO('mysql:host=' . $host . ';dbname=' . $dbnameInput . ';charset=utf8', $username, $password); + $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + } catch (PDOException $e) { + echo '
Cannot connect to database "' . htmlspecialchars($dbnameInput) . '": ' . htmlspecialchars($e->getMessage()) . '
'; + goto end_import; + } + $sql = file_get_contents($sqlFilePath); + $cleanSql = preg_replace('/CREATE DATABASE\s+IF NOT EXISTS.*?;|CREATE DATABASE.*?;|USE `.*?`;/is', '', $sql); + $queries = array_filter(array_map('trim', explode(';', $cleanSql))); + foreach ($queries as $query) { + if (!empty($query)) { + try { + $db->exec($query); + } catch (Exception $e) { + echo '
SQL execution error: ' . htmlspecialchars($e->getMessage()) . '
'; + } + } + } + // Only write the DB name to the config file once the import succeeded + $filePath = 'actions/database.php'; + $fileContent = file_get_contents($filePath); + $fileContent = preg_replace_callback('/\$dbname\s*=\s*\'[^\']*\';/', function ($m) use ($dbnameInput) { + return '$dbname = ' . var_export($dbnameInput, true) . ';'; + }, $fileContent); + file_put_contents($filePath, $fileContent); + if (function_exists('opcache_invalidate')) { opcache_invalidate($filePath, true); } + echo '
Tables imported. Reload the page.
'; + // End of import-only-tables flow + goto end_import; + } + + $sqlFilePath = 'actions/bookfind.sql'; + if (file_exists($sqlFilePath)) { + $sql = file_get_contents($sqlFilePath); + // Create the database without connecting to a non-existent database + try { + $tmpDsn = 'mysql:host=' . $host . ';charset=utf8'; + $tmpPdo = new PDO($tmpDsn, $username, $password); + $tmpPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $tmpPdo->exec('CREATE DATABASE IF NOT EXISTS `bookfind` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci'); + } catch (Exception $e) { + echo '
Unable to create the database: ' . htmlspecialchars($e->getMessage()) . '
'; + // Stop here + goto end_import; + } + // Connect directly to the newly created database + // (including database.php would serve the old version from the OPcache) + try { + $db = new PDO('mysql:host=' . $host . ';dbname=bookfind;charset=utf8', $username, $password); + $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + } catch (PDOException $e) { + echo '
Cannot connect to database "bookfind": ' . htmlspecialchars($e->getMessage()) . '
'; + goto end_import; + } + // Remove any CREATE DATABASE / USE lines from the dump before execution + $cleanSql = preg_replace('/CREATE DATABASE\s+IF NOT EXISTS.*?;|CREATE DATABASE.*?;|USE `.*?`;/is', '', $sql); + $queries = array_filter(array_map('trim', explode(';', $cleanSql))); + foreach ($queries as $query) { + if (!empty($query)) { + try { + $db->exec($query); + } catch (Exception $e) { + echo '
SQL execution error: ' . htmlspecialchars($e->getMessage()) . '
'; + } + } + } + // Only write the DB name to the config file once the import succeeded + $filePath = 'actions/database.php'; + $fileContent = file_get_contents($filePath); + $fileContent = preg_replace_callback('/\$dbname\s*=\s*\'[^\']*\';/', function ($m) { + return '$dbname = ' . var_export('bookfind', true) . ';'; + }, $fileContent); + file_put_contents($filePath, $fileContent); + if (function_exists('opcache_invalidate')) { opcache_invalidate($filePath, true); } + echo '
Database imported. Reload the page.
'; + } else { + echo '
SQL file not found.
'; + } + } else { + echo '
Identifiants MySQL manquants. Remplissez d\'abord le formulaire plus haut.
'; + } + } + end_import: + ?> +
+
+
Step 2 completed.
'; + $step2 = true; + } ?> + + +
+
3. Create classes
+
+
+ +
+ +
+ + ' . htmlspecialchars($_POST['class_name'] ?? '') . ''; ?> + + +
+ prepare('SELECT name FROM classes WHERE name = ?'); + $checkIfClassAlreadyExists->execute([$class_name]); + if ($checkIfClassAlreadyExists->rowCount() == 0) { + $addClass = $db->prepare('INSERT INTO classes SET name = ?'); + $addClass->execute([$class_name]); + echo '
Class added successfully.
'; + } else { + echo '
This class already exists.
'; + } + } else { + echo '
Identifiants MySQL manquants. Remplissez d\'abord le formulaire plus haut.
'; + } + } + + if (!empty($host) && !empty($dbname) && !empty($username) && isset($db) && $db !== null) { + $checkIfClassExists = $db->query('SELECT name FROM classes'); + if ($checkIfClassExists->rowCount() > 0) { + echo '
Step 3 completed.
'; + $step3 = true; + } + } + ?> +
+
+ + + query('SELECT id FROM users')->rowCount() > 0; + if (!$hasUsers) { ?> +
+ +
4. Create the first administrator account by signing up via the signup page.
+
+
Step 4 completed.
'; + $step4 = true; + } ?> + + + +
+
+

Congratulations! Configuration complete.

+

For security reasons, please delete this file.

+
+ + +
+
+
+ File deleted successfully. You can now access the site.'; + } + } ?> + + +
+ + + + diff --git a/emprunts.php b/emprunts.php deleted file mode 100644 index 5b0b45e..0000000 --- a/emprunts.php +++ /dev/null @@ -1,219 +0,0 @@ - - - - - - - - - - Emprunts - - - - - - - - rowCount(); - $nbAujourdhui = $selectInfosFromEmprunts2->rowCount(); - $nbEnCours = $selectInfosFromEmprunts3->rowCount(); - $nbRetournes = $selectInfosFromEmprunts4->rowCount(); ?> - -
-
- -
-
- -
-
- rowCount() > 0) { - while ($empruntsInfos1 = $selectInfosFromEmprunts1->fetch()) { - - $selectInfosFromBooksEmprunts1 = $bdd->prepare('SELECT * FROM books WHERE id = ?'); - $selectInfosFromBooksEmprunts1->execute(array($empruntsInfos1['id_book'])); - $recupBooks = $selectInfosFromBooksEmprunts1->fetch(); ?> -
-
-
-
-
-
-
    -
  • Emprunté le
  • -
  • Retour prévu le
  • -
-
- Voir - Emprunt -
-
-
-
-
- -
-
- rowCount() > 0) { - while ($empruntsInfos2 = $selectInfosFromEmprunts2->fetch()) { - - $selectInfosFromBooksEmprunts2 = $bdd->prepare('SELECT * FROM books WHERE id = ?'); - $selectInfosFromBooksEmprunts2->execute(array($empruntsInfos2['id_book'])); - $recupBooks = $selectInfosFromBooksEmprunts2->fetch(); ?> -
-
-
-
-
-
-
    -
  • Emprunté le
  • -
  • Retour prévu le
  • -
-
- Voir - Emprunt -
-
-
-
-
- -
-
- rowCount() > 0) { - while ($empruntsInfos3 = $selectInfosFromEmprunts3->fetch()) { - - $selectInfosFromBooksEmprunts3 = $bdd->prepare('SELECT * FROM books WHERE id = ?'); - $selectInfosFromBooksEmprunts3->execute(array($empruntsInfos3['id_book'])); - $recupBooks = $selectInfosFromBooksEmprunts3->fetch(); ?> -
-
-
-
-
-
-
    -
  • Emprunté le
  • -
  • Retour prévu le
  • -
-
- Voir - Emprunt -
-
-
-
-
- -
-
- rowCount() > 0) { - while ($empruntsInfos4 = $selectInfosFromEmprunts4->fetch()) { - - $selectInfosFromBooksEmprunts4 = $bdd->prepare('SELECT * FROM books WHERE id = ?'); - $selectInfosFromBooksEmprunts4->execute(array($empruntsInfos4['id_book'])); - $recupBooks = $selectInfosFromBooksEmprunts4->fetch(); ?> -
-
-
-
-
-
-
    -
  • Emprunté le
  • -
  • Retourné le
  • -
- Voir -
-
-
-
- -
-
- - - - - - - \ No newline at end of file diff --git a/errors/403.php b/errors/403.php old mode 100644 new mode 100755 index 5784966..5a63670 --- a/errors/403.php +++ b/errors/403.php @@ -1,7 +1,7 @@ @@ -10,36 +10,46 @@ require '../actions/functions/sessionInit.php'; } ?> - + - Erreur 403 + BookFind — Access denied - -
-

Erreur 403

- -

Vous n'avez pas les autorisations nécessaires pour accéder à cette page.

- - Se connecter - -
-
-
-
- - -
-
-
+ +
+
+
+ +
+ +
+

Access denied

+

You do not have the required permissions to access this page.

+ + +
+
+
- \ No newline at end of file + diff --git a/errors/404.php b/errors/404.php old mode 100644 new mode 100755 index 3d69064..8ba715c --- a/errors/404.php +++ b/errors/404.php @@ -1,7 +1,7 @@ @@ -10,33 +10,42 @@ require '../actions/functions/sessionInit.php'; } ?> - + - Erreur 404 + BookFind — Page not found - -
-

Erreur 404

- -

La page que vous recherchez n'existe pas.

-
-
-
-
- - -
-
-
+ +
+
+
+ +
+ +
+

Page not found

+

The page you are looking for does not exist or may have been moved.

+ + +
+
+
- \ No newline at end of file + diff --git a/gestion/actions/books/addBooksAction.php b/gestion/actions/books/addBooksAction.php old mode 100644 new mode 100755 index facb094..e7f2289 --- a/gestion/actions/books/addBooksAction.php +++ b/gestion/actions/books/addBooksAction.php @@ -1,62 +1,62 @@ - - - - -prepare('SELECT id_unique FROM books WHERE id_unique = ?'); - $checkIfIdUniqueAlreadyExists->execute(array($id_unique)); - - if($checkIfIdUniqueAlreadyExists->rowCount() == 0){ - - $id_u = true; - - } - }else{$id_unique = false; $id_u = true;} - - if(isset($_POST['serie']) AND isset($_POST['tome']) AND !empty($_POST['serie']) AND !empty($_POST['tome'])){ - $serie = $_POST['serie']; - $tome = $_POST['tome']; - }else{$serie = false; $tome = null;} - - if($id_u === true){ - - $addBook = $bdd->prepare('INSERT INTO books SET titre = ?, auteur = ?, isbn = ?, id_unique = ?, editeur = ?, type = ?, resume = ?, genre = ?, serie = ?, tome = ?, statut = ?'); - $addBook->execute(array($title, $author, $isbn, $id_unique, $editeur, $type, $resume, $genre, $serie, $tome, 0)); - - $successMsg = true; - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Ajout de livre', 'Le livre ' . htmlspecialchars($title) . ' a été ajouté avec succès.'); - - }else{ $errorMsg = 'Identifiant unique déjà attribué à un autre livre'; } - - }else{ $errorMsg = 'Tout les champs ne sont pas remplis.'; } - }else{ $errorMsg = 'Tout les champs n\'existent pas. Veuillez recharger la page.'; } + + + + +prepare('SELECT unique_id FROM books WHERE unique_id = ?'); + $checkIfIdUniqueAlreadyExists->execute(array($unique_id)); + + if($checkIfIdUniqueAlreadyExists->rowCount() == 0){ + + $id_u = true; + + } + }else{$unique_id = false; $id_u = true;} + + if(isset($_POST['series']) AND isset($_POST['volume']) AND !empty($_POST['series']) AND !empty($_POST['volume'])){ + $series = $_POST['series']; + $volume = $_POST['volume']; + }else{$series = false; $volume = null;} + + if($id_u === true){ + + $addBook = $db->prepare('INSERT INTO books SET title = ?, author = ?, isbn = ?, unique_id = ?, publisher = ?, type = ?, summary = ?, genre = ?, series = ?, volume = ?, status = ?'); + $addBook->execute(array($title, $author, $isbn, $unique_id, $publisher, $type, $summary, $genre, $series, $volume, 0)); + + $successMsg = true; + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Book added', 'The book ' . htmlspecialchars($title) . ' was added successfully.'); + + }else{ $errorMsg = 'Unique identifier already assigned to another book'; } + + }else{ $errorMsg = 'Not all fields are filled in.'; } + }else{ $errorMsg = 'Not all fields exist. Please reload the page.'; } } \ No newline at end of file diff --git a/gestion/actions/books/addEmpruntAction.php b/gestion/actions/books/addEmpruntAction.php deleted file mode 100644 index efbdb8a..0000000 --- a/gestion/actions/books/addEmpruntAction.php +++ /dev/null @@ -1,58 +0,0 @@ - - - - -prepare('SELECT * FROM books WHERE id = ?'); - $selectInfosFromBooks->execute(array($book)); - $booksInfos = $selectInfosFromBooks->fetch(); - } - $user_id = $_POST['user_id']; - $date = $_POST['date']; - - $checkIfUserAlreadyExists = $bdd->prepare('SELECT * FROM users WHERE id = ?'); - $checkIfUserAlreadyExists->execute(array($user_id)); - $user = $checkIfUserAlreadyExists->fetch(); - - if($checkIfUserAlreadyExists->rowCount() > 0){ - if($booksInfos['statut'] != 1){ - if($user['nb_emprunt'] < $user['nb_emprunt_max']){ - - $firstname_name = $user['prenom'] . ' ' . $user['nom']; - - $addEmprunt = $bdd->prepare('INSERT INTO emprunts SET id_book = ?, date_futur_retour = ?, id_emprunteur = ?, firstname_name = ?, statut = ?, titre_book = ?'); - $addEmprunt->execute(array($book, $date, $user_id, $firstname_name, 1, $booksInfos['titre'])); - - $updateEmpruntForBooks = $bdd->prepare('UPDATE books SET statut = ? WHERE id = ?'); - $updateEmpruntForBooks->execute(array(1, $book)); - - $user_nb_emprunt = $user['nb_emprunt'] + 1; - $updateUser = $bdd->prepare('UPDATE users SET nb_emprunt = ? WHERE id = ?'); - $updateUser->execute(array($user_nb_emprunt, $user_id)); - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Emprunt d\'un livre', 'Le livre ' . htmlspecialchars($booksInfos['titre']) . ' a été emprunté.'); - - header('Location: emprunt.php?id=' . $book . '&user_id=' . $user_id); - - }else{$msg1 = 'Cet utilisateur a atteint sa limite d\'emprunt.';} - }else{$msg1 = 'Ce livre est déjà emprunté.';} - }else{$msg1 = 'Cet utilisateur n\'existe pas.';} - }else{$msg1 = 'Tous les champs ne sont pas remplis.';} - }else{$msg1 = 'Tous les champs n\'existent pas.';} -} \ No newline at end of file diff --git a/gestion/actions/books/addLoanAction.php b/gestion/actions/books/addLoanAction.php new file mode 100755 index 0000000..1e1c313 --- /dev/null +++ b/gestion/actions/books/addLoanAction.php @@ -0,0 +1,58 @@ + + + + +prepare('SELECT * FROM books WHERE id = ?'); + $selectInfosFromBooks->execute(array($book)); + $booksInfos = $selectInfosFromBooks->fetch(); + } + $user_id = $_POST['user_id']; + $date = $_POST['date']; + + $checkIfUserAlreadyExists = $db->prepare('SELECT * FROM users WHERE id = ?'); + $checkIfUserAlreadyExists->execute(array($user_id)); + $user = $checkIfUserAlreadyExists->fetch(); + + if($checkIfUserAlreadyExists->rowCount() > 0){ + if($booksInfos['status'] != 1){ + if($user['loans_count'] < $user['max_loans']){ + + $borrower_name = $user['first_name'] . ' ' . $user['last_name']; + + $addLoan = $db->prepare('INSERT INTO loans SET book_id = ?, due_date = ?, borrower_id = ?, borrower_name = ?, status = ?, book_title = ?'); + $addLoan->execute(array($book, $date, $user_id, $borrower_name, 1, $booksInfos['title'])); + + $updateLoanForBooks = $db->prepare('UPDATE books SET status = ? WHERE id = ?'); + $updateLoanForBooks->execute(array(1, $book)); + + $user_loans_count = $user['loans_count'] + 1; + $updateUser = $db->prepare('UPDATE users SET loans_count = ? WHERE id = ?'); + $updateUser->execute(array($user_loans_count, $user_id)); + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Book loan', 'The book ' . htmlspecialchars($booksInfos['title']) . ' was loaned.'); + + header('Location: loan.php?id=' . $book . '&user_id=' . $user_id); + + }else{$msg1 = 'This user has reached their loan limit.';} + }else{$msg1 = 'This book is already on loan.';} + }else{$msg1 = 'This user does not exist.';} + }else{$msg1 = 'Not all fields are filled in.';} + }else{$msg1 = 'Not all fields exist.';} +} \ No newline at end of file diff --git a/gestion/actions/books/list-authors.php b/gestion/actions/books/list-authors.php old mode 100644 new mode 100755 index f2252b3..7896586 --- a/gestion/actions/books/list-authors.php +++ b/gestion/actions/books/list-authors.php @@ -1,20 +1,20 @@ - - -query('SELECT DISTINCT auteur FROM books'); - - //if(isset($['auteur'])){ - //while($authors = $selectAuthors->fetch()){ - //echo ''; - //} - //}else{ - - while($authors = $selectAuthors->fetch()){ - echo ''; + + +query('SELECT DISTINCT author FROM books'); + + //if(isset($['author'])){ + //while($authors = $selectAuthors->fetch()){ + //echo ''; + //} + //}else{ + + while($authors = $selectAuthors->fetch()){ + echo ''; }//} \ No newline at end of file diff --git a/gestion/actions/books/list-genres.php b/gestion/actions/books/list-genres.php old mode 100644 new mode 100755 index 2b68bdf..13fc3c8 --- a/gestion/actions/books/list-genres.php +++ b/gestion/actions/books/list-genres.php @@ -1,20 +1,20 @@ - - -query('SELECT DISTINCT genre FROM books'); - - //if(isset($['genre'])){ - //while($genres = $selectGenres->fetch()){ - //echo ''; - //} - //}else{ - - while($genres = $selectGenres->fetch()){ - echo ''; + + +query('SELECT DISTINCT genre FROM books'); + + //if(isset($['genre'])){ + //while($genres = $selectGenres->fetch()){ + //echo ''; + //} + //}else{ + + while($genres = $selectGenres->fetch()){ + echo ''; }//} \ No newline at end of file diff --git a/gestion/actions/books/list-isbns.php b/gestion/actions/books/list-isbns.php old mode 100644 new mode 100755 index 4bb5700..5bb335e --- a/gestion/actions/books/list-isbns.php +++ b/gestion/actions/books/list-isbns.php @@ -1,20 +1,20 @@ - - -query('SELECT DISTINCT isbn FROM books'); - - //if(isset($['isbn'])){ - //while($isbns = $selectISBNs->fetch()){ - //echo ''; - //} - //}else{ - - while($isbns = $selectISBNs->fetch()){ - echo ''; + + +query('SELECT DISTINCT isbn FROM books'); + + //if(isset($['isbn'])){ + //while($isbns = $selectISBNs->fetch()){ + //echo ''; + //} + //}else{ + + while($isbns = $selectISBNs->fetch()){ + echo ''; }//} \ No newline at end of file diff --git a/gestion/actions/books/list-publishers.php b/gestion/actions/books/list-publishers.php old mode 100644 new mode 100755 index e3ccd38..fecabb8 --- a/gestion/actions/books/list-publishers.php +++ b/gestion/actions/books/list-publishers.php @@ -1,20 +1,20 @@ - - -query('SELECT DISTINCT editeur FROM books'); - - //if(isset($['editeurs'])){ - //while($publishers = $selectPublishers->fetch()){ - //echo ''; - //} - //}else{ - - while($publishers = $selectPublishers->fetch()){ - echo ''; + + +query('SELECT DISTINCT publisher FROM books'); + + //if(isset($['editeurs'])){ + //while($publishers = $selectPublishers->fetch()){ + //echo ''; + //} + //}else{ + + while($publishers = $selectPublishers->fetch()){ + echo ''; }//} \ No newline at end of file diff --git a/gestion/actions/books/list-series.php b/gestion/actions/books/list-series.php old mode 100644 new mode 100755 index 3a6d472..a8a86a3 --- a/gestion/actions/books/list-series.php +++ b/gestion/actions/books/list-series.php @@ -1,20 +1,20 @@ - - -query('SELECT DISTINCT serie FROM books'); - - //if(isset($['series'])){ - //while($series = $selectSeries->fetch()){ - //echo ''; - //} - //}else{ - - while($series = $selectSeries->fetch()){ - echo ''; + + +query('SELECT DISTINCT series FROM books'); + + //if(isset($['series'])){ + //while($series = $selectSeries->fetch()){ + //echo ''; + //} + //}else{ + + while($series = $selectSeries->fetch()){ + echo ''; }//} \ No newline at end of file diff --git a/gestion/actions/books/list-types.php b/gestion/actions/books/list-types.php old mode 100644 new mode 100755 index 481f719..16e76b7 --- a/gestion/actions/books/list-types.php +++ b/gestion/actions/books/list-types.php @@ -1,20 +1,20 @@ - - -query('SELECT DISTINCT type FROM books'); - - //if(isset($['types'])){ - //while($types = $selectTypes->fetch()){ - //echo ''; - //} - //}else{ - - while($types = $selectTypes->fetch()){ - echo ''; + + +query('SELECT DISTINCT type FROM books'); + + //if(isset($['types'])){ + //while($types = $selectTypes->fetch()){ + //echo ''; + //} + //}else{ + + while($types = $selectTypes->fetch()){ + echo ''; }//} \ No newline at end of file diff --git a/gestion/actions/books/returnEmprunt.php b/gestion/actions/books/returnEmprunt.php deleted file mode 100644 index eb572ce..0000000 --- a/gestion/actions/books/returnEmprunt.php +++ /dev/null @@ -1,37 +0,0 @@ - - - - -prepare('SELECT nb_emprunt FROM users WHERE id = ?'); - $selectNbEmpruntsFromUsers->execute(array($user_id)); - $user_nb_emprunt = $selectNbEmpruntsFromUsers->fetch(); - - $nb_emprunt = $user_nb_emprunt['nb_emprunt'] - 1; - - $updateEmpruntForBooks = $bdd->prepare('UPDATE books SET statut = ? WHERE id = ?'); - $updateEmpruntForBooks->execute(array(2, $book)); - - $updateEmprunt = $bdd->prepare('UPDATE emprunts SET statut = ?, date_retour = NOW() WHERE id_book = ? AND id_emprunteur = ? AND statut = 1'); - $updateEmprunt->execute(array(2, $book, $user_id)); - - $updateMaxEmpruntUser = $bdd->prepare('UPDATE users SET nb_emprunt = ? WHERE id = ?'); - $updateMaxEmpruntUser->execute(array($nb_emprunt, $user_id)); - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Retour d\'un emprunt', 'Aucun commentaire'); - - header('Location: emprunt.php?id=' . $book . '&user_id=' . $user_id); - } -} \ No newline at end of file diff --git a/gestion/actions/books/returnLoan.php b/gestion/actions/books/returnLoan.php new file mode 100755 index 0000000..a05c2e1 --- /dev/null +++ b/gestion/actions/books/returnLoan.php @@ -0,0 +1,37 @@ + + + + +prepare('SELECT loans_count FROM users WHERE id = ?'); + $selectNbLoansFromUsers->execute(array($user_id)); + $user_loans_count = $selectNbLoansFromUsers->fetch(); + + $loans_count = $user_loans_count['loans_count'] - 1; + + $updateLoanForBooks = $db->prepare('UPDATE books SET status = ? WHERE id = ?'); + $updateLoanForBooks->execute(array(2, $book)); + + $updateLoan = $db->prepare('UPDATE loans SET status = ?, return_date = NOW() WHERE book_id = ? AND borrower_id = ? AND status = 1'); + $updateLoan->execute(array(2, $book, $user_id)); + + $updateMaxLoanUser = $db->prepare('UPDATE users SET loans_count = ? WHERE id = ?'); + $updateMaxLoanUser->execute(array($loans_count, $user_id)); + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Loan return', 'No comment'); + + header('Location: loan.php?id=' . $book . '&user_id=' . $user_id); + } +} \ No newline at end of file diff --git a/gestion/actions/books/showAllEmprunts.php b/gestion/actions/books/showAllEmprunts.php deleted file mode 100644 index 4688626..0000000 --- a/gestion/actions/books/showAllEmprunts.php +++ /dev/null @@ -1,22 +0,0 @@ - - - -prepare('SELECT * FROM emprunts WHERE statut = 1 AND date_futur_retour < ? ORDER BY date_futur_retour'); - $selectInfosFromEmprunts1->execute(array($Now)); - - $selectInfosFromEmprunts2 = $bdd->prepare('SELECT * FROM emprunts WHERE statut = 1 AND date_futur_retour = ? ORDER BY date_futur_retour'); - $selectInfosFromEmprunts2->execute(array($Now)); - - $selectInfosFromEmprunts3 = $bdd->prepare('SELECT * FROM emprunts WHERE statut = 1 AND date_futur_retour > ? ORDER BY date_futur_retour'); - $selectInfosFromEmprunts3->execute(array($Now)); - - $selectInfosFromEmprunts4 = $bdd->query('SELECT * FROM emprunts WHERE statut = 2 ORDER BY date_retour DESC'); diff --git a/gestion/actions/books/showAllLoans.php b/gestion/actions/books/showAllLoans.php new file mode 100755 index 0000000..75bb50f --- /dev/null +++ b/gestion/actions/books/showAllLoans.php @@ -0,0 +1,22 @@ + + + +prepare('SELECT * FROM loans WHERE status = 1 AND due_date < ? ORDER BY due_date'); + $selectLoans1->execute(array($Now)); + + $selectLoans2 = $db->prepare('SELECT * FROM loans WHERE status = 1 AND due_date = ? ORDER BY due_date'); + $selectLoans2->execute(array($Now)); + + $selectLoans3 = $db->prepare('SELECT * FROM loans WHERE status = 1 AND due_date > ? ORDER BY due_date'); + $selectLoans3->execute(array($Now)); + + $selectLoans4 = $db->query('SELECT * FROM loans WHERE status = 2 ORDER BY return_date DESC'); diff --git a/gestion/actions/books/showOneEmprunt.php b/gestion/actions/books/showOneEmprunt.php deleted file mode 100644 index c20d1c4..0000000 --- a/gestion/actions/books/showOneEmprunt.php +++ /dev/null @@ -1,15 +0,0 @@ - - - -prepare('SELECT * FROM emprunts WHERE id_book = ? AND statut = 1'); - $selectInfosFromEmprunts->execute(array($id)); - - $empruntInfos = $selectInfosFromEmprunts->fetch(); \ No newline at end of file diff --git a/gestion/actions/books/showOneLoan.php b/gestion/actions/books/showOneLoan.php new file mode 100755 index 0000000..3db1504 --- /dev/null +++ b/gestion/actions/books/showOneLoan.php @@ -0,0 +1,15 @@ + + + +prepare('SELECT * FROM loans WHERE book_id = ? AND status = 1'); + $selectLoans->execute(array($id)); + + $loanInfos = $selectLoans->fetch(); \ No newline at end of file diff --git a/gestion/actions/books/updateBooksAction.php b/gestion/actions/books/updateBooksAction.php old mode 100644 new mode 100755 index 652e9bc..6de47c5 --- a/gestion/actions/books/updateBooksAction.php +++ b/gestion/actions/books/updateBooksAction.php @@ -1,7 +1,7 @@ @@ -11,31 +11,31 @@ prepare('SELECT id, id_unique FROM books WHERE id_unique = ?'); - $checkIfIdUniqueAlreadyExists->execute(array($id_unique)); + $checkIfIdUniqueAlreadyExists = $db->prepare('SELECT id, unique_id FROM books WHERE unique_id = ?'); + $checkIfIdUniqueAlreadyExists->execute(array($unique_id)); $idUnique = $checkIfIdUniqueAlreadyExists->fetch(); @@ -44,24 +44,24 @@ $id_u = true; } - }else{$id_unique = false; $id_u = true;} + }else{$unique_id = false; $id_u = true;} - if(isset($_POST['serie']) AND isset($_POST['tome']) AND !empty($_POST['serie']) AND !empty($_POST['tome'])){ - $serie = $_POST['serie']; - $tome = $_POST['tome']; - }else{$serie = false; $tome = false;} + if(isset($_POST['series']) AND isset($_POST['volume']) AND !empty($_POST['series']) AND !empty($_POST['volume'])){ + $series = $_POST['series']; + $volume = $_POST['volume']; + }else{$series = false; $volume = false;} if($id_u === true){ - $addBook = $bdd->prepare('UPDATE books SET titre = ?, auteur = ?, isbn = ?, id_unique = ?, editeur = ?, type = ?, resume = ?, genre = ?, serie = ?, tome = ? WHERE id = ?'); - $addBook->execute(array($title, $author, $isbn, $id_unique, $editeur, $type, $resume, $genre, $serie, $tome, $id)); + $addBook = $db->prepare('UPDATE books SET title = ?, author = ?, isbn = ?, unique_id = ?, publisher = ?, type = ?, summary = ?, genre = ?, series = ?, volume = ? WHERE id = ?'); + $addBook->execute(array($title, $author, $isbn, $unique_id, $publisher, $type, $summary, $genre, $series, $volume, $id)); - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de livre', 'Le livre ' . htmlspecialchars($title) . ' a été modifié avec succès.'); + SaveLog($db, $_SERVER['REQUEST_URI'], 'Book modified', 'The book ' . htmlspecialchars($title) . ' was modified successfully.'); - $successMsg = 'Livre modifié avec succès'; + $successMsg = 'Book modified successfully'; - }else{ $errorMsg = 'Identifiant unique déjà attribué à un autre livre'; } + }else{ $errorMsg = 'Unique identifier already assigned to another book'; } - }else{ $errorMsg = 'Tout les champs ne sont pas remplis.'; } - }else{ $errorMsg = 'Tout les champs n\'existent pas. Veuillez recharger la page.'; } + }else{ $errorMsg = 'Not all fields are filled in.'; } + }else{ $errorMsg = 'Not all fields exist. Please reload the page.'; } } \ No newline at end of file diff --git a/gestion/actions/books/updateEmprunt.php b/gestion/actions/books/updateLoan.php old mode 100644 new mode 100755 similarity index 58% rename from gestion/actions/books/updateEmprunt.php rename to gestion/actions/books/updateLoan.php index 98a5076..9cb747c --- a/gestion/actions/books/updateEmprunt.php +++ b/gestion/actions/books/updateLoan.php @@ -1,24 +1,24 @@ - - - - -prepare('UPDATE emprunts SET date_futur_retour = ? WHERE id_book = ? AND id_emprunteur = ? AND statut = 1'); - $updateEmprunt->execute(array($date, $book, $user)); - - header('Location: emprunt.php?id=' . $book . '&user_id=' . $user . '&success'); - + + + + +prepare('UPDATE loans SET due_date = ? WHERE book_id = ? AND borrower_id = ? AND status = 1'); + $updateLoan->execute(array($date, $book, $user)); + + header('Location: loan.php?id=' . $book . '&user_id=' . $user . '&success'); + }} \ No newline at end of file diff --git a/gestion/actions/others/addClass.php b/gestion/actions/others/addClass.php new file mode 100755 index 0000000..85a1e2d --- /dev/null +++ b/gestion/actions/others/addClass.php @@ -0,0 +1,27 @@ + + + + +prepare('SELECT name FROM classes WHERE name = ?'); + $checkIfClassAlreadyExists->execute(array($newClass)); + + if($checkIfClassAlreadyExists->rowCount() == 0){ + + $addClass = $db->prepare('INSERT INTO classes SET name = ?'); + $addClass->execute(array($newClass)); + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Class added', 'The class "' . htmlspecialchars($newClass) . '" was added.'); + + header('Location: bookfind.php?tab=classes&successAddClass#addClass'); + + }else{ $msgC1 = 'This class already exists.'; } +} \ No newline at end of file diff --git a/gestion/actions/others/addClasse.php b/gestion/actions/others/addClasse.php deleted file mode 100644 index dc4f793..0000000 --- a/gestion/actions/others/addClasse.php +++ /dev/null @@ -1,27 +0,0 @@ - - - - -prepare('SELECT name FROM classes WHERE name = ?'); - $checkIfClasseAlreadyExists->execute(array($newClasse)); - - if($checkIfClasseAlreadyExists->rowCount() == 0){ - - $addClasse = $bdd->prepare('INSERT INTO classes SET name = ?'); - $addClasse->execute(array($newClasse)); - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Ajout d\'une classe', 'La classe "' . htmlspecialchars($newClasse) . '" à été ajoutée.'); - - header('Location: bookfind.php?tab=classes&successAddClasse#addClasse'); - - }else{ $msgC1 = 'Cette classe existe déjà.'; } -} \ No newline at end of file diff --git a/gestion/actions/others/cleanTempFiles.php b/gestion/actions/others/cleanTempFiles.php old mode 100644 new mode 100755 index eb9b7cc..8093dde --- a/gestion/actions/others/cleanTempFiles.php +++ b/gestion/actions/others/cleanTempFiles.php @@ -9,15 +9,15 @@ 0) { - error_log("Nettoyage automatique : $deletedCount fichier(s) CSV temporaire(s) supprimé(s)"); + error_log("Automatic cleanup: $deletedCount temporary CSV file(s) deleted"); } -exit("Nettoyage terminé : $deletedCount fichier(s) supprimé(s)."); +exit("Cleanup complete: $deletedCount file(s) deleted."); diff --git a/gestion/actions/others/countWeight.php b/gestion/actions/others/countWeight.php old mode 100644 new mode 100755 diff --git a/gestion/actions/others/count_data.php b/gestion/actions/others/count_data.php old mode 100644 new mode 100755 index f6bd6b9..2649594 --- a/gestion/actions/others/count_data.php +++ b/gestion/actions/others/count_data.php @@ -1,7 +1,7 @@ @@ -18,44 +18,54 @@ echo json_encode(['error' => 'Unauthenticated']); exit(); } -// Check admin role (grade '1' expected). Use permissive comparison -if (!isset($_SESSION['grade']) || $_SESSION['grade'] != '1') { +// Check graded role (grade '1' or '2', same as securityAdminAction.php) +if (!isset($_SESSION['grade']) || $_SESSION['grade'] == '0') { http_response_code(403); echo json_encode(['error' => 'Forbidden']); exit(); } // Retrieve total number of users -$requete_users = $bdd->query('SELECT COUNT(*) AS total_utilisateurs FROM users'); -$resultat_users = $requete_users->fetch(); -$nbCount1 = $resultat_users['total_utilisateurs']; +$usersQuery = $db->query('SELECT COUNT(*) AS total_users FROM users'); +$usersResult = $usersQuery->fetch(); +$totalUsers = $usersResult['total_users']; -$requete_books = $bdd->query('SELECT COUNT(*) AS total_livres FROM books'); -$resultat_books = $requete_books->fetch(); -$nbCount2 = $resultat_books['total_livres']; +$booksQuery = $db->query('SELECT COUNT(*) AS total_books FROM books'); +$booksResult = $booksQuery->fetch(); +$totalBooks = $booksResult['total_books']; -$requete_emprunts = $bdd->query('SELECT COUNT(*) AS total_emprunts FROM emprunts WHERE statut = 1'); -$resultat_emprunts = $requete_emprunts->fetch(); -$nbCount3 = $resultat_emprunts['total_emprunts']; +$loansQuery = $db->query('SELECT COUNT(*) AS total_loans FROM loans WHERE status = 1'); +$loansResult = $loansQuery->fetch(); +$totalLoans = $loansResult['total_loans']; -$requete_emprunts_retournes = $bdd->query('SELECT COUNT(*) AS total_emprunts_retournes FROM emprunts WHERE statut = 2'); -$resultat_emprunts_retournes = $requete_emprunts_retournes->fetch(); -$nbCount4 = $resultat_emprunts_retournes['total_emprunts_retournes']; +$returnedLoansQuery = $db->query('SELECT COUNT(*) AS total_returned_loans FROM loans WHERE status = 2'); +$returnedLoansResult = $returnedLoansQuery->fetch(); +$totalReturnedLoans = $returnedLoansResult['total_returned_loans']; -$requete_logs = $bdd->query('SELECT COUNT(*) AS total_logs FROM logs'); -$resultat_logs = $requete_logs->fetch(); -$nbCount5 = $resultat_logs['total_logs']; +$availableBooksQuery = $db->query('SELECT COUNT(*) AS total_available_books FROM books WHERE status = 0'); +$availableBooksResult = $availableBooksQuery->fetch(); +$totalAvailableBooks = $availableBooksResult['total_available_books']; -if (!$resultat_users || !$resultat_books || !$resultat_emprunts || !$resultat_emprunts_retournes || !$resultat_logs) { - echo json_encode(['error' => 'Erreur dans la récupération des données']); +$overdueLoansQuery = $db->query('SELECT COUNT(*) AS total_overdue_loans FROM loans WHERE status = 1 AND due_date < CURDATE()'); +$overdueLoansResult = $overdueLoansQuery->fetch(); +$totalOverdueLoans = $overdueLoansResult['total_overdue_loans']; + +$logsQuery = $db->query('SELECT COUNT(*) AS total_logs FROM logs'); +$logsResult = $logsQuery->fetch(); +$totalLogs = $logsResult['total_logs']; + +if (!$usersResult || !$booksResult || !$loansResult || !$returnedLoansResult || !$availableBooksResult || !$overdueLoansResult || !$logsResult) { + echo json_encode(['error' => 'Error retrieving data']); exit(); } echo json_encode([ - 'total_utilisateurs' => $nbCount1, - 'total_livres' => $nbCount2, - 'total_emprunts' => $nbCount3, - 'total_emprunts_retournes' => $nbCount4, - 'total_logs' => $nbCount5, + 'total_users' => $totalUsers, + 'total_books' => $totalBooks, + 'total_loans' => $totalLoans, + 'total_returned_loans' => $totalReturnedLoans, + 'total_available_books' => $totalAvailableBooks, + 'total_overdue_loans' => $totalOverdueLoans, + 'total_logs' => $totalLogs, ]); ?> diff --git a/gestion/actions/others/deleteClass.php b/gestion/actions/others/deleteClass.php new file mode 100755 index 0000000..a3e7bf9 --- /dev/null +++ b/gestion/actions/others/deleteClass.php @@ -0,0 +1,30 @@ + + + + +prepare('SELECT name FROM classes WHERE name = ?'); + $checkIfClassAlreadyExists->execute(array($existingClass)); + + if($checkIfClassAlreadyExists->rowCount() > 0){ + + $addClass = $db->prepare('DELETE FROM classes WHERE name = ?'); + $addClass->execute(array($existingClass)); + + $updateClassForUsers = $db->prepare('UPDATE users SET class_name = ? WHERE class_name = ?'); + $updateClassForUsers->execute(array('None', $existingClass)); + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Class deleted', 'The class "' . htmlspecialchars($existingClass) . '" was deleted. Users in this class were moved to the class "None".'); + + header('Location: bookfind.php?tab=classes&successDeleteClass#deleteClass'); + + }else{ $msgC3 = 'This class already exists.'; } +} \ No newline at end of file diff --git a/gestion/actions/others/deleteClasse.php b/gestion/actions/others/deleteClasse.php deleted file mode 100644 index b35ed90..0000000 --- a/gestion/actions/others/deleteClasse.php +++ /dev/null @@ -1,30 +0,0 @@ - - - - -prepare('SELECT name FROM classes WHERE name = ?'); - $checkIfClasseAlreadyExists->execute(array($existingClasse)); - - if($checkIfClasseAlreadyExists->rowCount() > 0){ - - $addClasse = $bdd->prepare('DELETE FROM classes WHERE name = ?'); - $addClasse->execute(array($existingClasse)); - - $updateClasseForUsers = $bdd->prepare('UPDATE users SET classe = ? WHERE classe = ?'); - $updateClasseForUsers->execute(array('Aucune', $existingClasse)); - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Suppression d\'une classe', 'La classe "' . htmlspecialchars($existingClasse) . '" à été supprimé. Les utilisateurs de cette classe ont été déplacé dans la classe "Aucune".'); - - header('Location: bookfind.php?tab=classes&successDeleteClasse#deleteClasse'); - - }else{ $msgC3 = 'Cette classe existe déjà.'; } -} \ No newline at end of file diff --git a/gestion/actions/others/exportLogs.php b/gestion/actions/others/exportLogs.php old mode 100644 new mode 100755 index 9200ce6..ee66020 --- a/gestion/actions/others/exportLogs.php +++ b/gestion/actions/others/exportLogs.php @@ -1,7 +1,7 @@ @@ -13,12 +13,12 @@ if (ob_get_length()) ob_clean(); // Retrieve logs - $req = $bdd->query("SELECT user_id, user_ip, user_card, user_name, type, comment, page, datetime FROM logs"); + $req = $db->query("SELECT user_id, user_ip, user_card, user_name, type, comment, page, datetime FROM logs"); $logs = $req->fetchAll(PDO::FETCH_ASSOC); // Check if logs exist if (empty($logs)) { - die("Aucun log trouvé."); + die("No logs found."); } // Set content type to CSV @@ -41,7 +41,7 @@ fclose($output); - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Export des logs', 'S\'engage à respecter la réglementation RGPD et reconnait que les logs peuvent contenir des données personnelles.'); + SaveLog($db, $_SERVER['REQUEST_URI'], 'Logs export', 'Commits to comply with GDPR and acknowledges that logs may contain personal data.'); exit(); } \ No newline at end of file diff --git a/gestion/actions/others/loadLogs.php b/gestion/actions/others/loadLogs.php old mode 100644 new mode 100755 index 794ee72..1253a71 --- a/gestion/actions/others/loadLogs.php +++ b/gestion/actions/others/loadLogs.php @@ -1,13 +1,11 @@ - - modify('-730 days')->format('Y-m-d H:i:s'); - $query = $bdd->prepare("DELETE FROM logs WHERE datetime <= ?"); + $query = $db->prepare("DELETE FROM logs WHERE datetime <= ?"); $query->execute([$twoYearsAgo]); } @@ -45,7 +43,7 @@ // Calculate total for pagination $countSql = 'SELECT COUNT(*) AS total FROM logs ' . $where; - $countStmt = $bdd->prepare($countSql); + $countStmt = $db->prepare($countSql); $countStmt->execute($params); $total = (int) ($countStmt->fetchColumn() ?? 0); @@ -63,18 +61,18 @@ // MySQL does not always support placeholders for LIMIT/OFFSET depending on configuration. // Values are cast to int below to prevent injection. $sql .= ' LIMIT ' . ((int)$perPage) . ' OFFSET ' . ((int)$offset); - $stmt = $bdd->prepare($sql); + $stmt = $db->prepare($sql); $stmt->execute($params); } else { - $stmt = $bdd->prepare($sql); + $stmt = $db->prepare($sql); $stmt->execute($params); } $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Build output in memory to reduce echo calls - $out = ''; + $out = '
'; foreach ($rows as $log) { - $dateFormattee = date("d/m/Y à H:i:s", strtotime($log['datetime'] ?? '')); + $dateFormattee = date("d/m/Y at H:i:s", strtotime($log['datetime'] ?? '')); $type = htmlspecialchars($log['type'] ?? '', ENT_QUOTES); $user_name = htmlspecialchars($log['user_name'] ?? '', ENT_QUOTES); // The comment field was sanitized on insertion via SaveLog(); it contains only safe fragments (text + ). @@ -83,35 +81,35 @@ $log_page = htmlspecialchars($log['page'] ?? '', ENT_QUOTES); $user_id = (int) ($log['user_id'] ?? 0); - $out .= ''; + $out .= '
' + . '
' + . '

' . $type . '

' + . '

' . $user_name . '

' + . '

' . $comment . '

' + . '
' + . '
Date' . $dateFormattee . '
' + . '
IP' . $user_ip . '
' + . '' + . '
' + . '' + . '
'; } + $out .= '
'; // Pagination HTML (numbered, condensed window) $totalPages = $perPage > 0 ? (int) ceil($total / $perPage) : 1; - $out .= '
'; + $out .= '
'; + $out .= '
'; - echo $out; \ No newline at end of file + echo $out; diff --git a/gestion/actions/others/stats_data.php b/gestion/actions/others/stats_data.php new file mode 100644 index 0000000..3cdd688 --- /dev/null +++ b/gestion/actions/others/stats_data.php @@ -0,0 +1,96 @@ + + + 'Unauthenticated']); + exit(); +} +if (!isset($_SESSION['grade']) || $_SESSION['grade'] == '0') { + http_response_code(403); + echo json_encode(['error' => 'Forbidden']); + exit(); +} + +header('Content-Type: application/json; charset=utf-8'); + +$data = []; + +// Monthly loans (last 6 months, including the current month) +$monthlyQuery = $db->query( + "SELECT DATE_FORMAT(loan_date, '%Y-%m') AS month, COUNT(*) AS nb + FROM loans + WHERE loan_date >= DATE_SUB(CURDATE(), INTERVAL 5 MONTH) + GROUP BY month + ORDER BY month" +); +$data['monthly_loans'] = $monthlyQuery->fetchAll(PDO::FETCH_ASSOC); + +// Loan evolution over 12 months (line chart) +$evolutionQuery = $db->query( + "SELECT DATE_FORMAT(loan_date, '%Y-%m') AS month, COUNT(*) AS nb + FROM loans + WHERE loan_date >= DATE_SUB(CURDATE(), INTERVAL 11 MONTH) + GROUP BY month + ORDER BY month" +); +$data['evolution_12_months'] = $evolutionQuery->fetchAll(PDO::FETCH_ASSOC); + +// Loan distribution by status (exclusive buckets) +$statusQuery = $db->query( + "SELECT + SUM(status = 1) AS in_progress, + SUM(status = 1 AND due_date < CURDATE()) AS overdue, + SUM(status = 2) AS returned + FROM loans" +)->fetch(); +$overdueCount = (int)($statusQuery['overdue'] ?? 0); +$data['loans_by_status'] = [ + ['label' => 'Overdue', 'nb' => $overdueCount], + ['label' => 'In progress', 'nb' => (int)($statusQuery['in_progress'] ?? 0) - $overdueCount], + ['label' => 'Returned', 'nb' => (int)($statusQuery['returned'] ?? 0)], +]; + +// Top borrowers (5 most active users) +$borrowersQuery = $db->query( + "SELECT CONCAT(u.first_name, ' ', u.last_name) AS label, COUNT(e.id) AS nb + FROM loans e + JOIN users u ON u.id = e.borrower_id + GROUP BY u.id + ORDER BY nb DESC, label ASC + LIMIT 5" +); +$data['top_borrowers'] = $borrowersQuery->fetchAll(PDO::FETCH_ASSOC); + +// User distribution by class +$classQuery = $db->query('SELECT class_name AS label, COUNT(*) AS nb FROM users GROUP BY class_name ORDER BY nb DESC'); +$data['users_by_class'] = $classQuery->fetchAll(PDO::FETCH_ASSOC); + +// Rate of books currently on loan (gauge) +$occupationQuery = $db->query('SELECT status, COUNT(*) AS nb FROM books GROUP BY status')->fetchAll(PDO::FETCH_ASSOC); +$onLoanCount = 0; +$availableCount = 0; +foreach ($occupationQuery as $row) { + if ((int)$row['status'] === 1) { + $onLoanCount = (int)$row['nb']; + } else { + $availableCount = (int)$row['nb']; + } +} +$data['books_occupancy'] = [ + 'on_loan' => $onLoanCount, + 'available' => $availableCount, + 'total' => $onLoanCount + $availableCount, +]; + +echo json_encode($data); diff --git a/gestion/actions/others/updateClass.php b/gestion/actions/others/updateClass.php new file mode 100755 index 0000000..c96b8f7 --- /dev/null +++ b/gestion/actions/others/updateClass.php @@ -0,0 +1,31 @@ + + + + +prepare('SELECT name FROM classes WHERE name = ?'); + $checkIfClassAlreadyExists->execute(array($existingClass)); + + if($checkIfClassAlreadyExists->rowCount() != 0){ + + $addClass = $db->prepare('UPDATE classes SET name = ? WHERE name = ?'); + $addClass->execute(array($newClass, $existingClass)); + + $updateClassForUsers = $db->prepare('UPDATE users SET class_name = ? WHERE class_name = ?'); + $updateClassForUsers->execute(array($newClass, $existingClass)); + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Class modified', 'The class "' . htmlspecialchars($existingClass) . '" was renamed to ' . htmlspecialchars($newClass) . '.'); + + header('Location: bookfind.php?tab=classes&successUpdateClass#updateClass'); + + }else{ $msgC2 = 'The class you want to modify does not exist.'; } +} \ No newline at end of file diff --git a/gestion/actions/others/updateClasse.php b/gestion/actions/others/updateClasse.php deleted file mode 100644 index e6f9eec..0000000 --- a/gestion/actions/others/updateClasse.php +++ /dev/null @@ -1,31 +0,0 @@ - - - - -prepare('SELECT name FROM classes WHERE name = ?'); - $checkIfClasseAlreadyExists->execute(array($existingClasse)); - - if($checkIfClasseAlreadyExists->rowCount() != 0){ - - $addClasse = $bdd->prepare('UPDATE classes SET name = ? WHERE name = ?'); - $addClasse->execute(array($newClasse, $existingClasse)); - - $updateClasseForUsers = $bdd->prepare('UPDATE users SET classe = ? WHERE classe = ?'); - $updateClasseForUsers->execute(array($newClasse, $existingClasse)); - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification d\'une classe', 'La classe "' . htmlspecialchars($existingClasse) . '" à été renommé en ' . htmlspecialchars($newClasse) . '.'); - - header('Location: bookfind.php?tab=classes&successUpdateClasse#updateClasse'); - - }else{ $msgC2 = 'La classe que vous souhaitez modifier n\'existe pas.'; } -} \ No newline at end of file diff --git a/gestion/actions/others/updateDatabase.php b/gestion/actions/others/updateDatabase.php old mode 100644 new mode 100755 index eac1d6f..8cfa248 --- a/gestion/actions/others/updateDatabase.php +++ b/gestion/actions/others/updateDatabase.php @@ -1,7 +1,7 @@ @@ -28,7 +28,7 @@ $testBdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $testOk = true; } catch (PDOException $e) { - $db_update_msg = 'Connexion impossible avec ces identifiants.'; + $db_update_msg = 'Unable to connect with these credentials.'; $db_update_type = 'danger'; } @@ -47,7 +47,7 @@ } } } else { - $db_update_msg = 'Impossible de lire actions/bookfind.sql pour vérifier les tables.'; + $db_update_msg = 'Unable to read actions/bookfind.sql to verify the tables.'; $db_update_type = 'danger'; $testOk = false; } @@ -64,7 +64,7 @@ } if (!empty($missingTables)) { - $db_update_msg = 'Connexion réussie mais tables manquantes : ' . implode(', ', $missingTables) . '. Mise à jour refusée.'; + $db_update_msg = 'Connection successful but missing tables: ' . implode(', ', $missingTables) . '. Update refused.'; $db_update_type = 'danger'; $testOk = false; } @@ -96,19 +96,19 @@ include $filePath; } - $appBdd = $GLOBALS['bdd'] ?? null; + $appBdd = $GLOBALS['db'] ?? null; if ($appBdd instanceof PDO) { try { $check = $appBdd->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'logs'"); $check->execute(); if ((int) $check->fetchColumn() > 0) { - SaveLog($appBdd, $_SERVER['REQUEST_URI'], 'Modification de database.php', 'Modification des informations de connexion à la base de donnée'); + SaveLog($appBdd, $_SERVER['REQUEST_URI'], 'database.php modified', 'Database connection details modified'); } } catch (Exception $e) { } } - $db_update_msg = 'Informations enregistrées avec succès.'; + $db_update_msg = 'Details saved successfully.'; $db_update_type = 'success'; header('Location: bookfind.php?tab=database'); diff --git a/gestion/actions/users/deleteAccountAction1.php b/gestion/actions/users/deleteAccountAction1.php old mode 100644 new mode 100755 index 2a526e2..53de756 --- a/gestion/actions/users/deleteAccountAction1.php +++ b/gestion/actions/users/deleteAccountAction1.php @@ -1,27 +1,27 @@ - - - - -prepare('SELECT nb_emprunt FROM users WHERE id = ?'); - $checkPassword->execute(array($id)); - - $InfoDelete = $checkPassword->fetch(); - - if($InfoDelete['nb_emprunt'] == '0'){ - - $deleteAccount = true; - - }else{ - $errorMsg4 = 'Vous devez avoir rendu tous vos emprunts pour supprimer votre compte. Il vous reste actuellement ' . $InfoDelete['nb_emprunt'] . ' livre(s) emprunté(s).'; - } + + + + +prepare('SELECT loans_count FROM users WHERE id = ?'); + $checkPassword->execute(array($id)); + + $InfoDelete = $checkPassword->fetch(); + + if($InfoDelete['loans_count'] == '0'){ + + $deleteAccount = true; + + }else{ + $errorMsg4 = 'You must return all your loans before deleting your account. You currently have ' . $InfoDelete['loans_count'] . ' book(s) on loan.'; + } } \ No newline at end of file diff --git a/gestion/actions/users/deleteAccountAction2.php b/gestion/actions/users/deleteAccountAction2.php old mode 100644 new mode 100755 index 19b96f1..64573fc --- a/gestion/actions/users/deleteAccountAction2.php +++ b/gestion/actions/users/deleteAccountAction2.php @@ -1,31 +1,31 @@ - - - - -prepare('SELECT id, prenom, nom FROM users WHERE id = ?'); - $getUser->execute(array($id)); - $usersInfos = $getUser->fetch(); - - $DeleteUserAccount = $bdd->prepare('DELETE FROM users WHERE id = ?'); - $DeleteUserAccount->execute(array($id)); - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Suppression de compte', 'Le compte de ' . htmlspecialchars($usersInfos['prenom'] ?? '') . ' ' . htmlspecialchars($usersInfos['nom'] ?? '') . ' a été supprimé.'); - - header('Location: users.php'); - - }else{ - $msg = 'Vous n\'avez pas de permissions suffisentes pour supprimer cet utilisateur.'; - } -} + + + + +prepare('SELECT id, first_name, last_name FROM users WHERE id = ?'); + $getUser->execute(array($id)); + $usersInfos = $getUser->fetch(); + + $DeleteUserAccount = $db->prepare('DELETE FROM users WHERE id = ?'); + $DeleteUserAccount->execute(array($id)); + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Account deleted', 'The account of ' . htmlspecialchars($usersInfos['first_name'] ?? '') . ' ' . htmlspecialchars($usersInfos['last_name'] ?? '') . ' was deleted.'); + + header('Location: users.php'); + + }else{ + $msg = 'You do not have sufficient permissions to delete this user.'; + } +} diff --git a/gestion/actions/users/importUsers.php b/gestion/actions/users/importUsers.php old mode 100644 new mode 100755 index 43095ad..66c5e81 --- a/gestion/actions/users/importUsers.php +++ b/gestion/actions/users/importUsers.php @@ -1,28 +1,28 @@ - 15 ? '...' : '') : ''); + return "Column $i: " . (isset($value) ? substr($value, 0, 15) . (strlen($value) > 15 ? '...' : '') : ''); }, array_keys($firstLine), $firstLine); // Treat first line as data @@ -83,7 +83,7 @@ } // Read data (max 5 rows for preview) - $previewRows = count($csvData); // 0 ou 1 selon si on a déjà ajouté la première ligne + $previewRows = count($csvData); // 0 or 1 depending on whether the first line was already added while (($data = fgetcsv($handle, 0, $separator, '"', "\\")) !== FALSE && $previewRows < 5) { $csvData[] = $data; $previewRows++; @@ -113,16 +113,16 @@ $_SESSION['csv_separator'] = $separator; $_SESSION['csv_file'] = $tempFile; $_SESSION['total_rows'] = $totalRows; - $_SESSION['csv_preview'] = $csvData; // Seulement 5 lignes pour l'aperçu + $_SESSION['csv_preview'] = $csvData; // Only 5 rows for preview - $msgImport = "Fichier CSV analysé avec succès. $totalRows lignes trouvées. Veuillez associer les colonnes."; + $msgImport = "CSV file analyzed successfully. $totalRows rows found. Please map the columns."; $alertImportType = "success"; } else { - $msgImport = "Erreur lors du traitement du fichier. Veuillez réessayer."; + $msgImport = "Error processing the file. Please try again."; } } } else { - $msgImport = "Impossible d'ouvrir le fichier CSV."; + $msgImport = "Unable to open the CSV file."; } } } @@ -142,13 +142,13 @@ unset($_SESSION['csv_has_headers']); unset($_SESSION['csv_preview']); - $msgImport = "Importation annulée."; + $msgImport = "Import canceled."; } // Step 2: Import data if(isset($_POST['csvImport'])) { if(!isset($_SESSION['csv_file']) || !file_exists($_SESSION['csv_file']) || !isset($_SESSION['csv_headers']) || !isset($_SESSION['csv_separator'])) { - $msgImport = "Aucun fichier CSV en attente d'importation."; + $msgImport = "No CSV file awaiting import."; } else { $db_mapping = $_POST['db_mapping'] ?? []; @@ -156,18 +156,18 @@ if (!isset($db_mapping['username']) || (isset($db_mapping['username']) && $db_mapping['username'] === 'autre' && empty($_POST['custom_username'])) && $db_mapping['username'] !== 'algorithm') { - $msgImport = "La correspondance de colonnes est incorrecte. Le champ 'username' est obligatoire."; + $msgImport = "The column mapping is incorrect. The 'username' field is required."; } else { // Retrieve custom values $custom_username = isset($_POST['custom_username']) ? trim($_POST['custom_username']) : null; - $custom_nom = isset($_POST['custom_nom']) ? trim($_POST['custom_nom']) : null; - $custom_prenom = isset($_POST['custom_prenom']) ? trim($_POST['custom_prenom']) : null; - $custom_classe = isset($_POST['custom_classe']) ? trim($_POST['custom_classe']) : null; - $custom_mdp = isset($_POST['custom_mdp']) ? trim($_POST['custom_mdp']) : null; - $custom_nb_emprunt_max = isset($_POST['custom_nb_emprunt_max']) && is_numeric($_POST['custom_nb_emprunt_max']) ? (int)$_POST['custom_nb_emprunt_max'] : null; + $custom_last_name = isset($_POST['custom_last_name']) ? trim($_POST['custom_last_name']) : null; + $custom_first_name = isset($_POST['custom_first_name']) ? trim($_POST['custom_first_name']) : null; + $custom_class_name = isset($_POST['custom_class_name']) ? trim($_POST['custom_class_name']) : null; + $custom_password = isset($_POST['custom_password']) ? trim($_POST['custom_password']) : null; + $custom_max_loans = isset($_POST['custom_max_loans']) && is_numeric($_POST['custom_max_loans']) ? (int)$_POST['custom_max_loans'] : null; try { - // We use the $bdd connection already established in database.php + // We use the $db connection already established in database.php $csvFile = $_SESSION['csv_file']; $separator = $_SESSION['csv_separator']; @@ -190,7 +190,7 @@ while (($data = fgetcsv($handle, 0, $separator, '"', "\\")) !== FALSE) { // Handle rows with incorrect column count if (count($data) !== count($headers)) { - $errors[] = "Ligne $lineNumber: Nombre de colonnes incorrect"; + $errors[] = "Line $lineNumber: Incorrect number of columns"; $errorCount++; $lineNumber++; continue; @@ -198,7 +198,7 @@ $userData = []; - // Associer les colonnes selon le mapping + // Map columns according to the mapping foreach ($db_mapping as $dbColumn => $csvIndex) { if ($csvIndex !== '' && $csvIndex !== 'autre' && $csvIndex !== 'algorithm' && is_numeric($csvIndex)) { $userData[$dbColumn] = $data[(int)$csvIndex]; @@ -206,16 +206,16 @@ } // Process last name and first name - if (isset($db_mapping['nom']) && $db_mapping['nom'] === 'autre') { - $userData['nom'] = $custom_nom; - } else if (!isset($userData['nom'])) { - $userData['nom'] = ''; + if (isset($db_mapping['last_name']) && $db_mapping['last_name'] === 'autre') { + $userData['last_name'] = $custom_last_name; + } else if (!isset($userData['last_name'])) { + $userData['last_name'] = ''; } - if (isset($db_mapping['prenom']) && $db_mapping['prenom'] === 'autre') { - $userData['prenom'] = $custom_prenom; - } else if (!isset($userData['prenom'])) { - $userData['prenom'] = ''; + if (isset($db_mapping['first_name']) && $db_mapping['first_name'] === 'autre') { + $userData['first_name'] = $custom_first_name; + } else if (!isset($userData['first_name'])) { + $userData['first_name'] = ''; } // Handle username processing @@ -223,8 +223,8 @@ $userData['username'] = $custom_username; } elseif (isset($db_mapping['username']) && $db_mapping['username'] === 'algorithm') { // Generation algorithm: first letter of first name + first 7 letters of last name - if (!empty($userData['prenom']) && !empty($userData['nom'])) { - $userData['username'] = strtolower(substr($userData['prenom'], 0, 1) . substr($userData['nom'], 0, 7)); + if (!empty($userData['first_name']) && !empty($userData['last_name'])) { + $userData['username'] = strtolower(substr($userData['first_name'], 0, 1) . substr($userData['last_name'], 0, 7)); } else { $errors[] = "Ligne $lineNumber: Unable to generate username (missing last name or first name)"; $errorCount++; @@ -235,26 +235,26 @@ // Ensure username is not empty if (empty($userData['username'])) { - $errors[] = "Ligne $lineNumber: Nom d'utilisateur vide"; + $errors[] = "Line $lineNumber: Empty username"; $errorCount++; $lineNumber++; continue; } // Process class - if (isset($db_mapping['classe']) && $db_mapping['classe'] === 'autre') { - $userData['classe'] = $custom_classe; - } else if (!isset($userData['classe'])) { - $userData['classe'] = ''; + if (isset($db_mapping['class_name']) && $db_mapping['class_name'] === 'autre') { + $userData['class_name'] = $custom_class_name; + } else if (!isset($userData['class_name'])) { + $userData['class_name'] = ''; } // Handle password processing - if (isset($db_mapping['mdp']) && $db_mapping['mdp'] === 'autre') { - $userData['mdp'] = password_hash($custom_mdp, PASSWORD_DEFAULT); - } elseif (!isset($userData['mdp']) || empty($userData['mdp'])) { - $userData['mdp'] = password_hash('ChangeMe123!', PASSWORD_DEFAULT); + if (isset($db_mapping['password']) && $db_mapping['password'] === 'autre') { + $userData['password'] = password_hash($custom_password, PASSWORD_DEFAULT); + } elseif (!isset($userData['password']) || empty($userData['password'])) { + $userData['password'] = password_hash('ChangeMe123!', PASSWORD_DEFAULT); } else { - $userData['mdp'] = password_hash($userData['mdp'], PASSWORD_DEFAULT); + $userData['password'] = password_hash($userData['password'], PASSWORD_DEFAULT); } // Process numeric values @@ -270,23 +270,23 @@ } // Rules and PDC default to 0 - $userData['regles'] = isset($userData['regles']) ? (int)$userData['regles'] : 0; - $userData['pdc'] = isset($userData['pdc']) ? (int)$userData['pdc'] : 0; + $userData['rules_accepted'] = isset($userData['rules_accepted']) ? (int)$userData['rules_accepted'] : 0; + $userData['privacy_accepted'] = isset($userData['privacy_accepted']) ? (int)$userData['privacy_accepted'] : 0; // Max borrow count - if (isset($db_mapping['nb_emprunt_max']) && $db_mapping['nb_emprunt_max'] === 'autre') { - $userData['nb_emprunt_max'] = $custom_nb_emprunt_max; - } elseif (!isset($userData['nb_emprunt_max']) || empty($userData['nb_emprunt_max'])) { - $userData['nb_emprunt_max'] = 5; + if (isset($db_mapping['max_loans']) && $db_mapping['max_loans'] === 'autre') { + $userData['max_loans'] = $custom_max_loans; + } elseif (!isset($userData['max_loans']) || empty($userData['max_loans'])) { + $userData['max_loans'] = 5; } // Additional default values - $userData['nb_emprunt'] = 0; + $userData['loans_count'] = 0; $userData['theme'] = 0; try { // Check if user already exists - $checkUser = $bdd->prepare('SELECT id FROM users WHERE username = ?'); + $checkUser = $db->prepare('SELECT id FROM users WHERE username = ?'); $checkUser->execute([$userData['username']]); if($checkUser->rowCount() > 0) { @@ -306,7 +306,7 @@ $sql .= ' WHERE username = ?'; $params[] = $userData['username']; - $stmt = $bdd->prepare($sql); + $stmt = $db->prepare($sql); $stmt->execute($params); } else { // Insert a new user @@ -314,7 +314,7 @@ $placeholders = implode(', ', array_fill(0, count($userData), '?')); $sql = "INSERT INTO users ($columns) VALUES ($placeholders)"; - $stmt = $bdd->prepare($sql); + $stmt = $db->prepare($sql); $stmt->execute(array_values($userData)); } @@ -343,31 +343,31 @@ unset($_SESSION['csv_has_headers']); unset($_SESSION['csv_preview']); - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Importation d\'utilisateurs via csv', $importedCount . ' utilisateurs importés'); + SaveLog($db, $_SERVER['REQUEST_URI'], 'Import users via CSV', $importedCount . ' users imported'); - $msgImport = "Importation terminée: $importedCount utilisateurs importés, $errorCount erreurs."; + $msgImport = "Import completed: $importedCount users imported, $errorCount errors."; if (!empty($errors)) { - $msgImport .= "
Détails des erreurs:
    "; + $msgImport .= "
    Error details:
      "; foreach(array_slice($errors, 0, 5) as $error) { $msgImport .= "
    • " . htmlspecialchars($error) . "
    • "; } if (count($errors) > 5) { - $msgImport .= "
    • ..." . (count($errors) - 5) . " autres erreurs
    • "; + $msgImport .= "
    • ..." . (count($errors) - 5) . " more errors
    • "; } $msgImport .= "
    "; } $alertImportType = ($errorCount > 0) ? "warning" : "success"; } else { - $msgImport = "Impossible d'ouvrir le fichier CSV."; + $msgImport = "Unable to open the CSV file."; } } catch (PDOException $e) { - $msgImport = "Erreur de connexion à la base de données: " . htmlspecialchars($e->getMessage()); + $msgImport = "Database connection error: " . htmlspecialchars($e->getMessage()); } } } } -// Retourner au script appelant avec les messages +// Return to the calling script with the messages return [ 'msgImport' => $msgImport, 'alertImportType' => $alertImportType diff --git a/gestion/actions/users/list-usersWithClasse.php b/gestion/actions/users/list-usersWithClass.php old mode 100644 new mode 100755 similarity index 56% rename from gestion/actions/users/list-usersWithClasse.php rename to gestion/actions/users/list-usersWithClass.php index 00225af..f2fc207 --- a/gestion/actions/users/list-usersWithClasse.php +++ b/gestion/actions/users/list-usersWithClass.php @@ -1,7 +1,7 @@ @@ -9,9 +9,9 @@ prepare('SELECT * FROM users'); + $selectUsers = $db->prepare('SELECT * FROM users'); $selectUsers->execute(); while($user = $selectUsers->fetch()){ - echo ''; + echo ''; } ?> \ No newline at end of file diff --git a/gestion/actions/users/regenUsernamesAction.php b/gestion/actions/users/regenUsernamesAction.php old mode 100644 new mode 100755 index 7475791..003ba22 --- a/gestion/actions/users/regenUsernamesAction.php +++ b/gestion/actions/users/regenUsernamesAction.php @@ -1,17 +1,17 @@ query('SELECT id, nom, prenom FROM users'); + $selectNames = $db->query('SELECT id, last_name, first_name FROM users'); $i = 0; while ($userInfos = $selectNames->fetch()) { - $newUsername = username($userInfos['prenom'], $userInfos['nom']); - $updateUsername = $bdd->prepare('UPDATE users SET username = ? WHERE id = ?'); + $newUsername = username($userInfos['first_name'], $userInfos['last_name']); + $updateUsername = $db->prepare('UPDATE users SET username = ? WHERE id = ?'); $updateUsername->execute(array($newUsername, $userInfos['id'])); $i += 1; } - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Régénération des noms d\'utilisateur', 'Le nom d\'utilisateur de ' . $i . ' utilisateurs a été régénéré.'); + SaveLog($db, $_SERVER['REQUEST_URI'], 'Username regeneration', 'The username of ' . $i . ' users was regenerated.'); - $msgRegenUsernames = 'Le nom d\'utilisateur de ' . $i . ' utilisateurs a été régénéré.'; + $msgRegenUsernames = 'The username of ' . $i . ' users was regenerated.'; } diff --git a/gestion/actions/users/sUsers.php b/gestion/actions/users/sUsers.php old mode 100644 new mode 100755 index 7bc6f69..1a6a735 --- a/gestion/actions/users/sUsers.php +++ b/gestion/actions/users/sUsers.php @@ -1,61 +1,68 @@ - - - - -prepare($sql); - $params = []; - foreach ($keywords as $keyword) { - $params = array_merge($params, array_fill(0, 6, "%$keyword%")); - } - $sUsers->execute($params); - - while ($users = $sUsers->fetch()) { ?> - -
    -
    -
    -
    -
    -
    -
      -
    • ID n°
    • -
    • Ne fait partie d'aucune classeEn classe de
    • - 0){ ?> -
    • - -
    • Grade :
    • -
    -
    - - Modifier - - Voir - Emprunts -
    -
    -
    -
    -
    -
    - + +prepare($sql); + $params = []; + foreach ($keywords as $keyword) { + $params = array_merge($params, array_fill(0, 6, "%$keyword%")); + } + $sUsers->execute($params); + + if ($sUsers->rowCount() == 0) { ?> +
    + +

    No users found with these search criteria.

    +
    + +
    + fetch()) { ?> + +
    +
    +
    + +
    +
    +
    @
    +
    +
    +
    + No class + 0) { ?> + +
    +
    + + Edit + + View + Loans +
    +
    +
    + +
    + diff --git a/gestion/actions/users/updateGradeAction.php b/gestion/actions/users/updateGradeAction.php old mode 100644 new mode 100755 index 295f4a6..59d7599 --- a/gestion/actions/users/updateGradeAction.php +++ b/gestion/actions/users/updateGradeAction.php @@ -1,46 +1,46 @@ - - - - -prepare('UPDATE users SET grade = ? WHERE id = ?'); - $updateInfoSco->execute(array($newGrade, $id)); - - // Retrieve user info for logging - $getUser = $bdd->prepare('SELECT id, prenom, nom, grade FROM users WHERE id = ?'); - $getUser->execute(array($id)); - $usersInfos = $getUser->fetch(); - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de grade', 'Le grade de ' . htmlspecialchars($usersInfos['prenom'] ?? '') . ' ' . htmlspecialchars($usersInfos['nom'] ?? '') . ' à été changé de ' . NoEchoGrade($usersInfos['grade'] ?? '') . ' vers ' . NoEchoGrade($newGrade) . '.'); - - header('Location: update-user.php?id=' . ($id ?? '') . '&msg5=true'); - } else { - $errorMsg5 = 'Vous n\'avez pas de permissions suffisentes pour appliquer ce grade.'; - } - } else { - $errorMsg5 = 'Veuillez remplir tous les champs.'; - } - } else { - $errorMsg5 = 'Tous les champs n\'existent pas. Veuillez recharger la page.'; - } - } else { - $errorMsg5 = 'Vous n\'avez pas les droits pour effectuer cette action.'; - } -} + + + + +prepare('UPDATE users SET grade = ? WHERE id = ?'); + $updateSchoolInfo->execute(array($newGrade, $id)); + + // Retrieve user info for logging + $getUser = $db->prepare('SELECT id, first_name, last_name, grade FROM users WHERE id = ?'); + $getUser->execute(array($id)); + $usersInfos = $getUser->fetch(); + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Grade changed', 'The grade of ' . htmlspecialchars($usersInfos['first_name'] ?? '') . ' ' . htmlspecialchars($usersInfos['last_name'] ?? '') . ' was changed from ' . NoEchoGrade($usersInfos['grade'] ?? '') . ' to ' . NoEchoGrade($newGrade) . '.'); + + header('Location: update-user.php?id=' . ($id ?? '') . '&msg5=true'); + } else { + $errorMsg5 = 'You do not have sufficient permissions to apply this grade.'; + } + } else { + $errorMsg5 = 'Please fill in all fields.'; + } + } else { + $errorMsg5 = 'Not all fields exist. Please reload the page.'; + } + } else { + $errorMsg5 = 'You do not have permission to perform this action.'; + } +} diff --git a/gestion/actions/users/updateInfoPersoAction.php b/gestion/actions/users/updateInfoPersoAction.php deleted file mode 100644 index b829315..0000000 --- a/gestion/actions/users/updateInfoPersoAction.php +++ /dev/null @@ -1,47 +0,0 @@ - - - - -prepare('UPDATE users SET nom = ?, prenom = ? WHERE id = ?'); - $updateInfoPerso->execute(array($name, $firstname, $id)); - - // Retrieve user information before change for logging - $getUser = $bdd->prepare('SELECT id, prenom, nom FROM users WHERE id = ?'); - $getUser->execute(array($id)); - $usersInfos = $getUser->fetch(); - - if ($name != ($usersInfos['nom'] ?? '') and $firstname == ($usersInfos['prenom'] ?? '')) { - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de compte', 'Modification du nom de famille de ' . htmlspecialchars($usersInfos['prenom'] ?? '') . ' ' . htmlspecialchars($usersInfos['nom'] ?? '') . ' passant de ' . htmlspecialchars($usersInfos['nom'] ?? '') . ' à ' . htmlspecialchars($name) . '.'); - } elseif ($name == ($usersInfos['nom'] ?? '') and $firstname != ($usersInfos['prenom'] ?? '')) { - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de compte', 'Modification du nom de prénom de ' . htmlspecialchars($usersInfos['prenom'] ?? '') . ' ' . htmlspecialchars($usersInfos['nom'] ?? '') . ' passant de ' . htmlspecialchars($usersInfos['prenom'] ?? '') . ' à ' . htmlspecialchars($firstname) . '.'); - } elseif ($name != ($usersInfos['nom'] ?? '') and $firstname != ($usersInfos['prenom'] ?? '')) { - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de compte', 'Modification du prénom et du nom de famille de ' . htmlspecialchars($usersInfos['prenom'] ?? '') . ' ' . htmlspecialchars($usersInfos['nom'] ?? '') . '. Son ancien prénom était ' . htmlspecialchars($usersInfos['prenom'] ?? '') . ' et est maintenant ' . htmlspecialchars($firstname) . '. Quant à son nom, il passe de ' . htmlspecialchars($usersInfos['nom'] ?? '') . ' à ' . htmlspecialchars($name) . '.'); - } - - header('Location: update-user.php?id=' . $id . '&msg1=true'); - } else { - $errorMsg1 = 'Veuillez remplir tous les champs.'; - } - } else { - $errorMsg1 = 'Tous les champs n\'existent pas. Veuillez recharger la page.'; - } - } else { - $errorMsg1 = 'Vous n\'avez pas les droits pour effectuer cette action.'; - } -} diff --git a/gestion/actions/users/updateInfoScoAction.php b/gestion/actions/users/updateInfoScoAction.php deleted file mode 100644 index 6dcdde4..0000000 --- a/gestion/actions/users/updateInfoScoAction.php +++ /dev/null @@ -1,52 +0,0 @@ - - - - -prepare('SELECT name FROM classes WHERE name = ?'); - $checkIfClasseAlreadyExists->execute(array($classe)); - - if ($checkIfClasseAlreadyExists->rowCount() > 0) { - - header('Location: update-user.php?id=' . $id . '&msg2=true'); - $updateInfoSco = $bdd->prepare('UPDATE users SET classe = ? WHERE id = ?'); - $updateInfoSco->execute(array($classe, $id)); - - // Retrieve info before change - $getUser = $bdd->prepare('SELECT id, prenom, nom, classe FROM users WHERE id = ?'); - $getUser->execute(array($id)); - $usersInfos = $getUser->fetch(); - - if ($classe != ($usersInfos['classe'] ?? '')) { - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de compte', 'La classe de ' . htmlspecialchars($usersInfos['prenom'] ?? '') . ' ' . htmlspecialchars($usersInfos['nom'] ?? '') . ' a été modifié passant de ' . htmlspecialchars($usersInfos['classe'] ?? '') . ' à ' . htmlspecialchars($classe) . '.'); - } - - header('Location: update-user.php?id=' . $id . '&msg2=true'); - } else { - $errorMsg2 = 'La classe sélectionnée n\'existe pas.'; - } - } else { - $errorMsg2 = 'Tous les champs doivent être remplis.'; - } - } else { - $errorMsg2 = 'Tous les champs n\'existent pas. Recharger la page ici.'; - } - } else { - $errorMsg2 = 'Vous n\'avez pas les droits pour effectuer cette action.'; - } -} diff --git a/gestion/actions/users/updateMdpAction.php b/gestion/actions/users/updateMdpAction.php deleted file mode 100644 index 615a617..0000000 --- a/gestion/actions/users/updateMdpAction.php +++ /dev/null @@ -1,46 +0,0 @@ - - - - -prepare('UPDATE users SET mdp = ? WHERE id = ?'); - $updateMdp->execute(array($newPassword, $id)); - - // Retrieve user information for logging - $getUser = $bdd->prepare('SELECT id, prenom, nom FROM users WHERE id = ?'); - $getUser->execute(array($id)); - $usersInfos = $getUser->fetch(); - - SaveLog($bdd, $_SERVER['REQUEST_URI'], 'Modification de mot de passe', 'Le mot de passe de ' . htmlspecialchars($usersInfos['prenom'] ?? '') . ' ' . htmlspecialchars($usersInfos['nom'] ?? '') . ' à été changé.'); - - header('Location: update-user.php?id=' . $id . '&msg3=true'); - } else { - $errorMsg3 = 'Les deux nouveaux mot de passe ne sont pas identiques.'; - } - } else { - $errorMsg3 = 'Veuillez remplir tous les champs.'; - } - } else { - $errorMsg3 = 'Tous les champs n\'existent pas. Veuillez recharger la page.'; - } - } else { - $errorMsg3 = 'Vous n\'avez pas les droits pour effectuer cette action.'; - } -} diff --git a/gestion/actions/users/updatePasswordAction.php b/gestion/actions/users/updatePasswordAction.php new file mode 100755 index 0000000..8b670cd --- /dev/null +++ b/gestion/actions/users/updatePasswordAction.php @@ -0,0 +1,46 @@ + + + + +prepare('UPDATE users SET password = ? WHERE id = ?'); + $updatePassword->execute(array($newPassword, $id)); + + // Retrieve user information for logging + $getUser = $db->prepare('SELECT id, first_name, last_name FROM users WHERE id = ?'); + $getUser->execute(array($id)); + $usersInfos = $getUser->fetch(); + + SaveLog($db, $_SERVER['REQUEST_URI'], 'Password changed', 'The password of ' . htmlspecialchars($usersInfos['first_name'] ?? '') . ' ' . htmlspecialchars($usersInfos['last_name'] ?? '') . ' was changed.'); + + header('Location: update-user.php?id=' . $id . '&msg3=true'); + } else { + $errorMsg3 = 'The two new passwords are not identical.'; + } + } else { + $errorMsg3 = 'Please fill in all fields.'; + } + } else { + $errorMsg3 = 'Not all fields exist. Please reload the page.'; + } + } else { + $errorMsg3 = 'You do not have permission to perform this action.'; + } +} diff --git a/gestion/actions/users/updatePersonalInfoAction.php b/gestion/actions/users/updatePersonalInfoAction.php new file mode 100755 index 0000000..9bde676 --- /dev/null +++ b/gestion/actions/users/updatePersonalInfoAction.php @@ -0,0 +1,47 @@ + + + + +prepare('UPDATE users SET last_name = ?, first_name = ? WHERE id = ?'); + $updatePersonalInfo->execute(array($name, $firstname, $id)); + + // Retrieve user information before change for logging + $getUser = $db->prepare('SELECT id, first_name, last_name FROM users WHERE id = ?'); + $getUser->execute(array($id)); + $usersInfos = $getUser->fetch(); + + if ($name != ($usersInfos['last_name'] ?? '') and $firstname == ($usersInfos['first_name'] ?? '')) { + SaveLog($db, $_SERVER['REQUEST_URI'], 'Account modified', 'Last name changed for ' . htmlspecialchars($usersInfos['first_name'] ?? '') . ' ' . htmlspecialchars($usersInfos['last_name'] ?? '') . ' from ' . htmlspecialchars($usersInfos['last_name'] ?? '') . ' to ' . htmlspecialchars($name) . '.'); + } elseif ($name == ($usersInfos['last_name'] ?? '') and $firstname != ($usersInfos['first_name'] ?? '')) { + SaveLog($db, $_SERVER['REQUEST_URI'], 'Account modified', 'First name changed for ' . htmlspecialchars($usersInfos['first_name'] ?? '') . ' ' . htmlspecialchars($usersInfos['last_name'] ?? '') . ' from ' . htmlspecialchars($usersInfos['first_name'] ?? '') . ' to ' . htmlspecialchars($firstname) . '.'); + } elseif ($name != ($usersInfos['last_name'] ?? '') and $firstname != ($usersInfos['first_name'] ?? '')) { + SaveLog($db, $_SERVER['REQUEST_URI'], 'Account modified', 'First name and last name changed for ' . htmlspecialchars($usersInfos['first_name'] ?? '') . ' ' . htmlspecialchars($usersInfos['last_name'] ?? '') . '. Their previous first name was ' . htmlspecialchars($usersInfos['first_name'] ?? '') . ' and is now ' . htmlspecialchars($firstname) . '. As for their last name, it changed from ' . htmlspecialchars($usersInfos['last_name'] ?? '') . ' to ' . htmlspecialchars($name) . '.'); + } + + header('Location: update-user.php?id=' . $id . '&msg1=true'); + } else { + $errorMsg1 = 'Please fill in all fields.'; + } + } else { + $errorMsg1 = 'Not all fields exist. Please reload the page.'; + } + } else { + $errorMsg1 = 'You do not have permission to perform this action.'; + } +} diff --git a/gestion/actions/users/updateSchoolInfoAction.php b/gestion/actions/users/updateSchoolInfoAction.php new file mode 100755 index 0000000..60c1c67 --- /dev/null +++ b/gestion/actions/users/updateSchoolInfoAction.php @@ -0,0 +1,52 @@ + + + + +prepare('SELECT name FROM classes WHERE name = ?'); + $checkIfClassAlreadyExists->execute(array($class_name)); + + if ($checkIfClassAlreadyExists->rowCount() > 0) { + + header('Location: update-user.php?id=' . $id . '&msg2=true'); + $updateSchoolInfo = $db->prepare('UPDATE users SET class_name = ? WHERE id = ?'); + $updateSchoolInfo->execute(array($class_name, $id)); + + // Retrieve info before change + $getUser = $db->prepare('SELECT id, first_name, last_name, class_name FROM users WHERE id = ?'); + $getUser->execute(array($id)); + $usersInfos = $getUser->fetch(); + + if ($class_name != ($usersInfos['class_name'] ?? '')) { + SaveLog($db, $_SERVER['REQUEST_URI'], 'Account modified', 'The class of ' . htmlspecialchars($usersInfos['first_name'] ?? '') . ' ' . htmlspecialchars($usersInfos['last_name'] ?? '') . ' was changed from ' . htmlspecialchars($usersInfos['class_name'] ?? '') . ' to ' . htmlspecialchars($class_name) . '.'); + } + + header('Location: update-user.php?id=' . $id . '&msg2=true'); + } else { + $errorMsg2 = 'The selected class does not exist.'; + } + } else { + $errorMsg2 = 'All fields must be filled in.'; + } + } else { + $errorMsg2 = 'Not all fields exist. Reload the page here.'; + } + } else { + $errorMsg2 = 'You do not have permission to perform this action.'; + } +} diff --git a/gestion/add-book.php b/gestion/add-book.php old mode 100644 new mode 100755 index 0635f5f..c6f80b4 --- a/gestion/add-book.php +++ b/gestion/add-book.php @@ -1,7 +1,7 @@ @@ -12,111 +12,107 @@ require '../actions/functions/logFunction.php'; require 'actions/books/addBooksAction.php'; ?> - + - Enregistrer un livre + BookFind — Add a book - + -
    - -
    -
    -
    -
    -
    Enregistrer un livre
    -