From c0dc531ebefd8912819f3b6c8bda1fed3c7e750c Mon Sep 17 00:00:00 2001 From: Evgeny Zinoviev Date: Wed, 31 Jan 2024 06:11:00 +0300 Subject: make it simple, but not simpler --- .gitignore | 5 +- LICENSE | 675 +------------------------- README.md | 4 +- cli_util.php | 20 +- composer.json | 6 +- config.php | 27 -- config.yaml.example | 35 ++ deploy/deploy.sh | 7 +- engine/AjaxErrorResponse.php | 9 - engine/AjaxOkResponse.php | 9 - engine/AjaxResponse.php | 13 - engine/InputType.php | 8 - engine/LangAccess.php | 8 - engine/LangData.php | 108 ----- engine/Model.php | 240 --------- engine/RedirectResponse.php | 10 - engine/RequestDispatcher.php | 84 ---- engine/RequestHandler.php | 56 --- engine/Response.php | 28 -- engine/Router.php | 165 ------- engine/Skin.php | 63 --- engine/SkinBase.php | 22 - engine/SkinContext.php | 118 ----- engine/SkinString.php | 23 - engine/SkinStringModificationType.php | 9 - engine/ansi.php | 34 -- engine/csrf.php | 22 - engine/database/CommonDatabase.php | 107 ---- engine/database/MySQLConnection.php | 82 ---- engine/database/SQLiteConnection.php | 81 ---- engine/exceptions/ForbiddenException.php | 9 - engine/exceptions/NotFoundException.php | 9 - engine/exceptions/NotImplementedException.php | 9 - engine/exceptions/UnauthorizedException.php | 9 - engine/logging.php | 271 +++++++---- engine/model.php | 331 +++++++++++++ engine/mysql.php | 261 ++++++++++ engine/request.php | 203 ++++++++ engine/router.php | 185 +++++++ engine/skin.php | 241 +++++++++ engine/strings.php | 138 ++++++ engine/themes.php | 38 -- functions.php | 84 ++-- handler/AdminHandler.php | 470 ++++++++++++++++++ handler/Auto.php | 110 ----- handler/Contacts.php | 16 - handler/Index.php | 20 - handler/MainHandler.php | 147 ++++++ handler/ProjectsHtml.php | 11 - handler/RSS.php | 32 -- handler/admin/AdminRequestHandler.php | 20 - handler/admin/AutoAddOrEdit.php | 99 ---- handler/admin/AutoDelete.php | 34 -- handler/admin/AutoEdit.php | 130 ----- handler/admin/Index.php | 13 - handler/admin/Login.php | 31 -- handler/admin/Logout.php | 17 - handler/admin/MarkdownPreview.php | 22 - handler/admin/PageAdd.php | 66 --- handler/admin/PostAdd.php | 68 --- handler/admin/UploadDelete.php | 25 - handler/admin/UploadEditNote.php | 25 - handler/admin/Uploads.php | 73 --- htdocs/index.php | 27 +- htdocs/js.php | 3 +- htdocs/sass.php | 5 +- init.php | 94 ++-- lang/en.php | 106 ---- lib/MyParsedown.php | 218 --------- lib/admin.php | 82 ++-- lib/ansi.php | 32 ++ lib/cli.php | 8 +- lib/config.php | 46 -- lib/ext/MyParsedown.php | 218 +++++++++ lib/markup.php | 2 + lib/pages.php | 58 ++- lib/posts.php | 306 ++++++++---- lib/stored_config.php | 14 + lib/tags.php | 87 ++++ lib/themes.php | 41 ++ lib/uploads.php | 215 +++++++- model/Page.php | 43 -- model/Post.php | 193 -------- model/Tag.php | 24 - model/Upload.php | 163 ------- routes.php | 23 + skin/admin.skin.php | 8 +- skin/base.skin.php | 17 +- skin/error.skin.php | 27 +- strings/main.yaml | 103 ++++ stubs/vkflex.php | 11 + 91 files changed, 3377 insertions(+), 4092 deletions(-) delete mode 100644 config.php create mode 100644 config.yaml.example delete mode 100644 engine/AjaxErrorResponse.php delete mode 100644 engine/AjaxOkResponse.php delete mode 100644 engine/AjaxResponse.php delete mode 100644 engine/InputType.php delete mode 100644 engine/LangAccess.php delete mode 100644 engine/LangData.php delete mode 100644 engine/Model.php delete mode 100644 engine/RedirectResponse.php delete mode 100644 engine/RequestDispatcher.php delete mode 100644 engine/RequestHandler.php delete mode 100644 engine/Response.php delete mode 100644 engine/Router.php delete mode 100644 engine/Skin.php delete mode 100644 engine/SkinBase.php delete mode 100644 engine/SkinContext.php delete mode 100644 engine/SkinString.php delete mode 100644 engine/SkinStringModificationType.php delete mode 100644 engine/ansi.php delete mode 100644 engine/csrf.php delete mode 100644 engine/database/CommonDatabase.php delete mode 100644 engine/database/MySQLConnection.php delete mode 100644 engine/database/SQLiteConnection.php delete mode 100644 engine/exceptions/ForbiddenException.php delete mode 100644 engine/exceptions/NotFoundException.php delete mode 100644 engine/exceptions/NotImplementedException.php delete mode 100644 engine/exceptions/UnauthorizedException.php create mode 100644 engine/model.php create mode 100644 engine/mysql.php create mode 100644 engine/request.php create mode 100644 engine/router.php create mode 100644 engine/skin.php create mode 100644 engine/strings.php delete mode 100644 engine/themes.php create mode 100644 handler/AdminHandler.php delete mode 100644 handler/Auto.php delete mode 100644 handler/Contacts.php delete mode 100644 handler/Index.php create mode 100644 handler/MainHandler.php delete mode 100644 handler/ProjectsHtml.php delete mode 100644 handler/RSS.php delete mode 100644 handler/admin/AdminRequestHandler.php delete mode 100644 handler/admin/AutoAddOrEdit.php delete mode 100644 handler/admin/AutoDelete.php delete mode 100644 handler/admin/AutoEdit.php delete mode 100644 handler/admin/Index.php delete mode 100644 handler/admin/Login.php delete mode 100644 handler/admin/Logout.php delete mode 100644 handler/admin/MarkdownPreview.php delete mode 100644 handler/admin/PageAdd.php delete mode 100644 handler/admin/PostAdd.php delete mode 100644 handler/admin/UploadDelete.php delete mode 100644 handler/admin/UploadEditNote.php delete mode 100644 handler/admin/Uploads.php delete mode 100644 lang/en.php delete mode 100644 lib/MyParsedown.php create mode 100644 lib/ansi.php delete mode 100644 lib/config.php create mode 100644 lib/ext/MyParsedown.php create mode 100644 lib/stored_config.php create mode 100644 lib/tags.php create mode 100644 lib/themes.php delete mode 100644 model/Page.php delete mode 100644 model/Post.php delete mode 100644 model/Tag.php delete mode 100644 model/Upload.php create mode 100644 routes.php create mode 100644 strings/main.yaml create mode 100644 stubs/vkflex.php diff --git a/.gitignore b/.gitignore index 8ae0b83..68f11a5 100644 --- a/.gitignore +++ b/.gitignore @@ -6,8 +6,9 @@ test.php .DS_Store ._.DS_Store .sass-cache/ -config-static.php -config-local.php +/config-static.php +/config.yaml /.idea /htdocs/dist-css /htdocs/dist-js +/log \ No newline at end of file diff --git a/LICENSE b/LICENSE index f288702..28c2a5d 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,9 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 +Copyright Evgeny Zinoviev. - 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. +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Preamble +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - The GNU General Public License is a free, copyleft license for -software and other kinds of works. +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/README.md b/README.md index 8d2f037..2a80337 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,9 @@ This is complete code of ch1p.io website. - dark theme - ultra fast on backend: - written from scratch + - no PSR BS - no heavy frameworks + - no 157 abstraction layers - no "classic" template engine - vanilla php templates designed from scratch (because why not) - thus, no overhead from templates "compilation" @@ -66,4 +68,4 @@ I'm willing to pay $50 to $500 in crypto (depending on severity) for every disco ## License -GPLv3 \ No newline at end of file +BSD-2-Clause \ No newline at end of file diff --git a/cli_util.php b/cli_util.php index 0c42bb5..e883ae7 100755 --- a/cli_util.php +++ b/cli_util.php @@ -4,12 +4,13 @@ namespace cli_util; use cli; +use pages; use posts; +use tags; use uploads; -use pages; -use config; require_once __DIR__.'/init.php'; +require_once 'lib/stored_config.php'; $cli = new cli(__NAMESPACE__); $cli->run(); @@ -24,18 +25,18 @@ function admin_reset(): void { if (trim($pwd1) == '') cli::die("Password can not be empty"); - if (!config::set('admin_pwd', salt_password($pwd1))) + if (!scSet('admin_pwd', salt_password($pwd1))) cli::die("Database error"); } function admin_check(): void { - $pwd = config::get('admin_pwd'); + $pwd = scGet('admin_pwd'); echo is_null($pwd) ? "Not set" : $pwd; echo "\n"; } function blog_erase(): void { - $db = getDb(); + $db = DB(); $tables = ['posts', 'posts_tags', 'tags']; foreach ($tables as $t) { $db->query("TRUNCATE TABLE $t"); @@ -43,14 +44,14 @@ function blog_erase(): void { } function tags_recount(): void { - $tags = posts::getAllTags(true); + $tags = tags::getAll(true); foreach ($tags as $tag) - posts::recountPostsWithTag($tag->id); + posts::tagsRecountPosts($tag->id); } function posts_html(): void { $kw = ['include_hidden' => true]; - $posts = posts::getPosts(0, posts::getPostsCount(...$kw), ...$kw); + $posts = posts::getList(0, posts::getCount(...$kw), ...$kw); foreach ($posts as $p) { $p->updateHtml(); $p->updateText(); @@ -59,7 +60,7 @@ function posts_html(): void { function posts_images(): void { $kw = ['include_hidden' => true]; - $posts = posts::getPosts(0, posts::getPostsCount(...$kw), ...$kw); + $posts = posts::getList(0, posts::getCount(...$kw), ...$kw); foreach ($posts as $p) { $p->updateImagePreviews(true); } @@ -77,7 +78,6 @@ function add_files_to_uploads(): void { if (!file_exists($path)) cli::die("file $path doesn't exists"); $name = basename($path); - $ext = extension($name); $id = uploads::add($path, $name, ''); echo "upload id: $id\n"; } diff --git a/composer.json b/composer.json index 5bdc23d..8d6cdee 100644 --- a/composer.json +++ b/composer.json @@ -7,7 +7,11 @@ "ext-gd": "*", "ext-mysqli": "*", "ext-json": "*", - "ext-sqlite3": "*" + "ext-sqlite3": "*", + "ext-memcached": "*", + "ext-yaml": "*", + "ext-iconv": "*", + "ext-gmp": "*" }, "repositories": [ { diff --git a/config.php b/config.php deleted file mode 100644 index b1f1244..0000000 --- a/config.php +++ /dev/null @@ -1,27 +0,0 @@ - 'example.com', - 'cookie_host' => '.example.com', - 'admin_email' => 'admin@example.com', - - 'db' => [ - 'type' => 'mysql', - 'host' => '127.0.0.1', - 'user' => '', - 'password' => '', - 'database' => '', - ], - - 'log_file' => '/var/log/example.com-backend.log', - - 'password_salt' => '12345', - 'csrf_token' => '12345', - 'uploads_dir' => '/home/user/files.example.com', - 'uploads_host' => 'files.example.com', - - 'dirs_mode' => 0775, - 'files_mode' => 0664, - 'group' => 33, // id -g www-data - 'is_dev' => false, -]; diff --git a/config.yaml.example b/config.yaml.example new file mode 100644 index 0000000..49f88d7 --- /dev/null +++ b/config.yaml.example @@ -0,0 +1,35 @@ +domain: example.org +cookie_host: .example.org +admin_email: admin@example.org + +dev_domains: + - dev + +db: + type: 'mysql' + mysql: + host: "127.0.0.1" + user: "user" + password: "password" + database: "dbname" + # misc + log: false + log_stat: false + + +umask: 0002 +group: www-data +files_mode: 0664 +dirs_mode: 0775 + +csrf_token: "123" +password_salt: "456" + +uploads_dir: /home/user/files.example.org +uploads_host: files.example.org + +# deploy config +git_repo: git@github.com:example/example_org.git + +# runtime variables +is_dev: false \ No newline at end of file diff --git a/deploy/deploy.sh b/deploy/deploy.sh index 9773a9f..4650ccf 100755 --- a/deploy/deploy.sh +++ b/deploy/deploy.sh @@ -13,6 +13,7 @@ DEV_DIR="$(realpath "$DIR/../")" STAGING_DIR="$HOME/staging" PROD_DIR="$HOME/prod" PHP=/usr/bin/php8.1 +REPO_URI=$(cat "$DEV_DIR/config.yaml" | grep ^git_repo | head -1 | awk '{print $2}') git push origin master @@ -21,7 +22,7 @@ pushd "$STAGING_DIR" if [ ! -d .git ]; then git init - git remote add origin git@ch1p.io:ch1p_io_web.git + git remote add origin "$REPO_URI" git fetch git checkout master fi @@ -35,8 +36,7 @@ if [ ! -d node_modules ]; then npm i fi -cp "$DEV_DIR/config-local.php" . -sed -i '/is_dev/d' ./config-local.php +cp "$DEV_DIR/config.yaml" . "$DIR"/build_js.sh -i "$DEV_DIR/htdocs/js" -o "$STAGING_DIR/htdocs/dist-js" || die "build_js failed" "$DIR"/build_css.sh -i "$DEV_DIR/htdocs/scss" -o "$STAGING_DIR/htdocs/dist-css" || die "build_css failed" @@ -48,6 +48,7 @@ popd rsync -a --delete --delete-excluded --info=progress2 "$STAGING_DIR/" "$PROD_DIR/" \ --exclude .git \ --exclude debug.log \ + --exclude='/log' \ --exclude='/composer.*' \ --exclude='/htdocs/scss' \ --exclude='/htdocs/js' \ diff --git a/engine/AjaxErrorResponse.php b/engine/AjaxErrorResponse.php deleted file mode 100644 index a1fe381..0000000 --- a/engine/AjaxErrorResponse.php +++ /dev/null @@ -1,9 +0,0 @@ - $error], JSON_UNESCAPED_UNICODE)); - } - -} \ No newline at end of file diff --git a/engine/AjaxOkResponse.php b/engine/AjaxOkResponse.php deleted file mode 100644 index 253a563..0000000 --- a/engine/AjaxOkResponse.php +++ /dev/null @@ -1,9 +0,0 @@ - $data], JSON_UNESCAPED_UNICODE)); - } - -} \ No newline at end of file diff --git a/engine/AjaxResponse.php b/engine/AjaxResponse.php deleted file mode 100644 index 931e5e7..0000000 --- a/engine/AjaxResponse.php +++ /dev/null @@ -1,13 +0,0 @@ -addHeader('Content-Type: application/json; charset=utf-8'); - $this->addHeader('Cache-Control: no-cache, must-revalidate'); - $this->addHeader('Pragma: no-cache'); - $this->addHeader('Content-Type: application/json; charset=utf-8'); - } - -} \ No newline at end of file diff --git a/engine/InputType.php b/engine/InputType.php deleted file mode 100644 index 401f7ca..0000000 --- a/engine/InputType.php +++ /dev/null @@ -1,8 +0,0 @@ -load('en'); - } - return self::$instance; - } - - public function __invoke(string $key, ...$args) { - $val = $this[$key]; - return empty($args) ? $val : sprintf($val, ...$args); - } - - public function load(string $name) { - if (array_key_exists($name, $this->loaded)) - return; - - $data = require_once ROOT."/lang/{$name}.php"; - $this->data = array_replace($this->data, - $data); - - $this->loaded[$name] = true; - } - - public function offsetSet(mixed $offset, mixed $value): void { - logError(__METHOD__ . ': not implemented'); - } - - public function offsetExists($offset): bool { - return isset($this->data[$offset]); - } - - public function offsetUnset(mixed $offset): void { - logError(__METHOD__ . ': not implemented'); - } - - public function offsetGet(mixed $offset): mixed { - return $this->data[$offset] ?? '{' . $offset . '}'; - } - - public function search(string $regexp): array|false { - return preg_grep($regexp, array_keys($this->data)); - } - - // function plural(array $s, int $n, array $opts = []) { - // $opts = array_merge([ - // 'format' => true, - // 'format_delim' => ' ', - // 'lang' => 'en', - // ], $opts); - // - // switch ($opts['lang']) { - // case 'ru': - // $n = $n % 100; - // if ($n > 19) - // $n %= 10; - // - // if ($n == 1) { - // $word = 0; - // } else if ($n >= 2 && $n <= 4) { - // $word = 1; - // } else if ($n == 0 && count($s) == 4) { - // $word = 3; - // } else { - // $word = 2; - // } - // break; - // - // default: - // if (!$n && count($s) == 4) { - // $word = 3; - // } else { - // $word = (int)!!$n; - // } - // break; - // } - // - // // if zero - // if ($word == 3) - // return $s[3]; - // - // if (is_callable($opts['format'])) { - // $num = $opts['format']($n); - // } else if ($opts['format'] === true) { - // $num = formatNumber($n, $opts['format_delim']); - // } - // - // return sprintf($s[$word], $num); - // } - // - // function formatNumber(int $num, string $delim = ' ', bool $short = false): string { - // if ($short) { - // if ($num >= 1000000) - // return floor($num / 1000000).'m'; - // if ($num >= 1000) - // return floor($num / 1000).'k'; - // } - // return number_format($num, 0, '.', $delim); - // } -} diff --git a/engine/Model.php b/engine/Model.php deleted file mode 100644 index e80b09d..0000000 --- a/engine/Model.php +++ /dev/null @@ -1,240 +0,0 @@ - $fields, - 'model_name_map' => $model_name_map, - 'db_name_map' => $db_name_map - ]; - } - - foreach (self::$SpecCache[static::class]['fields'] as $field) - $this->{$field['model_name']} = self::cast_to_type($field['type'], $raw[$field['db_name']]); - - if (is_null(static::DB_TABLE)) - trigger_error('class '.get_class($this).' doesn\'t have DB_TABLE defined'); - } - - public function edit(array $fields) { - $db = getDb(); - - $model_upd = []; - $db_upd = []; - - foreach ($fields as $name => $value) { - $index = self::$SpecCache[static::class]['db_name_map'][$name] ?? null; - if (is_null($index)) { - logError(__METHOD__.': field `'.$name.'` not found in '.static::class); - continue; - } - - $field = self::$SpecCache[static::class]['fields'][$index]; - switch ($field['type']) { - case Type::ARRAY: - if (is_array($value)) { - $db_upd[$name] = implode(',', $value); - $model_upd[$field['model_name']] = $value; - } else { - logError(__METHOD__.': field `'.$name.'` is expected to be array. skipping.'); - } - break; - - case Type::INTEGER: - $value = (int)$value; - $db_upd[$name] = $value; - $model_upd[$field['model_name']] = $value; - break; - - case Type::FLOAT: - $value = (float)$value; - $db_upd[$name] = $value; - $model_upd[$field['model_name']] = $value; - break; - - case Type::BOOLEAN: - $db_upd[$name] = $value ? 1 : 0; - $model_upd[$field['model_name']] = $value; - break; - - case Type::JSON: - $db_upd[$name] = json_encode($value, JSON_UNESCAPED_UNICODE); - $model_upd[$field['model_name']] = $value; - break; - - case Type::SERIALIZED: - $db_upd[$name] = serialize($value); - $model_upd[$field['model_name']] = $value; - break; - - default: - $value = (string)$value; - $db_upd[$name] = $value; - $model_upd[$field['model_name']] = $value; - break; - } - } - - if (!empty($db_upd) && !$db->update(static::DB_TABLE, $db_upd, static::DB_KEY."=?", $this->get_id())) { - logError(__METHOD__.': failed to update database'); - return; - } - - if (!empty($model_upd)) { - foreach ($model_upd as $name => $value) - $this->{$name} = $value; - } - } - - public function get_id() { - return $this->{to_camel_case(static::DB_KEY)}; - } - - public function as_array(array $fields = [], array $custom_getters = []): array { - if (empty($fields)) - $fields = array_keys(static::$SpecCache[static::class]['db_name_map']); - - $array = []; - foreach ($fields as $field) { - if (isset($custom_getters[$field]) && is_callable($custom_getters[$field])) { - $array[$field] = $custom_getters[$field](); - } else { - $array[$field] = $this->{to_camel_case($field)}; - } - } - - return $array; - } - - protected static function cast_to_type(Type $type, $value) { - switch ($type) { - case Type::BOOLEAN: - return (bool)$value; - - case Type::INTEGER: - return (int)$value; - - case Type::FLOAT: - return (float)$value; - - case Type::ARRAY: - return array_filter(explode(',', $value)); - - case Type::JSON: - $val = json_decode($value, true); - if (!$val) - $val = null; - return $val; - - case Type::SERIALIZED: - $val = unserialize($value); - if ($val === false) - $val = null; - return $val; - - default: - return (string)$value; - } - } - - protected static function get_spec(): array { - $rc = new ReflectionClass(static::class); - $props = $rc->getProperties(ReflectionProperty::IS_PUBLIC); - - $list = []; - $index = 0; - - $model_name_map = []; - $db_name_map = []; - - foreach ($props as $prop) { - if ($prop->isStatic()) - continue; - - $name = $prop->getName(); - if (str_starts_with($name, '_')) - continue; - - $type = $prop->getType(); - $phpdoc = $prop->getDocComment(); - - $mytype = null; - if (!$prop->hasType() && !$phpdoc) - $mytype = Type::STRING; - else { - $typename = $type->getName(); - switch ($typename) { - case 'string': - $mytype = Type::STRING; - break; - case 'int': - $mytype = Type::INTEGER; - break; - case 'float': - $mytype = Type::FLOAT; - break; - case 'array': - $mytype = Type::ARRAY; - break; - case 'bool': - $mytype = Type::BOOLEAN; - break; - } - - if ($phpdoc != '') { - $pos = strpos($phpdoc, '@'); - if ($pos === false) - continue; - - if (substr($phpdoc, $pos+1, 4) == 'json') - $mytype = Type::JSON; - else if (substr($phpdoc, $pos+1, 5) == 'array') - $mytype = Type::ARRAY; - else if (substr($phpdoc, $pos+1, 10) == 'serialized') - $mytype = Type::SERIALIZED; - } - } - - if (is_null($mytype)) - logError(__METHOD__.": ".$name." is still null in ".static::class); - - $dbname = from_camel_case($name); - $list[] = [ - 'type' => $mytype, - 'model_name' => $name, - 'db_name' => $dbname - ]; - - $model_name_map[$name] = $index; - $db_name_map[$dbname] = $index; - - $index++; - } - - return [$list, $model_name_map, $db_name_map]; - } - -} diff --git a/engine/RedirectResponse.php b/engine/RedirectResponse.php deleted file mode 100644 index 4526c6c..0000000 --- a/engine/RedirectResponse.php +++ /dev/null @@ -1,10 +0,0 @@ -addHeader('Location: '.$url); - } - -} \ No newline at end of file diff --git a/engine/RequestDispatcher.php b/engine/RequestDispatcher.php deleted file mode 100644 index adb61c9..0000000 --- a/engine/RequestDispatcher.php +++ /dev/null @@ -1,84 +0,0 @@ -router->find(self::path()); - if ($route === null) - throw new NotFoundException('Route not found'); - - $route = preg_split('/ +/', $route); - $handler_class = $route[0]; - if (($pos = strrpos($handler_class, '/')) !== false) { - $class_name = substr($handler_class, $pos+1); - $class_name = ucfirst(to_camel_case($class_name)); - $handler_class = str_replace('/', '\\', substr($handler_class, 0, $pos)).'\\'.$class_name; - } else { - $handler_class = ucfirst(to_camel_case($handler_class)); - } - $handler_class = 'handler\\'.$handler_class; - - if (!class_exists($handler_class)) - throw new NotFoundException($config['is_dev'] ? 'Handler class "'.$handler_class.'" not found' : ''); - - $router_input = []; - if (count($route) > 1) { - for ($i = 1; $i < count($route); $i++) { - $var = $route[$i]; - list($k, $v) = explode('=', $var); - $router_input[trim($k)] = trim($v); - } - } - - $skin = new Skin(); - $skin->static[] = 'css/common.css'; - $skin->static[] = 'js/common.js'; - - $lang = LangData::getInstance(); - $skin->addLangKeys($lang->search('/^theme_/')); - - /** @var RequestHandler $handler */ - $handler = new $handler_class($skin, $lang, $router_input); - $resp = $handler->beforeDispatch(); - if ($resp instanceof Response) { - $resp->send(); - return; - } - - $resp = call_user_func([$handler, strtolower($_SERVER['REQUEST_METHOD'])]); - } catch (NotFoundException $e) { - $resp = $this->getErrorResponse($e, 'not_found'); - } catch (ForbiddenException $e) { - $resp = $this->getErrorResponse($e, 'forbidden'); - } catch (NotImplementedException $e) { - $resp = $this->getErrorResponse($e, 'not_implemented'); - } catch (UnauthorizedException $e) { - $resp = $this->getErrorResponse($e, 'unauthorized'); - } - $resp->send(); - } - - protected function getErrorResponse(Exception $e, string $render_function): Response { - $ctx = new SkinContext('\\skin\\error'); - $html = call_user_func([$ctx, $render_function], $e->getMessage()); - return new Response($e->getCode(), $html); - } - - public static function path(): string { - $uri = $_SERVER['REQUEST_URI']; - if (($pos = strpos($uri, '?')) !== false) - $uri = substr($uri, 0, $pos); - return $uri; - } - -} diff --git a/engine/RequestHandler.php b/engine/RequestHandler.php deleted file mode 100644 index a9dfccd..0000000 --- a/engine/RequestHandler.php +++ /dev/null @@ -1,56 +0,0 @@ -routerInput[$name] ?? $_REQUEST[$name] ?? ''; - switch ($type) { - case InputType::INT: - $value = (int)$value; - break; - case InputType::FLOAT: - $value = (float)$value; - break; - case InputType::BOOL: - $value = (bool)$value; - break; - } - - $ret[] = $value; - } - return $ret; - } - - protected function isRetina(): bool { - return isset($_COOKIE['is_retina']) && $_COOKIE['is_retina']; - } -} diff --git a/engine/Response.php b/engine/Response.php deleted file mode 100644 index 6250063..0000000 --- a/engine/Response.php +++ /dev/null @@ -1,28 +0,0 @@ -setHeaders(); - if ($this->code == 200 || $this->code >= 400) - echo $this->body; - } - - public function addHeader(string $header): void { - $this->headers[] = $header; - } - - public function setHeaders(): void { - http_response_code($this->code); - foreach ($this->headers as $header) - header($header); - } - -} \ No newline at end of file diff --git a/engine/Router.php b/engine/Router.php deleted file mode 100644 index 0cb761d..0000000 --- a/engine/Router.php +++ /dev/null @@ -1,165 +0,0 @@ - [], - 're_children' => [] - ]; - - public function add($template, $value) { - if ($template == '') - return $this; - - // expand {enum,erat,ions} - $templates = [[$template, $value]]; - if (preg_match_all('/\{([\w\d_\-,]+)\}/', $template, $matches)) { - foreach ($matches[1] as $match_index => $variants) { - $variants = explode(',', $variants); - $variants = array_map('trim', $variants); - $variants = array_filter($variants, function($s) { return $s != ''; }); - - for ($i = 0; $i < count($templates); ) { - list($template, $value) = $templates[$i]; - $new_templates = []; - foreach ($variants as $variant_index => $variant) { - $new_templates[] = [ - str_replace_once($matches[0][$match_index], $variant, $template), - str_replace('${'.($match_index+1).'}', $variant, $value) - ]; - } - array_splice($templates, $i, 1, $new_templates); - $i += count($new_templates); - } - } - } - - // process all generated routes - foreach ($templates as $template) { - list($template, $value) = $template; - - $start_pos = 0; - $parent = &$this->routes; - $template_len = strlen($template); - - while ($start_pos < $template_len) { - $slash_pos = strpos($template, '/', $start_pos); - if ($slash_pos !== false) { - $part = substr($template, $start_pos, $slash_pos-$start_pos+1); - $start_pos = $slash_pos+1; - } else { - $part = substr($template, $start_pos); - $start_pos = $template_len; - } - - $parent = &$this->_addRoute($parent, $part, - $start_pos < $template_len ? null : $value); - } - } - - return $this; - } - - protected function &_addRoute(&$parent, $part, $value = null) { - $par_pos = strpos($part, '('); - $is_regex = $par_pos !== false && ($par_pos == 0 || $part[$par_pos-1] != '\\'); - - $children_key = !$is_regex ? 'children' : 're_children'; - - if (isset($parent[$children_key][$part])) { - if (is_null($value)) { - $parent = &$parent[$children_key][$part]; - } else { - if (!isset($parent[$children_key][$part]['value'])) { - $parent[$children_key][$part]['value'] = $value; - } else { - trigger_error(__METHOD__.': route is already defined'); - } - } - return $parent; - } - - $child = [ - 'children' => [], - 're_children' => [] - ]; - if (!is_null($value)) - $child['value'] = $value; - - $parent[$children_key][$part] = $child; - return $parent[$children_key][$part]; - } - - public function find($uri) { - if ($uri != '/' && $uri[0] == '/') { - $uri = substr($uri, 1); - } - $start_pos = 0; - $parent = &$this->routes; - $uri_len = strlen($uri); - $matches = []; - - while ($start_pos < $uri_len) { - $slash_pos = strpos($uri, '/', $start_pos); - if ($slash_pos !== false) { - $part = substr($uri, $start_pos, $slash_pos-$start_pos+1); - $start_pos = $slash_pos+1; - } else { - $part = substr($uri, $start_pos); - $start_pos = $uri_len; - } - - $found = false; - if (isset($parent['children'][$part])) { - $parent = &$parent['children'][$part]; - $found = true; - } else if (!empty($parent['re_children'])) { - foreach ($parent['re_children'] as $re => &$child) { - $exp = '#^'.$re.'$#'; - $re_result = preg_match($exp, $part, $match); - if ($re_result === false) { - logError(__METHOD__.": regex $exp failed"); - continue; - } - - if ($re_result) { - if (count($match) > 1) { - $matches = array_merge($matches, array_slice($match, 1)); - } - $parent = &$child; - $found = true; - break; - } - } - } - - if (!$found) - return false; - } - - if (!isset($parent['value'])) - return false; - - $value = $parent['value']; - if (!empty($matches)) { - foreach ($matches as $i => $match) { - $needle = '$('.($i+1).')'; - $pos = strpos($value, $needle); - if ($pos !== false) { - $value = substr_replace($value, $match, $pos, strlen($needle)); - } - } - } - - return $value; - } - - public function load($routes) { - $this->routes = $routes; - } - - public function dump(): array { - return $this->routes; - } - -} diff --git a/engine/Skin.php b/engine/Skin.php deleted file mode 100644 index b1523e6..0000000 --- a/engine/Skin.php +++ /dev/null @@ -1,63 +0,0 @@ - false, - 'wide' => false, - 'dynlogo_enabled' => true, - 'logo_path_map' => [], - 'logo_link_map' => [], - ]; - - public function renderPage($f, ...$vars): Response { - $f = '\\skin\\'.str_replace('/', '\\', $f); - $ctx = new SkinContext(substr($f, 0, ($pos = strrpos($f, '\\')))); - $body = call_user_func_array([$ctx, substr($f, $pos+1)], $vars); - if (is_array($body)) - list($body, $js) = $body; - else - $js = null; - - $theme = themes::getUserTheme(); - if ($theme != 'auto' && !themes::themeExists($theme)) - $theme = 'auto'; - - $layout_ctx = new SkinContext('\\skin\\base'); - $lang = $this->getLang(); - $lang = !empty($lang) ? json_encode($lang, JSON_UNESCAPED_UNICODE) : ''; - return new Response(200, $layout_ctx->layout( - static: $this->static, - theme: $theme, - title: $this->title, - opts: $this->options, - js: $js, - meta: $this->meta, - unsafe_lang: $lang, - unsafe_body: $body, - exec_time: exectime() - )); - } - - public function addLangKeys(array $keys): void { - $this->langKeys = array_merge($this->langKeys, $keys); - } - - protected function getLang(): array { - $lang = []; - $ld = LangData::getInstance(); - foreach ($this->langKeys as $key) - $lang[$key] = $ld[$key]; - return $lang; - } - - public function setOptions(array $options): void { - $this->options = array_merge($this->options, $options); - } - -} diff --git a/engine/SkinBase.php b/engine/SkinBase.php deleted file mode 100644 index b50c172..0000000 --- a/engine/SkinBase.php +++ /dev/null @@ -1,22 +0,0 @@ -langRaw(...$args)); - } - - public function langRaw(string $key, ...$args) { - $val = self::$ld[$key]; - return empty($args) ? $val : sprintf($val, ...$args); - } - -} - -SkinBase::__constructStatic(); \ No newline at end of file diff --git a/engine/SkinContext.php b/engine/SkinContext.php deleted file mode 100644 index c395453..0000000 --- a/engine/SkinContext.php +++ /dev/null @@ -1,118 +0,0 @@ -ns = $namespace; - require_once ROOT.str_replace('\\', DIRECTORY_SEPARATOR, $namespace).'.skin.php'; - } - - public function __call($name, array $arguments) { - $plain_args = array_is_list($arguments); - - $fn = $this->ns.'\\'.$name; - $refl = new ReflectionFunction($fn); - $fparams = $refl->getParameters(); - assert(count($fparams) == count($arguments)+1, "$fn: invalid number of arguments (".count($fparams)." != ".(count($arguments)+1).")"); - - foreach ($fparams as $n => $param) { - if ($n == 0) - continue; // skip $ctx - - $key = $plain_args ? $n-1 : $param->name; - if (!$plain_args && !array_key_exists($param->name, $arguments)) { - if (!$param->isDefaultValueAvailable()) - throw new InvalidArgumentException('argument '.$param->name.' not found'); - else - continue; - } - - if (is_string($arguments[$key]) || $arguments[$key] instanceof SkinString) { - if (is_string($arguments[$key])) - $arguments[$key] = new SkinString($arguments[$key]); - - if (($pos = strpos($param->name, '_')) !== false) { - $mod_type = match(substr($param->name, 0, $pos)) { - 'unsafe' => SkinStringModificationType::RAW, - 'urlencoded' => SkinStringModificationType::URL, - 'jsonencoded' => SkinStringModificationType::JSON, - 'addslashes' => SkinStringModificationType::ADDSLASHES, - default => SkinStringModificationType::HTML - }; - } else { - $mod_type = SkinStringModificationType::HTML; - } - $arguments[$key]->setModType($mod_type); - } - } - - array_unshift($arguments, $this); - return call_user_func_array($fn, $arguments); - } - - public function &__get(string $name) { - $fn = $this->ns.'\\'.$name; - if (function_exists($fn)) { - $f = [$this, $name]; - return $f; - } - - if (array_key_exists($name, $this->data)) - return $this->data[$name]; - } - - public function __set(string $name, $value) { - $this->data[$name] = $value; - } - - public function if_not($cond, $callback, ...$args) { - return $this->_if_condition(!$cond, $callback, ...$args); - } - - public function if_true($cond, $callback, ...$args) { - return $this->_if_condition($cond, $callback, ...$args); - } - - public function if_admin($callback, ...$args) { - return $this->_if_condition(admin::isAdmin(), $callback, ...$args); - } - - public function if_dev($callback, ...$args) { - global $config; - return $this->_if_condition($config['is_dev'], $callback, ...$args); - } - - public function if_then_else($cond, $cb1, $cb2) { - return $cond ? $this->_return_callback($cb1) : $this->_return_callback($cb2); - } - - public function csrf($key): string { - return csrf::get($key); - } - - protected function _if_condition($condition, $callback, ...$args) { - if (is_string($condition) || $condition instanceof Stringable) - $condition = (string)$condition !== ''; - if ($condition) - return $this->_return_callback($callback, $args); - return ''; - } - - protected function _return_callback($callback, $args = []) { - if (is_callable($callback)) - return call_user_func_array($callback, $args); - else if (is_string($callback)) - return $callback; - } - - public function for_each(array $iterable, callable $callback) { - $html = ''; - foreach ($iterable as $k => $v) - $html .= call_user_func($callback, $v, $k); - return $html; - } - -} diff --git a/engine/SkinString.php b/engine/SkinString.php deleted file mode 100644 index 0f8f14d..0000000 --- a/engine/SkinString.php +++ /dev/null @@ -1,23 +0,0 @@ -modType = $modType; - } - - public function __toString(): string { - return match ($this->modType) { - SkinStringModificationType::HTML => htmlescape($this->string), - SkinStringModificationType::URL => urlencode($this->string), - SkinStringModificationType::JSON => json_encode($this->string, JSON_UNESCAPED_UNICODE), - SkinStringModificationType::ADDSLASHES => addslashes($this->string), - default => $this->string, - }; - } - -} \ No newline at end of file diff --git a/engine/SkinStringModificationType.php b/engine/SkinStringModificationType.php deleted file mode 100644 index 7e750f2..0000000 --- a/engine/SkinStringModificationType.php +++ /dev/null @@ -1,9 +0,0 @@ -value + ($fg_bright ? 90 : 30); - if (!is_null($bg)) - $codes[] = $bg->value + ($bg_bright ? 100 : 40); - if ($bold) - $codes[] = 1; - - if (empty($codes)) - return $text; - - return "\033[".implode(';', $codes)."m".$text."\033[0m"; -} \ No newline at end of file diff --git a/engine/csrf.php b/engine/csrf.php deleted file mode 100644 index 20ea919..0000000 --- a/engine/csrf.php +++ /dev/null @@ -1,22 +0,0 @@ -= 0; $i--) { - $arg_val = $args[$i]; - if (is_null($arg_val)) { - $v = 'NULL'; - } else { - $v = '\''.$this->escape($arg_val) . '\''; - } - $sql = substr_replace($sql, $v, $positions[$i], 1); - } - } - if (!empty($config['db']['log'])) - logDebug(__METHOD__.': ', $sql); - return $sql; - } - - public function insert(string $table, array $fields) { - return $this->performInsert('INSERT', $table, $fields); - } - - public function replace(string $table, array $fields) { - return $this->performInsert('REPLACE', $table, $fields); - } - - protected function performInsert(string $command, string $table, array $fields) { - $names = []; - $values = []; - $count = 0; - foreach ($fields as $k => $v) { - $names[] = $k; - $values[] = $v; - $count++; - } - - $sql = "{$command} INTO `{$table}` (`" . implode('`, `', $names) . "`) VALUES (" . implode(', ', array_fill(0, $count, '?')) . ")"; - array_unshift($values, $sql); - - return $this->query(...$values); - } - - public function update(string $table, array $rows, ...$cond) { - $fields = []; - $args = []; - foreach ($rows as $row_name => $row_value) { - $fields[] = "`{$row_name}`=?"; - $args[] = $row_value; - } - $sql = "UPDATE `$table` SET ".implode(', ', $fields); - if (!empty($cond)) { - $sql .= " WHERE ".$cond[0]; - if (count($cond) > 1) - $args = array_merge($args, array_slice($cond, 1)); - } - return $this->query($sql, ...$args); - } - - public function multipleInsert(string $table, array $rows) { - list($names, $values) = $this->getMultipleInsertValues($rows); - $sql = "INSERT INTO `{$table}` (`".implode('`, `', $names)."`) VALUES ".$values; - return $this->query($sql); - } - - public function multipleReplace(string $table, array $rows) { - list($names, $values) = $this->getMultipleInsertValues($rows); - $sql = "REPLACE INTO `{$table}` (`".implode('`, `', $names)."`) VALUES ".$values; - return $this->query($sql); - } - - protected function getMultipleInsertValues(array $rows): array { - $names = []; - $sql_rows = []; - foreach ($rows as $i => $fields) { - $row_values = []; - foreach ($fields as $field_name => $field_val) { - if ($i == 0) { - $names[] = $field_name; - } - $row_values[] = $this->escape($field_val); - } - $sql_rows[] = "('".implode("', '", $row_values)."')"; - } - return [$names, implode(', ', $sql_rows)]; - } - -} \ No newline at end of file diff --git a/engine/database/MySQLConnection.php b/engine/database/MySQLConnection.php deleted file mode 100644 index c4e47e5..0000000 --- a/engine/database/MySQLConnection.php +++ /dev/null @@ -1,82 +0,0 @@ -link) - $this->link->close(); - } - - public function connect(): bool { - $this->link = new mysqli(); - $result = $this->link->real_connect($this->host, $this->user, $this->password, $this->database); - if ($result) - $this->link->set_charset('utf8mb4'); - return !!$result; - } - - public function query(string $sql, ...$args): mysqli_result|bool { - $sql = $this->prepareQuery($sql, ...$args); - $q = $this->link->query($sql); - if (!$q) - logError(__METHOD__.': '.$this->link->error."\n$sql\n".backtrace(1)); - return $q; - } - - public function fetch($q): ?array { - $row = $q->fetch_assoc(); - if (!$row) { - $q->free(); - return null; - } - return $row; - } - - public function fetchAll($q): ?array { - if (!$q) - return null; - $list = []; - while ($f = $q->fetch_assoc()) { - $list[] = $f; - } - $q->free(); - return $list; - } - - public function fetchRow($q): ?array { - return $q?->fetch_row(); - } - - public function result($q, $field = 0) { - return $q?->fetch_row()[$field]; - } - - public function insertId(): int { - return $this->link->insert_id; - } - - public function numRows($q): ?int { - return $q?->num_rows; - } - - // public function affectedRows() { - // return $this->link->affected_rows; - // } - // - // public function foundRows() { - // return $this->fetch($this->query("SELECT FOUND_ROWS() AS `count`"))['count']; - // } - - public function escape(string $s): string { - return $this->link->real_escape_string($s); - } - -} diff --git a/engine/database/SQLiteConnection.php b/engine/database/SQLiteConnection.php deleted file mode 100644 index 6b03c7c..0000000 --- a/engine/database/SQLiteConnection.php +++ /dev/null @@ -1,81 +0,0 @@ -link = new SQLite3($db_path); - if ($will_create) - setperm($db_path); - $this->link->enableExceptions(true); - $this->upgradeSchema(); - } - - protected function upgradeSchema() { - $cur = $this->getSchemaVersion(); - if ($cur == self::SCHEMA_VERSION) - return; - - if ($cur < 1) { - // TODO - } - - $this->syncSchemaVersion(); - } - - protected function getSchemaVersion() { - return $this->link->query("PRAGMA user_version")->fetchArray()[0]; - } - - protected function syncSchemaVersion() { - $this->link->exec("PRAGMA user_version=".self::SCHEMA_VERSION); - } - - public function query(string $sql, ...$params): SQLite3Result { - return $this->link->query($this->prepareQuery($sql, ...$params)); - } - - public function exec(string $sql, ...$params) { - return $this->link->exec($this->prepareQuery($sql, ...$params)); - } - - public function querySingle(string $sql, ...$params) { - return $this->link->querySingle($this->prepareQuery($sql, ...$params)); - } - - public function querySingleRow(string $sql, ...$params) { - return $this->link->querySingle($this->prepareQuery($sql, ...$params), true); - } - - public function insertId(): int { - return $this->link->lastInsertRowID(); - } - - public function escape(string $s): string { - return $this->link->escapeString($s); - } - - public function fetch($q): ?array { - // TODO: Implement fetch() method. - } - - public function fetchAll($q): ?array { - // TODO: Implement fetchAll() method. - } - - public function fetchRow($q): ?array { - // TODO: Implement fetchRow() method. - } - - public function result($q, int $field = 0) { - return $q?->fetchArray()[$field]; - } - - public function numRows($q): ?int { - // TODO: Implement numRows() method. - } -} \ No newline at end of file diff --git a/engine/exceptions/ForbiddenException.php b/engine/exceptions/ForbiddenException.php deleted file mode 100644 index 4184908..0000000 --- a/engine/exceptions/ForbiddenException.php +++ /dev/null @@ -1,9 +0,0 @@ -log(LogLevel::DEBUG, ...$args); } +function logInfo(...$args): void { global $__logger; $__logger->log(LogLevel::INFO, ...$args); } +function logWarning(...$args): void { global $__logger; $__logger->log(LogLevel::WARNING, ...$args); } +function logError(...$args): void { global $__logger; $__logger->log(LogLevel::ERROR, ...$args); } - protected static ?string $logFile = null; - protected static bool $enabled = false; - protected static int $counter = 0; +abstract class Logger { + protected bool $enabled = false; + protected int $counter = 0; + protected int $recursionLevel = 0; /** @var ?callable $filter */ - protected static $filter = null; + protected $filter = null; - public static function setLogFile(string $log_file): void { - self::$logFile = $log_file; + function setErrorFilter(callable $filter): void { + $this->filter = $filter; } - public static function setErrorFilter(callable $filter): void { - self::$filter = $filter; + function disable(): void { + $this->enabled = false; } - public static function disable(): void { - self::$enabled = false; + function enable(): void { + static $error_handler_set = false; + $this->enabled = true; - restore_error_handler(); - register_shutdown_function(function() {}); - } + if ($error_handler_set) + return; - public static function enable(): void { - self::$enabled = true; + $self = $this; - set_error_handler(function($no, $str, $file, $line) { - if (is_callable(self::$filter) && !(self::$filter)($no, $file, $line, $str)) + set_error_handler(function($no, $str, $file, $line) use ($self) { + if (!$self->enabled) return; - self::write(LogLevel::ERROR, $str, + if (is_callable($self->filter) && !($self->filter)($no, $file, $line, $str)) + return; + + static::write(LogLevel::ERROR, $str, errno: $no, errfile: $file, errline: $line); }); - register_shutdown_function(function() { - if (!($error = error_get_last())) + register_shutdown_function(function () use ($self) { + if (!$self->enabled || !($error = error_get_last())) return; - if (is_callable(self::$filter) - && !(self::$filter)($error['type'], $error['file'], $error['line'], $error['message'])) { + if (is_callable($self->filter) + && !($self->filter)($error['type'], $error['file'], $error['line'], $error['message'])) { return; } - self::write(LogLevel::ERROR, $error['message'], + static::write(LogLevel::ERROR, $error['message'], errno: $error['type'], - errfile: $error['file'], + errfile: $error['file'], errline: $error['line']); }); + + $error_handler_set = true; } - public static function logCustom(LogLevel $level, ...$args): void { - global $config; - if (!$config['is_dev'] && $level == LogLevel::DEBUG) + function log(LogLevel $level, ...$args): void { + if (!is_dev() && $level == LogLevel::DEBUG) return; - self::write($level, self::strVars($args)); + $this->write($level, strVars($args)); } - protected static function write(LogLevel $level, - string $message, - ?int $errno = null, - ?string $errfile = null, - ?string $errline = null): void { + protected function canReport(): bool { + return $this->recursionLevel < 3; + } + + protected function write(LogLevel $level, + string $message, + ?int $errno = null, + ?string $errfile = null, + ?string $errline = null): void { + $this->recursionLevel++; + + if ($this->canReport()) + $this->writer($level, $this->counter++, $message, $errno, $errfile, $errline); + + $this->recursionLevel--; + } + + abstract protected function writer(LogLevel $level, + int $num, + string $message, + ?int $errno = null, + ?string $errfile = null, + ?string $errline = null): void; +} + +class FileLogger extends Logger { + + function __construct(protected string $logFile) {} - // TODO test - if (is_null(self::$logFile)) { + protected function writer(LogLevel $level, + int $num, + string $message, + ?int $errno = null, + ?string $errfile = null, + ?string $errline = null): void + { + if (is_null($this->logFile)) { fprintf(STDERR, __METHOD__.': logfile is not set'); return; } - $num = self::$counter++; $time = time(); // TODO rewrite using sprintf @@ -98,47 +124,56 @@ class logging { if (strlen($exec_time) < 6) $exec_time .= str_repeat('0', 6 - strlen($exec_time)); - // $bt = backtrace(2); - - $title = PHP_SAPI == 'cli' ? 'cli' : $_SERVER['REQUEST_URI']; + $title = is_cli() ? 'cli' : $_SERVER['REQUEST_URI']; $date = date('d/m/y H:i:s', $time); $buf = ''; if ($num == 0) { - $buf .= wrap(" $title ", - fg: Color::WHITE, - bg: Color::MAGENTA, - fg_bright: true, - bold: true); - $buf .= wrap(" $date ", fg: Color::WHITE, bg: Color::BLUE, fg_bright: true); + $buf .= ansi(" $title ", + fg: AnsiColor::WHITE, + bg: AnsiColor::MAGENTA, + bold: true, + fg_bright: true); + $buf .= ansi(" $date ", fg: AnsiColor::WHITE, bg: AnsiColor::BLUE, fg_bright: true); $buf .= "\n"; } $letter = strtoupper($level->name[0]); $color = match ($level) { - LogLevel::ERROR => Color::RED, - LogLevel::INFO, LogLevel::DEBUG => Color::WHITE, - LogLevel::WARNING => Color::YELLOW + LogLevel::ERROR => AnsiColor::RED, + LogLevel::INFO => AnsiColor::GREEN, + LogLevel::DEBUG => AnsiColor::WHITE, + LogLevel::WARNING => AnsiColor::YELLOW }; - $buf .= wrap($letter.wrap('='.wrap($num, bold: true)), fg: $color).' '; - $buf .= wrap($exec_time, fg: Color::CYAN).' '; + $buf .= ansi($letter.ansi('='.ansi($num, bold: true)), fg: $color).' '; + $buf .= ansi($exec_time, fg: AnsiColor::CYAN).' '; if (!is_null($errno)) { - $buf .= wrap($errfile, fg: Color::GREEN); - $buf .= wrap(':', fg: Color::WHITE); - $buf .= wrap($errline, fg: Color::GREEN, fg_bright: true); - $buf .= ' ('.self::getPhpErrorName($errno).') '; + $buf .= ansi($errfile, fg: AnsiColor::GREEN); + $buf .= ansi(':', fg: AnsiColor::WHITE); + $buf .= ansi($errline, fg: AnsiColor::GREEN, fg_bright: true); + $buf .= ' ('.getPHPErrorName($errno).') '; } $buf .= $message."\n"; if (in_array($level, [LogLevel::ERROR, LogLevel::WARNING])) - $buf .= backtrace(2)."\n"; + $buf .= backtrace_as_string(2)."\n"; + + $set_perm = false; + if (!file_exists($this->logFile)) { + $set_perm = true; + $dir = dirname($this->logFile); + echo "dir: $dir\n"; + + if (!file_exists($dir)) { + mkdir($dir); + setperm($dir); + } + } - // TODO test - $set_perm = !file_exists(self::$logFile); - $f = fopen(self::$logFile, 'a'); + $f = fopen($this->logFile, 'a'); if (!$f) { - fprintf(STDERR, __METHOD__.': failed to open file "'.self::$logFile.'" for writing'); + fprintf(STDERR, __METHOD__.': failed to open file \''.$this->logFile.'\' for writing'); return; } @@ -146,34 +181,76 @@ class logging { fclose($f); if ($set_perm) - setperm(self::$logFile); + setperm($this->logFile); } - protected static function getPhpErrorName(int $errno): string { - static $errors = null; - if (is_null($errors)) - $errors = array_flip(array_slice(get_defined_constants(true)['Core'], 0, 15, true)); - return $errors[$errno]; - } +} - protected static function strVarDump($var, bool $print_r = false): string { - ob_start(); - $print_r ? print_r($var) : var_dump($var); - return trim(ob_get_clean()); - } +class DatabaseLogger extends Logger { + protected function writer(LogLevel $level, + int $num, + string $message, + ?int $errno = null, + ?string $errfile = null, + ?string $errline = null): void + { + $db = DB(); + + $data = [ + 'ts' => time(), + 'num' => $num, + 'time' => exectime(), + 'errno' => $errno, + 'file' => $errfile, + 'line' => $errline, + 'text' => $message, + 'level' => $level->value, + 'stacktrace' => backtrace_as_string(2), + 'is_cli' => intval(is_cli()), + 'user_id' => 0, + ]; + + if (is_cli()) { + $data += [ + 'ip' => '', + 'ua' => '', + 'url' => '', + ]; + } else { + $data += [ + 'ip' => ip2ulong($_SERVER['REMOTE_ADDR']), + 'ua' => $_SERVER['HTTP_USER_AGENT'] ?? '', + 'url' => $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] + ]; + } - protected static function strVars(array $args): string { - $args = array_map(fn($a) => match (gettype($a)) { - 'string' => $a, - 'array', 'object' => self::strVarDump($a, true), - default => self::strVarDump($a) - }, $args); - return implode(' ', $args); + $db->insert('backend_errors', $data); } +} + +function getPHPErrorName(int $errno): string { + static $errors = null; + if (is_null($errors)) + $errors = array_flip(array_slice(get_defined_constants(true)['Core'], 0, 15, true)); + return $errors[$errno]; +} + +function strVarDump($var, bool $print_r = false): string { + ob_start(); + $print_r ? print_r($var) : var_dump($var); + return trim(ob_get_clean()); +} +function strVars(array $args): string { + $args = array_map(fn($a) => match (gettype($a)) { + 'string' => $a, + 'array', 'object' => strVarDump($a, true), + default => strVarDump($a) + }, $args); + return implode(' ', $args); } -function backtrace(int $shift = 0): string { +function backtrace_as_string(int $shift = 0): string { $bt = debug_backtrace(); $lines = []; foreach ($bt as $i => $t) { @@ -187,4 +264,4 @@ function backtrace(int $shift = 0): string { } } return implode("\n", $lines); -} +} \ No newline at end of file diff --git a/engine/model.php b/engine/model.php new file mode 100644 index 0000000..e967dc2 --- /dev/null +++ b/engine/model.php @@ -0,0 +1,331 @@ +getProperties() as $prop) + $this->{$prop->getModelName()} = $prop->fromRawValue($raw[$prop->getDbName()]); + + if (is_null(static::DB_TABLE)) + trigger_error('class '.get_class($this).' doesn\'t have DB_TABLE defined'); + } + + /** + * TODO: support adding or subtracting (SET value=value+1) + */ + public function edit(array $fields) { + $db = DB(); + + $model_upd = []; + $db_upd = []; + + $spec_db_name_map = self::$SpecCache[static::class]->getDbNameMap(); + $spec_props = self::$SpecCache[static::class]->getProperties(); + + foreach ($fields as $name => $value) { + $index = $spec_db_name_map[$name] ?? null; + if (is_null($index)) { + logError(__METHOD__.': field `'.$name.'` not found in '.static::class); + continue; + } + + $field = $spec_props[$index]; + if ($field->isNullable() && is_null($value)) { + $model_upd[$field->getModelName()] = $value; + $db_upd[$name] = $value; + continue; + } + + switch ($field->getType()) { + case ModelFieldType::ARRAY: + if (is_array($value)) { + $db_upd[$name] = implode(',', $value); + $model_upd[$field->getModelName()] = $value; + } else { + logError(__METHOD__.': field `'.$name.'` is expected to be array. skipping.'); + } + break; + + case ModelFieldType::INTEGER: + $value = (int)$value; + $db_upd[$name] = $value; + $model_upd[$field->getModelName()] = $value; + break; + + case ModelFieldType::FLOAT: + $value = (float)$value; + $db_upd[$name] = $value; + $model_upd[$field->getModelName()] = $value; + break; + + case ModelFieldType::BOOLEAN: + $db_upd[$name] = $value ? 1 : 0; + $model_upd[$field->getModelName()] = $value; + break; + + case ModelFieldType::JSON: + $db_upd[$name] = jsonEncode($value); + $model_upd[$field->getModelName()] = $value; + break; + + case ModelFieldType::SERIALIZED: + $db_upd[$name] = serialize($value); + $model_upd[$field->getModelName()] = $value; + break; + + case ModelFieldType::BITFIELD: + $db_upd[$name] = $value; + $model_upd[$field->getModelName()] = $value; + break; + + default: + $value = (string)$value; + $db_upd[$name] = $value; + $model_upd[$field->getModelName()] = $value; + break; + } + } + + if (!empty($db_upd) && !$db->update(static::DB_TABLE, $db_upd, static::DB_KEY."=?", $this->get_id())) { + logError(__METHOD__.': failed to update database'); + return; + } + + if (!empty($model_upd)) { + foreach ($model_upd as $name => $value) + $this->{$name} = $value; + } + } + + public function get_id() { + return $this->{to_camel_case(static::DB_KEY)}; + } + + public function as_array(array $properties = [], array $custom_getters = []): array { + if (empty($properties)) + $properties = static::$SpecCache[static::class]->getPropNames(); + + $array = []; + foreach ($properties as $field) { + if (isset($custom_getters[$field]) && is_callable($custom_getters[$field])) { + $array[$field] = $custom_getters[$field](); + } else { + $array[$field] = $this->{to_camel_case($field)}; + } + } + + return $array; + } + + protected static function get_spec(): ModelSpec { + $rc = new ReflectionClass(static::class); + $props = $rc->getProperties(ReflectionProperty::IS_PUBLIC); + + $list = []; + $index = 0; + + $db_name_map = []; + + foreach ($props as $prop) { + if ($prop->isStatic()) + continue; + + $name = $prop->getName(); + if (str_starts_with($name, '_')) + continue; + + $real_type = null; + $type = $prop->getType(); + $phpdoc = $prop->getDocComment(); + + /** @var ?ModelFieldType $mytype */ + $mytype = null; + if (!$prop->hasType() && !$phpdoc) + $mytype = ModelFieldType::STRING; + else { + $typename = $type->getName(); + switch ($typename) { + case 'string': + $mytype = ModelFieldType::STRING; + break; + case 'int': + $mytype = ModelFieldType::INTEGER; + break; + case 'float': + $mytype = ModelFieldType::FLOAT; + break; + case 'array': + $mytype = ModelFieldType::ARRAY; + break; + case 'bool': + $mytype = ModelFieldType::BOOLEAN; + break; + case 'mysql_bitfield': + $mytype = ModelFieldType::BITFIELD; + break; + default: + if (enum_exists($typename)) { + $mytype = ModelFieldType::BACKED_ENUM; + $real_type = $typename; + } + break; + } + + if ($phpdoc != '') { + $pos = strpos($phpdoc, '@'); + if ($pos === false) + continue; + + if (substr($phpdoc, $pos+1, 4) == 'json') + $mytype = ModelFieldType::JSON; + else if (substr($phpdoc, $pos+1, 5) == 'array') + $mytype = ModelFieldType::ARRAY; + else if (substr($phpdoc, $pos+1, 10) == 'serialized') + $mytype = ModelFieldType::SERIALIZED; + } + } + + if (is_null($mytype)) + logError(__METHOD__.": ".$name." is still null in ".static::class); + + // $dbname = from_camel_case($name); + $model_descr = new ModelProperty( + type: $mytype, + realType: $real_type, + nullable: $type->allowsNull(), + modelName: $name, + dbName: from_camel_case($name) + ); + $list[] = $model_descr; + $db_name_map[$model_descr->getDbName()] = $index++; + } + + return new ModelSpec($list, $db_name_map); + } + +} + +class ModelSpec { + + public function __construct( + /** @var ModelProperty[] */ + protected array $properties, + protected array $dbNameMap + ) {} + + /** + * @return ModelProperty[] + */ + public function getProperties(): array { + return $this->properties; + } + + public function getDbNameMap(): array { + return $this->dbNameMap; + } + + public function getPropNames(): array { + return array_keys($this->dbNameMap); + } + +} + +class ModelProperty { + + public function __construct( + protected ?ModelFieldType $type, + protected mixed $realType, + protected bool $nullable, + protected string $modelName, + protected string $dbName + ) {} + + public function getDbName(): string { + return $this->dbName; + } + + public function getModelName(): string { + return $this->modelName; + } + + public function isNullable(): bool { + return $this->nullable; + } + + public function getType(): ?ModelFieldType { + return $this->type; + } + + public function fromRawValue(mixed $value): mixed { + if ($this->nullable && is_null($value)) + return null; + + switch ($this->type) { + case ModelFieldType::BOOLEAN: + return (bool)$value; + + case ModelFieldType::INTEGER: + return (int)$value; + + case ModelFieldType::FLOAT: + return (float)$value; + + case ModelFieldType::ARRAY: + return array_filter(explode(',', $value)); + + case ModelFieldType::JSON: + $val = jsonDecode($value); + if (!$val) + $val = null; + return $val; + + case ModelFieldType::SERIALIZED: + $val = unserialize($value); + if ($val === false) + $val = null; + return $val; + + case ModelFieldType::BITFIELD: + return new mysql_bitfield($value); + + case ModelFieldType::BACKED_ENUM: + try { + return $this->realType::from($value); + } catch (ValueError $e) { + if ($this->nullable) + return null; + throw $e; + } + + default: + return (string)$value; + } + } + +} \ No newline at end of file diff --git a/engine/mysql.php b/engine/mysql.php new file mode 100644 index 0000000..bab8048 --- /dev/null +++ b/engine/mysql.php @@ -0,0 +1,261 @@ += 0; $i--) { + $arg_val = $args[$i]; + if (is_null($arg_val)) { + $v = 'NULL'; + } else { + $v = '\''.$this->escape($arg_val) . '\''; + } + $sql = substr_replace($sql, $v, $positions[$i], 1); + } + } + if (!empty($config['mysql']['log'])) + logDebug(__METHOD__.': ', $sql); + return $sql; + } + + function insert(string $table, array $fields) { + return $this->performInsert('INSERT', $table, $fields); + } + + function replace(string $table, array $fields) { + return $this->performInsert('REPLACE', $table, $fields); + } + + protected function performInsert(string $command, string $table, array $fields) { + $names = []; + $values = []; + $count = 0; + foreach ($fields as $k => $v) { + $names[] = $k; + $values[] = $v; + $count++; + } + + $sql = "{$command} INTO `{$table}` (`" . implode('`, `', $names) . "`) VALUES (" . implode(', ', array_fill(0, $count, '?')) . ")"; + array_unshift($values, $sql); + + return $this->query(...$values); + } + + function update(string $table, array $rows, ...$cond) { + $fields = []; + $args = []; + foreach ($rows as $row_name => $row_value) { + $fields[] = "`{$row_name}`=?"; + $args[] = $row_value; + } + $sql = "UPDATE `$table` SET ".implode(', ', $fields); + if (!empty($cond)) { + $sql .= " WHERE ".$cond[0]; + if (count($cond) > 1) + $args = array_merge($args, array_slice($cond, 1)); + } + return $this->query($sql, ...$args); + } + + function multipleInsert(string $table, array $rows) { + list($names, $values) = $this->getMultipleInsertValues($rows); + $sql = "INSERT INTO `{$table}` (`".implode('`, `', $names)."`) VALUES ".$values; + return $this->query($sql); + } + + function multipleReplace(string $table, array $rows) { + list($names, $values) = $this->getMultipleInsertValues($rows); + $sql = "REPLACE INTO `{$table}` (`".implode('`, `', $names)."`) VALUES ".$values; + return $this->query($sql); + } + + protected function getMultipleInsertValues(array $rows): array { + $names = []; + $sql_rows = []; + foreach ($rows as $i => $fields) { + $row_values = []; + foreach ($fields as $field_name => $field_val) { + if ($i == 0) { + $names[] = $field_name; + } + $row_values[] = $this->escape($field_val); + } + $sql_rows[] = "('".implode("', '", $row_values)."')"; + } + return [$names, implode(', ', $sql_rows)]; + } + + function __destruct() { + if ($this->link) + $this->link->close(); + } + + function connect(): bool { + $this->link = new mysqli(); + $result = $this->link->real_connect($this->host, $this->user, $this->password, $this->database); + if ($result) + $this->link->set_charset('utf8mb4'); + return !!$result; + } + + function query(string $sql, ...$args): mysqli_result|bool { + $sql = $this->prepareQuery($sql, ...$args); + $q = $this->link->query($sql); + if (!$q) + logError(__METHOD__.': '.$this->link->error."\n$sql\n".backtrace_as_string(1)); + return $q; + } + + function fetch($q): ?array { + $row = $q->fetch_assoc(); + if (!$row) { + $q->free(); + return null; + } + return $row; + } + + function fetchAll($q): ?array { + if (!$q) + return null; + $list = []; + while ($f = $q->fetch_assoc()) { + $list[] = $f; + } + $q->free(); + return $list; + } + + function fetchRow($q): ?array { + return $q?->fetch_row(); + } + + function result($q, $field = 0) { + return $q?->fetch_row()[$field]; + } + + function insertId(): int { + return $this->link->insert_id; + } + + function numRows($q): ?int { + return $q?->num_rows; + } + + function affectedRows(): ?int { + return $this->link?->affected_rows; + } + + function foundRows(): int { + return (int)$this->fetch($this->query("SELECT FOUND_ROWS() AS `count`"))['count']; + } + + function escape(string $s): string { + return $this->link->real_escape_string($s); + } + +} + +class mysql_bitfield { + + private GMP $value; + private int $size; + + public function __construct($value, int $size = 64) { + $this->value = gmp_init($value); + $this->size = $size; + } + + public function has(int $bit): bool { + $this->validateBit($bit); + return gmp_testbit($this->value, $bit); + } + + public function set(int $bit): void { + $this->validateBit($bit); + gmp_setbit($this->value, $bit); + } + + public function clear(int $bit): void { + $this->validateBit($bit); + gmp_clrbit($this->value, $bit); + } + + public function isEmpty(): bool { + return !gmp_cmp($this->value, 0); + } + + public function __toString(): string { + $buf = ''; + for ($bit = $this->size-1; $bit >= 0; --$bit) + $buf .= gmp_testbit($this->value, $bit) ? '1' : '0'; + if (($pos = strpos($buf, '1')) !== false) { + $buf = substr($buf, $pos); + } else { + $buf = '0'; + } + return $buf; + } + + private function validateBit(int $bit): void { + if ($bit < 0 || $bit >= $this->size) + throw new Exception('invalid bit '.$bit.', allowed range: [0..'.$this->size.')'); + } + + +} + +function DB(): mysql|null { + global $config; + + /** @var ?mysql $link */ + static $link = null; + if (!is_null($link)) + return $link; + + $link = new mysql( + $config['mysql']['host'], + $config['mysql']['user'], + $config['mysql']['password'], + $config['mysql']['database']); + if (!$link->connect()) { + if (!is_cli()) { + header('HTTP/1.1 503 Service Temporarily Unavailable'); + header('Status: 503 Service Temporarily Unavailable'); + header('Retry-After: 300'); + die('database connection failed'); + } else { + fwrite(STDERR, 'database connection failed'); + exit(1); + } + } + + return $link; +} + +function MC(): Memcached { + static $mc = null; + if ($mc === null) { + $mc = new Memcached(); + $mc->addServer("127.0.0.1", 11211); + } + return $mc; +} diff --git a/engine/request.php b/engine/request.php new file mode 100644 index 0000000..e67d4fb --- /dev/null +++ b/engine/request.php @@ -0,0 +1,203 @@ + 2) { + for ($i = 2; $i < count($route); $i++) { + $var = $route[$i]; + list($k, $v) = explode('=', $var); + $RouterInput[trim($k)] = trim($v); + } + } + + /** @var request_handler $handler */ + $handler = new $handler_class(); + $handler->call_act($_SERVER['REQUEST_METHOD'], $action); +} + +function request_path(): string { + $uri = $_SERVER['REQUEST_URI']; + if (($pos = strpos($uri, '?')) !== false) + $uri = substr($uri, 0, $pos); + return $uri; +} + + +enum HTTPCode: int { + case MovedPermanently = 301; + case Found = 302; + + case Unauthorized = 401; + case NotFound = 404; + case Forbidden = 403; + + case InternalServerError = 500; + case NotImplemented = 501; +} + +function http_error(HTTPCode $http_code, string $message = ''): void { + $ctx = new SkinContext('\\skin\\error'); + $http_message = preg_replace('/(?name); + $html = $ctx->http_error($http_code->value, $http_message, $message); + http_response_code($http_code->value); + echo $html; + exit; +} + +function redirect(string $url, HTTPCode $code = HTTPCode::MovedPermanently): void { + if (!in_array($code, [HTTPCode::MovedPermanently, HTTPCode::Found])) + internal_server_error('invalid http code'); + http_response_code($code->value); + header('Location: '.$url); + exit; +} + +function internal_server_error(string $message = '') { http_error(HTTPCode::InternalServerError, $message); } +function not_found(string $message = '') { http_error(HTTPCode::NotFound, $message); } +function forbidden(string $message = '') { http_error(HTTPCode::Forbidden, $message); } +function is_xhr_request(): bool { return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'; } +function ajax_ok(mixed $data): void { ajax_response(['response' => $data]); } +function ajax_error(mixed $error, int $code = 200): void { ajax_response(['error' => $error], $code); } + +function ajax_response(mixed $data, int $code = 200): void { + header('Cache-Control: no-cache, must-revalidate'); + header('Pragma: no-cache'); + header('Content-Type: application/json; charset=utf-8'); + http_response_code($code); + echo jsonEncode($data); + exit; +} + + +abstract class request_handler { + function __construct() { + add_static( + 'css/common.css', + 'js/common.js' + ); + add_skin_strings_re('/^theme_/'); + } + + function before_dispatch(string $http_method, string $action) {} + + function call_act(string $http_method, string $action, array $input = []) { + global $RouterInput; + + $handler_method = $_SERVER['REQUEST_METHOD'].'_'.$action; + if (!method_exists($this, $handler_method)) + not_found(static::class.'::'.$handler_method.' is not defined'); + + if (!((new ReflectionMethod($this, $handler_method))->isPublic())) + not_found(static::class.'::'.$handler_method.' is not public'); + + if (!empty($input)) { + foreach ($input as $k => $v) + $RouterInput[$k] = $v; + } + + $args = $this->before_dispatch($http_method, $action); + return call_user_func_array([$this, $handler_method], is_array($args) ? [$args] : []); + } +} + + +enum InputVarType: string { + case INTEGER = 'i'; + case FLOAT = 'f'; + case BOOLEAN = 'b'; + case STRING = 's'; + case ENUM = 'e'; +} + +function input(string $input): array { + global $RouterInput; + $input = preg_split('/,\s+?/', $input, -1, PREG_SPLIT_NO_EMPTY); + $ret = []; + foreach ($input as $var) { + $enum_values = null; + $enum_default = null; + + $pos = strpos($var, ':'); + if ($pos !== false) { + $type = substr($var, 0, $pos); + $rest = substr($var, $pos + 1); + + $vartype = InputVarType::tryFrom($type); + if (is_null($vartype)) + internal_server_error('invalid input type '.$type); + + if ($vartype == InputVarType::ENUM) { + $br_from = strpos($rest, '('); + $br_to = strpos($rest, ')'); + + if ($br_from === false || $br_to === false) + internal_server_error('failed to parse enum values: '.$rest); + + $enum_values = array_map('trim', explode('|', trim(substr($rest, $br_from + 1, $br_to - $br_from - 1)))); + $name = trim(substr($rest, 0, $br_from)); + + if (!empty($enum_values)) { + foreach ($enum_values as $key => $val) { + if (str_starts_with($val, '=')) { + $enum_values[$key] = substr($val, 1); + $enum_default = $enum_values[$key]; + } + } + } + } else { + $name = trim($rest); + } + + } else { + $vartype = InputVarType::STRING; + $name = trim($var); + } + + $val = null; + if (isset($RouterInput[$name])) { + $val = $RouterInput[$name]; + } else if (isset($_POST[$name])) { + $val = $_POST[$name]; + } else if (isset($_GET[$name])) { + $val = $_GET[$name]; + } + if (is_array($val)) + $val = implode($val); + + $ret[] = match($vartype) { + InputVarType::INTEGER => (int)$val, + InputVarType::FLOAT => (float)$val, + InputVarType::BOOLEAN => (bool)$val, + InputVarType::ENUM => !in_array($val, $enum_values) ? $enum_default ?? '' : (string)$val, + default => (string)$val + }; + } + return $ret; +} + +function csrf_get(string $key): string { return _csrf_get_token($_SERVER['REMOTE_ADDR'], $key); } +function csrf_check(string $key) { + if (csrf_get($key) != ($_REQUEST['token'] ?? '')) { + forbidden('invalid token'); + } +} + +function _csrf_get_token(string $user_token, string $key): string { + global $config; + return substr(sha1($config['csrf_token'].$user_token.$key), 0, 20); +} \ No newline at end of file diff --git a/engine/router.php b/engine/router.php new file mode 100644 index 0000000..401e177 --- /dev/null +++ b/engine/router.php @@ -0,0 +1,185 @@ + [], + 're_children' => [] +]; + +function router_init(): void { + global $Routes; + $mc = MC(); + + $from_cache = !is_dev(); + $write_cache = !is_dev(); + + if ($from_cache) { + $cache = $mc->get(ROUTER_MC_KEY); + + if ($cache === false || !isset($cache['version']) || $cache['version'] < ROUTER_VERSION) { + $from_cache = false; + } else { + $Routes = $cache['routes']; + } + } + + if (!$from_cache) { + $routes_table = require_once APP_ROOT.'/routes.php'; + + foreach ($routes_table as $controller => $routes) { + foreach ($routes as $route => $resolve) + router_add($route, $controller.' '.$resolve); + } + + if ($write_cache) + $mc->set(ROUTER_MC_KEY, ['version' => ROUTER_VERSION, 'routes' => $Routes]); + } +} + +function router_add(string $template, string $value): void { + global $Routes; + if ($template == '') + return; + + // expand {enum,erat,ions} + $templates = [[$template, $value]]; + if (preg_match_all('/\{([\w\d_\-,]+)\}/', $template, $matches)) { + foreach ($matches[1] as $match_index => $variants) { + $variants = explode(',', $variants); + $variants = array_map('trim', $variants); + $variants = array_filter($variants, function($s) { return $s != ''; }); + + for ($i = 0; $i < count($templates); ) { + list($template, $value) = $templates[$i]; + $new_templates = []; + foreach ($variants as $variant_index => $variant) { + $new_templates[] = [ + str_replace_once($matches[0][$match_index], $variant, $template), + str_replace('${'.($match_index+1).'}', $variant, $value) + ]; + } + array_splice($templates, $i, 1, $new_templates); + $i += count($new_templates); + } + } + } + + // process all generated routes + foreach ($templates as $template) { + list($template, $value) = $template; + + $start_pos = 0; + $parent = &$Routes; + $template_len = strlen($template); + + while ($start_pos < $template_len) { + $slash_pos = strpos($template, '/', $start_pos); + if ($slash_pos !== false) { + $part = substr($template, $start_pos, $slash_pos-$start_pos+1); + $start_pos = $slash_pos+1; + } else { + $part = substr($template, $start_pos); + $start_pos = $template_len; + } + + $parent = &_router_add($parent, $part, + $start_pos < $template_len ? null : $value); + } + } +} + +function &_router_add(&$parent, $part, $value = null) { + $par_pos = strpos($part, '('); + $is_regex = $par_pos !== false && ($par_pos == 0 || $part[$par_pos-1] != '\\'); + + $children_key = !$is_regex ? 'children' : 're_children'; + + if (isset($parent[$children_key][$part])) { + if (is_null($value)) { + $parent = &$parent[$children_key][$part]; + } else { + if (!isset($parent[$children_key][$part]['value'])) { + $parent[$children_key][$part]['value'] = $value; + } else { + trigger_error(__METHOD__.': route is already defined'); + } + } + return $parent; + } + + $child = [ + 'children' => [], + 're_children' => [] + ]; + if (!is_null($value)) + $child['value'] = $value; + + $parent[$children_key][$part] = $child; + return $parent[$children_key][$part]; +} + +function router_find($uri) { + global $Routes; + if ($uri != '/' && $uri[0] == '/') + $uri = substr($uri, 1); + + $start_pos = 0; + $parent = &$Routes; + $uri_len = strlen($uri); + $matches = []; + + while ($start_pos < $uri_len) { + $slash_pos = strpos($uri, '/', $start_pos); + if ($slash_pos !== false) { + $part = substr($uri, $start_pos, $slash_pos-$start_pos+1); + $start_pos = $slash_pos+1; + } else { + $part = substr($uri, $start_pos); + $start_pos = $uri_len; + } + + $found = false; + if (isset($parent['children'][$part])) { + $parent = &$parent['children'][$part]; + $found = true; + } else if (!empty($parent['re_children'])) { + foreach ($parent['re_children'] as $re => &$child) { + $exp = '#^'.$re.'$#'; + $re_result = preg_match($exp, $part, $match); + if ($re_result === false) { + logError(__METHOD__.": regex $exp failed"); + continue; + } + + if ($re_result) { + if (count($match) > 1) + $matches = array_merge($matches, array_slice($match, 1)); + $parent = &$child; + $found = true; + break; + } + } + } + + if (!$found) + return null; + } + + if (!isset($parent['value'])) + return null; + + $value = $parent['value']; + if (!empty($matches)) { + foreach ($matches as $i => $match) { + $needle = '$('.($i+1).')'; + $pos = strpos($value, $needle); + if ($pos !== false) + $value = substr_replace($value, $match, $pos, strlen($needle)); + } + } + + return $value; +} diff --git a/engine/skin.php b/engine/skin.php new file mode 100644 index 0000000..6150668 --- /dev/null +++ b/engine/skin.php @@ -0,0 +1,241 @@ + false, + 'wide' => false, + 'dynlogo_enabled' => true, + 'logo_path_map' => [], + 'logo_link_map' => [], + ]; + public array $static = []; +}; + +function render($f, ...$vars): void { + global $SkinState; + + $f = '\\skin\\'.str_replace('/', '\\', $f); + $ctx = new SkinContext(substr($f, 0, ($pos = strrpos($f, '\\')))); + $body = call_user_func_array([$ctx, substr($f, $pos + 1)], $vars); + if (is_array($body)) + list($body, $js) = $body; + else + $js = null; + + $theme = getUserTheme(); + if ($theme != 'auto' && !themeExists($theme)) + $theme = 'auto'; + + $layout_ctx = new SkinContext('\\skin\\base'); + + $lang = []; + foreach ($SkinState->lang as $key) + $lang[$key] = lang($key); + $lang = !empty($lang) ? json_encode($lang, JSON_UNESCAPED_UNICODE) : ''; + + $html = $layout_ctx->layout( + static: $SkinState->static, + theme: $theme, + title: $SkinState->title, + opts: $SkinState->options, + js: $js, + meta: $SkinState->meta, + unsafe_lang: $lang, + unsafe_body: $body, + exec_time: exectime() + ); + echo $html; + exit; +} + +function set_title(string $title): void { + global $SkinState; + if (str_starts_with($title, '$')) + $title = lang(substr($title, 1)); + else if (str_starts_with($title, '\\$')) + $title = substr($title, 1); + $SkinState->title = $title; +} + +function set_skin_opts(array $options) { + global $SkinState; + $SkinState->options = array_merge($SkinState->options, $options); +} + +function add_skin_strings(array $keys): void { + global $SkinState; + $SkinState->lang = array_merge($SkinState->lang, $keys); +} + +function add_skin_strings_re(string $re): void { + global $__lang; + add_skin_strings($__lang->search($re)); +} + +function add_static(string ...$files): void { + global $SkinState; + foreach ($files as $file) + $SkinState->static[] = $file; +} + +function add_meta(array ...$data) { + global $SkinState; + $SkinState->meta = array_merge($SkinState->meta, $data); +} + + +class SkinContext { + + protected string $ns; + protected array $data = []; + + function __construct(string $namespace) { + $this->ns = $namespace; + require_once APP_ROOT.str_replace('\\', DIRECTORY_SEPARATOR, $namespace).'.skin.php'; + } + + function __call($name, array $arguments) { + $plain_args = array_is_list($arguments); + + $fn = $this->ns.'\\'.$name; + $refl = new ReflectionFunction($fn); + $fparams = $refl->getParameters(); + assert(count($fparams) == count($arguments) + 1, "$fn: invalid number of arguments (".count($fparams)." != ".(count($arguments) + 1).")"); + + foreach ($fparams as $n => $param) { + if ($n == 0) + continue; // skip $ctx + + $key = $plain_args ? $n - 1 : $param->name; + if (!$plain_args && !array_key_exists($param->name, $arguments)) { + if (!$param->isDefaultValueAvailable()) + throw new InvalidArgumentException('argument '.$param->name.' not found'); + else + continue; + } + + if (is_string($arguments[$key]) || $arguments[$key] instanceof SkinString) { + if (is_string($arguments[$key])) + $arguments[$key] = new SkinString($arguments[$key]); + + if (($pos = strpos($param->name, '_')) !== false) { + $mod_type = match (substr($param->name, 0, $pos)) { + 'unsafe' => SkinStringModificationType::RAW, + 'urlencoded' => SkinStringModificationType::URL, + 'jsonencoded' => SkinStringModificationType::JSON, + 'addslashes' => SkinStringModificationType::ADDSLASHES, + default => SkinStringModificationType::HTML + }; + } else { + $mod_type = SkinStringModificationType::HTML; + } + $arguments[$key]->setModType($mod_type); + } + } + + array_unshift($arguments, $this); + return call_user_func_array($fn, $arguments); + } + + function &__get(string $name) { + $fn = $this->ns.'\\'.$name; + if (function_exists($fn)) { + $f = [$this, $name]; + return $f; + } + + if (array_key_exists($name, $this->data)) + return $this->data[$name]; + } + + function __set(string $name, $value) { + $this->data[$name] = $value; + } + + function if_not($cond, $callback, ...$args) { + return $this->_if_condition(!$cond, $callback, ...$args); + } + + function if_true($cond, $callback, ...$args) { + return $this->_if_condition($cond, $callback, ...$args); + } + + function if_admin($callback, ...$args) { + return $this->_if_condition(is_admin(), $callback, ...$args); + } + + function if_dev($callback, ...$args) { + return $this->_if_condition(is_dev(), $callback, ...$args); + } + + function if_then_else($cond, $cb1, $cb2) { + return $cond ? $this->_return_callback($cb1) : $this->_return_callback($cb2); + } + + function csrf($key): string { + return csrf_get($key); + } + + protected function _if_condition($condition, $callback, ...$args) { + if (is_string($condition) || $condition instanceof Stringable) + $condition = (string)$condition !== ''; + if ($condition) + return $this->_return_callback($callback, $args); + return ''; + } + + protected function _return_callback($callback, $args = []) { + if (is_callable($callback)) + return call_user_func_array($callback, $args); + else if (is_string($callback)) + return $callback; + } + + function for_each(array $iterable, callable $callback) { + $html = ''; + foreach ($iterable as $k => $v) + $html .= call_user_func($callback, $v, $k); + return $html; + } + + function lang(...$args): string { + return htmlescape($this->langRaw(...$args)); + } + + function langRaw(string $key, ...$args) { + $val = lang($key); + return empty($args) ? $val : sprintf($val, ...$args); + } + +} + + +enum SkinStringModificationType { + case RAW; + case URL; + case HTML; + case JSON; + case ADDSLASHES; +} + +class SkinString implements Stringable { + protected SkinStringModificationType $modType; + + function __construct(protected string $string) {} + function setModType(SkinStringModificationType $modType) { $this->modType = $modType; } + + function __toString(): string { + return match ($this->modType) { + SkinStringModificationType::HTML => htmlescape($this->string), + SkinStringModificationType::URL => urlencode($this->string), + SkinStringModificationType::JSON => json_encode($this->string, JSON_UNESCAPED_UNICODE), + SkinStringModificationType::ADDSLASHES => addslashes($this->string), + default => $this->string, + }; + } +} diff --git a/engine/strings.php b/engine/strings.php new file mode 100644 index 0000000..2d9b1d3 --- /dev/null +++ b/engine/strings.php @@ -0,0 +1,138 @@ +data[$offset]); + } + + function offsetUnset(mixed $offset): void { + throw new RuntimeException('Not implemented'); + } + + function offsetGet(mixed $offset): mixed { + if (!isset($this->data[$offset])) { + logError(__METHOD__.': '.$offset.' not found'); + return '{'.$offset.'}'; + } + return $this->data[$offset]; + } + + function get(string $key, mixed ...$sprintf_args): string|array { + $val = $this[$key]; + if (!empty($sprintf_args)) { + array_unshift($sprintf_args, $val); + return call_user_func_array('sprintf', $sprintf_args); + } else { + return $val; + } + } + + function num(string $key, int $num, array$opts = []) { + $s = $this[$key]; + + $default_opts = [ + 'format' => true, + 'format_delim' => ' ', + 'lang' => 'ru', + ]; + $opts = array_merge($default_opts, $opts); + + switch ($opts['lang']) { + case 'ru': + $n = $num % 100; + if ($n > 19) + $n %= 10; + + if ($n == 1) { + $word = 0; + } elseif ($n >= 2 && $n <= 4) { + $word = 1; + } elseif ($num == 0 && count($s) == 4) { + $word = 3; + } else { + $word = 2; + } + break; + + default: + if ($num == 0 && count($s) == 4) { + $word = 3; + } else { + $word = $num == 1 ? 0 : 1; + } + break; + } + + // if zero + if ($word == 3) { + return $s[3]; + } + + if (is_callable($opts['format'])) { + $num = $opts['format']($num); + } else if ($opts['format'] === true) { + $num = formatNumber($num, $opts['format_delim']); + } + + return sprintf($s[$word], $num); + } +} + +class Strings extends StringsBase { + private static ?Strings $instance = null; + protected array $loadedPackages = []; + + private function __construct() {} + protected function __clone() {} + + public static function getInstance(): self { + if (is_null(self::$instance)) + self::$instance = new self(); + return self::$instance; + } + + function load(string ...$pkgs): array { + $keys = []; + foreach ($pkgs as $name) { + $raw = yaml_parse_file(APP_ROOT.'/strings/'.$name.'.yaml'); + $this->data = array_merge($this->data, $raw); + $keys = array_merge($keys, array_keys($raw)); + $this->loadedPackages[$name] = true; + } + return $keys; + } + + function flex(string $s, DeclensionCase $case, NameSex $sex, NameType $type): string { + $s = iconv('utf-8', 'cp1251', $s); + $s = vkflex($s, $case->value, $sex->value, 0, $type->value); + return iconv('cp1251', 'utf-8', $s); + } + + function search(string $regexp): array { + return preg_grep($regexp, array_keys($this->data)); + } +} \ No newline at end of file diff --git a/engine/themes.php b/engine/themes.php deleted file mode 100644 index 839377f..0000000 --- a/engine/themes.php +++ /dev/null @@ -1,38 +0,0 @@ - [ - 'bg' => 0x222222, - // 'alpha' => 0x303132, - 'alpha' => 0x222222, - ], - 'light' => [ - 'bg' => 0xffffff, - // 'alpha' => 0xf2f2f2, - 'alpha' => 0xffffff, - ] - ]; - - public static function getThemes(): array { - return array_keys(self::$Themes); - } - - public static function themeExists(string $name): bool { - return array_key_exists($name, self::$Themes); - } - - public static function getThemeAlphaColorAsRGB(string $name): array { - $color = self::$Themes[$name]['alpha']; - $r = ($color >> 16) & 0xff; - $g = ($color >> 8) & 0xff; - $b = $color & 0xff; - return [$r, $g, $b]; - } - - public static function getUserTheme(): string { - return ($_COOKIE['theme'] ?? 'auto'); - } - -} \ No newline at end of file diff --git a/functions.php b/functions.php index 9f62f32..84d3e4b 100644 --- a/functions.php +++ b/functions.php @@ -1,5 +1,32 @@ ($orig_domain_len = strlen($config['domain']))) { + $sub = substr($host, 0, -$orig_domain_len-1); + if (in_array($sub, $config['dev_domains'])) { + $config['is_dev'] = true; + } else if (!in_array($sub, $config['subdomains'])) { + throw new RuntimeException('invalid subdomain '.$sub); + } + } + + if (is_cli() && str_ends_with(dirname(__DIR__), 'www-dev')) + $config['is_dev'] = true; +} + function htmlescape(string|array $s): string|array { if (is_array($s)) { foreach ($s as $k => $v) { @@ -247,52 +274,31 @@ function salt_password(string $pwd): string { return hash('sha256', "{$pwd}|{$config['password_salt']}"); } -function exectime(?string $format = null) { +function exectime(?string $format = null): string|float { $time = round(microtime(true) - START_TIME, 4); if (!is_null($format)) $time = sprintf($format, $time); return $time; } -function fullURL(string $url): string { - global $config; - return 'https://'.$config['domain'].$url; +function formatNumber(int|float $num, string $delim = ' ', bool $short = false): string { + if ($short) { + if ($num >= 1000000) + return floor($num / 1000000).'m'; + if ($num >= 1000) + return floor($num / 1000).'k'; + } + return number_format($num, 0, '.', $delim); } -function getDb(): SQLiteConnection|MySQLConnection|null { - global $config; - static $link = null; - if (!is_null($link)) - return $link; - - switch ($config['db']['type']) { - case 'mysql': - $link = new MySQLConnection( - $config['db']['host'], - $config['db']['user'], - $config['db']['password'], - $config['db']['database']); - if (!$link->connect()) { - if (PHP_SAPI != 'cli') { - header('HTTP/1.1 503 Service Temporarily Unavailable'); - header('Status: 503 Service Temporarily Unavailable'); - header('Retry-After: 300'); - die('database connection failed'); - } else { - fwrite(STDERR, 'database connection failed'); - exit(1); - } - } - break; - - case 'sqlite': - $link = new SQLiteConnection($config['db']['path']); - break; +function lang() { + global $__lang; + return call_user_func_array([$__lang, 'get'], func_get_args()); +} - default: - logError('invalid database type'); - break; - } +function is_dev(): bool { global $config; return $config['is_dev']; } +function is_cli(): bool { return PHP_SAPI == 'cli'; }; +function is_retina(): bool { return isset($_COOKIE['is_retina']) && $_COOKIE['is_retina']; } - return $link; -} +function jsonEncode($obj): ?string { return json_encode($obj, JSON_UNESCAPED_UNICODE) ?: null; } +function jsonDecode($json) { return json_decode($json, true); } diff --git a/handler/AdminHandler.php b/handler/AdminHandler.php new file mode 100644 index 0000000..f90fc42 --- /dev/null +++ b/handler/AdminHandler.php @@ -0,0 +1,470 @@ + $_FILES['files']['name'][$i], + 'type' => $_FILES['files']['type'][$i], + 'tmp_name' => $_FILES['files']['tmp_name'][$i], + 'error' => $_FILES['files']['error'][$i], + 'size' => $_FILES['files']['size'][$i], + ]; + } + + if (count($files) > 1) { + $note = ''; + $custom_name = ''; + } + + foreach ($files as $f) { + if ($f['error']) + redirect('/uploads/?error='.urlencode('error code '.$f['error'])); + + if (!$f['size']) + redirect('/uploads/?error='.urlencode('received empty file')); + + $ext = extension($f['name']); + if (!uploads::isExtensionAllowed($ext)) + redirect('/uploads/?error='.urlencode('extension not allowed')); + + $upload_id = uploads::add( + $f['tmp_name'], + $custom_name ?: $f['name'], + $note); + + if (!$upload_id) + redirect('/uploads/?error='.urlencode('failed to create upload')); + } + + redirect('/uploads/'); + } + + function GET_upload_delete() { + list($id) = input('i:id'); + $upload = uploads::get($id); + if (!$upload) + redirect('/uploads/?error='.urlencode('upload not found')); + csrf_check('delupl'.$id); + uploads::delete($id); + redirect('/uploads/'); + } + + function POST_upload_edit_note() { + list($id, $note) = input('i:id, note'); + + $upload = uploads::get($id); + if (!$upload) + redirect('/uploads/?error='.urlencode('upload not found')); + + csrf_check('editupl'.$id); + + $upload->setNote($note); + redirect('/uploads/'); + } + + function POST_ajax_md_preview() { + list($md, $title, $use_image_previews) = input('md, title, b:use_image_previews'); + $html = markup::markdownToHtml($md, $use_image_previews); + $ctx = new SkinContext('\\skin\\admin'); + $html = $ctx->markdownPreview( + unsafe_html: $html, + title: $title + ); + ajax_ok(['html' => $html]); + } + + function GET_page_add() { + list($name) = input('short_name'); + $page = pages::getByName($name); + if ($page) + not_found(); + return $this->_get_pageAdd($name); + } + + function POST_page_add() { + csrf_check('addpage'); + + list($name, $text, $title) = input('short_name, text, title'); + $page = pages::getByName($name); + if ($page) + not_found(); + + $error_code = null; + + if (!$title) { + $error_code = 'no_title'; + } else if (!$text) { + $error_code = 'no_text'; + } + + if ($error_code) { + return $this->_get_pageAdd( + name: $name, + title: $title, + text: $text, + error_code: $error_code + ); + } + + if (!pages::add([ + 'short_name' => $name, + 'title' => $title, + 'md' => $text + ])) { + return $this->_get_pageAdd( + name: $name, + title: $title, + text: $text, + error_code: 'db_err' + ); + } + + $page = pages::getByName($name); + redirect($page->getUrl()); + } + + function GET_post_add() { + return $this->_get_postAdd(); + } + + function POST_post_add() { + csrf_check('addpost'); + + list($text, $title, $tags, $visible, $short_name) + = input('text, title, tags, b:visible, short_name'); + $tags = tags::splitString($tags); + + $error_code = null; + if (!$title) { + $error_code = 'no_title'; + } else if (!$text) { + $error_code = 'no_text'; + } else if (empty($tags)) { + $error_code = 'no_tags'; + } else if (empty($short_name)) { + $error_code = 'no_short_name'; + } + + if ($error_code) + return $this->_get_postAdd( + title: $title, + text: $text, + tags: $tags, + short_name: $short_name, + error_code: $error_code + ); + + $id = posts::add([ + 'title' => $title, + 'md' => $text, + 'visible' => (int)$visible, + 'short_name' => $short_name, + ]); + + if (!$id) + $this->_get_postAdd( + title: $title, + text: $text, + tags: $tags, + short_name: $short_name, + error_code: 'db_err' + ); + + // set tags + $post = posts::get($id); + $tag_ids = array_values(tags::getTags($tags)); + $post->setTagIds($tag_ids); + + redirect($post->getUrl()); + } + + function GET_auto_delete() { + list($name) = input('short_name'); + + $post = posts::getByName($name); + if ($post) { + csrf_check('delpost'.$post->id); + posts::delete($post); + redirect('/'); + } + + $page = pages::getByName($name); + if ($page) { + csrf_check('delpage'.$page->shortName); + pages::delete($page); + redirect('/'); + } + + not_found(); + } + + function GET_auto_edit() { + list($short_name, $saved) = input('short_name, b:saved'); + + $post = posts::getByName($short_name); + if ($post) { + $tags = $post->getTags(); + return $this->_get_postEdit($post, + title: $post->title, + text: $post->md, + tags: $post->getTags(), + visible: $post->visible, + toc: $post->toc, + short_name: $post->shortName, + saved: $saved, + ); + } + + $page = pages::getByName($short_name); + if ($page) { + return $this->_get_pageEdit($page, + title: $page->title, + text: $page->md, + saved: $saved, + visible: $page->visible, + ); + } + + not_found(); + } + + function POST_auto_edit() { + list($short_name) = input('short_name'); + + $post = posts::getByName($short_name); + if ($post) { + csrf_check('editpost'.$post->id); + + list($text, $title, $tags, $visible, $toc, $short_name) + = input('text, title, tags, b:visible, b:toc, new_short_name'); + + $tags = tags::splitString($tags); + $error_code = null; + + if (!$title) { + $error_code = 'no_title'; + } else if (!$text) { + $error_code = 'no_text'; + } else if (empty($tags)) { + $error_code = 'no_tags'; + } else if (empty($short_name)) { + $error_code = 'no_short_name'; + } + + if ($error_code) + $this->_get_postEdit($post, + title: $title, + text: $text, + tags: $tags, + visible: $visible, + toc: $toc, + short_name: $short_name, + error_code: $error_code + ); + + $post->edit([ + 'title' => $title, + 'md' => $text, + 'visible' => (int)$visible, + 'toc' => (int)$toc, + 'short_name' => $short_name + ]); + $tag_ids = array_values(tags::getTags($tags)); + $post->setTagIds($tag_ids); + + redirect($post->getUrl().'edit/?saved=1'); + } + + $page = pages::getByName($short_name); + if ($page) { + csrf_check('editpage'.$page->shortName); + + list($text, $title, $visible, $short_name) + = input('text, title, b:visible, new_short_name'); + + $text = trim($text); + $title = trim($title); + $error_code = null; + + if (!$title) { + $error_code = 'no_title'; + } else if (!$text) { + $error_code = 'no_text'; + } else if (!$short_name) { + $error_code = 'no_short_name'; + } + + if ($error_code) { + return $this->_get_pageEdit($page, + title: $title, + text: $text, + visible: $visible, + error_code: $error_code + ); + } + + $page->edit([ + 'title' => $title, + 'md' => $text, + 'visible' => (int)$visible, + 'short_name' => $short_name, + ]); + + redirect($page->getUrl().'edit/?saved=1'); + } + + not_found(); + } + + protected static function setWidePage() { + set_skin_opts([ + 'full_width' => true, + 'no_footer' => true + ]); + } + + protected function _get_pageAdd( + string $name, + string $title = '', + string $text = '', + ?string $error_code = null + ) { + add_skin_strings_re('/^(err_)?pages_/'); + set_title(lang('pages_create_title', $name)); + static::setWidePage(); + render('admin/pageForm', + short_name: $name, + title: $title, + text: $text, + error_code: $error_code); + } + + protected function _get_pageEdit( + Page $page, + string $title = '', + string $text = '', + bool $saved = false, + bool $visible = false, + ?string $error_code = null + ) { + add_skin_strings_re('/^(err_)?pages_/'); + set_title(lang('pages_page_edit_title', $page->shortName.'.html')); + static::setWidePage(); + render('admin/pageForm', + is_edit: true, + short_name: $page->shortName, + title: $title, + text: $text, + visible: $visible, + saved: $saved, + error_code: $error_code); + } + + protected function _get_postEdit( + Post $post, + string $title = '', + string $text = '', + ?array $tags = null, + bool $visible = false, + bool $toc = false, + string $short_name = '', + ?string $error_code = null, + bool $saved = false, + ) { + add_skin_strings_re('/^(err_)?blog_/'); + set_title(lang('blog_post_edit_title', $post->title)); + static::setWidePage(); + render('admin/postForm', + is_edit: true, + post_id: $post->id, + post_url: $post->getUrl(), + title: $title, + text: $text, + tags: $tags ? implode(', ', $tags) : '', + visible: $visible, + toc: $toc, + saved: $saved, + short_name: $short_name, + error_code: $error_code + ); + } + + protected function _get_postAdd( + string $title = '', + string $text = '', + ?array $tags = null, + string $short_name = '', + ?string $error_code = null + ) { + add_skin_strings_re('/^(err_)?blog_/'); + set_title('$blog_write'); + static::setWidePage(); + render('admin/postForm', + title: $title, + text: $text, + tags: $tags ? implode(', ', $tags) : '', + short_name: $short_name, + error_code: $error_code); + } + +} \ No newline at end of file diff --git a/handler/Auto.php b/handler/Auto.php deleted file mode 100644 index 0656c44..0000000 --- a/handler/Auto.php +++ /dev/null @@ -1,110 +0,0 @@ -input('name'); - if ($name == 'coreboot-mba51-flashing') - return new RedirectResponse('/coreboot-mba52-flashing/', 301); - - if (is_numeric($name)) { - $post = posts::get((int)$name); - } else { - $post = posts::getPostByName($name); - } - if ($post) - return $this->getPost($post); - - $tag = posts::getTag($name); - if ($tag) - return $this->getTag($tag); - - $page = pages::getPageByName($name); - if ($page) - return $this->getPage($page); - - if (admin::isAdmin()) { - $this->skin->title = $name; - return $this->skin->renderPage('admin/pageNew', - short_name: $name); - } - - throw new NotFoundException(); - } - - public function getPost(Post $post): Response { - global $config; - - if (!$post->visible && !admin::isAdmin()) - throw new NotFoundException(); - - $tags = $post->getTags(); - - $s = $this->skin; - $s->meta[] = ['property' => 'og:title', 'content' => $post->title]; - $s->meta[] = ['property' => 'og:url', 'content' => fullURL($post->getUrl())]; - if (($img = $post->getFirstImage()) !== null) - $s->meta[] = ['property' => 'og:image', 'content' => $img->getDirectUrl()]; - $s->meta[] = [ - 'name' => 'description', - 'property' => 'og:description', - 'content' => $post->getDescriptionPreview(155) - ]; - - $s->title = $post->title; - - if ($post->toc) - $s->setOptions(['wide' => true]); - - return $s->renderPage('main/post', - title: $post->title, - id: $post->id, - unsafe_html: $post->getHtml($this->isRetina(), \themes::getUserTheme()), - unsafe_toc_html: $post->getToc(), - date: $post->getFullDate(), - tags: $tags, - visible: $post->visible, - url: $post->getUrl(), - email: $config['admin_email'], - urlencoded_reply_subject: 'Re: '.$post->title); - } - - public function getTag(Tag $tag): Response { - $tag = posts::getTag($tag); - if (!admin::isAdmin() && !$tag->visiblePostsCount) - throw new NotFoundException(); - - $count = posts::getPostsCountByTagId($tag->id, admin::isAdmin()); - $posts = $count ? posts::getPostsByTagId($tag->id, admin::isAdmin()) : []; - - $this->skin->title = '#'.$tag->tag; - return $this->skin->renderPage('main/tag', - count: $count, - posts: $posts, - tag: $tag->tag); - } - - public function getPage(\Page $page): Response { - if (!admin::isAdmin() && !$page->visible) - throw new NotFoundException(); - - $this->skin->title = $page ? $page->title : '???'; - return $this->skin->renderPage('main/page', - unsafe_html: $page->getHtml($this->isRetina(), \themes::getUserTheme()), - page_url: $page->getUrl(), - short_name: $page->shortName); - } - -} \ No newline at end of file diff --git a/handler/Contacts.php b/handler/Contacts.php deleted file mode 100644 index c60479d..0000000 --- a/handler/Contacts.php +++ /dev/null @@ -1,16 +0,0 @@ -skin->title = $this->lang['contacts']; - return $this->skin->renderPage('main/contacts', - email: $config['admin_email']); - } - -} \ No newline at end of file diff --git a/handler/Index.php b/handler/Index.php deleted file mode 100644 index c852511..0000000 --- a/handler/Index.php +++ /dev/null @@ -1,20 +0,0 @@ -skin->title = "ch1p's Blog"; - $this->skin->setOptions(['dynlogo_enabled' => false]); - return $this->skin->renderPage('main/index', - posts: $posts, - tags: $tags); - } -} \ No newline at end of file diff --git a/handler/MainHandler.php b/handler/MainHandler.php new file mode 100644 index 0000000..889cb48 --- /dev/null +++ b/handler/MainHandler.php @@ -0,0 +1,147 @@ + false]); + render('main/index', + posts: $posts, + tags: $tags); + } + + function GET_projects() { + redirect('/projects/'); + } + + function GET_contacts() { + global $config; + set_title(lang('contacts')); + render('main/contacts', + email: $config['admin_email']); + } + + function GET_auto() { + list($name) = input('name'); + if ($name == 'coreboot-mba51-flashing') + redirect('/coreboot-mba52-flashing/'); + + if (is_numeric($name)) { + $post = posts::get((int)$name); + } else { + $post = posts::getByName($name); + } + if ($post) + return $this->renderPost($post); + + $tag = tags::get($name); + if ($tag) + return $this->renderTag($tag); + + $page = pages::getByName($name); + if ($page) + return $this->renderPage($page); + + if (is_admin()) { + set_title($name); + render('admin/pageNew', + short_name: $name); + } + + not_found(); + } + + protected function renderPost(Post $post) { + global $config; + + if (!$post->visible && !is_admin()) + not_found(); + + $tags = $post->getTags(); + + add_meta( + ['property' => 'og:title', 'content' => $post->title], + ['property' => 'og:url', 'content' => $config['domain'].$post->getUrl()] + ); + if (($img = $post->getFirstImage()) !== null) + add_meta(['property' => 'og:image', 'content' => $img->getDirectUrl()]); + + add_meta([ + 'name' => 'description', + 'property' => 'og:description', + 'content' => $post->getDescriptionPreview(155) + ]); + + set_title($post->title); + + if ($post->toc) + set_skin_opts(['wide' => true]); + + render('main/post', + title: $post->title, + id: $post->id, + unsafe_html: $post->getHtml(is_retina(), getUserTheme()), + unsafe_toc_html: $post->getToc(), + date: $post->getFullDate(), + tags: $tags, + visible: $post->visible, + url: $post->getUrl(), + email: $config['admin_email'], + urlencoded_reply_subject: 'Re: '.$post->title); + } + + protected function renderTag(Tag $tag) { + $tag = tags::get($tag); + if (!is_admin() && !$tag->visiblePostsCount) + not_found(); + + $count = posts::getCountByTagId($tag->id, is_admin()); + $posts = $count ? posts::getPostsByTagId($tag->id, is_admin()) : []; + + set_title('#'.$tag->tag); + render('main/tag', + count: $count, + posts: $posts, + tag: $tag->tag); + } + + protected function renderPage(Page $page) { + if (!is_admin() && !$page->visible) + not_found(); + + set_title($page ? $page->title : '???'); + render('main/page', + unsafe_html: $page->getHtml(is_retina(), getUserTheme()), + page_url: $page->getUrl(), + short_name: $page->shortName); + } + + function GET_rss() { + global $config; + + $items = array_map(fn(Post $post) => [ + 'title' => $post->title, + 'link' => $post->getUrl(), + 'pub_date' => date(DATE_RSS, $post->ts), + 'description' => $post->getDescriptionPreview(500), + ], posts::getList(0, 20)); + + $ctx = new SkinContext('\\skin\\rss'); + $body = $ctx->atom( + title: lang('site_title'), + link: 'https://'.$config['domain'], + rss_link: 'https://'.$config['domain'].'/feed.rss', + items: $items); + + header('Content-Type: application/rss+xml; charset=utf-8'); + echo $body; + exit; + } + +} \ No newline at end of file diff --git a/handler/ProjectsHtml.php b/handler/ProjectsHtml.php deleted file mode 100644 index 0c1dcbb..0000000 --- a/handler/ProjectsHtml.php +++ /dev/null @@ -1,11 +0,0 @@ - [ - 'title' => $post->title, - 'link' => $post->getUrl(), - 'pub_date' => date(DATE_RSS, $post->ts), - 'description' => $post->getDescriptionPreview(500), - ], posts::getPosts(0, 20)); - - $ctx = new SkinContext('\\skin\\rss'); - $body = $ctx->atom( - title: ($this->lang)('site_title'), - link: 'https://'.$config['domain'], - rss_link: 'https://'.$config['domain'].'/feed.rss', - items: $items); - - $response = new Response(200, $body); - $response->addHeader('Content-Type: application/rss+xml; charset=utf-8'); - return $response; - } - -} \ No newline at end of file diff --git a/handler/admin/AdminRequestHandler.php b/handler/admin/AdminRequestHandler.php deleted file mode 100644 index 5a6bd12..0000000 --- a/handler/admin/AdminRequestHandler.php +++ /dev/null @@ -1,20 +0,0 @@ -skin->static[] = 'css/admin.css'; - $this->skin->static[] = 'js/admin.js'; - - if (!($this instanceof Login) && !admin::isAdmin()) - throw new \ForbiddenException('looks like you are not admin'); - - return null; - } - -} \ No newline at end of file diff --git a/handler/admin/AutoAddOrEdit.php b/handler/admin/AutoAddOrEdit.php deleted file mode 100644 index 1627642..0000000 --- a/handler/admin/AutoAddOrEdit.php +++ /dev/null @@ -1,99 +0,0 @@ -skin->setOptions([ - 'full_width' => true, - 'no_footer' => true - ]); - return parent::beforeDispatch(); - } - - protected function _get_postAdd( - string $title = '', - string $text = '', - ?array $tags = null, - string $short_name = '', - ?string $error_code = null - ): Response { - $this->skin->addLangKeys($this->lang->search('/^(err_)?blog_/')); - $this->skin->title = $this->lang['blog_write']; - return $this->skin->renderPage('admin/postForm', - title: $title, - text: $text, - tags: $tags ? implode(', ', $tags) : '', - short_name: $short_name, - error_code: $error_code); - } - - protected function _get_postEdit( - Post $post, - string $title = '', - string $text = '', - ?array $tags = null, - bool $visible = false, - bool $toc = false, - string $short_name = '', - ?string $error_code = null, - bool $saved = false, - ): Response { - $this->skin->addLangKeys($this->lang->search('/^(err_)?blog_/')); - $this->skin->title = ($this->lang)('blog_post_edit_title', $post->title); - return $this->skin->renderPage('admin/postForm', - is_edit: true, - post_id: $post->id, - post_url: $post->getUrl(), - title: $title, - text: $text, - tags: $tags ? implode(', ', $tags) : '', - visible: $visible, - toc: $toc, - saved: $saved, - short_name: $short_name, - error_code: $error_code - ); - } - - protected function _get_pageAdd( - string $name, - string $title = '', - string $text = '', - ?string $error_code = null - ): Response { - $this->skin->addLangKeys($this->lang->search('/^(err_)?pages_/')); - $this->skin->title = ($this->lang)('pages_create_title', $name); - return $this->skin->renderPage('admin/pageForm', - short_name: $name, - title: $title, - text: $text, - error_code: $error_code); - } - - protected function _get_pageEdit( - Page $page, - string $title = '', - string $text = '', - bool $saved = false, - bool $visible = false, - ?string $error_code = null - ): Response { - $this->skin->addLangKeys($this->lang->search('/^(err_)?pages_/')); - $this->skin->title = ($this->lang)('pages_page_edit_title', $page->shortName.'.html'); - return $this->skin->renderPage('admin/pageForm', - is_edit: true, - short_name: $page->shortName, - title: $title, - text: $text, - visible: $visible, - saved: $saved, - error_code: $error_code); - } - -} \ No newline at end of file diff --git a/handler/admin/AutoDelete.php b/handler/admin/AutoDelete.php deleted file mode 100644 index 80c8eef..0000000 --- a/handler/admin/AutoDelete.php +++ /dev/null @@ -1,34 +0,0 @@ -input('short_name'); - - $post = posts::getPostByName($name); - if ($post) { - csrf::check('delpost'.$post->id); - posts::delete($post); - return new RedirectResponse('/'); - } - - $page = pages::getPageByName($name); - if ($page) { - csrf::check('delpage'.$page->shortName); - pages::delete($page); - return new RedirectResponse('/'); - } - - throw new NotFoundException(); - } - -} \ No newline at end of file diff --git a/handler/admin/AutoEdit.php b/handler/admin/AutoEdit.php deleted file mode 100644 index ba6a7d8..0000000 --- a/handler/admin/AutoEdit.php +++ /dev/null @@ -1,130 +0,0 @@ -input('short_name, b:saved'); - - $post = posts::getPostByName($short_name); - if ($post) { - $tags = $post->getTags(); - return $this->_get_postEdit($post, - title: $post->title, - text: $post->md, - tags: $post->getTags(), - visible: $post->visible, - toc: $post->toc, - short_name: $post->shortName, - saved: $saved, - ); - } - - $page = pages::getPageByName($short_name); - if ($page) { - return $this->_get_pageEdit($page, - title: $page->title, - text: $page->md, - saved: $saved, - visible: $page->visible, - ); - } - - throw new \NotFoundException(); - } - - public function post(): Response { - list($short_name) = $this->input('short_name'); - - $post = posts::getPostByName($short_name); - if ($post) { - csrf::check('editpost'.$post->id); - - list($text, $title, $tags, $visible, $toc, $short_name) - = $this->input('text, title, tags, b:visible, b:toc, new_short_name'); - - $tags = posts::splitStringToTags($tags); - $error_code = null; - - if (!$title) { - $error_code = 'no_title'; - } else if (!$text) { - $error_code = 'no_text'; - } else if (empty($tags)) { - $error_code = 'no_tags'; - } else if (empty($short_name)) { - $error_code = 'no_short_name'; - } - - if ($error_code) - $this->_get_postEdit($post, - title: $title, - text: $text, - tags: $tags, - visible: $visible, - toc: $toc, - short_name: $short_name, - error_code: $error_code - ); - - $post->edit([ - 'title' => $title, - 'md' => $text, - 'visible' => (int)$visible, - 'toc' => (int)$toc, - 'short_name' => $short_name - ]); - $tag_ids = posts::getTagIds($tags); - $post->setTagIds($tag_ids); - - return new \RedirectResponse($post->getUrl().'edit/?saved=1'); - } - - $page = pages::getPageByName($short_name); - if ($page) { - csrf::check('editpage'.$page->shortName); - - list($text, $title, $visible, $short_name) - = $this->input('text, title, b:visible, new_short_name'); - - $text = trim($text); - $title = trim($title); - $error_code = null; - - if (!$title) { - $error_code = 'no_title'; - } else if (!$text) { - $error_code = 'no_text'; - } else if (!$short_name) { - $error_code = 'no_short_name'; - } - - if ($error_code) { - return $this->_get_pageEdit($page, - title: $title, - text: $text, - visible: $visible, - error_code: $error_code - ); - } - - $page->edit([ - 'title' => $title, - 'md' => $text, - 'visible' => (int)$visible, - 'short_name' => $short_name, - ]); - - return new \RedirectResponse($page->getUrl().'edit/?saved=1'); - } - - throw new \NotFoundException(); - } - -} \ No newline at end of file diff --git a/handler/admin/Index.php b/handler/admin/Index.php deleted file mode 100644 index e829913..0000000 --- a/handler/admin/Index.php +++ /dev/null @@ -1,13 +0,0 @@ -skin->renderPage('admin/index'); - } - -} \ No newline at end of file diff --git a/handler/admin/Login.php b/handler/admin/Login.php deleted file mode 100644 index cade137..0000000 --- a/handler/admin/Login.php +++ /dev/null @@ -1,31 +0,0 @@ -skin->renderPage('admin/login'); - } - - public function post(): Response { - csrf::check('adminlogin'); - $password = $_POST['password'] ?? ''; - $valid = admin::checkPassword($password); - if ($valid) { - admin::logAuth(); - admin::setCookie(); - return new RedirectResponse('/admin/'); - } - throw new UnauthorizedException('nice try'); - } - -} \ No newline at end of file diff --git a/handler/admin/Logout.php b/handler/admin/Logout.php deleted file mode 100644 index bb11e43..0000000 --- a/handler/admin/Logout.php +++ /dev/null @@ -1,17 +0,0 @@ -input('md, title, b:use_image_previews'); - - $html = \markup::markdownToHtml($md, $use_image_previews); - - $ctx = new \SkinContext('\\skin\\admin'); - $html = $ctx->markdownPreview( - unsafe_html: $html, - title: $title - ); - return new \AjaxOkResponse(['html' => $html]); - } - -} \ No newline at end of file diff --git a/handler/admin/PageAdd.php b/handler/admin/PageAdd.php deleted file mode 100644 index 42a9911..0000000 --- a/handler/admin/PageAdd.php +++ /dev/null @@ -1,66 +0,0 @@ -input('short_name'); - $page = pages::getPageByName($name); - if ($page) - throw new NotFoundException(); - - return $this->_get_pageAdd($name); - } - - public function post(): Response { - csrf::check('addpage'); - - list($name) = $this->input('short_name'); - $page = pages::getPageByName($name); - if ($page) - throw new NotFoundException(); - - $text = trim($_POST['text'] ?? ''); - $title = trim($_POST['title'] ?? ''); - $error_code = null; - - if (!$title) { - $error_code = 'no_title'; - } else if (!$text) { - $error_code = 'no_text'; - } - - if ($error_code) { - return $this->_get_pageAdd( - name: $name, - title: $title, - text: $text, - error_code: $error_code - ); - } - - if (!pages::add([ - 'short_name' => $name, - 'title' => $title, - 'md' => $text - ])) { - return $this->_get_pageAdd( - name: $name, - title: $title, - text: $text, - error_code: 'db_err' - ); - } - - $page = pages::getPageByName($name); - return new RedirectResponse($page->getUrl()); - } - -} \ No newline at end of file diff --git a/handler/admin/PostAdd.php b/handler/admin/PostAdd.php deleted file mode 100644 index c21a239..0000000 --- a/handler/admin/PostAdd.php +++ /dev/null @@ -1,68 +0,0 @@ -_get_postAdd(); - } - - public function post(): Response { - csrf::check('addpost'); - - list($text, $title, $tags, $visible, $short_name) - = $this->input('text, title, tags, b:visible, short_name'); - $tags = posts::splitStringToTags($tags); - - $error_code = null; - - if (!$title) { - $error_code = 'no_title'; - } else if (!$text) { - $error_code = 'no_text'; - } else if (empty($tags)) { - $error_code = 'no_tags'; - } else if (empty($short_name)) { - $error_code = 'no_short_name'; - } - - if ($error_code) - return $this->_get_postAdd( - text: $text, - title: $title, - tags: $tags, - short_name: $short_name, - error_code: $error_code - ); - - $id = posts::add([ - 'title' => $title, - 'md' => $text, - 'visible' => (int)$visible, - 'short_name' => $short_name, - ]); - - if (!$id) - $this->_get_postAdd( - text: $text, - title: $title, - tags: $tags, - short_name: $short_name, - error_code: 'db_err' - ); - - // set tags - $post = posts::get($id); - $tag_ids = posts::getTagIds($tags); - $post->setTagIds($tag_ids); - - return new RedirectResponse($post->getUrl()); - } - -} \ No newline at end of file diff --git a/handler/admin/UploadDelete.php b/handler/admin/UploadDelete.php deleted file mode 100644 index 26b58b7..0000000 --- a/handler/admin/UploadDelete.php +++ /dev/null @@ -1,25 +0,0 @@ -input('i:id'); - - $upload = \uploads::get($id); - if (!$upload) - return new RedirectResponse('/uploads/?error='.urlencode('upload not found')); - - csrf::check('delupl'.$id); - - \uploads::delete($id); - - return new RedirectResponse('/uploads/'); - } - -} \ No newline at end of file diff --git a/handler/admin/UploadEditNote.php b/handler/admin/UploadEditNote.php deleted file mode 100644 index e7cdbb2..0000000 --- a/handler/admin/UploadEditNote.php +++ /dev/null @@ -1,25 +0,0 @@ -input('i:id'); - - $upload = \uploads::get($id); - if (!$upload) - return new \RedirectResponse('/uploads/?error='.urlencode('upload not found')); - - csrf::check('editupl'.$id); - - $note = $_POST['note'] ?? ''; - $upload->setNote($note); - - return new \RedirectResponse('/uploads/'); - } - -} \ No newline at end of file diff --git a/handler/admin/Uploads.php b/handler/admin/Uploads.php deleted file mode 100644 index 0cbb2f6..0000000 --- a/handler/admin/Uploads.php +++ /dev/null @@ -1,73 +0,0 @@ -input('error'); - $uploads = \uploads::getAll(); - - $this->skin->title = ($this->lang)('blog_upload'); - return $this->skin->renderPage('admin/uploads', - error: $error, - uploads: $uploads); - } - - public function post(): Response { - csrf::check('addupl'); - - list($custom_name, $note) = $this->input('name, note'); - - if (!isset($_FILES['files'])) - return new RedirectResponse('/uploads/?error='.urlencode('no file')); - - $files = []; - for ($i = 0; $i < count($_FILES['files']['name']); $i++) { - $files[] = [ - 'name' => $_FILES['files']['name'][$i], - 'type' => $_FILES['files']['type'][$i], - 'tmp_name' => $_FILES['files']['tmp_name'][$i], - 'error' => $_FILES['files']['error'][$i], - 'size' => $_FILES['files']['size'][$i], - ]; - } - - if (count($files) > 1) { - $note = ''; - $custom_name = ''; - } - - foreach ($files as $f) { - if ($f['error']) - return new RedirectResponse('/uploads/?error='.urlencode('error code '.$f['error'])); - - if (!$f['size']) - return new RedirectResponse('/uploads/?error='.urlencode('received empty file')); - - $ext = extension($f['name']); - if (!\uploads::isExtensionAllowed($ext)) - return new RedirectResponse('/uploads/?error='.urlencode('extension not allowed')); - - $upload_id = \uploads::add( - $f['tmp_name'], - $custom_name ?: $f['name'], - $note); - - if (!$upload_id) - return new RedirectResponse('/uploads/?error='.urlencode('failed to create upload')); - } - - return new RedirectResponse('/uploads/'); - } - -} \ No newline at end of file diff --git a/htdocs/index.php b/htdocs/index.php index 150b14a..397696f 100644 --- a/htdocs/index.php +++ b/htdocs/index.php @@ -2,28 +2,5 @@ require_once __DIR__.'/../init.php'; -$r = (new Router()) - // route handler input - // ----- ------- ----- - ->add('/', 'index') - ->add('contacts/', 'contacts') - ->add('projects.html', 'projects') - ->add('blog/(\d+)/', 'post_id id=$(1)') - ->add('([a-z0-9-]+)/', 'auto name=$(1)') - - ->add('feed.rss', 'RSS') - ->add('rss/', 'RSS') - - ->add('admin/', 'admin/index') - ->add('admin/{login,logout,log}/', 'admin/${1}') - - ->add('([a-z0-9-]+)/{delete,edit}/', 'admin/auto_${1} short_name=$(1)') - ->add('([a-z0-9-]+)/create/', 'admin/page_add short_name=$(1)') - ->add('write/', 'admin/post_add') - ->add('admin/markdown-preview.ajax', 'admin/markdown_preview') - - ->add('uploads/', 'admin/uploads') - ->add('uploads/{edit_note,delete}/(\d+)/','admin/upload_${1} id=$(1)') -; - -(new RequestDispatcher($r))->dispatch(); \ No newline at end of file +router_init(); +dispatch_request(); diff --git a/htdocs/js.php b/htdocs/js.php index c9939fe..57d847f 100644 --- a/htdocs/js.php +++ b/htdocs/js.php @@ -1,11 +1,10 @@ ['pipe', 'w'], // stderr ]; -$process = proc_open($cmd, $descriptorspec, $pipes, ROOT); +$process = proc_open($cmd, $descriptorspec, $pipes, APP_ROOT); if (!is_resource($process)) { http_response_code(500); logError('could not open sassc process'); diff --git a/init.php b/init.php index 6d9f5f0..b139624 100644 --- a/init.php +++ b/init.php @@ -2,68 +2,100 @@ error_reporting(E_ALL); ini_set('display_errors', 1); +ini_set('assert.exception', 1); date_default_timezone_set('Europe/Moscow'); mb_internal_encoding('UTF-8'); mb_regex_encoding('UTF-8'); -define('ROOT', __DIR__); +const APP_ROOT = __DIR__; define('START_TIME', microtime(true)); -set_include_path(get_include_path().PATH_SEPARATOR.ROOT); +set_include_path(get_include_path().PATH_SEPARATOR.APP_ROOT); spl_autoload_register(function($class) { - if (str_ends_with($class, 'Exception')) { - $path = ROOT.'/engine/exceptions/'.$class.'.php'; - } else if (in_array($class, ['MySQLConnection', 'SQLiteConnection', 'CommonDatabase'])) { - $path = ROOT.'/engine/database/'.$class.'.php'; - } else if (str_starts_with($class, 'handler\\')) { - $path = ROOT.'/'.str_replace('\\', '/', $class).'.php'; - } + static $libs = [ + 'lib/tags' => ['Tag', 'tags'], + 'lib/pages' => ['Page', 'pages'], + 'lib/posts' => ['Post', 'posts'], + 'lib/uploads' => ['Upload', 'uploads'], + 'engine/model' => ['model'], + 'engine/skin' => ['SkinContext'], + ]; - if (isset($path)) { - if (!is_file($path)) - return; + if (str_ends_with($class, 'Handler')) { + $path = APP_ROOT.'/handler/'.str_replace('\\', '/', $class).'.php'; } else { - foreach (['engine', 'lib', 'model'] as $dir) { - if (is_file($path = ROOT.'/'.$dir.'/'.$class.'.php')) + foreach ($libs as $lib_file => $class_names) { + if (in_array($class, $class_names)) { + $path = APP_ROOT.'/'.$lib_file.'.php'; break; + } } } + if (!isset($path)) + $path = APP_ROOT.'/lib/'.$class.'.php'; + + if (!is_file($path)) + return; + require_once $path; }); -$config = require_once 'config.php'; -if (file_exists(ROOT.'/config-local.php')) { - $config = array_replace($config, require 'config-local.php'); -} +if (!file_exists(APP_ROOT.'/config.yaml')) + die('Fatal: config.yaml not found'); + +$config = yaml_parse_file(APP_ROOT.'/config.yaml'); +if ($config === false) + die('Fatal: failed to parse config.yaml'); -// turn off errors output on production domains +// i know what i'm doing. do you? +umask($config['umask']); require_once 'functions.php'; +require_once 'engine/mysql.php'; +require_once 'engine/router.php'; +require_once 'engine/request.php'; +require_once 'engine/logging.php'; -if (PHP_SAPI == 'cli') { - $_SERVER['HTTP_HOST'] = $config['domain']; - $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; -} else { - if (array_key_exists('HTTP_X_REAL_IP', $_SERVER)) - $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_REAL_IP']; +try { + if (is_cli()) { + verify_hostname($config['domain']); + $_SERVER['HTTP_HOST'] = $config['domain']; + $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; + } else { + verify_hostname(); + if (array_key_exists('HTTP_X_REAL_IP', $_SERVER)) + $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_REAL_IP']; + + require_once 'engine/strings.php'; + require_once 'engine/skin.php'; + require_once 'lib/admin.php'; + } +} catch (RuntimeException $e) { + die('Fatal error: '.$e->getMessage()); } -if (!$config['is_dev']) { - if (file_exists(ROOT.'/config-static.php')) +$__logger = is_dev() + ? new FileLogger(APP_ROOT.'/log/debug.log') + : new DatabaseLogger(); +$__logger->enable(); + +if (!is_dev()) { + if (file_exists(APP_ROOT.'/config-static.php')) $config['static'] = require_once 'config-static.php'; else die('confic-static.php not found'); -} -if (!$config['is_dev']) { + // turn off errors output on production domains error_reporting(0); ini_set('display_errors', 0); } -logging::setLogFile($config['log_file']); -logging::enable(); +if (!is_cli()) { + $__lang = Strings::getInstance(); + $__lang->load('main'); +} require 'vendor/autoload.php'; diff --git a/lang/en.php b/lang/en.php deleted file mode 100644 index 7d17205..0000000 --- a/lang/en.php +++ /dev/null @@ -1,106 +0,0 @@ - 'ch1p', - 'site_title' => 'ch1p', - 'index_title' => 'Home | ch1p', - - 'posts' => 'posts', - 'all_posts' => 'all posts', - 'blog' => 'blog', - 'contacts' => 'contacts', - 'email' => 'email', - 'projects' => 'projects', - 'unknown_error' => 'Unknown error', - 'error' => 'Error', - 'write' => 'Write', - 'submit' => 'submit', - 'edit' => 'edit', - 'delete' => 'delete', - 'info_saved' => 'Information saved.', - 'toc' => 'Table of Contents', - - // theme switcher - 'theme_auto' => 'auto', - 'theme_dark' => 'dark', - 'theme_light' => 'light', - - // contacts - 'contacts_email' => 'email', - 'contacts_pgp' => 'OpenPGP public key', - 'contacts_tg' => 'telegram', - 'contacts_freenode' => 'freenode', - - // blog - 'blog_tags' => 'tags', - 'blog_latest' => 'Latest posts', - 'blog_no' => 'No posts yet.', - 'blog_view_all' => 'View all', - 'blog_write' => 'Write a post', - 'blog_post_delete_confirmation' => 'Are you sure you want to delete this post?', - 'blog_post_edit_title' => 'Edit post "%s"', - 'blog_post_hidden' => 'Hidden', - 'blog_tag_title' => 'Posts tagged with "%s"', - 'blog_tag_not_found' => 'No posts found.', - 'blog_comments_text' => 'If you have any comments, contact me by email.', - - 'blog_write_form_preview_btn' => 'Preview', - 'blog_write_form_submit_btn' => 'Submit', - 'blog_write_form_title' => 'Title', - 'blog_write_form_text' => 'Text', - 'blog_write_form_preview' => 'Preview', - 'blog_write_form_enter_text' => 'Enter text..', - 'blog_write_form_enter_title' => 'Enter title..', - 'blog_write_form_tags' => 'Tags', - 'blog_write_form_visible' => 'Visible', - 'blog_write_form_toc' => 'ToC', - 'blog_write_form_short_name' => 'Short name', - 'blog_write_form_toggle_wrap' => 'Toggle wrap', - 'blog_write_form_options' => 'Options', - - 'blog_uploads' => 'Uploads', - 'blog_upload' => 'Upload files', - 'blog_upload_delete' => 'Delete', - 'blog_upload_delete_confirmation' => 'Are you sure you want to delete this upload?', - 'blog_upload_show_md' => 'Show md', - 'blog_upload_form_file' => 'File', - 'blog_upload_form_custom_name' => 'Custom name', - 'blog_upload_form_note' => 'Note', - - // blog (errors) - 'err_blog_no_title' => 'Title not specified', - 'err_blog_no_text' => 'Text not specified', - 'err_blog_no_tags' => 'Tags not specified', - 'err_blog_db_err' => 'Database error', - 'err_blog_no_short_name' => 'Short name not specified', - 'err_blog_short_name_exists' => 'This short name already exists', - - // pages - 'pages_create' => 'create new page', - 'pages_edit' => 'edit', - 'pages_delete' => 'delete', - 'pages_create_title' => 'create new page "%s"', - 'pages_page_delete_confirmation' => 'Are you sure you want to delete this page?', - 'pages_page_edit_title' => 'Edit %s', - - 'pages_write_form_submit_btn' => 'Submit', - 'pages_write_form_title' => 'Title', - 'pages_write_form_text' => 'Text', - 'pages_write_form_enter_text' => 'Enter text..', - 'pages_write_form_enter_title' => 'Enter title..', - 'pages_write_form_visible' => 'Visible', - 'pages_write_form_short_name' => 'Short name', - 'pages_write_form_toggle_wrap' => 'Toggle wrap', - 'pages_write_form_options' => 'Options', - - // pages (errors) - 'err_pages_no_title' => 'Title not specified', - 'err_pages_no_text' => 'Text not specified', - 'err_pages_no_id' => 'ID not specified', - 'err_pages_no_short_name' => 'Short name not specified', - 'err_pages_db_err' => 'Database error', - - // admin-switch - 'as_form_password' => 'Password', -]; diff --git a/lib/MyParsedown.php b/lib/MyParsedown.php deleted file mode 100644 index 85ed9c4..0000000 --- a/lib/MyParsedown.php +++ /dev/null @@ -1,218 +0,0 @@ - [ - 'tablespan' => true - ] - ]; - if (!is_null($opts)) { - $parsedown_opts = array_merge($parsedown_opts, $opts); - } - parent::__construct($parsedown_opts); - - $this->InlineTypes['{'][] = 'FileAttach'; - $this->InlineTypes['{'][] = 'Image'; - $this->InlineTypes['{'][] = 'Video'; - $this->inlineMarkerList .= '{'; - } - - protected function inlineFileAttach($excerpt) { - if (preg_match('/^{fileAttach:([\w]{8})}{\/fileAttach}/', $excerpt['text'], $matches)) { - $random_id = $matches[1]; - $upload = uploads::getByRandomId($random_id); - $result = [ - 'extent' => strlen($matches[0]), - 'element' => [ - 'name' => 'span', - 'text' => '', - ], - 'type' => '' - ]; - - if (!$upload) { - return $result; - } - - unset($result['element']['text']); - - $ctx = self::getSkinContext(); - $result['element']['rawHtml'] = $ctx->fileupload($upload->name, $upload->getDirectUrl(), $upload->note, $upload->getSize()); - - return $result; - } - } - - protected function inlineImage($excerpt) { - global $config; - - if (preg_match('/^{image:([\w]{8}),(.*?)}{\/image}/', $excerpt['text'], $matches)) { - $random_id = $matches[1]; - - $opts = [ - 'w' => 'auto', - 'h' => 'auto', - 'align' => 'left', - 'nolabel' => false, - ]; - $inputopts = explode(',', $matches[2]); - - foreach ($inputopts as $opt) { - if ($opt == 'nolabel') - $opts[$opt] = true; - else { - list($k, $v) = explode('=', $opt); - if (!isset($opts[$k])) - continue; - $opts[$k] = $v; - } - } - - $image = uploads::getByRandomId($random_id); - $result = [ - 'extent' => strlen($matches[0]), - 'element' => [ - 'name' => 'span', - 'text' => '', - ], - 'type' => '' - ]; - - if (!$image) { - return $result; - } - - list($w, $h) = $image->getImagePreviewSize( - $opts['w'] == 'auto' ? null : $opts['w'], - $opts['h'] == 'auto' ? null : $opts['h'] - ); - $opts['w'] = $w; - // $opts['h'] = $h; - - if (!$this->useImagePreviews) - $image_url = $image->getDirectUrl(); - else - $image_url = $image->getDirectPreviewUrl($w, $h); - - unset($result['element']['text']); - - $ctx = self::getSkinContext(); - $result['element']['rawHtml'] = $ctx->image( - w: $opts['w'], - nolabel: $opts['nolabel'], - align: $opts['align'], - padding_top: round($h / $w * 100, 4), - may_have_alpha: $image->imageMayHaveAlphaChannel(), - - url: $image_url, - direct_url: $image->getDirectUrl(), - note: $image->note - ); - - return $result; - } - } - - protected function inlineVideo($excerpt) { - if (preg_match('/^{video:([\w]{8})(?:,(.*?))?}{\/video}/', $excerpt['text'], $matches)) { - $random_id = $matches[1]; - - $opts = [ - 'w' => 'auto', - 'h' => 'auto', - 'align' => 'left', - 'nolabel' => false, - ]; - $inputopts = !empty($matches[2]) ? explode(',', $matches[2]) : []; - - foreach ($inputopts as $opt) { - if ($opt == 'nolabel') - $opts[$opt] = true; - else { - list($k, $v) = explode('=', $opt); - if (!isset($opts[$k])) - continue; - $opts[$k] = $v; - } - } - - $video = uploads::getByRandomId($random_id); - $result = [ - 'extent' => strlen($matches[0]), - 'element' => [ - 'name' => 'span', - 'text' => '', - ], - 'type' => '' - ]; - - if (!$video) { - return $result; - } - - $video_url = $video->getDirectUrl(); - - unset($result['element']['text']); - - $ctx = self::getSkinContext(); - $result['element']['rawHtml'] = $ctx->video( - url: $video_url, - w: $opts['w'], - h: $opts['h'] - ); - - return $result; - } - } - - protected function paragraph($line) { - if (preg_match('/^{fileAttach:([\w]{8})}{\/fileAttach}$/', $line['text'])) { - return $this->inlineFileAttach($line); - } - if (preg_match('/^{image:([\w]{8}),(?:.*?)}{\/image}/', $line['text'])) { - return $this->inlineImage($line); - } - if (preg_match('/^{video:([\w]{8})(?:,(?:.*?))?}{\/video}/', $line['text'])) { - return $this->inlineVideo($line); - } - return parent::paragraph($line); - } - - protected function blockFencedCodeComplete($block) { - if (!isset($block['element']['element']['attributes'])) { - return $block; - } - - $code = $block['element']['element']['text']; - $languageClass = $block['element']['element']['attributes']['class']; - $language = explode('-', $languageClass); - - if ($language[1] == 'term') { - $lines = explode("\n", $code); - for ($i = 0; $i < count($lines); $i++) { - $line = $lines[$i]; - if (str_starts_with($line, '$ ') || str_starts_with($line, '# ')) { - $lines[$i] = ''.substr($line, 0, 2).''.htmlspecialchars(substr($line, 2), ENT_NOQUOTES, 'UTF-8'); - } else { - $lines[$i] = htmlspecialchars($line, ENT_NOQUOTES, 'UTF-8'); - } - } - $block['element']['element']['rawHtml'] = implode("\n", $lines); - unset($block['element']['element']['text']); - - return $block; - } - - return parent::blockFencedCodeComplete($block); - } - - protected static function getSkinContext(): SkinContext { - return new SkinContext('\\skin\\markdown'); - } - -} diff --git a/lib/admin.php b/lib/admin.php index 91aa620..116ee3c 100644 --- a/lib/admin.php +++ b/lib/admin.php @@ -1,55 +1,51 @@ insert('admin_log', [ - 'ts' => time(), - 'ip' => ip2ulong($_SERVER['REMOTE_ADDR']), - 'ua' => $_SERVER['HTTP_USER_AGENT'] ?? '', - ]); - } +function admin_unset_cookie(): void { + global $config; + setcookie(ADMIN_COOKIE_NAME, '', 1, '/', $config['cookie_host']); +} +function admin_log_auth(): void { + DB()->insert('admin_log', [ + 'ts' => time(), + 'ip' => ip2ulong($_SERVER['REMOTE_ADDR']), + 'ua' => $_SERVER['HTTP_USER_AGENT'] ?? '', + ]); } diff --git a/lib/ansi.php b/lib/ansi.php new file mode 100644 index 0000000..9e0a425 --- /dev/null +++ b/lib/ansi.php @@ -0,0 +1,32 @@ +value + ($fg_bright ? 90 : 30); + if (!is_null($bg)) + $codes[] = $bg->value + ($bg_bright ? 100 : 40); + if ($bold) + $codes[] = 1; + + if (empty($codes)) + return $text; + + return "\033[".implode(';', $codes)."m".$text."\033[0m"; +} \ No newline at end of file diff --git a/lib/cli.php b/lib/cli.php index a860871..910f4c1 100644 --- a/lib/cli.php +++ b/lib/cli.php @@ -4,7 +4,7 @@ class cli { protected ?array $commandsCache = null; - public function __construct( + function __construct( protected string $ns ) {} @@ -21,7 +21,7 @@ class cli { exit(is_null($error) ? 0 : 1); } - public function getCommands(): array { + function getCommands(): array { if (is_null($this->commandsCache)) { $funcs = array_filter(get_defined_functions()['user'], fn(string $f) => str_starts_with($f, $this->ns)); $funcs = array_map(fn(string $f) => str_replace('_', '-', substr($f, strlen($this->ns.'\\'))), $funcs); @@ -30,10 +30,10 @@ class cli { return $this->commandsCache; } - public function run(): void { + function run(): void { global $argv, $argc; - if (PHP_SAPI != 'cli') + if (!is_cli()) cli::die('SAPI != cli'); if ($argc < 2) diff --git a/lib/config.php b/lib/config.php deleted file mode 100644 index bb7e5ca..0000000 --- a/lib/config.php +++ /dev/null @@ -1,46 +0,0 @@ -query("SELECT value FROM config WHERE name=?", $key); - if (!$db->numRows($q)) - return null; - return $db->result($q); - } - - public static function mget($keys) { - $map = []; - foreach ($keys as $key) { - $map[$key] = null; - } - - $db = getDb(); - $keys = array_map(fn($s) => $db->escape($s), $keys); - - $q = $db->query("SELECT * FROM config WHERE name IN('".implode("','", $keys)."')"); - while ($row = $db->fetch($q)) - $map[$row['name']] = $row['value']; - - return $map; - } - - public static function set($key, $value) { - $db = getDb(); - return $db->query("REPLACE INTO config (name, value) VALUES (?, ?)", $key, $value); - } - - public static function mset($map) { - $rows = []; - foreach ($map as $name => $value) { - $rows[] = [ - 'name' => $name, - 'value' => $value - ]; - } - $db = getDb(); - return $db->multipleReplace('config', $rows); - } - -} diff --git a/lib/ext/MyParsedown.php b/lib/ext/MyParsedown.php new file mode 100644 index 0000000..71dfa7f --- /dev/null +++ b/lib/ext/MyParsedown.php @@ -0,0 +1,218 @@ + [ + 'tablespan' => true + ] + ]; + if (!is_null($opts)) { + $parsedown_opts = array_merge($parsedown_opts, $opts); + } + parent::__construct($parsedown_opts); + + $this->InlineTypes['{'][] = 'FileAttach'; + $this->InlineTypes['{'][] = 'Image'; + $this->InlineTypes['{'][] = 'Video'; + $this->inlineMarkerList .= '{'; + } + + protected function inlineFileAttach($excerpt) { + if (preg_match('/^{fileAttach:([\w]{8})}{\/fileAttach}/', $excerpt['text'], $matches)) { + $random_id = $matches[1]; + $upload = uploads::getUploadByRandomId($random_id); + $result = [ + 'extent' => strlen($matches[0]), + 'element' => [ + 'name' => 'span', + 'text' => '', + ], + 'type' => '' + ]; + + if (!$upload) { + return $result; + } + + unset($result['element']['text']); + + $ctx = self::getSkinContext(); + $result['element']['rawHtml'] = $ctx->fileupload($upload->name, $upload->getDirectUrl(), $upload->note, $upload->getSize()); + + return $result; + } + } + + protected function inlineImage($excerpt) { + global $config; + + if (preg_match('/^{image:([\w]{8}),(.*?)}{\/image}/', $excerpt['text'], $matches)) { + $random_id = $matches[1]; + + $opts = [ + 'w' => 'auto', + 'h' => 'auto', + 'align' => 'left', + 'nolabel' => false, + ]; + $inputopts = explode(',', $matches[2]); + + foreach ($inputopts as $opt) { + if ($opt == 'nolabel') + $opts[$opt] = true; + else { + list($k, $v) = explode('=', $opt); + if (!isset($opts[$k])) + continue; + $opts[$k] = $v; + } + } + + $image = uploads::getUploadByRandomId($random_id); + $result = [ + 'extent' => strlen($matches[0]), + 'element' => [ + 'name' => 'span', + 'text' => '', + ], + 'type' => '' + ]; + + if (!$image) { + return $result; + } + + list($w, $h) = $image->getImagePreviewSize( + $opts['w'] == 'auto' ? null : $opts['w'], + $opts['h'] == 'auto' ? null : $opts['h'] + ); + $opts['w'] = $w; + // $opts['h'] = $h; + + if (!$this->useImagePreviews) + $image_url = $image->getDirectUrl(); + else + $image_url = $image->getDirectPreviewUrl($w, $h); + + unset($result['element']['text']); + + $ctx = self::getSkinContext(); + $result['element']['rawHtml'] = $ctx->image( + w: $opts['w'], + nolabel: $opts['nolabel'], + align: $opts['align'], + padding_top: round($h / $w * 100, 4), + may_have_alpha: $image->imageMayHaveAlphaChannel(), + + url: $image_url, + direct_url: $image->getDirectUrl(), + note: $image->note + ); + + return $result; + } + } + + protected function inlineVideo($excerpt) { + if (preg_match('/^{video:([\w]{8})(?:,(.*?))?}{\/video}/', $excerpt['text'], $matches)) { + $random_id = $matches[1]; + + $opts = [ + 'w' => 'auto', + 'h' => 'auto', + 'align' => 'left', + 'nolabel' => false, + ]; + $inputopts = !empty($matches[2]) ? explode(',', $matches[2]) : []; + + foreach ($inputopts as $opt) { + if ($opt == 'nolabel') + $opts[$opt] = true; + else { + list($k, $v) = explode('=', $opt); + if (!isset($opts[$k])) + continue; + $opts[$k] = $v; + } + } + + $video = uploads::getUploadByRandomId($random_id); + $result = [ + 'extent' => strlen($matches[0]), + 'element' => [ + 'name' => 'span', + 'text' => '', + ], + 'type' => '' + ]; + + if (!$video) { + return $result; + } + + $video_url = $video->getDirectUrl(); + + unset($result['element']['text']); + + $ctx = self::getSkinContext(); + $result['element']['rawHtml'] = $ctx->video( + url: $video_url, + w: $opts['w'], + h: $opts['h'] + ); + + return $result; + } + } + + protected function paragraph($line) { + if (preg_match('/^{fileAttach:([\w]{8})}{\/fileAttach}$/', $line['text'])) { + return $this->inlineFileAttach($line); + } + if (preg_match('/^{image:([\w]{8}),(?:.*?)}{\/image}/', $line['text'])) { + return $this->inlineImage($line); + } + if (preg_match('/^{video:([\w]{8})(?:,(?:.*?))?}{\/video}/', $line['text'])) { + return $this->inlineVideo($line); + } + return parent::paragraph($line); + } + + protected function blockFencedCodeComplete($block) { + if (!isset($block['element']['element']['attributes'])) { + return $block; + } + + $code = $block['element']['element']['text']; + $languageClass = $block['element']['element']['attributes']['class']; + $language = explode('-', $languageClass); + + if ($language[1] == 'term') { + $lines = explode("\n", $code); + for ($i = 0; $i < count($lines); $i++) { + $line = $lines[$i]; + if (str_starts_with($line, '$ ') || str_starts_with($line, '# ')) { + $lines[$i] = ''.substr($line, 0, 2).''.htmlspecialchars(substr($line, 2), ENT_NOQUOTES, 'UTF-8'); + } else { + $lines[$i] = htmlspecialchars($line, ENT_NOQUOTES, 'UTF-8'); + } + } + $block['element']['element']['rawHtml'] = implode("\n", $lines); + unset($block['element']['element']['text']); + + return $block; + } + + return parent::blockFencedCodeComplete($block); + } + + protected static function getSkinContext(): SkinContext { + return new SkinContext('\\skin\\markdown'); + } + +} diff --git a/lib/markup.php b/lib/markup.php index f6ddd0f..9872dae 100644 --- a/lib/markup.php +++ b/lib/markup.php @@ -1,5 +1,7 @@ md) + $fields['html'] = markup::markdownToHtml($fields['md']); + parent::edit($fields); + } + + function isUpdated(): bool { + return $this->updateTs && $this->updateTs != $this->ts; + } + + function getHtml(bool $is_retina, string $user_theme): string { + $html = $this->html; + $html = markup::htmlImagesFix($html, $is_retina, $user_theme); + return $html; + } + + function getUrl(): string { + return "/{$this->shortName}/"; + } + + function updateHtml(): void { + $html = markup::markdownToHtml($this->md); + $this->html = $html; + DB()->query("UPDATE pages SET html=? WHERE short_name=?", $html, $this->shortName); + } + +} + class pages { - public static function add(array $data): ?int { - $db = getDb(); + static function add(array $data): ?int { + $db = DB(); $data['ts'] = time(); $data['html'] = markup::markdownToHtml($data['md']); if (!$db->insert('pages', $data)) @@ -11,12 +53,12 @@ class pages { return $db->insertId(); } - public static function delete(Page $page): void { - getDb()->query("DELETE FROM pages WHERE short_name=?", $page->shortName); + static function delete(Page $page): void { + DB()->query("DELETE FROM pages WHERE short_name=?", $page->shortName); } - public static function getPageByName(string $short_name): ?Page { - $db = getDb(); + static function getByName(string $short_name): ?Page { + $db = DB(); $q = $db->query("SELECT * FROM pages WHERE short_name=?", $short_name); return $db->numRows($q) ? new Page($db->fetch($q)) : null; } @@ -24,8 +66,8 @@ class pages { /** * @return Page[] */ - public static function getAll(): array { - $db = getDb(); + static function getAll(): array { + $db = DB(); return array_map('Page::create_instance', $db->fetchAll($db->query("SELECT * FROM pages"))); } diff --git a/lib/posts.php b/lib/posts.php index 1537749..8ffb92b 100644 --- a/lib/posts.php +++ b/lib/posts.php @@ -1,9 +1,202 @@ visible && $fields['visible']) + $fields['ts'] = $cur_ts; + + $fields['update_ts'] = $cur_ts; + + if ($fields['md'] != $this->md) { + $fields['html'] = markup::markdownToHtml($fields['md']); + $fields['text'] = markup::htmlToText($fields['html']); + } + + if ((isset($fields['toc']) && $fields['toc']) || $this->toc) { + $fields['toc_html'] = markup::toc($fields['md']); + } + + parent::edit($fields); + $this->updateImagePreviews(); + } + + function updateHtml() { + $html = markup::markdownToHtml($this->md); + $this->html = $html; + + DB()->query("UPDATE posts SET html=? WHERE id=?", $html, $this->id); + } + + function updateText() { + $html = markup::markdownToHtml($this->md); + $text = markup::htmlToText($html); + $this->text = $text; + + DB()->query("UPDATE posts SET text=? WHERE id=?", $text, $this->id); + } + + function getDescriptionPreview(int $len): string { + if (mb_strlen($this->text) >= $len) + return mb_substr($this->text, 0, $len-3).'...'; + return $this->text; + } + + function getFirstImage(): ?Upload { + if (!preg_match('/\{image:([\w]{8})/', $this->md, $match)) + return null; + return uploads::getUploadByRandomId($match[1]); + } + + function getUrl(): string { + return $this->shortName != '' ? "/{$this->shortName}/" : "/{$this->id}/"; + } + + function getDate(): string { + return date('j M', $this->ts); + } + + function getYear(): int { + return (int)date('Y', $this->ts); + } + + function getFullDate(): string { + return date('j F Y', $this->ts); + } + + function getUpdateDate(): string { + return date('j M', $this->updateTs); + } + + function getFullUpdateDate(): string { + return date('j F Y', $this->updateTs); + } + + function getHtml(bool $is_retina, string $theme): string { + $html = $this->html; + $html = markup::htmlImagesFix($html, $is_retina, $theme); + return $html; + } + + function getToc(): ?string { + return $this->toc ? $this->tocHtml : null; + } + + function isUpdated(): bool { + return $this->updateTs && $this->updateTs != $this->ts; + } + + /** + * @return Tag[] + */ + function getTags(): array { + $db = DB(); + $q = $db->query("SELECT tags.* FROM posts_tags + LEFT JOIN tags ON tags.id=posts_tags.tag_id + WHERE posts_tags.post_id=? + ORDER BY posts_tags.tag_id", $this->id); + return array_map('Tag::create_instance', $db->fetchAll($q)); + } + + /** + * @return int[] + */ + function getTagIds(): array { + $ids = []; + $db = DB(); + $q = $db->query("SELECT tag_id FROM posts_tags WHERE post_id=? ORDER BY tag_id", $this->id); + while ($row = $db->fetch($q)) { + $ids[] = (int)$row['tag_id']; + } + return $ids; + } + + function setTagIds(array $new_tag_ids) { + $cur_tag_ids = $this->getTagIds(); + $add_tag_ids = array_diff($new_tag_ids, $cur_tag_ids); + $rm_tag_ids = array_diff($cur_tag_ids, $new_tag_ids); + + $db = DB(); + if (!empty($add_tag_ids)) { + $rows = []; + foreach ($add_tag_ids as $id) + $rows[] = ['post_id' => $this->id, 'tag_id' => $id]; + $db->multipleInsert('posts_tags', $rows); + } + + if (!empty($rm_tag_ids)) + $db->query("DELETE FROM posts_tags WHERE post_id=? AND tag_id IN(".implode(',', $rm_tag_ids).")", $this->id); + + $upd_tag_ids = array_merge($new_tag_ids, $rm_tag_ids); + $upd_tag_ids = array_unique($upd_tag_ids); + foreach ($upd_tag_ids as $id) + tags::recountTagPosts($id); + } + + /** + * @param bool $update Whether to overwrite preview if already exists + * @return int + * @throws Exception + */ + function updateImagePreviews(bool $update = false): int { + $images = []; + if (!preg_match_all('/\{image:([\w]{8}),(.*?)}/', $this->md, $matches)) + return 0; + + for ($i = 0; $i < count($matches[0]); $i++) { + $id = $matches[1][$i]; + $w = $h = null; + $opts = explode(',', $matches[2][$i]); + foreach ($opts as $opt) { + if (str_contains($opt, '=')) { + list($k, $v) = explode('=', $opt); + if ($k == 'w') + $w = (int)$v; + else if ($k == 'h') + $h = (int)$v; + } + } + $images[$id][] = [$w, $h]; + } + + if (empty($images)) + return 0; + + $images_affected = 0; + $uploads = uploads::getUploadsByRandomId(array_keys($images), true); + foreach ($uploads as $u) { + foreach ($images[$u->randomId] as $s) { + list($w, $h) = $s; + list($w, $h) = $u->getImagePreviewSize($w, $h); + if ($u->createImagePreview($w, $h, $update, $u->imageMayHaveAlphaChannel())) + $images_affected++; + } + } + + return $images_affected; + } + +} + class posts { - public static function getPostsCount(bool $include_hidden = false): int { - $db = getDb(); + static function getCount(bool $include_hidden = false): int { + $db = DB(); $sql = "SELECT COUNT(*) FROM posts"; if (!$include_hidden) { $sql .= " WHERE visible=1"; @@ -11,14 +204,14 @@ class posts { return (int)$db->result($db->query($sql)); } - public static function getPostsCountByTagId(int $tag_id, bool $include_hidden = false): int { - $db = getDb(); + static function getCountByTagId(int $tag_id, bool $include_hidden = false): int { + $db = DB(); if ($include_hidden) { $sql = "SELECT COUNT(*) FROM posts_tags WHERE tag_id=?"; } else { $sql = "SELECT COUNT(*) FROM posts_tags - LEFT JOIN posts ON posts.id=posts_tags.post_id - WHERE posts_tags.tag_id=? AND posts.visible=1"; + LEFT JOIN posts ON posts.id=posts_tags.post_id + WHERE posts_tags.tag_id=? AND posts.visible=1"; } return (int)$db->result($db->query($sql, $tag_id)); } @@ -26,8 +219,8 @@ class posts { /** * @return Post[] */ - public static function getPosts(int $offset = 0, int $count = -1, bool $include_hidden = false): array { - $db = getDb(); + static function getList(int $offset = 0, int $count = -1, bool $include_hidden = false): array { + $db = DB(); $sql = "SELECT * FROM posts"; if (!$include_hidden) $sql .= " WHERE visible=1"; @@ -41,11 +234,11 @@ class posts { /** * @return Post[] */ - public static function getPostsByTagId(int $tag_id, bool $include_hidden = false): array { - $db = getDb(); + static function getPostsByTagId(int $tag_id, bool $include_hidden = false): array { + $db = DB(); $sql = "SELECT posts.* FROM posts_tags - LEFT JOIN posts ON posts.id=posts_tags.post_id - WHERE posts_tags.tag_id=?"; + LEFT JOIN posts ON posts.id=posts_tags.post_id + WHERE posts_tags.tag_id=?"; if (!$include_hidden) $sql .= " AND posts.visible=1"; $sql .= " ORDER BY posts.ts DESC"; @@ -53,8 +246,8 @@ class posts { return array_map('Post::create_instance', $db->fetchAll($q)); } - public static function add(array $data = []): int|bool { - $db = getDb(); + static function add(array $data = []): int|bool { + $db = DB(); $html = \markup::markdownToHtml($data['md']); $text = \markup::htmlToText($html); @@ -70,64 +263,41 @@ class posts { $id = $db->insertId(); - $post = posts::get($id); + $post = self::get($id); $post->updateImagePreviews(); return $id; } - public static function delete(Post $post): void { + static function delete(Post $post): void { $tags = $post->getTags(); - $db = getDb(); + $db = DB(); $db->query("DELETE FROM posts WHERE id=?", $post->id); $db->query("DELETE FROM posts_tags WHERE post_id=?", $post->id); foreach ($tags as $tag) - self::recountPostsWithTag($tag->id); + tags::recountTagPosts($tag->id); } - public static function getTagIds(array $tags): array { - $found_tags = []; - $map = []; - - $db = getDb(); - $q = $db->query("SELECT id, tag FROM tags - WHERE tag IN ('".implode("','", array_map(function($tag) use ($db) { return $db->escape($tag); }, $tags))."')"); - while ($row = $db->fetch($q)) { - $found_tags[] = $row['tag']; - $map[$row['tag']] = (int)$row['id']; - } - - $notfound_tags = array_diff($tags, $found_tags); - if (!empty($notfound_tags)) { - foreach ($notfound_tags as $tag) { - $db->insert('tags', ['tag' => $tag]); - $map[$tag] = $db->insertId(); - } - } - - return $map; - } - - public static function get(int $id): ?Post { - $db = getDb(); + static function get(int $id): ?Post { + $db = DB(); $q = $db->query("SELECT * FROM posts WHERE id=?", $id); return $db->numRows($q) ? new Post($db->fetch($q)) : null; } - public static function getPostByName(string $short_name): ?Post { - $db = getDb(); + static function getByName(string $short_name): ?Post { + $db = DB(); $q = $db->query("SELECT * FROM posts WHERE short_name=?", $short_name); return $db->numRows($q) ? new Post($db->fetch($q)) : null; } - public static function getPostsById(array $ids, bool $flat = false): array { + static function getPostsById(array $ids, bool $flat = false): array { if (empty($ids)) { return []; } - $db = getDb(); + $db = DB(); $posts = array_fill_keys($ids, null); $q = $db->query("SELECT * FROM posts WHERE id IN(".implode(',', $ids).")"); @@ -148,44 +318,4 @@ class posts { return $posts; } - public static function getAllTags(bool $include_hidden = false): array { - $db = getDb(); - $field = $include_hidden ? 'posts_count' : 'visible_posts_count'; - $q = $db->query("SELECT * FROM tags WHERE $field > 0 ORDER BY $field DESC, tag"); - return array_map('Tag::create_instance', $db->fetchAll($q)); - } - - public static function getTag(string $tag): ?Tag { - $db = getDb(); - $q = $db->query("SELECT * FROM tags WHERE tag=?", $tag); - return $db->numRows($q) ? new Tag($db->fetch($q)) : null; - } - - /** - * @param int $tag_id - */ - public static function recountPostsWithTag($tag_id) { - $db = getDb(); - $count = $db->result($db->query("SELECT COUNT(*) FROM posts_tags WHERE tag_id=?", $tag_id)); - $vis_count = $db->result($db->query("SELECT COUNT(*) FROM posts_tags - LEFT JOIN posts ON posts.id=posts_tags.post_id - WHERE posts_tags.tag_id=? AND posts.visible=1", $tag_id)); - $db->query("UPDATE tags SET posts_count=?, visible_posts_count=? WHERE id=?", - $count, $vis_count, $tag_id); - } - - public static function splitStringToTags(string $tags): array { - $tags = trim($tags); - if ($tags == '') { - return []; - } - - $tags = preg_split('/,\s+/', $tags); - $tags = array_filter($tags, function($tag) { return trim($tag) != ''; }); - $tags = array_map('trim', $tags); - $tags = array_map('mb_strtolower', $tags); - - return $tags; - } - -} +} \ No newline at end of file diff --git a/lib/stored_config.php b/lib/stored_config.php new file mode 100644 index 0000000..2e7dc8a --- /dev/null +++ b/lib/stored_config.php @@ -0,0 +1,14 @@ +query("SELECT value FROM config WHERE name=?", $key); + if (!$db->numRows($q)) + return null; + return $db->result($q); +} + +function scSet($key, $value) { + $db = DB(); + return $db->query("REPLACE INTO config (name, value) VALUES (?, ?)", $key, $value); +} diff --git a/lib/tags.php b/lib/tags.php new file mode 100644 index 0000000..ecc9e5a --- /dev/null +++ b/lib/tags.php @@ -0,0 +1,87 @@ +tag.'/'; + } + + function getPostsCount(bool $is_admin): int { + return $is_admin ? $this->postsCount : $this->visiblePostsCount; + } + + function __toString(): string { + return $this->tag; + } + +} + +class tags { + + static function getAll(bool $include_hidden = false): array { + $db = DB(); + $field = $include_hidden ? 'posts_count' : 'visible_posts_count'; + $q = $db->query("SELECT * FROM tags WHERE $field > 0 ORDER BY $field DESC, tag"); + return array_map('Tag::create_instance', $db->fetchAll($q)); + } + + static function get(string $tag): ?Tag { + $db = DB(); + $q = $db->query("SELECT * FROM tags WHERE tag=?", $tag); + return $db->numRows($q) ? new Tag($db->fetch($q)) : null; + } + + static function recountTagPosts(int $tag_id): void { + $db = DB(); + $count = $db->result($db->query("SELECT COUNT(*) FROM posts_tags WHERE tag_id=?", $tag_id)); + $vis_count = $db->result($db->query("SELECT COUNT(*) FROM posts_tags + LEFT JOIN posts ON posts.id=posts_tags.post_id + WHERE posts_tags.tag_id=? AND posts.visible=1", $tag_id)); + $db->query("UPDATE tags SET posts_count=?, visible_posts_count=? WHERE id=?", + $count, $vis_count, $tag_id); + } + + static function splitString(string $tags): array { + $tags = trim($tags); + if ($tags == '') + return []; + $tags = preg_split('/,\s+/', $tags); + $tags = array_filter($tags, static function($tag) { return trim($tag) != ''; }); + $tags = array_map('trim', $tags); + $tags = array_map('mb_strtolower', $tags); + + return $tags; + } + + static function getTags(array $tags): array { + $found_tags = []; + $map = []; + + $db = DB(); + $q = $db->query("SELECT id, tag FROM tags + WHERE tag IN ('".implode("','", array_map(fn($tag) => $db->escape($tag), $tags))."')"); + + while ($row = $db->fetch($q)) { + $found_tags[] = $row['tag']; + $map[$row['tag']] = (int)$row['id']; + } + + $notfound_tags = array_diff($tags, $found_tags); + if (!empty($notfound_tags)) { + foreach ($notfound_tags as $tag) { + $db->insert('tags', ['tag' => $tag]); + $map[$tag] = $db->insertId(); + } + } + + return $map; + } + +} \ No newline at end of file diff --git a/lib/themes.php b/lib/themes.php new file mode 100644 index 0000000..f9b9857 --- /dev/null +++ b/lib/themes.php @@ -0,0 +1,41 @@ + [ + 'bg' => 0x222222, + // 'alpha' => 0x303132, + 'alpha' => 0x222222, + ], + 'light' => [ + 'bg' => 0xffffff, + // 'alpha' => 0xf2f2f2, + 'alpha' => 0xffffff, + ] +]; + + +function getThemes(): array { + return array_keys(THEMES); +} + +function themeExists(string $name): bool { + return array_key_exists($name, THEMES); +} + +function getThemeAlphaColorAsRGB(string $name): array { + $color = THEMES[$name]['alpha']; + $r = ($color >> 16) & 0xff; + $g = ($color >> 8) & 0xff; + $b = $color & 0xff; + return [$r, $g, $b]; +} + +function getUserTheme(): string { + if (isset($_COOKIE['theme'])) { + $val = $_COOKIE['theme']; + if (is_array($val)) + $val = implode($val); + } else + $val = 'auto'; + return $val; +} diff --git a/lib/uploads.php b/lib/uploads.php index 6c7e6bc..7540f11 100644 --- a/lib/uploads.php +++ b/lib/uploads.php @@ -1,30 +1,30 @@ result($db->query("SELECT COUNT(*) FROM uploads")); } - public static function isExtensionAllowed(string $ext): bool { - return in_array($ext, self::$allowedExtensions); + static function isExtensionAllowed(string $ext): bool { + return in_array($ext, UPLOADS_ALLOWED_EXTENSIONS); } - public static function add(string $tmp_name, string $name, string $note): ?int { + static function add(string $tmp_name, string $name, string $note): ?int { global $config; $name = sanitize_filename($name); if (!$name) $name = 'file'; - $random_id = self::getNewRandomId(); + $random_id = self::_getNewUploadRandomId(); $size = filesize($tmp_name); $is_image = detect_image_type($tmp_name) !== false; $image_w = 0; @@ -33,7 +33,7 @@ class uploads { list($image_w, $image_h) = getimagesize($tmp_name); } - $db = getDb(); + $db = DB(); if (!$db->insert('uploads', [ 'random_id' => $random_id, 'ts' => time(), @@ -62,12 +62,12 @@ class uploads { return $id; } - public static function delete(int $id): bool { + static function delete(int $id): bool { $upload = self::get($id); if (!$upload) return false; - $db = getDb(); + $db = DB(); $db->query("DELETE FROM uploads WHERE id=?", $id); rrmdir($upload->getDirectory()); @@ -77,14 +77,14 @@ class uploads { /** * @return Upload[] */ - public static function getAll(): array { - $db = getDb(); + static function getAllUploads(): array { + $db = DB(); $q = $db->query("SELECT * FROM uploads ORDER BY id DESC"); return array_map('Upload::create_instance', $db->fetchAll($q)); } - public static function get(int $id): ?Upload { - $db = getDb(); + static function get(int $id): ?Upload { + $db = DB(); $q = $db->query("SELECT * FROM uploads WHERE id=?", $id); if ($db->numRows($q)) { return new Upload($db->fetch($q)); @@ -98,12 +98,12 @@ class uploads { * @param bool $flat * @return Upload[] */ - public static function getUploadsByRandomId(array $ids, bool $flat = false): array { + static function getUploadsByRandomId(array $ids, bool $flat = false): array { if (empty($ids)) { return []; } - $db = getDb(); + $db = DB(); $uploads = array_fill_keys($ids, null); $q = $db->query("SELECT * FROM uploads WHERE random_id IN('".implode('\',\'', array_map([$db, 'escape'], $ids))."')"); @@ -124,8 +124,8 @@ class uploads { return $uploads; } - public static function getByRandomId(string $random_id): ?Upload { - $db = getDb(); + static function getUploadByRandomId(string $random_id): ?Upload { + $db = DB(); $q = $db->query("SELECT * FROM uploads WHERE random_id=? LIMIT 1", $random_id); if ($db->numRows($q)) { return new Upload($db->fetch($q)); @@ -134,12 +134,175 @@ class uploads { } } - protected static function getNewRandomId(): string { - $db = getDb(); + static function _getNewUploadRandomId(): string { + $db = DB(); do { $random_id = strgen(8); } while ($db->numRows($db->query("SELECT id FROM uploads WHERE random_id=?", $random_id)) > 0); return $random_id; - } + } } + + +class Upload extends model { + + const DB_TABLE = 'uploads'; + + public static array $ImageExtensions = ['jpg', 'jpeg', 'png', 'gif']; + public static array $VideoExtensions = ['mp4', 'ogg']; + + public int $id; + public string $randomId; + public int $ts; + public string $name; + public int $size; + public int $downloads; + public int $image; // TODO: remove + public int $imageW; + public int $imageH; + public string $note; + + function getDirectory(): string { + global $config; + return $config['uploads_dir'].'/'.$this->randomId; + } + + function getDirectUrl(): string { + global $config; + return 'https://'.$config['uploads_host'].'/'.$this->randomId.'/'.$this->name; + } + + function getDirectPreviewUrl(int $w, int $h, bool $retina = false): string { + global $config; + if ($w == $this->imageW && $this->imageH == $h) + return $this->getDirectUrl(); + + if ($retina) { + $w *= 2; + $h *= 2; + } + + $prefix = $this->imageMayHaveAlphaChannel() ? 'a' : 'p'; + return 'https://'.$config['uploads_host'].'/'.$this->randomId.'/'.$prefix.$w.'x'.$h.'.jpg'; + } + + // TODO remove? + function incrementDownloads() { + $db = DB(); + $db->query("UPDATE uploads SET downloads=downloads+1 WHERE id=?", $this->id); + $this->downloads++; + } + + function getSize(): string { + return sizeString($this->size); + } + + function getMarkdown(): string { + if ($this->isImage()) { + $md = '{image:'.$this->randomId.',w='.$this->imageW.',h='.$this->imageH.'}{/image}'; + } else if ($this->isVideo()) { + $md = '{video:'.$this->randomId.'}{/video}'; + } else { + $md = '{fileAttach:'.$this->randomId.'}{/fileAttach}'; + } + $md .= ' '; + return $md; + } + + function setNote(string $note) { + $db = DB(); + $db->query("UPDATE uploads SET note=? WHERE id=?", $note, $this->id); + } + + function isImage(): bool { + return in_array(extension($this->name), self::$ImageExtensions); + } + + // assume all png images have alpha channel + // i know this is wrong, but anyway + function imageMayHaveAlphaChannel(): bool { + return strtolower(extension($this->name)) == 'png'; + } + + function isVideo(): bool { + return in_array(extension($this->name), self::$VideoExtensions); + } + + function getImageRatio(): float { + return $this->imageW / $this->imageH; + } + + function getImagePreviewSize(?int $w = null, ?int $h = null): array { + if (is_null($w) && is_null($h)) + throw new Exception(__METHOD__.': both width and height can\'t be null'); + + if (is_null($h)) + $h = round($w / $this->getImageRatio()); + + if (is_null($w)) + $w = round($h * $this->getImageRatio()); + + return [$w, $h]; + } + + function createImagePreview(?int $w = null, + ?int $h = null, + bool $force_update = false, + bool $may_have_alpha = false): bool { + global $config; + + $orig = $config['uploads_dir'].'/'.$this->randomId.'/'.$this->name; + $updated = false; + + foreach (themes::getThemes() as $theme) { + if (!$may_have_alpha && $theme == 'dark') + continue; + + for ($mult = 1; $mult <= 2; $mult++) { + $dw = $w * $mult; + $dh = $h * $mult; + + $prefix = $may_have_alpha ? 'a' : 'p'; + $dst = $config['uploads_dir'].'/'.$this->randomId.'/'.$prefix.$dw.'x'.$dh.($theme == 'dark' ? '_dark' : '').'.jpg'; + + if (file_exists($dst)) { + if (!$force_update) + continue; + unlink($dst); + } + + $img = imageopen($orig); + imageresize($img, $dw, $dh, themes::getThemeAlphaColorAsRGB($theme)); + imagejpeg($img, $dst, $mult == 1 ? 93 : 67); + imagedestroy($img); + + setperm($dst); + $updated = true; + } + } + + return $updated; + } + + /** + * @return int Number of deleted files + */ + function deleteAllImagePreviews(): int { + global $config; + $dir = $config['uploads_dir'].'/'.$this->randomId; + $files = scandir($dir); + $deleted = 0; + foreach ($files as $f) { + if (preg_match('/^[ap](\d+)x(\d+)(?:_dark)?\.jpg$/', $f)) { + if (is_file($dir.'/'.$f)) + unlink($dir.'/'.$f); + else + logError(__METHOD__.': '.$dir.'/'.$f.' is not a file!'); + $deleted++; + } + } + return $deleted; + } + +} \ No newline at end of file diff --git a/model/Page.php b/model/Page.php deleted file mode 100644 index f516836..0000000 --- a/model/Page.php +++ /dev/null @@ -1,43 +0,0 @@ -md) - $data['html'] = markup::markdownToHtml($data['md']); - parent::edit($data); - } - - public function isUpdated(): bool { - return $this->updateTs && $this->updateTs != $this->ts; - } - - public function getHtml(bool $is_retina, string $user_theme): string { - $html = $this->html; - $html = markup::htmlImagesFix($html, $is_retina, $user_theme); - return $html; - } - - public function getUrl(): string { - return "/{$this->shortName}/"; - } - - public function updateHtml() { - $html = markup::markdownToHtml($this->md); - $this->html = $html; - getDb()->query("UPDATE pages SET html=? WHERE short_name=?", $html, $this->shortName); - } - -} diff --git a/model/Post.php b/model/Post.php deleted file mode 100644 index 6f3f1ab..0000000 --- a/model/Post.php +++ /dev/null @@ -1,193 +0,0 @@ -visible && $data['visible']) - $data['ts'] = $cur_ts; - - $data['update_ts'] = $cur_ts; - - if ($data['md'] != $this->md) { - $data['html'] = markup::markdownToHtml($data['md']); - $data['text'] = markup::htmlToText($data['html']); - } - - if ((isset($data['toc']) && $data['toc']) || $this->toc) { - $data['toc_html'] = markup::toc($data['md']); - } - - parent::edit($data); - $this->updateImagePreviews(); - } - - public function updateHtml() { - $html = markup::markdownToHtml($this->md); - $this->html = $html; - - getDb()->query("UPDATE posts SET html=? WHERE id=?", $html, $this->id); - } - - public function updateText() { - $html = markup::markdownToHtml($this->md); - $text = markup::htmlToText($html); - $this->text = $text; - - getDb()->query("UPDATE posts SET text=? WHERE id=?", $text, $this->id); - } - - public function getDescriptionPreview(int $len): string { - if (mb_strlen($this->text) >= $len) - return mb_substr($this->text, 0, $len-3).'...'; - return $this->text; - } - - public function getFirstImage(): ?Upload { - if (!preg_match('/\{image:([\w]{8})/', $this->md, $match)) - return null; - return uploads::getByRandomId($match[1]); - } - - public function getUrl(): string { - return $this->shortName != '' ? "/{$this->shortName}/" : "/{$this->id}/"; - } - - public function getDate(): string { - return date('j M', $this->ts); - } - - public function getYear(): int { - return (int)date('Y', $this->ts); - } - - public function getFullDate(): string { - return date('j F Y', $this->ts); - } - - public function getUpdateDate(): string { - return date('j M', $this->updateTs); - } - - public function getFullUpdateDate(): string { - return date('j F Y', $this->updateTs); - } - - public function getHtml(bool $is_retina, string $theme): string { - $html = $this->html; - $html = markup::htmlImagesFix($html, $is_retina, $theme); - return $html; - } - - public function getToc(): ?string { - return $this->toc ? $this->tocHtml : null; - } - - public function isUpdated(): bool { - return $this->updateTs && $this->updateTs != $this->ts; - } - - /** - * @return Tag[] - */ - public function getTags(): array { - $db = getDb(); - $q = $db->query("SELECT tags.* FROM posts_tags - LEFT JOIN tags ON tags.id=posts_tags.tag_id - WHERE posts_tags.post_id=? - ORDER BY posts_tags.tag_id", $this->id); - return array_map('Tag::create_instance', $db->fetchAll($q)); - } - - /** - * @return int[] - */ - public function getTagIds(): array { - $ids = []; - $db = getDb(); - $q = $db->query("SELECT tag_id FROM posts_tags WHERE post_id=? ORDER BY tag_id", $this->id); - while ($row = $db->fetch($q)) { - $ids[] = (int)$row['tag_id']; - } - return $ids; - } - - public function setTagIds(array $new_tag_ids) { - $cur_tag_ids = $this->getTagIds(); - $add_tag_ids = array_diff($new_tag_ids, $cur_tag_ids); - $rm_tag_ids = array_diff($cur_tag_ids, $new_tag_ids); - - $db = getDb(); - if (!empty($add_tag_ids)) { - $rows = []; - foreach ($add_tag_ids as $id) - $rows[] = ['post_id' => $this->id, 'tag_id' => $id]; - $db->multipleInsert('posts_tags', $rows); - } - - if (!empty($rm_tag_ids)) - $db->query("DELETE FROM posts_tags WHERE post_id=? AND tag_id IN(".implode(',', $rm_tag_ids).")", $this->id); - - $upd_tag_ids = array_merge($new_tag_ids, $rm_tag_ids); - $upd_tag_ids = array_unique($upd_tag_ids); - foreach ($upd_tag_ids as $id) - posts::recountPostsWithTag($id); - } - - /** - * @param bool $update Whether to overwrite preview if already exists - * @return int - */ - public function updateImagePreviews(bool $update = false): int { - $images = []; - if (!preg_match_all('/\{image:([\w]{8}),(.*?)}/', $this->md, $matches)) - return 0; - - for ($i = 0; $i < count($matches[0]); $i++) { - $id = $matches[1][$i]; - $w = $h = null; - $opts = explode(',', $matches[2][$i]); - foreach ($opts as $opt) { - if (strpos($opt, '=') !== false) { - list($k, $v) = explode('=', $opt); - if ($k == 'w') - $w = (int)$v; - else if ($k == 'h') - $h = (int)$v; - } - } - $images[$id][] = [$w, $h]; - } - - if (empty($images)) - return 0; - - $images_affected = 0; - $uploads = uploads::getUploadsByRandomId(array_keys($images), true); - foreach ($uploads as $u) { - foreach ($images[$u->randomId] as $s) { - list($w, $h) = $s; - list($w, $h) = $u->getImagePreviewSize($w, $h); - if ($u->createImagePreview($w, $h, $update, $u->imageMayHaveAlphaChannel())) - $images_affected++; - } - } - - return $images_affected; - } - -} diff --git a/model/Tag.php b/model/Tag.php deleted file mode 100644 index a8324f7..0000000 --- a/model/Tag.php +++ /dev/null @@ -1,24 +0,0 @@ -tag.'/'; - } - - public function getPostsCount(bool $is_admin): int { - return $is_admin ? $this->postsCount : $this->visiblePostsCount; - } - - public function __toString(): string { - return $this->tag; - } - -} diff --git a/model/Upload.php b/model/Upload.php deleted file mode 100644 index 06b348b..0000000 --- a/model/Upload.php +++ /dev/null @@ -1,163 +0,0 @@ -randomId; - } - - public function getDirectUrl(): string { - global $config; - return 'https://'.$config['uploads_host'].'/'.$this->randomId.'/'.$this->name; - } - - public function getDirectPreviewUrl(int $w, int $h, bool $retina = false): string { - global $config; - if ($w == $this->imageW && $this->imageH == $h) - return $this->getDirectUrl(); - - if ($retina) { - $w *= 2; - $h *= 2; - } - - $prefix = $this->imageMayHaveAlphaChannel() ? 'a' : 'p'; - return 'https://'.$config['uploads_host'].'/'.$this->randomId.'/'.$prefix.$w.'x'.$h.'.jpg'; - } - - // TODO remove? - public function incrementDownloads() { - $db = getDb(); - $db->query("UPDATE uploads SET downloads=downloads+1 WHERE id=?", $this->id); - $this->downloads++; - } - - public function getSize(): string { - return sizeString($this->size); - } - - public function getMarkdown(): string { - if ($this->isImage()) { - $md = '{image:'.$this->randomId.',w='.$this->imageW.',h='.$this->imageH.'}{/image}'; - } else if ($this->isVideo()) { - $md = '{video:'.$this->randomId.'}{/video}'; - } else { - $md = '{fileAttach:'.$this->randomId.'}{/fileAttach}'; - } - $md .= ' '; - return $md; - } - - public function setNote(string $note) { - $db = getDb(); - $db->query("UPDATE uploads SET note=? WHERE id=?", $note, $this->id); - } - - public function isImage(): bool { - return in_array(extension($this->name), self::$ImageExtensions); - } - - // assume all png images have alpha channel - // i know this is wrong, but anyway - public function imageMayHaveAlphaChannel(): bool { - return strtolower(extension($this->name)) == 'png'; - } - - public function isVideo(): bool { - return in_array(extension($this->name), self::$VideoExtensions); - } - - public function getImageRatio(): float { - return $this->imageW / $this->imageH; - } - - public function getImagePreviewSize(?int $w = null, ?int $h = null): array { - if (is_null($w) && is_null($h)) - throw new Exception(__METHOD__.': both width and height can\'t be null'); - - if (is_null($h)) - $h = round($w / $this->getImageRatio()); - - if (is_null($w)) - $w = round($h * $this->getImageRatio()); - - return [$w, $h]; - } - - public function createImagePreview(?int $w = null, - ?int $h = null, - bool $force_update = false, - bool $may_have_alpha = false): bool { - global $config; - - $orig = $config['uploads_dir'].'/'.$this->randomId.'/'.$this->name; - $updated = false; - - foreach (themes::getThemes() as $theme) { - if (!$may_have_alpha && $theme == 'dark') - continue; - - for ($mult = 1; $mult <= 2; $mult++) { - $dw = $w * $mult; - $dh = $h * $mult; - - $prefix = $may_have_alpha ? 'a' : 'p'; - $dst = $config['uploads_dir'].'/'.$this->randomId.'/'.$prefix.$dw.'x'.$dh.($theme == 'dark' ? '_dark' : '').'.jpg'; - - if (file_exists($dst)) { - if (!$force_update) - continue; - unlink($dst); - } - - $img = imageopen($orig); - imageresize($img, $dw, $dh, themes::getThemeAlphaColorAsRGB($theme)); - imagejpeg($img, $dst, $mult == 1 ? 93 : 67); - imagedestroy($img); - - setperm($dst); - $updated = true; - } - } - - return $updated; - } - - /** - * @return int Number of deleted files - */ - public function deleteAllImagePreviews(): int { - global $config; - $dir = $config['uploads_dir'].'/'.$this->randomId; - $files = scandir($dir); - $deleted = 0; - foreach ($files as $f) { - if (preg_match('/^[ap](\d+)x(\d+)(?:_dark)?\.jpg$/', $f)) { - if (is_file($dir.'/'.$f)) - unlink($dir.'/'.$f); - else - logError(__METHOD__.': '.$dir.'/'.$f.' is not a file!'); - $deleted++; - } - } - return $deleted; - } - -} diff --git a/routes.php b/routes.php new file mode 100644 index 0000000..8cda1bb --- /dev/null +++ b/routes.php @@ -0,0 +1,23 @@ + [ + '/' => 'index', + 'contacts/' => 'contacts', + 'projects.html' => 'projects', + 'blog/(\d+)/' => 'post_id id=$(1)', + 'feed.rss' => 'rss', + 'rss/' => 'rss', + '([a-z0-9-]+)/' => 'auto name=$(1)' + ], + 'Admin' => [ + 'admin/' => 'index', + 'admin/{login,logout,log}/' => '${1}', + '([a-z0-9-]+)/{delete,edit}/' => 'auto_${1} short_name=$(1)', + '([a-z0-9-]+)/create/' => 'page_add short_name=$(1)', + 'write/' => 'post_add', + 'admin/markdown-preview.ajax' => 'ajax_md_preview', + 'uploads/' => 'uploads', + 'uploads/{edit_note,delete}/(\d+)/' => 'upload_${1} id=$(1)' + ], +]; \ No newline at end of file diff --git a/skin/admin.skin.php b/skin/admin.skin.php index b2d9bb4..d2fc148 100644 --- a/skin/admin.skin.php +++ b/skin/admin.skin.php @@ -135,8 +135,8 @@ function postForm($ctx, $form_url = !$is_edit ? '/write/' : $post_url.'edit/'; $html = <<if_true($error_code, '
'.$ctx->lang('err_blog_'.$error_code).'
')} -{$ctx->if_true($saved, '
'.$ctx->lang('info_saved').'
')} +{$ctx->if_true($error_code, fn() => '
'.$ctx->lang('err_blog_'.$error_code).'
')} +{$ctx->if_true($saved, fn() => '
'.$ctx->lang('info_saved').'
')}
@@ -228,8 +228,8 @@ function pageForm($ctx, bool $visible = false): array { $form_url = '/'.$short_name.'/'.($is_edit ? 'edit' : 'create').'/'; $html = <<if_true($error_code, '
'.$ctx->lang('err_pages_'.$error_code).'
')} -{$ctx->if_true($saved, '
'.$ctx->lang('info_saved').'
')} +{$ctx->if_true($error_code, fn() => '
'.$ctx->lang('err_pages_'.$error_code).'
')} +{$ctx->if_true($saved, fn() => '
'.$ctx->lang('info_saved').'
')}
diff --git a/skin/base.skin.php b/skin/base.skin.php index d39a0a8..d583ffe 100644 --- a/skin/base.skin.php +++ b/skin/base.skin.php @@ -2,9 +2,6 @@ namespace skin\base; -use admin; -use RequestDispatcher; - function layout($ctx, $title, $unsafe_body, $static, $meta, $js, $opts, $exec_time, $unsafe_lang, $theme) { global $config; $app_config = json_encode([ @@ -15,9 +12,13 @@ $app_config = json_encode([ $body_class = []; if ($opts['full_width']) - $body_class = 'full-width'; + $body_class[] = 'full-width'; else if ($opts['wide']) - $body_class = 'wide'; + $body_class[] = 'wide'; +if (!empty($body_class)) + $body_class = implode(' ', $body_class); +else + $body_class = ''; return << @@ -196,7 +197,7 @@ $items = [ ['url' => '/misc/', 'label' => 'misc'], ['url' => '/contacts/', 'label' => 'contacts'], ]; -if (\admin::isAdmin()) +if (\is_admin()) $items[] = ['url' => '/admin/', 'label' => 'admin']; // here, items are rendered using for_each, so that there are no gaps (whitespaces) between tags @@ -226,9 +227,9 @@ HTML; // TODO rewrite this fcking crap function renderLogo($ctx, array $path_map = [], array $link_map = []): string { - $uri = RequestDispatcher::path(); + $uri = request_path(); - if (!admin::isAdmin()) { + if (!is_admin()) { $prompt_sign = '$'; } else { $prompt_sign = '#'; diff --git a/skin/error.skin.php b/skin/error.skin.php index 5276bfa..8f7e4c7 100644 --- a/skin/error.skin.php +++ b/skin/error.skin.php @@ -4,34 +4,17 @@ namespace skin\error; use Stringable; -function forbidden($ctx, $message) { - return $ctx->common(403, 'Forbidden', $message); -} - -function not_found($ctx, $message) { - return $ctx->common(404, 'Not Found', $message); -} - -function unauthorized($ctx, $message) { - return $ctx->common(401, 'Unauthorized', $message); -} - -function not_implemented($ctx, $message) { - return $ctx->common(501, 'Not Implemented', $message); -} - -function common($ctx, - int $code, - string|Stringable $title, - string|Stringable|null $message = null) { +function http_error($ctx, + int $code, + string|Stringable $title, + string|Stringable|null $message = null) { return << $code $title

$code $title

-
{$ctx->if_true($message, - '

'.$message.'

' + '

'.$message.'

' )} diff --git a/strings/main.yaml b/strings/main.yaml new file mode 100644 index 0000000..e06e51d --- /dev/null +++ b/strings/main.yaml @@ -0,0 +1,103 @@ +# common +ch1p: 'ch1p' +site_title: 'ch1p' +index_title: 'Home | ch1p' + +posts: 'posts' +all_posts: 'all posts' +blog: 'blog' +contacts: 'contacts' +email: 'email' +projects: 'projects' +unknown_error: 'Unknown error' +error: 'Error' +write: 'Write' +submit: 'submit' +edit: 'edit' +delete: 'delete' +info_saved: 'Information saved.' +toc: 'Table of Contents' + +# theme switcher +theme_auto: 'auto' +theme_dark: 'dark' +theme_light: 'light' + +# contacts +contacts_email: 'email' +contacts_pgp: 'OpenPGP public key' +contacts_tg: 'telegram' +contacts_freenode: 'freenode' + +# blog +blog_tags: 'tags' +blog_latest: 'Latest posts' +blog_no: 'No posts yet.' +blog_view_all: 'View all' +blog_write: 'Write a post' +blog_post_delete_confirmation: 'Are you sure you want to delete this post?' +blog_post_edit_title: 'Edit post "%s"' +blog_post_hidden: 'Hidden' +blog_tag_title: 'Posts tagged with "%s"' +blog_tag_not_found: 'No posts found.' +blog_comments_text: 'If you have any comments, contact me by email.' + +blog_write_form_preview_btn: 'Preview' +blog_write_form_submit_btn: 'Submit' +blog_write_form_title: 'Title' +blog_write_form_text: 'Text' +blog_write_form_preview: 'Preview' +blog_write_form_enter_text: 'Enter text..' +blog_write_form_enter_title: 'Enter title..' +blog_write_form_tags: 'Tags' +blog_write_form_visible: 'Visible' +blog_write_form_toc: 'ToC' +blog_write_form_short_name: 'Short name' +blog_write_form_toggle_wrap: 'Toggle wrap' +blog_write_form_options: 'Options' + +blog_uploads: 'Uploads' +blog_upload: 'Upload files' +blog_upload_delete: 'Delete' +blog_upload_delete_confirmation: 'Are you sure you want to delete this upload?' +blog_upload_show_md: 'Show md' +blog_upload_form_file: 'File' +blog_upload_form_custom_name: 'Custom name' +blog_upload_form_note: 'Note' + +# blog (errors) +err_blog_no_title: 'Title not specified' +err_blog_no_text: 'Text not specified' +err_blog_no_tags: 'Tags not specified' +err_blog_db_err: 'Database error' +err_blog_no_short_name: 'Short name not specified' +err_blog_short_name_exists: 'This short name already exists' + +# pages +pages_create: 'create new page' +pages_edit: 'edit' +pages_delete: 'delete' +pages_create_title: 'create new page "%s"' +pages_page_delete_confirmation: 'Are you sure you want to delete this page?' +pages_page_edit_title: 'Edit %s' + +pages_write_form_submit_btn: 'Submit' +pages_write_form_title: 'Title' +pages_write_form_text: 'Text' +pages_write_form_enter_text: 'Enter text..' +pages_write_form_enter_title: 'Enter title..' +pages_write_form_visible: 'Visible' +pages_write_form_short_name: 'Short name' +pages_write_form_toggle_wrap: 'Toggle wrap' +pages_write_form_options: 'Options' + +# pages (errors) +err_pages_no_title: 'Title not specified' +err_pages_no_text: 'Text not specified' +err_pages_no_id: 'ID not specified' +err_pages_no_short_name: 'Short name not specified' +err_pages_db_err: 'Database error' + +# admin-switch +admin_title: "Admin" +as_form_password: 'Password' diff --git a/stubs/vkflex.php b/stubs/vkflex.php new file mode 100644 index 0000000..9a92533 --- /dev/null +++ b/stubs/vkflex.php @@ -0,0 +1,11 @@ +