diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..a5156fbfa --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +static/* linguist-vendored +config/* linguist-vendored +data/* linguist-vendored +files/* linguist-vendored +fileslocal/* linguist-vendored +log/* linguist-vendored +nimcache/* linguist-vendored +private/* linguist-vendored +public/* linguist-vendored +plugins/* linguist-vendored diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 000000000..497791eea --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,69 @@ + +### Bug Short Description: + +Short concise description of the problem. No narrative or conversational language. + + + +### Operating System: +*Choose 1 or more. Mark the checkbox it with an `X`.* +- [ ] GNU/Linux. +- [ ] Apple Os X. +- [ ] Microsoft Windows. +- [ ] Other or Unknown or Unsupported. + + + +### Bug Severity: +*Choose only 1. Mark the checkbox it with an `X`.* +- [ ] Low, Minor, Aesthetic, Small, Detail, Trivial. +- [ ] Medium, Normal, Standard. +- [ ] High, Important, Major. +- [ ] Critical, Catastrophic, Epic Fail. +- [ ] Other or Unknown. + + + +## Version +*Semantic Version of this software the Bug Reproduces into. Type in the Version Number* +``` + 0.0.0 +``` + + + +### Workarounds: +*Any Workarounds you have tried. Choose none or one or more. Mark the checkbox it with an `X`.* +- [ ] Uninstalling and Reinstalling, Reloading, Rebooting, Restarting, etc. +- [ ] Run as Administrator, Run as root, Run as different user, etc. +- [ ] Run on another computer, Run on a Virtual Machine, Run on another OS, etc. + + + +### Steps to reproduce: +- 1. +- 2. +- 3. +- 4. +- 5. + + + +### Actual Output: +``` +PASTE ACTUAL OUTPUT CODE HERE, TRACEBACK, CRASH, CORE DUMP, ERROR, ETC, IF ANY. +``` + + + +### Expected Output: +``` +PASTE EXPECTED OUTPUT CODE HERE, WHEN THE SOFTWARE WORKS OK, ETC, IF ANY. +``` + + + +### Screenshots or Images +*(if applicable)* + +![Screenshots_Here](https://... ) diff --git a/.github/PULL REQUEST_TEMPLATE.md b/.github/PULL REQUEST_TEMPLATE.md new file mode 100644 index 000000000..67d7200b3 --- /dev/null +++ b/.github/PULL REQUEST_TEMPLATE.md @@ -0,0 +1,40 @@ + +### Pull Request Short Description: + +Short concise description of the problem. No narrative or conversational language. + + + +### What does this implement/fix/improves? + +Explain your changes. No narrative or conversational language. + + + +### Does this close any currently open issues? +*Choose only 1. Mark the checkbox it with an `X`.* +- [ ] **No**, this does Not close any currently open issues. +- [ ] **Yes**, this close the currently open issue number: + + + +### Checklist: +*Choose 1 or more. Mark the checkbox it with an `X`.* +- [ ] Is in Sync with latest origin master branch. +- [ ] Added Examples. +- [ ] Added Unit Tests or Integration Tests or Automation Tests. +- [ ] Added Documentation or DocStrings or code comments. +- [ ] I ran the code locally, it works on my machine. + + + +### Any other comments? + +Short comments. No narrative or conversational language. + + + +### Screenshots or Images +*(if applicable)* + +![Screenshots_Here](https://... ) diff --git a/CHANGELOG.md b/CHANGELOG.md index 31f689196..639f68cf5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,16 +1,41 @@ -## v4.0.12 +## v5.0.0 ### Changes - Add Server Info page for Admins, it displays runtime server stats - Add Force Server Restart for Admins, restart on 1 second - Update Bulma version - Filter avatar image file format, because Crop thingy get buggy/slow with GIF +- 2 Factor Authentication - Add MimeType, Size, CheckSum to Files page, useful for UI/UX building - Add button to Copy all the Logs content on one click on Logs page - Add Dockerfile to the repo +- Add Vagrantfile to the repo +- Add Service file to the repo - Update Readme - Update Nimble file - First release of 2019 +### Breaking changes +- New column in `person` table: `twofa`: +```sql +ALTER TABLE person ADD COLUMN twofa varchar(60); +``` +- New column in `blog` table: `viewCount`: +```sql +ALTER TABLE blog ADD COLUMN viewCount INTEGER default 1; +``` +- New column in `blog` table: `pubDate`: +```sql +ALTER TABLE blog ADD COLUMN pubDate VARCHAR(100); +``` +- New table: `files`: +```nim +./nimwc --newdb +``` +- Dependency [firejail](https://github.com/juancarlospaco/nim-firejail), install firejail on your system +- Dependency [webp](https://github.com/juancarlospaco/nim-webp-tools), install libwebp on your system + + + ## v4.0.11 ### Changes - Remove min and max length on meta text diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 418f8c4d8..000000000 --- a/Dockerfile +++ /dev/null @@ -1,4 +0,0 @@ -FROM nimlang/nim -RUN nimble -y refresh -RUN nimble -y install nimwc@4.0.12 -RUN rm -rf /var/lib/apt/lists/* /var/tmp/* /tmp/nimblecache/ /tmp/* diff --git a/LICENSE b/LICENSE index 94a9ed024..f17901554 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,100 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +Peer Production License (PPL) + +THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS COPYFARLEFT PUBLIC LICENSE ("LICENSE"). +THE WORK IS PROTECTED BY COPYRIGHT AND ALL OTHER APPLICABLE LAWS. +ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. + +BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED IN THIS LICENSE, YOU AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. +TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN AS CONSIDERATION FOR ACCEPTING THE TERMS AND CONDITIONS OF THIS LICENSE AND FOR AGREEING TO BE BOUND BY THE TERMS AND CONDITIONS OF THIS LICENSE. + +1. Definitions + +a. "Adaptation" means a Work based upon the Work, or upon the Work and other pre-existing Works, such as a translation, adaptation, derivative Work, arrangement of music or other alterations of a literary or artistic Work, or phonogram or performance and includes cinematographic Adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a Work that constitutes a Collection will not be considered an adaptation for the purpose of this license. For the avoidance of doubt, where the Work is a musical Work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an adaptation for the purpose of this license. + +b. "Collection" means a Collection of literary or artistic Works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other Works or subject matter other than Works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent Works in themselves, which together are assembled into a collective whole. A Work that constitutes a Collection will not be considered an adaptation (as defined above) for the purposes of this license. + +c. "Distribute" means to make available to the public the original and copies of the Work or adaptation, as appropriate, through sale, gift or any other transfer of possession or ownership. + +d. "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this license. + +e. "Original Author" means, in the case of a literary or artistic Work, the individual, in dividuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic Works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast. + +f. "Work" means the literary and/or artistic Work offered under the terms of this license including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other Work of the same nature; a dramatic or dramatico-musical Work; a choreographic Work or entertainment in dumb show; a musical composition with or without words; a cinematographic Work to which are assimilated Works expressed by a process analogous to cinematography; a Work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic Work to which are assimilated Works expressed by a pro cess analogous to photography; a Work of applied art; an illustration, map, plan, sketch or three-dimensional Work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable Work; or a Work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic Work. + +g. "You" means an individual or entity exercising rights under this license who has not previously violated the terms of this license with respect to the Work, or who has received express permission from the Licensor to exercise rights under this license despite a previous violation. + +h. "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images. + +i. "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium. + +2. FAIR DEALING RIGHTS + +Nothing in this license is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws. + +3. LICENSE GRANT + +Subject to the terms and conditions of this license, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: + +a. To Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; + +b. To create and Reproduce Adaptations provided that any such adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "the original Work was translated from English to Spanish," or a modification could indicate "the original Work has been modified."; + +c. To Distribute and Publicly Perform the Work including as incorporated in Collections; and, + +d. To Distribute and Publicly Perform Adaptations. The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved, including but not limited to the rights set forth in Section 4(f). + +4. RESTRICTIONS + +The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: + +a. You may distribute or publicly perform the Work only under the terms of this license. You must include a copy of, or the uniform resource identifier (uri) for, this license with every copy of the Work You distribute or publicly perform. You may not offer or impose any terms on the Work that restrict the terms of this license or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the license. You may not sublicense the Work. You must keep intact all notices that refer to this license and to the disclaimer of warranties with every copy of the Work You distribute or publicly perform. When You distribute or publicly perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the license. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this license. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(d), as requested. If You create an adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the adaptation any credit as required by Section 4(d), as requested. + +b. Subject to the exception in Section 4(c), You may not exercise any of the rights granted to You in Section 3 above in any manner that is primarily intended for or directed to ward commercial advantage or private monetary compensation. The exchange of the Work for other copyrighted Works by means of digital filesharing or otherwise shall not be considered to be intended for or directed toward commercial advantage or private monetary compensation, provided there is no payment of any monetary compensation in connection with the exchange of copyrighted Works. + +c. You may exercise the rights granted in Section 3 for commercial purposes only if: + +i. You are a Worker-owned business or Worker-owned collective; and + +ii. All financial gain, surplus, profits and benefits produced by the business or collective are distributed among the Workerowners + +d. Any use by a business that is privately owned and managed, and that seeks to generate profit from the labor of employees paid by salary or other wages, is not permitted under this license. + +e. If You distribute, or publicly perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("attribution parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reason ably practicable, the uri, if any, that Licensor specifies to be associated with the Work, unless such uri does not refer to the copyright notice or licensing information for the Work; and, (iv) consistent with Section 3(b), in the case of an adaptation, a credit identifying the use of the Work in the adaptation (e.g., "french translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(d) may be implemented in any reasonable manner; provided, however, that in the case of a adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this license, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or attribution parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or attribution parties. + +f. For the avoidance of doubt: + +i. Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can not be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this license; + +ii. Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this license if Your exercise of such rights is for a purpose or use which is otherwise than noncommercial as permitted under Section 4(b) and otherwise waives the right to collect royalties through any statutory or compulsory licensing scheme; and, + +iii. Voluntary License Schemes. The Licensor reserves the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this license that is for a purpose or use which is otherwise than noncommercial as permitted under Section 4(b). + +g. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, distribute or publicly perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this license (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this license (right to make Adaptations) but not otherwise. + +5. REPRESENTATIONS, WARRANTIES AND DISCLAIMER + +UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. + +6. LIMITATION ON LIABILITY + +EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POS SIBILITY OF SUCH DAMAGES. + +7. TERMINATION + +a. This license and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this license. Individuals or entities who have received Adaptations or Collections from You under this license, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this license. + +b. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this license (or any other license that has been, or is required to be, granted under the terms of this license), and this license will continue in full force and effect unless terminated as stated above. + +8. MISCELLANEOUS + +a. Each time You distribute or publicly perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this license. + +b. Each time You distribute or publicly perform an adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this license. + +c. If any provision of this license is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this license, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. + +d. No term or provision of this license shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. + +e. This license constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This license may not be modified without the mutual written agreement of the Licensor and You. + +f. The rights granted under, and the subject matter referenced, in this license were draft ed utilizing the terminology of the berne convention for the protection of literary and artistic Works (as amended on september 28, 1979), the rome convention of 1961, the wipo copyright treaty of 1996, the wipo performances and phonograms treaty of 1996 and the universal copyright convention (as revised on july 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the license terms are sought to be enforced according to the corresponding provisions of the implemen tation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this license, such additional rights are deemed to be included in the license; this license is not intended to restrict the license of any rights under applicable law. diff --git a/README.md b/README.md index 3fba2d241..ad02863f4 100644 --- a/README.md +++ b/README.md @@ -5,40 +5,103 @@ A quick website tool. Run the nim file and access your webpage. Website: [https: -## Main features: - -- Webserver hosting your page on 127.0.0.1:7000 -- Edit your pages with Summernote, raw HTML (CodeMirror) or drag'n'drop with GrapesJS -- Blog - add and edit blog posts -- Pages - add and edit pages -- Custom head, navbar and footer -- Custom title, meta description and keywords for each page -- Edit core or custom js- and css-files -- Upload files (private or public) +# Features + +## Blogs and pages +- 1 Click Blogging posts directly from browser. +- 1 Click Static web pages directly from browser. +- WYSIWYG & Drag'n'Drop Editors with [Summernote](https://summernote.org), [CodeMirror](https://codemirror.net) or [GrapesJS](https://grapesjs.com). +- Custom title, meta description and keywords for each page, SEO friendly. +- Custom head, navbar and footer, no hardcoded watermarks, links or logos. +- Upload files and images (private or public) directly from browser. +- 1 language for the whole stack, including high performance modules, scripting, devops, deploy, from WebAssembly to Assembly. + +## Security +- Self-Firejailing Web Framework (It Firejails itself) Best Linux Security integrated on the Core. +- 2 Factor Athentication TOTP +- ReCAPTCHA +- HoneyPot-Field +- BCrypt+Salt password hashing +- SQL Type-checked and Query-checked at compile-time, no SQL injections. +- Multiple users with different ranks, role based access control. +- Admin can choose how much CPU & RAM NimWC can use from the Admin Dashboard. +- [We recommend FreeOTP 2 Factor Athentication App because is Open Source.](https://freeotp.github.io) + +## Configuration +- Edit core or custom JS and CSS directly from browser, UI/UX Designer friendly. - Log Viewer directly from browser. - Auto-Rotating file Logger. -- Uses responsive Bulma CSS framework, supports Bootstrap CSS framework. -- JavaScript framework agnostic, use Nim, Karax, vanilla JS, you choose. +- Server Info Page for Admins. +- Force Server restart for Admins. +- Edit main config file directly from browser +- Recompilation without down times. +- Webserver hosting your page on 127.0.0.1:7000 - Colored output on the Terminal. -- Plugin skeleton creator. -- Multiple users -- Add plugins +- Email notification on critical errors. + +## Plugins +- Plugin Store integrated +- Enable and disable plugins directly from browser. Open Source or Private Plugins. +- Plugin skeleton creator to create your own new plugins. +- Plugins can do anything you want on Frontend and Backend. +- Develop your own plugins - [NimWC plugin repository](https://github.com/ThomasTJdev/nimwc_plugins) + +## Database +- [Postgres](https://www.postgresql.org) (if you are using the NimWC docker file, you do not need to install Postgres) +- SQLite + +## Performance +- High performance with low resources (RPi, VPS, cloud, old pc, etc). +- Runs on any non-Windows OS, Architecture and Hardware that can compile C code. +- [Independent TechEmpower Benchmarks show Nim web server as one of the fastest in the world.](https://www.techempower.com/benchmarks/#section=data-r17&hw=cl&test=json) +- High Availability design by default. +- Full Stack with the same programming language, including DevOps and Scripting. +- 0 Dependency binary (Postgres/SSL/WebP/Firejail required if using it). +- No `/node_modules/`, but very powerful builtin Templating engine. +- Compile-Time precomputed arbitrary function execution is used when possible. +- No Global Interpreter Lock, no single-Thread, no single-Core, no Interpreter. Use all your 32 CPU Cores. + +## Responsive +- Uses responsive [Bulma CSS framework](https://bulma.io), supports [Bootstrap CSS framework](https://getbootstrap.com). +- JavaScript framework agnostic, use Nim, [Karax](https://github.com/pragmagic/karax), vanilla JS, you choose. + +## Other +- [WebP](https://caniuse.com/#feat=webp) automatic Image and Photo Optimizations. +- [NGINX Config](https://github.com/ThomasTJdev/nim_websitecreator/tree/master/devops/) template. +- [SystemD Service](https://github.com/ThomasTJdev/nim_websitecreator/tree/master/devops/) template. +- [Vagrantfile](https://github.com/ThomasTJdev/nim_websitecreator/tree/master/devops/) template. +- [Dockerfile](https://github.com/ThomasTJdev/nim_websitecreator/tree/master/devops/) template. + + +# Requirements + +To get started you only need: + +- Linux (For Windows [see Docker-for-Windows](http://docs.docker.com/docker-for-windows)) +- Nim >= `0.19.2` +
-## Requirements +Development Dependencies (automatically installed by Nimble): + +- Jester >= `0.4.1` +- reCAPTCHA >= `1.0.2` +- bCrypt >= `0.2.1` +- datetime2human >= `0.2.2` +- otp >= `0.1.1` +- firejail >= `0.4.0` +- webp >= `0.1.0` -- Linux -- Nim >= `0.19.2` -- Nim modules (automated when using Nimble): - - jester >= `0.4.1` - - reCAPTCHA >= `1.0.2` - - bcrypt >= `0.2.1` +
-# Compiling / Installing + +# Install ## Install Nim + To compile and install you need [Nim](https://nim-lang.org/). You can easily install Nim using [choosenim](https://nim-lang.org/install_unix.html) with: + ``` curl https://nim-lang.org/choosenim/init.sh -sSf | sh ``` @@ -48,8 +111,9 @@ curl https://nim-lang.org/choosenim/init.sh -sSf | sh You only need to perform 1a **or** 1b - not both of them. -### 1a) Install: +### 1a) Install +
If you are using [Nimble](https://github.com/nim-lang/nimble) an executable will be generated and symlinked to `nimwc`, which then can be executed anywhere on your system. ```bash @@ -68,9 +132,12 @@ nimwc # Login 127.0.0.1:7000/login ``` +
-### 1b) Compile: +### 1b) Compile + +
This will generate the executable in the folder. @@ -95,8 +162,12 @@ nim c -d:ssl nimwc.nim 127.0.0.1:7000/login ``` +
+ + +# Use -## Argument (args): +## Arguments These arguments should be prepended to executable file, e.g. `./nimwc cdata` @@ -122,6 +193,7 @@ These options are only available at compiletime: * `-d:devemailon` = Send email when `-d:dev` is activated * `-d:demo` = Used on public test site [Nim Website Creator](https://nimwc.org). This option will override the database each hour with the standard data. * `-d:gitupdate` = Updates and force a hard reset +* `-d:postgres` = Use Postgres database instead of SQLite # User profiles @@ -133,6 +205,8 @@ There are 3 main user profiles: The access rights below applies to main program. Plugins can have their own definition of user rights. +
+ ## User The "User" can login and see private pages and blog pages. This user has no access to adding or editing anything. @@ -145,6 +219,8 @@ The "Moderator" can login and see private pages and blog pages. The user **can** The "Admin" has access to anything. +
+ # Blog You can easily add and edit blogpages. The blogpages support metadata: meta description and meta keywords. It is also possible to specify a category and tags. @@ -174,35 +250,45 @@ The plugin repository are located here: [NimWC plugin repository](https://github When editing a blogpage or a normal page press Ctrl+S to save. -# Google reCAPTCHA + +# GrapesJS + +GrapesJS is a Web Builder Framework. To use GrapeJS with a CSS framework (Bulma or Bootstrap), you have to edit `public/js/grapejs_custom.js` and `public/js/grapejsbs4.min.js`. Bootstrap support in `public/js/grapejs_custom.js` is commented out. + + +# DevOps + +
+ Docker, Vagrant, SystemD Service, NGNIX, Admin stuff, etc + +**Docker** + +- [Use the Dockerfile](https://github.com/ThomasTJdev/nim_websitecreator/blob/master/devops/Dockerfile) as starting point for your NimWC containers. + + +**Vagrant** + +- [Use the Vagrantfile](https://github.com/ThomasTJdev/nim_websitecreator/blob/master/devops/Vagrantfile) as starting point for your NimWC VMs. + + +**NGNIX Config** + +- [Use the NGNIX Config file](https://github.com/ThomasTJdev/nim_websitecreator/blob/master/devops/config_nginx_default.cfg) as starting point for your NGNIX Server configuration. + + +**Google reCAPTCHA** To activate Google reCAPTCHA [claim you site and server key](https://www.google.com/recaptcha/admin) and insert them into `config.cfg`. -# Autorun - systemctl -## Service file +**SystemD** -Create a new file called nimwc.service inside /lib/systemd/system/: -``` -sudo nano /lib/systemd/system/nimwc.service -``` +- [Use the SystemD Service file](https://github.com/ThomasTJdev/nim_websitecreator/blob/master/devops/nimwc.service) as starting point for your NimWC SystemD Services. + +Copy the file called `nimwc.service` inside `/lib/systemd/system/` -Add the following to the file: ``` -[Unit] -Description=nimwc -After=network.target - -[Service] -User=ubuntu # MODIFY to your username -Type=simple -WorkingDirectory=/home//.nimble/pkgs/nimwc-2.0.0/ # MODIFY to your installation path -ExecStart=/home//.nimble/pkgs/nimwc-2.0.0/nimwc # MODIFY to your installation path -Restart=always -RestartSec=3 - -[Install] -WantedBy=multi-user.target +sudo nano /lib/systemd/system/nimwc.service ``` ## Enable auto start and start it: @@ -212,14 +298,43 @@ sudo systemctl start nimwc sudo systemctl status nimwc ``` -# GrapesJS -GrapesJS is a Web Builder Framework. To use GrapeJS with a CSS framework (Bulma or Bootstrap), you have to edit `public/js/grapejs_custom.js` and `public/js/grapejsbs4.min.js`. Bootstrap support in `public/js/grapejs_custom.js` is commented out. -# Trouble +
+ + +# How to Firejail + +
+ +- Default settings will work Ok on most systems, sane defaults. +- Some settings are kind of technical, you should know some Linux Kernel related stuff. +- Links are provided on the Firejail config page when makes sense. +- You can harden your system even more by tweaking the Firejail config. +- You can always come back to the default settings and it will work Ok. +- Check that Firejail Status at bottom of the page is mostly green. + +You can choose how much CPU & RAM NimWC can use, +Firejail will make NimWC believe that theres less CPU & RAM that the actually physically available. +If you choose too small resources for too big load, +then it will feel like when you try to run a heavy program on a VirtualBox with too small CPU & RAM, +but will still run, or do the best to try to run. +This can be useful for Clouds that charge you extra when you pass certain threshold of CPU & RAM usage. + +NimWC does not depend on any Hardware device to run, like audio, video, USB, DVD, etc, +so you can block the access to the hardware peripehals, +that also blocks its hardware drivers and libraries that may have vulnerabilities, making your NimWC more secure. + +Theres options to block root user and the rest of the users on the Linux system, +thats help protect your NimWC agaisnt Privilege Scalations, +thats when an unprivileged normal user becomes superuser root, or an user can see other users stuff. -Remove `nimcache` and `nimwcpkg/nimcache` and re-compile +Caches and Temporary directories are mounted as private temporary unique autogenerated TMPFS, +meaning that the real ones can not be altered from within NimWC. +The features come from the Linux Kernel itself, +so theres zero cost on performance and the technology is already there even if you use it or not. -# Docker +So in conclusion NimWC being compiled binary wont need access to most of your system, +just its own folder, the integration with Firejails hides everything else. -- [Use the Dockerfile](https://github.com/ThomasTJdev/nim_websitecreator/blob/master/Dockerfile) as starting point for your NimWC containers. +
diff --git a/config/config_default.cfg b/config/config_default.cfg index a0e05043f..002f9d8ca 100644 --- a/config/config_default.cfg +++ b/config/config_default.cfg @@ -1,9 +1,10 @@ [Database] -folder = "data" -host = "data/website.db" -name = "website" +folder = "data" # Not relevant when using Postgres +host = "data/website.db" # Postgres example: localhost +name = "website" # Database name user = "user" pass = "" +port = 5432 [Storage] storagedev = "fileslocal" @@ -16,8 +17,8 @@ logfile = "log/log.log" [Server] website = "https://nimwc.org" # Pretty url title = "Nim Website Creator" -url = "127.0.0.1" # Where is jester binding the webserver -port = "7000" +url = "127.0.0.1" # Where jester is binding the webserver +port = 7000 # The port jester uses [Proxy] url = "/" @@ -35,3 +36,40 @@ SMTPPassword = "" SMTPFrom = "" SMTPEmailAdmin = "" SMTPEmailSupport = "" + +[firejail] +noDvd=true +noSound=true +noAutoPulse=true +no3d=true +noX=true +noVideo=true +noDbus=true +noDebuggers=true +noMachineId=true +noRoot=true +noAllusers=true +noU2f=true +privateTmp=true +privateCache=true +privateDev=true +noShell=true +forceEnUsUtf8=true +caps=true +seccomp=true +noTv=true +writables=true +noMnt=true +maxSubProcesses=0 +maxOpenFiles=0 +maxFileSize=0 +maxPendingSignals=0 +timeout=0 +maxCpu=0 +maxRam=0 +cpuCoresByNumber=0 +hostsFile=/etc/hosts +dns0="" +dns1="" +dns2="" +dns3="" diff --git a/devops/Dockerfile b/devops/Dockerfile new file mode 100644 index 000000000..f370c28ff --- /dev/null +++ b/devops/Dockerfile @@ -0,0 +1,12 @@ +FROM archlinux/base +RUN export CHOOSENIM_NO_ANALYTICS=1 ; export PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH ; echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> ~/.profile ; echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> ~/.bashrc ; echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> /root/.profile ; echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> /root/.bashrc ; source /root/.bashrc +RUN pacman -Syu --needed --noconfirm --quiet git pacman-contrib base-devel libwebp firejail +RUN curl -sfk https://nim-lang.org/choosenim/init.sh > init.sh && sh init.sh -y +RUN /root/.nimble/bin/nimble -y refresh +# RUN nimble -y install nimwc@4.5.0 +# RUN /root/.nimble/bin/nimble -y install nimwc@4.0.12 +RUN git clone https://github.com/ThomasTJdev/nim_websitecreator.git && cd nim_websitecreator +# RUN /root/.nimble/bin/nim c -d:release -d:ssl -d:sqlite --passL:"-s" /root/nim_websitecreator/nimwc.nim +RUN rm -rf /var/lib/apt/lists/* /var/tmp/* /tmp/nimblecache/* /tmp/* /var/log/journal/* +EXPOSE 5000 +EXPOSE 7000 diff --git a/devops/Vagrantfile b/devops/Vagrantfile new file mode 100644 index 000000000..705326ee6 --- /dev/null +++ b/devops/Vagrantfile @@ -0,0 +1,106 @@ +# -*- mode: ruby -*- +# vi: set ft=ruby : + + +ENV["LC_ALL"] = "en_US.UTF-8" # This Locale will be shared on Host and Guest. + +VAGRANTFILE_API_VERSION = "2" # Vagrantfile API/syntax version. Dont touch. + + +$script = <<-SCRIPT + +echo Updating and Upgrading Pacman... +yes | pacman -Syuu --needed + +echo Installing Database Server... +pacman -Syu --needed --noconfirm --quiet git pacman-contrib base-devel libwebp firejail + +echo Installing Nim with ChooseNim... +export CHOOSENIM_NO_ANALYTICS=1 +export PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH +echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> ~/.profile +echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> ~/.bashrc +echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> /root/.profile +echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> /root/.bashrc +source /root/.bashrc +curl -sfk https://nim-lang.org/choosenim/init.sh > init.sh +sh init.sh -y + +echo Updating Nimble... +nimble -y refresh + +echo Installing Nim Website Creator... +git clone https://github.com/ThomasTJdev/nim_websitecreator.git +cd nim_websitecreator +nim c -d:release -d:ssl -d:sqlite --passL:"-s" nimwc.nim + +echo Clean out... +yes | pacman -Scc +rm -rf /var/lib/apt/lists/* /var/tmp/* /tmp/nimblecache/* /tmp/* /var/log/journal/* + +SCRIPT + + +Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| + + # Every Vagrant requires a box. See list http://vagrantbox.es + config.vm.box = "archlinux/archlinux" + + # If true, then any SSH connections made will enable agent forwarding. + config.ssh.forward_agent = true + + # Check for updates of the box on every boot. + config.vm.box_check_update = true + + # Check SSL certificates of the server. + config.vm.box_download_insecure = true + + # Checks all HTTP redirects, will be treated as trusted. + config.vm.box_download_location_trusted = true + + # Time in seconds that Vagrant will wait for the machine to gracefully halt. + config.vm.graceful_halt_timeout = 5 + + # The hostname the virtual machine should have. + config.vm.hostname = "nim" + + # Post boot up message. + config.vm.post_up_message = "Nim Website Creator Vagrant Box http://nimwc.org" + + # Simple Bash Shell Provider, more than enough for Nim. + config.vm.provision "shell", inline: $script + + # Create a forwarded port mapping which allows access to a specific port + # within the machine from a port on the host machine. In the example below, + # accessing "localhost:8080" will access port 80 on the guest machine. + # config.vm.network "forwarded_port", guest: 80, host: 8080 + + # Create a private network, which allows host-only access to the machine + # using a specific IP. + # config.vm.network "private_network", ip: "192.168.33.10" + # config.vm.network :private_network, ip: "192.168.58.111" + + # Create a public network, which generally matched to bridged network. + # Bridged networks make the machine appear as another physical device on + # your network. + # config.vm.network "public_network" + + # Share an additional folder to the guest VM. The first argument is + # the path on the host to the actual folder. The second argument is + # the path on the guest to mount the folder. And the optional third + # argument is a set of non-required options. + # config.vm.synced_folder "../data", "/vagrant_data" + + config.vm.provider :virtualbox do |vb| + # Boot with headless mode or not. + vb.gui = false + + # Use VBoxManage to customize the VM. For example to change memory: + vb.customize [ + 'modifyvm', :id, + '--natdnshostresolver1', 'on', + '--memory', '1024', + '--cpus', '2' + ] + end +end diff --git a/devops/build_docker.sh b/devops/build_docker.sh new file mode 100755 index 000000000..3c16f24a0 --- /dev/null +++ b/devops/build_docker.sh @@ -0,0 +1,2 @@ +#!/bin/bash +docker build -t nimwc:1.0 . # Build a Docker from the Dockerfile. diff --git a/config/config_nginx_default.cfg b/devops/config_nginx_default.cfg similarity index 89% rename from config/config_nginx_default.cfg rename to devops/config_nginx_default.cfg index ccf388b72..edb7acba4 100644 --- a/config/config_nginx_default.cfg +++ b/devops/config_nginx_default.cfg @@ -1,4 +1,5 @@ # Template for nginx configuration sites-available/default +# Check if the config is valid using: nginx -t YourConfig.cfg # To use SSL Let's Encrypt, install certbot and run: # $sudo certbot --nginx -d webpage.com www.webpage.com @@ -18,7 +19,7 @@ server { location / { root /home/user/nim/nimwc/public; - if ($request_uri ~* ".(ico|css|js|gif|jpe?g|png|svg)$") { + if ($request_uri ~* ".(ico|css|js|gif|jpeg|jpg|png|svg|bmp|webp)$") { expires max; access_log off; add_header Pragma public; @@ -36,4 +37,4 @@ server { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } -} \ No newline at end of file +} diff --git a/devops/nimwc.desktop b/devops/nimwc.desktop new file mode 100644 index 000000000..1ba469ec6 --- /dev/null +++ b/devops/nimwc.desktop @@ -0,0 +1,12 @@ +[Desktop Entry] +Comment=Nim Website Creator +Exec=nimwc +GenericName=Nim Website Creator +Icon=system-run +Name=nimwc +StartupNotify=false +Terminal=true +Type=Application +Categories=Utility +X-DBUS-ServiceName=nimwc +X-KDE-StartupNotify=false diff --git a/devops/nimwc.service b/devops/nimwc.service new file mode 100644 index 000000000..384c7cdfc --- /dev/null +++ b/devops/nimwc.service @@ -0,0 +1,25 @@ +[Unit] +Description=Nim Website Creator SystemD Service +Documentation=https://github.com/ThomasTJdev/nim_websitecreator#nim-website-creator +After=network-online.target # postgres.service + +[Service] +Type=simple +User=nobody # Change to your user. +Restart=always # on-failure +RestartSec=1 # Sleep Seconds before restarting the process. +RuntimeMaxSec=1w # Restart process periodically. 1w=week, 1d=day, 1m=minute. +TimeoutStartSec=999 # Timeout Seconds while starting the process. +TimeoutStopSec=999 # Timeout Seconds while stopping the process. +# ExecStartPre= # Execute BEFORE start. +ExecStart=nimwc # Execute your nimwc command. +# ExecStartPost= # Execute AFTER start. +# ExecReload= # Execute while restarting the process. +# ExecStop= # Execute while stopping the process. +# ExecStopPost= # Execute AFTER stopping the process. +# Environment= # You can add any Environment variables here. +WorkingDirectory=/home//.nimble/pkgs/nimwc-5.0.0/ # MODIFY to your installation path +ExecStart=/home//.nimble/bin/nimwc + +[Install] +WantedBy=multi-user.target diff --git a/devops/run_docker.sh b/devops/run_docker.sh new file mode 100755 index 000000000..ea6491eb5 --- /dev/null +++ b/devops/run_docker.sh @@ -0,0 +1,2 @@ +#!/bin/bash +docker run --rm -i -t -w /tmp -p 5000:5000 nimwc:1.0 # Run docker. diff --git a/nimwc.nim b/nimwc.nim index 42b48d6f7..a626a4dd8 100644 --- a/nimwc.nim +++ b/nimwc.nim @@ -1,5 +1,11 @@ import os, osproc, rdstdin, sequtils, strutils, terminal, times, json -{.passL: "-s".} # Force strip all on the resulting Binary, so its smaller. + +when not defined(firejail): {.warning: "Firejail is Disabled, Running Unsecure.".} +else: import firejail, parsecfg + +when defined(windows): + {.fatal: "Cannot run on Windows, but you can try Docker for Windows: http://docs.docker.com/docker-for-windows".} +when defined(release): {.passL: "-s".} # Force strip all on the resulting Binary. const update_cmds = [ @@ -15,41 +21,43 @@ const "mv tmp/js_custom.js plugins/js/js_custom.js", ] ## Bash Commands to Update NimWC. - compile_start_msg = """Compiling, Please wait... - - Using compile options from *.nim.cfg - - Using params: """ ## Message to show when started Compiling. + compile_start_msg = """⏰ Compiling, Please wait ⏰ + ☑️ Using compile options from *.nim.cfg + ☑️ Using params: """ ## Message to show when started Compiling. - compile_ok_msg = """Compiling done!. + compile_ok_msg = """ Nim Website Creator Compiled Ok! - - To start Nim Website Creator and access at http://127.0.0.1: - # Manually compiled - ./nimwc + ☑️️ To start Nim Website Creator and access at http://127.0.0.1: + # Manually compiled + ./nimwc - # Through nimble, then just run with symlink - nimwc + # Through nimble, then just run with symlink + nimwc - - To add an admin user, append args: - ./nimwc newuser -u:name -p:password -e:email + ☑️ To add an admin user, append args: + ./nimwc newuser -u:name -p:password -e:email - - To insert standard data in the database, append args: - ./nimwc insertdata + ☑️ To insert standard data in the database, append args: + ./nimwc insertdata - - To insert standard data in the database: - ./nimwc --insertdata + ☑️ To insert standard data in the database: + ./nimwc --insertdata - - Access Settings page at http://127.0.0.1:/settings + ☑️ Access Settings page at http://127.0.0.1:/settings """ ## Message to show when finished Compiling OK. - compile_fail_msg = """Compiling Failed. + compile_fail_msg = """ Compile Error - - A Compile-time or Configuration error occurred. - You can check your source code with: nim check - Check the Configuration of NimWC and its Plugins. + ⚠️ Compile-time or Configuration or Plugin error occurred. + ➡️ You can check your source code with: nim check YourFile.nim + ➡️ Check the Configuration of NimWC and its Plugins. + ➡️ Remove new Plugins, restore previous Configuration. + Check that you have the latest Version. Check the Documentation. """ ## Message to show when Compiling Failed. - doc = """ - nimwc: Nim Website Creator. - A quick website tool. Run the nim file and access your webpage. + doc = """ Nim Website Creator - https://NimWC.org + Self-Firejailing 2-Factor-Auth Nim Web Framework thats simple to use. + Run it, access your web, customize, add plugins, deploy today anywhere. Usage: nimwc @@ -60,41 +68,50 @@ const -u: -p: -e:` - --insertdata Insert standard data (this will override existing data). - bulma - standard data based on Bulma - bootstrap - standard data based on Bootstrap - clean - standard data without a CSS/JS framework - --newdb Generates the database with standard tables (does **not** - override or delete tables). `newdb` will be initialized - automatic, if no database exists. + --insertdata Insert standard data (override existing data). + bulma - standard data based on Bulma + bootstrap - standard data based on Bootstrap + clean - standard data without a CSS/JS framework + --newdb Generates the database with standard tables + (does NOT override or delete tables). + newdb will be initialized automatic, if no database exists. --gitupdate Updates and force a hard reset. --initplugin Create plugin skeleton inside tmp/ Compile options: - -d:rc Recompile. NinmWC is using a launcher, it is therefore - needed to force a recompile. - -d:adminnotify Send error logs (ERROR) to the specified admin email - -d:dev Development (ignore reCaptcha) - -d:devemailon Send email when `-d:dev` is activated - -d:demo Used on public test site. Enables a test user. - This option will override the database each hour with - the standard data. - -d:gitupdate Updates and force a hard reset + -d:sqlite SQLite Dabatase is enabled. Postgres dabatase is disabled. + -d:firejail Firejail is enabled. Runs secure. + -d:webp WebP is enabled. Optimize images. + -d:rc Force Recompile (good for Troubleshooting). + -d:adminnotify Send error logs (ERROR) to the specified Admin email. + -d:dev Development (ignore reCaptcha, no emails, more Verbose). + -d:devemailon Send email when -d:dev is activated. + -d:demo Public demo mode. Enable Test user. 2FA ignored. + Force database reset every 1 hour. Some options Disabled. + -d:gitupdate Force update from Git and force a hard reset. + + Tips: + Always Compile with -d:release for Production. We recommend Firejail too. + Learn more: http://nim-lang.org/learn.html http://nim-lang.github.io/Nim/lib.html """ compileOptions = ["", when defined(adminnotify): " -d:adminnotify", - when defined(dev): " -d:dev", - when defined(devemailon): " -d:devemailon", - when defined(demo): " -d:demo", - when defined(ssl): " -d:ssl", + when defined(dev): " -d:dev", + when defined(devemailon): " -d:devemailon", + when defined(demo): " -d:demo", + when defined(ssl): " -d:ssl", + when defined(postgres): " -d:postgres", + when defined(webp): " -d:webp", + when defined(firejail): " -d:firejail", + when defined(release): " -d:release" ].join ## Checking for known compile options and returning them as a space separated string at Compile-Time. See README.md for explanation of the options. nimwc_version = try: filter_it("nimwc.nimble".readFile.splitLines, it.substr(0, 6) == "version")[0].split("=")[1].normalize ## Get NimWC Version at Compile-Time. except: - "4.0.12" ## Set NimWC Version at Compile-Time, if ready from file failed. + "5.0.0" ## Set NimWC Version at Compile-Time, if ready from file failed. var @@ -113,7 +130,7 @@ proc handler() {.noconv.} = ## Catch ctrl+c from user runInLoop = false kill(nimhaMain) - styledEcho(fgYellow, bgBlack, "CTRL+C Pressed, NimWC is shutting down.") + styledEcho(fgYellow, bgBlack, "CTRL+C Pressed, NimWC is shutting down, Bye.") quit() setControlCHook(handler) @@ -123,9 +140,64 @@ proc launcherActivated() = ## 1) Executing the main-program in a loop. ## 2) Each time a new compiled file is available, ## the program exits the running process and starts a new - styledEcho(fgGreen, bgBlack, $now() & ": Nim Website Creator: Launcher initialized") - - nimhaMain = startProcess(getAppDir() & "/nimwcpkg/nimwc_main" & userArgsRun, options = {poParentStreams, poEvalCommand}) + styledEcho(fgGreen, bgBlack, $now() & ": Nim Website Creator: Launcher starting.") + var nimwcCommand: string + + when not defined(firejail): + nimwcCommand = getAppDir() & "/nimwcpkg/nimwc_main" & userArgsRun + else: + let + dict = loadConfig(getAppDir() & "/config/config.cfg") + cpuCores = dict.getSectionValue("firejail", "cpuCoresByNumber").parseInt + corez = if cpuCores != 0: toSeq(0..cpuCores) else: @[] + hostz = dict.getSectionValue("firejail", "hostsFile").strip + dnsz = [dict.getSectionValue("firejail", "dns0").strip, dict.getSectionValue("firejail", "dns1").strip, + dict.getSectionValue("firejail", "dns2").strip, dict.getSectionValue("firejail", "dns3").strip] + assert countProcessors() > cpuCores, "Dedicated CPU Cores must be less or equal than the actual CPU Cores: " & $cpuCores + assert hostz.existsFile, "Hosts file not found: " & hostz + let myjail = Firejail( + noDvd: dict.getSectionValue("firejail", "noDvd").parseBool, + noSound: dict.getSectionValue("firejail", "noSound").parseBool, + noAutoPulse: dict.getSectionValue("firejail", "noAutoPulse").parseBool, + no3d: dict.getSectionValue("firejail", "no3d").parseBool, + noX: dict.getSectionValue("firejail", "noX").parseBool, + noVideo: dict.getSectionValue("firejail", "noVideo").parseBool, + noDbus: dict.getSectionValue("firejail", "noDbus").parseBool, + noShell: dict.getSectionValue("firejail", "noShell").parseBool, + noDebuggers: dict.getSectionValue("firejail", "noDebuggers").parseBool, + noMachineId: dict.getSectionValue("firejail", "noMachineId").parseBool, + noRoot: dict.getSectionValue("firejail", "noRoot").parseBool, + noAllusers: dict.getSectionValue("firejail", "noAllusers").parseBool, + noU2f: dict.getSectionValue("firejail", "noU2f").parseBool, + privateTmp: dict.getSectionValue("firejail", "privateTmp").parseBool, + privateCache: dict.getSectionValue("firejail", "privateCache").parseBool, + privateDev: dict.getSectionValue("firejail", "privateDev").parseBool, + forceEnUsUtf8: dict.getSectionValue("firejail", "forceEnUsUtf8").parseBool, + caps: dict.getSectionValue("firejail", "caps").parseBool, + seccomp: dict.getSectionValue("firejail", "seccomp").parseBool, + noTv: dict.getSectionValue("firejail", "noTv").parseBool, + writables: dict.getSectionValue("firejail", "writables").parseBool, + noMnt: dict.getSectionValue("firejail", "noMnt").parseBool, + ) + nimwcCommand = myjail.makeCommand( + command=getAppDir() & "/nimwcpkg/nimwc_main" & userArgsRun, + name="nimwc_main", # whitelist= @[getAppDir(), getCurrentDir()], + maxSubProcesses = dict.getSectionValue("firejail", "maxSubProcesses").parseInt * 1_000_000, # 1 is Ok, 0 is Disabled, int.high max. + maxOpenFiles = dict.getSectionValue("firejail", "maxOpenFiles").parseInt * 1_000, # Below 1000 NimWC may not start. + maxFileSize = dict.getSectionValue("firejail", "maxFileSize").parseInt * 1_000_000_000, # Below 1Mb NimWC may not start. + maxPendingSignals = dict.getSectionValue("firejail", "maxPendingSignals").parseInt * 10, # 1 is Ok, 0 is Disabled, int.high max. + timeout = dict.getSectionValue("firejail", "timeout").parseInt, # 1 is Ok, 0 is Disabled, 255 max. It will actually Restart instead of Stopping. + maxRam = dict.getSectionValue("firejail", "maxRam").parseInt * 1_000_000_000, # Below 1Gb NimWC may fail. + maxCpu = dict.getSectionValue("firejail", "maxCpu").parseInt, # 1 is Ok, 0 is Disabled, 255 max. + cpuCoresByNumber = corez, # 0 is Disabled, else toSeq(0..corez) + hostsFile = hostz, # Optional Alternative/Fake /etc/hosts + dnsServers = dnsz, # Optional Alternative/Fake DNS, 4 Servers must be provided + ) + + const processOpts = + when defined(release): {poParentStreams, poEvalCommand} + else: {poParentStreams, poEvalCommand, poEchoCmd} + nimhaMain = startProcess(nimwcCommand, options = processOpts) while runInLoop: if fileExists(getAppDir() & "/nimwcpkg/nimwc_main_new"): @@ -133,7 +205,7 @@ proc launcherActivated() = moveFile(getAppDir() & "/nimwcpkg/nimwc_main_new", getAppDir() & "/nimwcpkg/nimwc_main") if not running(nimhaMain): - styledEcho(fgYellow, bgBlack, $now() & ": Restarting program in 1 second") + styledEcho(fgYellow, bgBlack, $now() & ": Restarting in 1 second.") discard execCmd("pkill nimwc_main") sleep(1000) @@ -141,11 +213,11 @@ proc launcherActivated() = if userArgsRun != "": styledEcho(fgGreen, bgBlack, " Using args: " & userArgsRun) - nimhaMain = startProcess(getAppDir() & "/nimwcpkg/nimwc_main" & userArgsRun, options = {poParentStreams, poEvalCommand}) + nimhaMain = startProcess(nimwcCommand, options = processOpts) sleep(2000) - styledEcho(fgYellow, bgBlack, $now() & ": Nim Website Creator: Quitted") + styledEcho(fgYellow, bgBlack, $now() & ": Nim Website Creator: Stopping.") quit() @@ -168,7 +240,7 @@ proc updateNimwc() = if "gitupdate" in commandLineParams() or defined(gitupdate): discard existsOrCreateDir("tmp") for comand in update_cmds: - discard execCmd(comand) + discard execCmd(comand) styledEcho(fgGreen, bgBlack, "\n\nNimWC has been updated\n\n") quit() diff --git a/nimwc.nim.cfg b/nimwc.nim.cfg index 521e21de4..bf4a9fce1 100644 --- a/nimwc.nim.cfg +++ b/nimwc.nim.cfg @@ -1 +1,3 @@ -d:ssl +-d:firejail +-d:webp diff --git a/nimwc.nimble b/nimwc.nimble index d06fbbea1..dbe0d7fec 100644 --- a/nimwc.nimble +++ b/nimwc.nimble @@ -1,19 +1,23 @@ # Package -version = "4.0.12" -author = "Thomas T. Jarløv (https://github.com/ThomasTJdev)" +version = "5.0.0" +author = "Thomas T. Jarløv (https://github.com/ThomasTJdev) & Juan Carlos (https://github.com/juancarlospaco)" description = "Generate and host a website. Run the package and access your new webpage." license = "GPLv3" bin = @["nimwc"] -skipDirs = @["private", "tmp"] +skipDirs = @["private", "tmp", "devops"] installDirs = @["config", "nimwcpkg", "plugins", "public"] # Dependencies -requires "nim >= 0.19.2" +requires "nim >= 0.19.4" requires "jester >= 0.4.1" requires "recaptcha >= 1.0.2" requires "bcrypt >= 0.2.1" +requires "datetime2human >= 0.2.2" +requires "otp >= 0.1.1" +requires "firejail >= 0.5.0" +requires "webp >= 0.2.0" import distros diff --git a/nimwcpkg/nimwc_main.nim b/nimwcpkg/nimwc_main.nim index f59807b4a..0fb49351d 100644 --- a/nimwcpkg/nimwc_main.nim +++ b/nimwcpkg/nimwc_main.nim @@ -1,15 +1,17 @@ -# -# # TTJ -# (c) Copyright 2018 Thomas Toftgaard Jarløv +# (c) Copyright 2019 Thomas Toftgaard Jarløv # Look at LICENSE for more info. # All rights reserved. -# +when defined(windows): + {.fatal: "Cannot run on Windows, but you can try Docker for Windows: http://docs.docker.com/docker-for-windows".} {.passL: "-s".} # Force strip all on the resulting Binary, so its smaller. +# when defined(demo): {.passC: "-flto -ffast-math -march=native".} import - asyncdispatch, bcrypt, cgi, db_sqlite, jester, json, macros, os, osproc, logging, - parsecfg, random, re, recaptcha, sequtils, strutils, times, oswalkdir as oc, + asyncdispatch, bcrypt, cgi, jester, json, macros, os, osproc, logging, otp, + parsecfg, random, re, recaptcha, sequtils, strutils, times, datetime2human, + base32, streams, encodings, nativesockets, + oswalkdir as oc, resources/administration/create_adminuser, resources/administration/create_standarddata, @@ -21,37 +23,48 @@ import resources/password/password_generate, resources/password/salt_generate, resources/session/user_data, - resources/utils/dates, resources/utils/logging_nimwc, resources/utils/plugins, - resources/utils/random_generator, resources/web/google_recaptcha -when defined(windows): quit("\n Windows is not supported \n") +when defined(postgres): import db_postgres +else: import db_sqlite + +when not defined(webp): {. warning: "WebP is Disabled, No Image Optimizations." .} +else: from webp import cwebp + +when not defined(firejail): {. warning: "Firejail is Disabled, Running Unsecure." .} +else: from firejail import firejailVersion, firejailFeatures + const config_not_found_msg = """ - ERROR: Config file (config.cfg) could not be found. - A copy of the template (config_default.cfg) has been copied to config/config.cfg. - - The program will now quit. Please configure it and restart the program. - """ + 🐛 ERROR: Config file (config.cfg) could not be found. 🐛 + A template (config_default.cfg) is copied to "config/config.cfg". + Please configure it and restart Nim Website Creator. Bye. """ startup_msg = """ - Package: Nim Website Creator - Description: Website creator build with Nim - Author name: Thomas Toftgaard Jarløv (TTJ) - Current time: """ + Package: Nim Website Creator - https://NimWC.org + Description: Self-Firejailing Nim Web Framework thats simple to use. + Author name: Thomas Toftgaard Jarløv (TTJ) & Juan Carlos (http://github.com/juancarlospaco)""" checkCompileOptions* = ["", when defined(adminnotify): " -d:adminnotify", - when defined(dev): " -d:dev", - when defined(devemailon): " -d:devemailon", - when defined(demo): " -d:demo", - when defined(ssl): " -d:ssl", + when defined(dev): " -d:dev", + when defined(devemailon): " -d:devemailon", + when defined(demo): " -d:demo", + when defined(ssl): " -d:ssl", + when defined(postgres): " -d:postgres", + when defined(webp): " -d:webp", + when defined(firejail): " -d:firejail", + when defined(release): " -d:release" ].join ## Checking for known compile options and returning them as a space separated string. # Used within plugin route, where a recompile is required to include/exclude a plugin. + sql_now = + when defined(postgres): "(extract(epoch from now()))" # Postgres epoch. + else: "(strftime('%s', 'now'))" # SQLite 3 epoch. + macro configExists(): untyped = ## Macro to check if the config file is present @@ -62,23 +75,26 @@ macro configExists(): untyped = quit() configExists() +randomize() + +# +# Macros +# -#[ - Macros -__________________________________________________]# proc getPluginsPath*(): seq[string] {.compileTime.} = ## Get all plugins path ## ## Generates a seq[string] with the path to the plugins + let + dir = parentDir(currentSourcePath()) + realPath = replace(dir, "/nimwcpkg", "") - let dir = parentDir(currentSourcePath()) - let realPath = replace(dir, "/nimwcpkg", "") - - var plugins = (staticRead(realPath & "/plugins/plugin_import.txt").split("\n")) + var + plugins = (staticRead(realPath & "/plugins/plugin_import.txt").split("\n")) + extensions: seq[string] # Loop through all files and folders - var extensions: seq[string] for plugin in oc.walkDir("plugins/"): let (pd, ppath) = plugin discard pd @@ -101,15 +117,13 @@ macro extensionImport(): untyped = ## Generate code for importing modules from extensions. ## The extensions main module needs to be in plugins/plugin_import.txt ## to be activated. Only 1 module will be imported. - var extensions = "" for ppath in pluginsPath: let splitted = split(ppath, "/") extensions.add("import " & ppath & "/" & splitted[splitted.len-1] & "\n") when defined(dev): - echo "Plugins - imports:" - echo extensions + echo "Plugins - imports:\n" & $extensions result = parseStmt(extensions) @@ -122,7 +136,6 @@ macro extensionUpdateDatabase(): untyped = ## Generate proc for updating the database with new tables etc. ## The extensions main module shall contain a proc named 'proc Start(db: DbConn) =' ## The proc will be executed when the program is executed. - var extensions = "" extensions.add("proc extensionUpdateDB*(db: DbConn) =\n") @@ -137,8 +150,7 @@ macro extensionUpdateDatabase(): untyped = extensions.add(" echo \" \"") when defined(dev): - echo "Plugins - required proc:" - echo extensions + echo "Plugins - required proc:\n" & $extensions result = parseStmt(extensions) @@ -152,26 +164,22 @@ macro extensionCss(): string = ## renaming to .css ## ## 2) Insert +

Frontpage

Login to edit

""" @@ -509,12 +512,11 @@ const """ + proc standardDataSettings*(db: DbConn, dataStyle: string) = ## Settings - echo " - Standard data: Inserting settings-data" - let settingsExists = getValue(db, sql"SELECT id FROM settings WHERE id = ?", "1") - if settingsExists != "": - exec(db, sql"DELETE FROM settings WHERE id = ?", "1") + info"Standard data: Inserting settings-data." + exec(db, sql"DELETE FROM settings") if dataStyle == "bootstrap": discard insertID(db, sql"INSERT INTO settings (title, head, navbar, footer) VALUES (?, ?, ?, ?)", title, headBootstrap, navbarBootstrap, footer) @@ -526,7 +528,7 @@ proc standardDataSettings*(db: DbConn, dataStyle: string) = proc standardDataFrontpage*(db: DbConn, dataStyle = "") = ## Frontpage - echo " - Standard data: Inserting frontpage-data" + info"Standard data: Inserting frontpage-data." let frontpageExists = getValue(db, sql"SELECT id FROM pages WHERE url = ?", "frontpage") if frontpageExists != "": exec(db, sql"DELETE FROM pages WHERE id = ?", frontpageExists) @@ -539,7 +541,7 @@ proc standardDataFrontpage*(db: DbConn, dataStyle = "") = proc standardDataAbout*(db: DbConn) = ## About - echo " - Standard data: Inserting about-data" + info"Standard data: Inserting about-data." let aboutExists = getValue(db, sql"SELECT id FROM pages WHERE url = ?", "about") if aboutExists != "": exec(db, sql"DELETE FROM pages WHERE id = ?", aboutExists) @@ -549,34 +551,37 @@ proc standardDataAbout*(db: DbConn) = proc standardDataBlogpost1*(db: DbConn) = ## Blog post - echo " - Standard data: Inserting blog post-data" + info"Standard data: Inserting blog post-data" let blogExists = getValue(db, sql"SELECT id FROM blog WHERE url = ?", "standardpost") if blogExists != "": exec(db, sql"DELETE FROM blog WHERE id = ?", blogExists) discard insertID(db, sql"INSERT INTO blog (author_id, status, url, name, description, standardhead, standardnavbar, standardfooter, title, metadescription, metakeywords) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "1", "2", "standardpost", "Standard blogpost", blogpost1, "1", "1", "1", "NimWC Example blogpost", "This is an example blogpost using the default styling.", "website,blog,nim,nimwc") + proc standardDataBlogpost2*(db: DbConn) = ## Blog post - echo " - Standard data: Inserting blog post-data" + info"Standard data: Inserting blog post-data." let blogExists = getValue(db, sql"SELECT id FROM blog WHERE url = ?", "standardpostv2") if blogExists != "": exec(db, sql"DELETE FROM blog WHERE id = ?", blogExists) discard insertID(db, sql"INSERT INTO blog (author_id, status, url, name, description, standardhead, standardnavbar, standardfooter, title, metadescription, metakeywords) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "1", "2", "standardpostv2", "Parallax post v2", blogpost2, "1", "1", "1", "NimWC Example blogpost parallax", "This is an example blogpost using parallax created with NimWC.", "website,blog,nim,nimwc,parallax") + proc standardDataBlogpost3*(db: DbConn) = ## Blog post - echo " - Standard data: Inserting blog post-data" + info"Standard data: Inserting blog post-data." let blogExists = getValue(db, sql"SELECT id FROM blog WHERE url = ?", "standardpostv3") if blogExists != "": exec(db, sql"DELETE FROM blog WHERE id = ?", blogExists) discard insertID(db, sql"INSERT INTO blog (author_id, status, url, name, description, standardhead, standardnavbar, standardfooter, title, metadescription, metakeywords) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "1", "2", "standardpostv3", "Custom styling", blogpost3, "1", "1", "1", "NimWC Example blogpost custom", "This is an example blogpost using custom styling.", "website,blog,nim,nimwc") + proc createStandardData*(db: DbConn, dataStyle = "bulma") = ## Insert basic data - echo "Standard data: Inserting standard data" + info"Standard data: Inserting standard data." standardDataSettings(db, dataStyle) standardDataFrontpage(db, dataStyle) if dataStyle != "clean": diff --git a/nimwcpkg/resources/administration/createdb.nim b/nimwcpkg/resources/administration/createdb.nim index efb74ac18..cbe2bd00e 100644 --- a/nimwcpkg/resources/administration/createdb.nim +++ b/nimwcpkg/resources/administration/createdb.nim @@ -1,181 +1,202 @@ -# -# -# Hubanize / Cx Manager -# (c) Copyright 2017 Thomas Toftgaard Jarløv -# All rights reserved. -# -# +import + os, parsecfg, strutils, logging, + ../administration/create_standarddata, + ../utils/logging_nimwc -import db_sqlite, os, parsecfg, strutils +when defined(postgres): import db_postgres +else: import db_sqlite -import ../administration/create_standarddata setCurrentDir(getAppDir().replace("/nimwcpkg", "") & "/") const - TUserName = "varchar(20)" - TPassword = "varchar(32)" - TEmail = "varchar(30)" + sql_now = + when defined(postgres): "(extract(epoch from now()))" # Postgres epoch. + else: "(strftime('%s', 'now'))" # SQLite 3 epoch. + + sql_timestamp = + when defined(postgres): "integer" # is internally Hardcoded to UTC anyways + else: "timestamp" # SQLite 3 Timestamp. + + sql_id = # http://blog.2ndquadrant.com/postgresql-10-identity-columns + when defined(postgres): "integer generated by default as identity" + else: "integer" # SQLite 3 integer ID. + + personTable = sql(""" + create table if not exists person( + id $3 primary key, + name varchar(60) not null, + password varchar(300) not null, + twofa varchar(60), + email varchar(254) not null unique, + creation $2 not null default $1, + modified $2 not null default $1, + salt varchar(128) not null, + status varchar(30) not null, + timezone varchar(100), + secretUrl varchar(250), + lastOnline $2 not null default $1 + );""".format(sql_now, sql_timestamp, sql_id)) + + sessionTable = sql(""" + create table if not exists session( + id $3 primary key, + ip inet not null, + key varchar(300) not null, + userid integer not null, + lastModified $2 not null default $1, + foreign key (userid) references person(id) + );""".format(sql_now, sql_timestamp, sql_id)) + + historyTable = sql(""" + create table if not exists history( + id $3 primary key, + user_id integer not null, + item_id integer, + element varchar(100), + choice varchar(100), + text varchar(1000), + creation $2 not null default $1 + );""".format(sql_now, sql_timestamp, sql_id)) + + settingsTable = sql(""" + create table if not exists settings( + id $1 primary key, + analytics text, + head text, + footer text, + navbar text, + title text, + disabled integer, + blogorder text, + blogsort text + );""".format(sql_id)) + + pagesTable = sql(""" + create table if not exists pages( + id $3 primary key, + author_id INTEGER NOT NULL, + status INTEGER NOT NULL, + name VARCHAR(200) NOT NULL, + url VARCHAR(200) NOT NULL UNIQUE, + title TEXT, + metadescription TEXT, + metakeywords TEXT, + description TEXT, + head TEXT, + navbar TEXT, + footer TEXT, + standardhead INTEGER, + standardnavbar INTEGER, + standardfooter INTEGER, + tags VARCHAR(1000), + category VARCHAR(1000), + date_start VARCHAR(100), + date_end VARCHAR(100), + views INTEGER, + public INTEGER, + changes INTEGER, + modified $2 not null default $1, + creation $2 not null default $1, + foreign key (author_id) references person(id) + );""".format(sql_now, sql_timestamp, sql_id)) + + blogTable = sql(""" + create table if not exists blog( + id $3 primary key, + author_id INTEGER NOT NULL, + status INTEGER NOT NULL, + name VARCHAR(200) NOT NULL, + url VARCHAR(200) NOT NULL UNIQUE, + title TEXT, + metadescription TEXT, + metakeywords TEXT, + description TEXT, + head TEXT, + navbar TEXT, + footer TEXT, + standardhead INTEGER, + standardnavbar INTEGER, + standardfooter INTEGER, + tags VARCHAR(1000), + category VARCHAR(1000), + date_start VARCHAR(100), + date_end VARCHAR(100), + views INTEGER, + public INTEGER, + changes INTEGER, + pubDate VARCHAR(100), + modified $2 not null default $1, + creation $2 not null default $1, + viewCount INTEGER NOT NULL default 1, + foreign key (author_id) references person(id) + );""".format(sql_now, sql_timestamp, sql_id)) + + filesTable = sql(""" + create table if not exists files( + id $3 primary key, + url VARCHAR(1000) NOT NULL UNIQUE, + downloadCount integer NOT NULL default 1, + lastModified $2 NOT NULL default $1 + );""".format(sql_now, sql_timestamp, sql_id)) + proc generateDB*() = - echo "Generating database" + info("Database: Generating database") let dict = loadConfig("config/config.cfg") - db_user = dict.getSectionValue("Database","user") - db_pass = dict.getSectionValue("Database","pass") - db_name = dict.getSectionValue("Database","name") - db_host = dict.getSectionValue("Database","host") - db_folder = dict.getSectionValue("Database","folder") - dbexists = if fileExists(db_host): true else: false + db_user = dict.getSectionValue("Database", "user") + db_pass = dict.getSectionValue("Database", "pass") + db_name = dict.getSectionValue("Database", "name") + db_host = dict.getSectionValue("Database", "host") + db_folder = dict.getSectionValue("Database", "folder") + dbexists = + when defined(postgres): db_host.len > 2 + else: fileExists(db_host) if dbexists: - echo " - Database already exists. Inserting standard tables if they do not exist." - - # Creating folder - discard existsOrCreateDir(db_folder) - - # Open DB - echo " - Opening database" - var db = open(connection=db_host, user=db_user, password=db_pass, database=db_name) - - if not db.tryExec(sql(""" - create table if not exists person( - id integer primary key, - name varchar(60) not null, - password varchar(300) not null, - email varchar(60) not null, - creation timestamp not null default (STRFTIME('%s', 'now')), - modified timestamp not null default (STRFTIME('%s', 'now')), - salt varbin(128) not null, - status varchar(30) not null, - timezone VARCHAR(100), - secretUrl VARCHAR(250), - lastOnline timestamp not null default (STRFTIME('%s', 'now')) - );""" % [TUserName, TPassword, TEmail]), []): - echo " - Database: person table already exists" - - - - - # -------------------- Session ------------------------------------------------- - - if not db.tryExec(sql(""" - create table if not exists session( - id integer primary key, - ip inet not null, - key $# not null, - userid integer not null, - lastModified timestamp not null default (STRFTIME('%s', 'now')), - foreign key (userid) references person(id) - );""" % [TPassword]), []): - echo " - Database: session table already exists" - - - - # ----------------------- History ----------------------------------- - - if not db.tryExec(sql""" - create table if not exists history( - id INTEGER primary key, - user_id INTEGER NOT NULL, - item_id INTEGER, - element VARCHAR(100), - choice VARCHAR(100), - text VARCHAR(1000), - creation timestamp not null default (STRFTIME('%s', 'now')) - );""", []): - echo " - Database: history table already exists" - - - - # ----------------------- Settings ----------------------------------- - - if not db.tryExec(sql""" - create table if not exists settings( - id INTEGER primary key, - analytics TEXT, - head TEXT, - footer TEXT, - navbar TEXT, - title TEXT, - disabled INTEGER, - blogorder TEXT, - blogsort TEXT - );""", []): - echo " - Database: settings table already exists" - - # ----------------------- Pages ---------------------------------------------- - - if not db.tryExec(sql""" - create table if not exists pages( - id INTEGER primary key, - author_id INTEGER NOT NULL, - status INTEGER NOT NULL, - name VARCHAR(200) NOT NULL, - url VARCHAR(200) NOT NULL UNIQUE, - title TEXT, - metadescription TEXT, - metakeywords TEXT, - description TEXT, - head TEXT, - navbar TEXT, - footer TEXT, - standardhead INTEGER, - standardnavbar INTEGER, - standardfooter INTEGER, - tags VARCHAR(1000), - category VARCHAR(1000), - date_start VARCHAR(100) , - date_end VARCHAR(100) , - views INTEGER, - public INTEGER, - changes INTEGER, - modified timestamp not null default (STRFTIME('%s', 'now')), - creation timestamp not null default (STRFTIME('%s', 'now')), - - foreign key (author_id) references person(id) - );""", []): - echo " - Database: pages table already exists" - - - - # ----------------------- Blog ---------------------------------------------- - - if not db.tryExec(sql""" - create table if not exists blog( - id INTEGER primary key, - author_id INTEGER NOT NULL, - status INTEGER NOT NULL, - name VARCHAR(200) NOT NULL, - url VARCHAR(200) NOT NULL UNIQUE, - title TEXT, - metadescription TEXT, - metakeywords TEXT, - description TEXT, - head TEXT, - navbar TEXT, - footer TEXT, - standardhead INTEGER, - standardnavbar INTEGER, - standardfooter INTEGER, - tags VARCHAR(1000), - category VARCHAR(1000), - date_start VARCHAR(100) , - date_end VARCHAR(100) , - views INTEGER, - public INTEGER, - changes INTEGER, - modified timestamp not null default (STRFTIME('%s', 'now')), - creation timestamp not null default (STRFTIME('%s', 'now')), - - foreign key (author_id) references person(id) - );""", []): - echo " - Database:blog table already exists" + info("Database: Database already exists. Inserting standard tables if they do not exist.") + + when not defined(postgres): discard existsOrCreateDir(db_folder) # Creating folder + + info("Database: Opening database") # Open DB + var db = + when defined(postgres): + db_postgres.open(connection=db_host, user=db_user, password=db_pass, database=db_name) + else: + db_sqlite.open(db_host, "", "", "") + + # User + if not db.tryExec(personTable): + info("Database: Person table already exists") + + # Session + if not db.tryExec(sessionTable): + info("Database: Session table already exists") + + # History + if not db.tryExec(historyTable): + info("Database: History table already exists") + + # Settings + if not db.tryExec(settingsTable): + info("Database: Settings table already exists") + + # Pages + if not db.tryExec(pagesTable): + info("Database: Pages table already exists") + + # Blog + if not db.tryExec(blogTable): + info("Database: Blog table already exists") + # Files + if not db.tryExec(filesTable): + info("Database: Files table already exists") if not dbexists: - echo "Inserting standard elements" + info("Database: Inserting standard elements") createStandardData(db) - echo " - Database: Closing database" + info("Database: Closing database") close(db) diff --git a/nimwcpkg/resources/administration/help.nim b/nimwcpkg/resources/administration/help.nim index 430d19b54..d395bfd5f 100644 --- a/nimwcpkg/resources/administration/help.nim +++ b/nimwcpkg/resources/administration/help.nim @@ -1,16 +1,18 @@ -# Copyright 2018 - Thomas T. Jarløv - -func commandLineHelp*(): string = +func commandLineHelp*(): string {.inline.} = return """ - _____________________________________ + ∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽ - Nim Website Creator - A quick website tool. Run the file and access your webpage. + Nim Website Creator 👑 https://NimWC.org + 2-Factor-Auth Self-Firejailing C-Speed Web Framework thats simple to use. + Run it, access your web, customize, add plugins, deploy today anywhere. Commandline arguments: - - newdb = Generates the database with standard tables (does **not** override or delete tables). `newdb` will be initialized automatic, if the no database exists. - - newuser = Add the Admin user - - insertdata = Insert standard data (this will override existing data) - - help - _____________________________________ + 🔹 newdb = Generate the database with the standard tables. + Does not override or delete any tables. + Will be initialized automatically, if no database exists. + 🔹 newuser = Add 1 new Admin user to database. + 🔹 insertdata = Insert standard data to database (overrides existing data) + 🔹 help = Help and info for users. + + ∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽ """ diff --git a/nimwcpkg/resources/email/email_admin.nim b/nimwcpkg/resources/email/email_admin.nim index 5b8d5fbe8..d990693d2 100644 --- a/nimwcpkg/resources/email/email_admin.nim +++ b/nimwcpkg/resources/email/email_admin.nim @@ -1,19 +1,18 @@ -import asyncdispatch, smtp, strutils, os, htmlparser, asyncnet, parsecfg +import + asyncdispatch, smtp, strutils, os, htmlparser, asyncnet, parsecfg, + ../email/email_connection, + ../email/email_generate_message - -import ../email/email_connection -import ../email/email_generate_message +const AdminErrorMsg = """ + Hi Admin +

+ An error occurred. +

+ $1 +

""" proc sendEmailAdminError*(msg: string) {.async.} = ## Send email - user removed - - let message = """Hi Admin -

-An error occurred. -

-$1 -

-""" % [msg] - - await sendAdminMailNow("Admin: Error occurred", genEmailMessage(message)) + await sendAdminMailNow("Admin: Error occurred", + genEmailMessage(AdminErrorMsg.format(msg))) diff --git a/nimwcpkg/resources/email/email_connection.nim b/nimwcpkg/resources/email/email_connection.nim index 9e2862083..06e7fa18d 100644 --- a/nimwcpkg/resources/email/email_connection.nim +++ b/nimwcpkg/resources/email/email_connection.nim @@ -1,85 +1,79 @@ -import asyncdispatch, smtp, strutils, os, htmlparser, asyncnet, parsecfg, times +import + asyncdispatch, smtp, strutils, os, htmlparser, asyncnet, parsecfg, times, logging, + ../utils/logging_nimwc # Changing app dir due to, that module is not imported from main module setCurrentDir(getAppDir()) -var dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg") +const otherHeaders = @[("Content-Type", "text/html; charset=\"UTF-8\"")] -let smtpAddress = dict.getSectionValue("SMTP","SMTPAddress") -let smtpPort = dict.getSectionValue("SMTP","SMTPPort") -let smtpFrom = dict.getSectionValue("SMTP","SMTPFrom") -let smtpUser = dict.getSectionValue("SMTP","SMTPUser") -let smtpPassword = dict.getSectionValue("SMTP","SMTPPassword") -let adminEmail = dict.getSectionValue("SMTP","SMTPEmailAdmin") +let + dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg") + smtpAddress = dict.getSectionValue("SMTP", "SMTPAddress") + smtpPort = dict.getSectionValue("SMTP", "SMTPPort") + smtpFrom = dict.getSectionValue("SMTP", "SMTPFrom") + smtpUser = dict.getSectionValue("SMTP", "SMTPUser") + smtpPassword = dict.getSectionValue("SMTP", "SMTPPassword") + adminEmail = dict.getSectionValue("SMTP", "SMTPEmailAdmin") proc sendMailNow*(subject, message, recipient: string) {.async.} = ## Send the email through smtp - when defined(demo): - echo "Demo is true, email is not send" - + info("Demo is true, email is not send") when defined(dev) and not defined(devemailon): - echo "Dev is true, email is not send" + info("Dev is true, email is not send") return - const otherHeaders = @[("Content-Type", "text/html; charset=\"UTF-8\"")] - - # Go Cx Manager - var client = newAsyncSmtp(useSsl = true, debug = false) - await client.connect(smtpAddress, Port(parseInt(smtpPort))) - await client.auth(smtpUser, smtpPassword) + let + from_addr = smtpFrom + toList = @[recipient] - let from_addr = smtpFrom - let toList = @[recipient] - - var headers = otherHeaders + var + client = newAsyncSmtp(useSsl = true, debug = false) + headers = otherHeaders headers.add(("From", from_addr)) let encoded = createMessage(subject, message, toList, @[], headers) try: + await client.connect(smtpAddress, Port(parseInt(smtpPort))) + await client.auth(smtpUser, smtpPassword) await client.sendMail(from_addr, toList, $encoded) - except: - echo "Error in sending mail: " & recipient + info("Error in sending mail: " & recipient) when defined(dev): - echo "Email send" - + info("Email sent") proc sendAdminMailNow*(subject, message: string) {.async.} = - ## Send the email through smtp - ## Clean admin mailing - + ## Send email only to Admin. when defined(dev): - echo "Dev is true, email is not send" + info("Dev is true, email is not sent") return - if adminEmail == "": - echo "No admin email specified" + info("No admin email specified") return - let recipient = adminEmail let from_addr = adminEmail - const otherHeaders = @[("Content-Type", "text/html; charset=\"UTF-8\"")] - var client = newAsyncSmtp(useSsl = true, debug = false) - - await client.connect(smtpAddress, Port(parseInt(smtpPort))) - - await client.auth(smtpUser, smtpPassword) - - let toList = @[recipient] - - var headers = otherHeaders + var + headers = otherHeaders + client = newAsyncSmtp(useSsl = true, debug = false) headers.add(("From", from_addr)) - let encoded = createMessage("Admin - " & subject, message, - toList, @[], headers) + let + recipient = adminEmail + toList = @[recipient] + encoded = createMessage("Admin - " & subject, message, toList, @[], headers) - await client.sendMail(from_addr, toList, $encoded) + try: + await client.connect(smtpAddress, Port(parseInt(smtpPort))) + await client.auth(smtpUser, smtpPassword) + await client.sendMail(from_addr, toList, $encoded) + except: + info("Error in sending mail: " & recipient) when defined(dev): - echo "Admin email send" \ No newline at end of file + info("Admin email sent") diff --git a/nimwcpkg/resources/email/email_generate_message.nim b/nimwcpkg/resources/email/email_generate_message.nim index 5e0804213..a16ba2c8d 100644 --- a/nimwcpkg/resources/email/email_generate_message.nim +++ b/nimwcpkg/resources/email/email_generate_message.nim @@ -1,19 +1,14 @@ +import parsecfg, strutils, os -import parsecfg +let + dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg") + title = dict.getSectionValue("Server","title") + website = dict.getSectionValue("Server","website") + mailStyleHeader = """
""" + mailStyleFrom = """
Kind regards
""" + mailStyleFooter = """
""" -from os import getAppDir -from strutils import replace -let dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg") -let title = dict.getSectionValue("Server","title") -let website = dict.getSectionValue("Server","website") - -let mailStyleHeader = """
""" -let mailStyleFrom = """
Kind regards
""" -let mailStyleFooter = """
""" - - -proc genEmailMessage*(msgContent: string): string = +proc genEmailMessage*(msgContent: string): string {.inline.} = ## Generate email content - - return mailStyleHeader & msgContent & mailStyleFrom & mailStyleFooter + mailStyleHeader & msgContent & mailStyleFrom & mailStyleFooter diff --git a/nimwcpkg/resources/email/email_registration.nim b/nimwcpkg/resources/email/email_registration.nim index bbe5138ce..6a9775b91 100644 --- a/nimwcpkg/resources/email/email_registration.nim +++ b/nimwcpkg/resources/email/email_registration.nim @@ -1,54 +1,60 @@ -import asyncdispatch, smtp, strutils, os, htmlparser, asyncnet, parsecfg - -import ../email/email_connection -import ../email/email_generate_message - - -let dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg") - -let title = dict.getSectionValue("Server","title") -let website = dict.getSectionValue("Server","website") -let supportEmail = dict.getSectionValue("SMTP","SMTPEmailSupport") - +import + asyncdispatch, smtp, strutils, os, htmlparser, asyncnet, parsecfg, + ../email/email_connection, + ../email/email_generate_message + +const + activationMsg = """ +

Hello $1

+

+ $2 has created a user account for you on $7. +

+ As the final step in your registration, we require that you confirm your email + via the following link: +
+ $5 +

+ To login use the details below. On your first login, please navigate to your settings and change your password! +
    +
  • Email: $3
  • +
  • + Password: + +
  • +
+ Please do not hesitate to contact us at $8, if you have any questions. +

+ Thank you for registering and becoming a part of $6!""" + + registrationMsg = """ +

Hello $1

+

+ We are looking forward to see you at $3! + We have sent you an activation email with your password. + You just need to click on the link become a part of $3. + Get FreeOTP App at https://freeotp.github.io +

+ Please do not hesitate to contact us at $5, if you have any questions. +

+ Thank you for registering and becoming a part of $2!""" + +let + dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg") + title = dict.getSectionValue("Server","title") + website = dict.getSectionValue("Server","website") + supportEmail = dict.getSectionValue("SMTP","SMTPEmailSupport") proc sendEmailActivationManual*(email, userName, password, activateUrl, invitorName: string) {.async.} = ## Send the activation email, when admin added a new user - - let message = """Hello $1, -

-$2 has created a user account for you on $7. -

-As the final step in your registration, we require that you confirm your email -via the following link: -
- $5 -

-To login use the details below. On your first login, please navigate to your settings and change your password! -
-Email: $3 -
-Password: $4 -

-Please do not hesitate to contact us at $8, if you have any questions. -

-Thank you for registering and becoming a part of $6!""" % [userName, invitorName, email, password, (website & activateUrl), title, website, supportEmail] - + let message = activationMsg.format( + userName, invitorName, email, password, + (website & activateUrl), title, website, supportEmail) await sendMailNow(title & " - Email Confirmation", genEmailMessage(message), email) - - proc sendEmailRegistrationFollowup*(email, userName: string) {.async.} = ## Send a follow up mail, if user ## has not used their activation link - - let message = """Hello $1, -

-We are looking forward to see you at $3! We have sent you an activation email with your password. You just need to click on the link become a part of $3. -

-Please do not hesitate to contact us at $5, if you have any questions. -

-Thank you for registering and becoming a part of $2!""" % [userName, title, website, supportEmail] - + let message = registrationMsg.format(userName, title, website, supportEmail) await sendMailNow(title & "- Reminder: Email Confirmation", genEmailMessage(message), email) diff --git a/nimwcpkg/resources/files/files_efs.nim b/nimwcpkg/resources/files/files_efs.nim index 807e87dd2..edd64313d 100644 --- a/nimwcpkg/resources/files/files_efs.nim +++ b/nimwcpkg/resources/files/files_efs.nim @@ -1,7 +1,4 @@ -import parsecfg, os, strutils, osproc, os, logging - - -import ../utils/logging_nimwc +import parsecfg, os, strutils, osproc, os, logging, ../utils/logging_nimwc setCurrentDir(getAppDir().replace("/nimwcpkg", "")) @@ -15,8 +12,9 @@ let dict = loadConfig("config/config.cfg") tempDir = dict.getSectionValue("Storage", section) paths2create = [ - "files", "files/efs", "fileslocal", tempDir, tempDir & "/tmp", tempDir & "/files", - tempDir & "/files/private", tempDir & "/files/public", tempDir & "/users", + "files", "files/efs", "fileslocal", tempDir, tempDir & "/tmp", + tempDir & "/files", tempDir & "/files/private", + tempDir & "/files/public", tempDir & "/users", ] # Create folders diff --git a/nimwcpkg/resources/files/files_utils.nim b/nimwcpkg/resources/files/files_utils.nim index ba9cf3fe9..de745a14d 100644 --- a/nimwcpkg/resources/files/files_utils.nim +++ b/nimwcpkg/resources/files/files_utils.nim @@ -1,33 +1,23 @@ -import os, strutils, sequtils, asyncdispatch +import os, strutils, sequtils, asyncdispatch, ../files/files_efs - -import ../files/files_efs +const + filesListPrivatePath = storageEFS & "/files/private/*.*" + filesListPublicPath = storageEFS & "/files/public/*.*" proc filesListPrivate*(): seq[string] = ## Get all filenames for project files - result = @[] - - for file in walkFiles(storageEFS & "/files/private/*.*"): + for file in walkFiles(filesListPrivatePath): result.add(file) + proc filesListPublic*(): seq[string] = ## Get all filenames for project files - result = @[] - - for file in walkFiles(storageEFS & "/files/public/*.*"): + for file in walkFiles(filesListPublicPath): result.add(file) -proc filesListPublicFolderFiles*(): seq[string] = - ## Get all filenames for project files - result = @[] - - for file in walkFiles("public/files/*.*"): - result.add(file) -proc filesListPublicFolderImages*(): seq[string] = +proc filesListPublicFolderFiles*(): seq[string] = ## Get all filenames for project files - result = @[] - for file in walkFiles("public/images/*.*"): result.add(file) diff --git a/nimwcpkg/resources/password/password_generate.nim b/nimwcpkg/resources/password/password_generate.nim index 287498e98..6c6a5acc3 100644 --- a/nimwcpkg/resources/password/password_generate.nim +++ b/nimwcpkg/resources/password/password_generate.nim @@ -1,16 +1,11 @@ -import md5, bcrypt +import md5, bcrypt, ../password/salt_generate -import ../password/salt_generate - - -proc makeSessionKey*(): string = +proc makeSessionKey*(): string {.inline.} = ## Creates a random key to be used to authorize a session. - let random = makeSalt() - return bcrypt.hash(random, genSalt(8)) + bcrypt.hash(makeSalt(), genSalt(8)) -proc makePassword*(password, salt: string, comparingTo = ""): string = - ## Creates an MD5 hash by combining password and salt - let bcryptSalt = if comparingTo != "": comparingTo else: genSalt(8) - result = hash(getMD5(salt & getMD5(password)), bcryptSalt) \ No newline at end of file +proc makePassword*(password, salt: string, comparingTo = ""): string {.inline.} = + ## Creates an MD5 hash by combining password and salt. + hash(getMD5(salt & getMD5(password)), if comparingTo != "": comparingTo else: genSalt(8)) diff --git a/nimwcpkg/resources/password/salt_generate.nim b/nimwcpkg/resources/password/salt_generate.nim index 4799a0d09..b5f484d76 100644 --- a/nimwcpkg/resources/password/salt_generate.nim +++ b/nimwcpkg/resources/password/salt_generate.nim @@ -7,13 +7,12 @@ let useUrandom = urandom.open("/dev/urandom") proc makeSalt*(): string = ## Generate random salt. Uses cryptographically secure /dev/urandom ## on platforms where it is available, and Nim's random module in other cases. - result = "" - if useUrandom: + if likely(useUrandom): var randomBytes: array[0..127, char] discard urandom.readBuffer(addr(randomBytes), 128) for ch in randomBytes: if ord(ch) in {32..126}: result.add(ch) - else: + else: # Fallback to Nim random when no /dev/urandom for i in 0..127: result.add(chr(rand(94) + 32)) # Generate numbers from 32 to 94 + 32 = 126 diff --git a/nimwcpkg/resources/session/user_data.nim b/nimwcpkg/resources/session/user_data.nim index 3784b900f..7d4f69d8c 100644 --- a/nimwcpkg/resources/session/user_data.nim +++ b/nimwcpkg/resources/session/user_data.nim @@ -1,22 +1,20 @@ from jester import Request - type - Rank* = enum + Rank* = enum ## Rank for the User. User Moderator Admin Deactivated NotLoggedin -type Session* = object of RootObj loggedIn*: bool username*, userpass*, email*: string - + TData* = ref object of Session req*: Request - userid*: string # User ID - timezone*: string # User timezone - rank*: Rank # User status (rank) \ No newline at end of file + userid*: string ## User ID + timezone*: string ## User timezone + rank*: Rank ## User status (rank) diff --git a/nimwcpkg/resources/utils/dates.nim b/nimwcpkg/resources/utils/dates.nim deleted file mode 100644 index 522bca29d..000000000 --- a/nimwcpkg/resources/utils/dates.nim +++ /dev/null @@ -1,132 +0,0 @@ -import strutils, times, logging - - -import ../utils/logging_nimwc - - -const monthNames = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - - -proc currentDatetime*(formatting: string): string= - ## Getting the current local time - - if formatting == "full": - result = format(local(getTime()), "yyyy-MM-dd HH:mm:ss") - elif formatting == "date": - result = format(local(getTime()), "yyyy-MM-dd") - elif formatting == "compact": - result = format(local(getTime()), "yyyyMMdd") - elif formatting == "year": - result = format(local(getTime()), "yyyy") - elif formatting == "month": - result = format(local(getTime()), "MM") - elif formatting == "day": - result = format(local(getTime()), "dd") - elif formatting == "time": - result = format(local(getTime()), "HH:mm:ss") - - - -proc getDaysInMonthU*(month, year: int): int = - ## Gets the number of days in the month and year - ## - ## Examples: - ## - runnableExamples: - doAssert getDaysInMonthU(02, 2018) == 28 - doAssert getDaysInMonthU(10, 2020) == 31 - if month notin {1..12}: - warn("getDaysInMonthU() wrong format input.") - else: - result = getDaysInMonth(Month(month), year) - - - - -proc dateEpoch*(date, format: string): int64 = - ## Transform a date in user format to epoch - ## Does not utilize timezone - ## - ## Examples: - ## - runnableExamples: - doAssert dateEpoch("2018-02-18", "YYYY-MM-DD") == "1518908400" - - try: - case format - of "YYYYMMDD": - return toUnix(toTime(parse(date, "yyyyMMdd"))) - of "YYYY-MM-DD": - return toUnix(toTime(parse(date, "yyyy-MM-dd"))) - of "YYYY-MM-DD HH:mm": - return toUnix(toTime(parse(date, "yyyy-MM-dd HH:mm"))) - of "DD-MM-YYYY": - return toUnix(toTime(parse(date, "dd-MM-yyyy"))) - else: - warn("dateEpoch() wrong format input.") - return 0 - except: - warn("dateEpoch() failed.") - - return 0 - - - -proc epochDate*(epochTime, format: string, timeZone = "0"): string = - ## Transform epoch to user formatted date - ## - ## Examples: - ## - runnableExamples: - doAssert epochDate("1522995050", "YYYY-MM-DD HH:mm", "2") == "2018-04-06 - 08:10" - - - if epochTime == "": - return "" - - try: - case format - of "YYYY": - let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone))) - return toTime.substr(0, 3) - - of "YYYY_MM_DD-HH_mm": - let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone))) - return toTime.substr(0, 3) & "_" & toTime.substr(5, 6) & "_" & toTime.substr(8, 9) & "-" & toTime.substr(11, 12) & "_" & toTime.substr(14, 15) - - of "YYYY MM DD": - let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone))) - return toTime.substr(0, 3) & " " & toTime.substr(5, 6) & " " & toTime.substr(8, 9) - - of "YYYY-MM-DD": - let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone))) - return toTime.substr(0, 9) - - of "YYYY-MM-DD HH:mm": - let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone))) - return toTime.substr(0, 9) & " - " & toTime.substr(11, 15) - - of "DD MM YYYY": - let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone))) - return toTime.substr(8, 9) & " " & toTime.substr(5, 6) & " " & toTime.substr(0, 3) - - of "DD": - let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone))) - return toTime.substr(8, 9) - - of "MMM DD": - let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone))) - return monthNames[parseInt(toTime.substr(5, 6))] & " " & toTime.substr(8, 9) - - of "MMM": - let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone))) - return monthNames[parseInt(toTime.substr(5, 6))] - - else: - let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone))) - warn("epochDate() no input specified.") - return toTime.substr(0, 9) - - except: - error("epochDate() failed.") - return "" diff --git a/nimwcpkg/resources/utils/logging_nimwc.nim b/nimwcpkg/resources/utils/logging_nimwc.nim index 2933451ac..f64e1d5b1 100644 --- a/nimwcpkg/resources/utils/logging_nimwc.nim +++ b/nimwcpkg/resources/utils/logging_nimwc.nim @@ -6,8 +6,8 @@ discard existsOrCreateDir("log") let dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg") - fileDebug = dict.getSectionValue("Logging","logfiledev") - fileProd = dict.getSectionValue("Logging","logfile") + fileDebug = dict.getSectionValue("Logging", "logfiledev") + fileProd = dict.getSectionValue("Logging", "logfile") var console_logger = newConsoleLogger(fmtStr = verboseFmtStr) # Logs to terminal. diff --git a/nimwcpkg/resources/utils/plugins.nim b/nimwcpkg/resources/utils/plugins.nim index ea53e300c..0c2ad9719 100644 --- a/nimwcpkg/resources/utils/plugins.nim +++ b/nimwcpkg/resources/utils/plugins.nim @@ -1,93 +1,67 @@ -# Copyright 2018 - Thomas T. Jarløv - import strutils, osproc, os, json +const + pluginRepo = "https://github.com/ThomasTJdev/nimwc_plugins.git" + pluginRepoName = "nimwc_plugins" + pluginHtmlListItem = """ +
  • + +
    Start
    +
    Stop
    +
  • """ + -const pluginRepo = "https://github.com/ThomasTJdev/nimwc_plugins.git" -const pluginRepoName = "nimwc_plugins" +proc pluginCheckGit*(): bool {.inline.} = + ## Checks if git exists + "git".findExe.len > 0 proc pluginExtractDetails*(pluginFolder: string): tuple[name, version, description, url: string] = ## Get plugin data from [pluginName]/plugin.json - let pluginJson = parseFile("plugins/" & pluginFolder & "/plugin.json") for plugin in items(pluginJson): - let name = plugin["name"].getStr() - let version = plugin["version"].getStr() - let description = plugin["description"].getStr() - let url = plugin["url"].getStr() - + let + name = plugin["name"].getStr() + version = plugin["version"].getStr() + description = plugin["description"].getStr() + url = plugin["url"].getStr() return (name, version, description, url) -proc pluginCheckGit*(): bool = - ## Checks if git exists - - if execCmd("git > /dev/null") == 1: - true - else: - false - - -proc pluginRepoExists(): bool = - ## Check if plugin repo exists - - if fileExists("plugins/nimwc_plugins/plugins.json"): - true - else: - false - - proc pluginRepoClone*(): bool = ## Clones (updates) the plugin repo - - if not pluginCheckGit(): + if unlikely(not pluginCheckGit()): return false - - let output = execCmd("git clone " & pluginRepo & " " & replace(getAppDir(), "/nimwcpkg", "") & "/plugins/" & pluginRepoName) - + let output = execCmd("git clone " & pluginRepo & " " & + replace(getAppDir(), "/nimwcpkg", "") & "/plugins/" & pluginRepoName) if output != 0: return false - - return pluginRepoExists() + return fileExists("plugins/nimwc_plugins/plugins.json") proc pluginRepoUpdate*(): bool = ## Clones (updates) the plugin repo - - if not pluginCheckGit(): + if unlikely(not pluginCheckGit()): return false - let output = execCmd("git -C plugins/" & pluginRepoName & " pull") - if output != 0: return false - - return pluginRepoExists() + return fileExists("plugins/nimwc_plugins/plugins.json") proc pluginDownload*(pluginGit, pluginFolder: string): bool = ## Downloads an external plugin with clone - - let output = execProcess("git clone " & pluginGit & " " & replace(getAppDir(), "/nimwcpkg", "") & "/plugins/" & pluginFolder) - - if output == ("fatal: repository '" & pluginGit & "' does not exists"): - false - else: - true + let output = execProcess("git clone " & pluginGit & " " & + replace(getAppDir(), "/nimwcpkg", "") & "/plugins/" & pluginFolder) + result = output != "fatal: repository '" & pluginGit & "' does not exists" proc pluginUpdate*(pluginFolder: string): bool = ## Updates an external plugin with pull - discard execCmd("git -C plugins/" & pluginFolder & " fetch --all") discard execCmd("git -C plugins/" & pluginFolder & " reset --hard origin/master") let output = execProcess("git -C plugins/" & pluginFolder & " pull") - - if output == ("fatal: cannot change to " & pluginFolder & ": No such file or directory"): - false - else: - true + result = output != "fatal: cannot change to " & pluginFolder & ": No such file or directory" proc pluginDelete*(pluginFolder: string): bool = @@ -95,13 +69,8 @@ proc pluginDelete*(pluginFolder: string): bool = for line in lines("plugins/plugin_import.txt"): if line == pluginFolder: return false - let output = execProcess("rm -rf plugins/" & pluginFolder) - - if output == ("fatal: cannot change to " & pluginFolder & ": No such file or directory"): - false - else: - true + result = output != "fatal: cannot change to " & pluginFolder & ": No such file or directory" proc pluginEnableDisable*(pluginPath, pluginName, status: string) = @@ -166,28 +135,34 @@ proc extensionSettings(): seq[string] = proc genExtensionSettings*(): string = ## Generate HTML list items with plugins - - var extensions = "" for plugin in extensionSettings(): let pluginName = (split(plugin, ":"))[1] - let status = if (split(plugin, ":"))[0] == "true": "enabled" else: "disabled" - extensions.add("
  • ") - extensions.add("
    ") - if (split(plugin, ":"))[0] == "true": - extensions.add(" " & pluginName & " [" & status & "]") - else: - extensions.add(" " & pluginName & " [" & status & "]") - extensions.add("
    ") - extensions.add("
    Start
    ") - extensions.add("
    Stop
    ") - extensions.add("
  • ") + # $3 + if (split(plugin, ":"))[0] == "true": + pluginName & "/settings" + else: + "#", - return extensions + # $4 + pluginName.capitalizeAscii, + + # $5 + if (split(plugin, ":"))[0] == "true": + "ON" + else: + "OFF", + + # $6 + if (split(plugin, ":"))[0] == "true": + "enabled" + else: + "disabled" + )) diff --git a/nimwcpkg/resources/utils/random_generator.nim b/nimwcpkg/resources/utils/random_generator.nim deleted file mode 100644 index b27bbf554..000000000 --- a/nimwcpkg/resources/utils/random_generator.nim +++ /dev/null @@ -1,84 +0,0 @@ -import strutils, random, sequtils - - -const rlAscii = toSeq('a'..'z') -const rhAscii = toSeq('A'..'Z') -const rDigit = toSeq('0'..'9') -const rSpecial = ["!", ",", "$", "/", "(", ")", "?", "_"] - -proc randomString*(length: int): string = - ## Generate random number with special chars, alpha and digits. - ## The length is specified as parameter. - randomize() - result = "" - - for i in countUp(1, length): - var runRandom = rand(3) - - case runRandom - of 0: - result.add(rand(rlAscii)) - of 1: - result.add(rand(rhAscii)) - of 2: - result.add(rand(rDigit)) - of 3: - result.add(rand(rSpecial)) - else: - discard - - return result - - -proc randomStringAlpha*(length: int): string = - ## Generate random number with alpha. - ## The length is specified as parameter. - randomize() - result = "" - - for i in countUp(1, length): - var runRandom = rand(1) - - case runRandom - of 0: - result.add(rand(rlAscii)) - of 1: - result.add(rand(rhAscii)) - else: - discard - - return result - - -proc randomStringDigit*(length: int): string = - ## Generate random number with digits. - ## The length is specified as parameter. - randomize() - result = "" - - for i in countUp(1, length): - result.add(rand(rDigit)) - - return result - - -proc randomStringDigitAlpha*(length: int): string = - ## Generate random number with alpha and digits. - ## The length is specified as parameter. - randomize() - result = "" - - for i in countUp(1, length): - var runRandom = rand(2) - - case runRandom - of 0: - result.add(rand(rlAscii)) - of 1: - result.add(rand(rhAscii)) - of 2: - result.add(rand(rDigit)) - else: - discard - - return result \ No newline at end of file diff --git a/nimwcpkg/resources/web/google_recaptcha.nim b/nimwcpkg/resources/web/google_recaptcha.nim index 282478ee4..64dde39f7 100644 --- a/nimwcpkg/resources/web/google_recaptcha.nim +++ b/nimwcpkg/resources/web/google_recaptcha.nim @@ -9,25 +9,21 @@ var useCaptcha*: bool captcha*: ReCaptcha - -# Using config.ini -let dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg") - -# Web settings -let recaptchaSecretKey = dict.getSectionValue("reCAPTCHA","Secretkey") -let recaptchaSiteKey* = dict.getSectionValue("reCAPTCHA","Sitekey") +let + dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg") + recaptchaSecretKey = dict.getSectionValue("reCAPTCHA","Secretkey") + recaptchaSiteKey* = dict.getSectionValue("reCAPTCHA","Sitekey") proc setupReCapthca*() = - # Activate Google reCAPTCHA + ## Activate Google reCAPTCHA if len(recaptchaSecretKey) > 0 and len(recaptchaSiteKey) > 0: useCaptcha = true captcha = initReCaptcha(recaptchaSecretKey, recaptchaSiteKey) - info("Initialized reCAPTCHA.") - + info("Initialized ReCAPTCHA.") else: useCaptcha = false - error("setupReCapthca(): Failed to initialize reCAPTCHA.") + warn("Failed to initialize ReCAPTCHA.") proc checkReCaptcha*(antibot, userIP: string): Future[bool] {.async.} = diff --git a/nimwcpkg/resources/web/routes.nim b/nimwcpkg/resources/web/routes.nim index 1e2ba73a8..d04697075 100644 --- a/nimwcpkg/resources/web/routes.nim +++ b/nimwcpkg/resources/web/routes.nim @@ -1,4 +1,3 @@ -# Copyright 2018 - Thomas T. Jarløv routes: #error Http404: @@ -20,12 +19,15 @@ routes: post "/dologin": createTFD() + if @"password2" != "": # DONT TOUCH, HoneyPot: https://github.com/ThomasTJdev/nim_websitecreator/issues/43#issue-403507393 + when not defined(release): echo "HONEYPOT: " & @"password2" + redirect("/login?msg=" & encodeUrl("Error: You need to verify, that you are not a robot!")) when not defined(dev): if useCaptcha: if not await checkReCaptcha(@"g-recaptcha-response", c.req.ip): redirect("/login?msg=" & encodeUrl("Error: You need to verify, that you are not a robot!")) - let (loginB, loginS) = login(c, replace(toLowerAscii(@"email"), " ", ""), replace(@"password", " ", "")) + let (loginB, loginS) = login(c, replace(toLowerAscii(@"email"), " ", ""), replace(@"password", " ", ""), @"totp") if loginB: jester.setCookie("sid", loginS, daysForward(7)) redirect("/settings") @@ -42,14 +44,11 @@ routes: resp genMain(c, "

    " & decodeUrl(@"errorMsg") & "

    ") +# +# Plugins +# - #[ - - Plugins - - ]# - get "/plugins": ## Access the plugin overview @@ -185,11 +184,10 @@ routes: redirect("/error/" & encodeUrl("Something went wrong. Please check the git: " & @"pluginrepo")) - #[ +# +# Settings +# - Settings - - ]# get "/settings": createTFD() @@ -308,7 +306,7 @@ routes: get "/settings/logs": createTFD() restrictAccessTo(c, [Admin, Moderator]) - resp genViewLogs(logcontent=readFile(logfile)) + resp genMainAdmin(c, genViewLogs(logcontent=readFile(logfile))) get "/settings/forcerestart": createTFD() @@ -318,14 +316,133 @@ routes: get "/settings/serverinfo": createTFD() restrictAccessTo(c, [Admin, Moderator]) - resp genServerInfo() + resp genMainAdmin(c, genServerInfo()) + + get "/settings/termsofservice": + createTFD() + let tos = readFile(getAppDir() & "/tmpl/tos.html") + resp tos + + get "/settings/firejail": + createTFD() + restrictTestuser(c.req.reqMethod) + restrictAccessTo(c, [Admin]) + + when not defined(firejail): + redirect("/") + else: + let dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg") + resp genMainAdmin(c, genFirejail( + dict.getSectionValue("firejail", "noDvd").parseBool, + dict.getSectionValue("firejail", "noSound").parseBool, + dict.getSectionValue("firejail", "noAutoPulse").parseBool, + dict.getSectionValue("firejail", "no3d").parseBool, + dict.getSectionValue("firejail", "noX").parseBool, + dict.getSectionValue("firejail", "noVideo").parseBool, + dict.getSectionValue("firejail", "noDbus").parseBool, + dict.getSectionValue("firejail", "noShell").parseBool, + dict.getSectionValue("firejail", "noDebuggers").parseBool, + dict.getSectionValue("firejail", "noMachineId").parseBool, + dict.getSectionValue("firejail", "noRoot").parseBool, + dict.getSectionValue("firejail", "noAllusers").parseBool, + dict.getSectionValue("firejail", "noU2f").parseBool, + dict.getSectionValue("firejail", "privateTmp").parseBool, + dict.getSectionValue("firejail", "privateCache").parseBool, + dict.getSectionValue("firejail", "privateDev").parseBool, + dict.getSectionValue("firejail", "forceEnUsUtf8").parseBool, + dict.getSectionValue("firejail", "caps").parseBool, + dict.getSectionValue("firejail", "seccomp").parseBool, + dict.getSectionValue("firejail", "noTv").parseBool, + dict.getSectionValue("firejail", "writables").parseBool, + dict.getSectionValue("firejail", "noMnt").parseBool, + dict.getSectionValue("firejail", "maxSubProcesses").parseInt, + dict.getSectionValue("firejail", "maxOpenFiles").parseInt, + dict.getSectionValue("firejail", "maxFileSize").parseInt, + dict.getSectionValue("firejail", "maxPendingSignals").parseInt, + dict.getSectionValue("firejail", "timeout").parseInt, + dict.getSectionValue("firejail", "maxCpu").parseInt, + dict.getSectionValue("firejail", "maxRam").parseInt, + dict.getSectionValue("firejail", "cpuCoresByNumber").parseInt, + dict.getSectionValue("firejail", "hostsFile"), + dict.getSectionValue("firejail", "dns0"), + dict.getSectionValue("firejail", "dns1"), + dict.getSectionValue("firejail", "dns2"), + dict.getSectionValue("firejail", "dns3"), + )) + + post "/settings/firejail/save": + createTFD() + restrictTestuser(c.req.reqMethod) + restrictAccessTo(c, [Admin]) + + when not defined(firejail): + redirect("/") + else: + let konfig = replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg" + var dict = loadConfig(konfig) + try: # HTML Checkbox returns empty string for false and "on" for true. + dict.setSectionKey("firejail", "noDvd", $(len(@"noDvd") > 0)) + dict.setSectionKey("firejail", "noSound", $(len(@"noSound") > 0)) + dict.setSectionKey("firejail", "noAutoPulse", $(len(@"noAutoPulse") > 0)) + dict.setSectionKey("firejail", "no3d", $(len(@"no3d") > 0)) + dict.setSectionKey("firejail", "noX", $(len(@"noX") > 0)) + dict.setSectionKey("firejail", "noVideo", $(len(@"noVideo") > 0)) + dict.setSectionKey("firejail", "noDbus", $(len(@"noDbus") > 0)) + dict.setSectionKey("firejail", "noShell", $(len(@"noShell") > 0)) + dict.setSectionKey("firejail", "noDebuggers", $(len(@"noDebuggers") > 0)) + dict.setSectionKey("firejail", "noMachineId", $(len(@"noMachineId") > 0)) + dict.setSectionKey("firejail", "noRoot", $(len(@"noRoot") > 0)) + dict.setSectionKey("firejail", "noAllusers", $(len(@"noAllusers") > 0)) + dict.setSectionKey("firejail", "noU2f", $(len(@"noU2f") > 0)) + dict.setSectionKey("firejail", "privateTmp", $(len(@"privateTmp") > 0)) + dict.setSectionKey("firejail", "privateCache", $(len(@"privateCache") > 0)) + dict.setSectionKey("firejail", "privateDev", $(len(@"privateDev") > 0)) + dict.setSectionKey("firejail", "forceEnUsUtf8", $(len(@"forceEnUsUtf8") > 0)) + dict.setSectionKey("firejail", "caps", $(len(@"caps") > 0)) + dict.setSectionKey("firejail", "seccomp", $(len(@"seccomp") > 0)) + dict.setSectionKey("firejail", "noTv", $(len(@"noTv") > 0)) + dict.setSectionKey("firejail", "writables", $(len(@"writables") > 0)) + dict.setSectionKey("firejail", "noMnt", $(len(@"noMnt") > 0)) + dict.setSectionKey("firejail", "maxSubProcesses", @"maxSubProcesses") + dict.setSectionKey("firejail", "maxOpenFiles", @"maxOpenFiles") + dict.setSectionKey("firejail", "maxFileSize", @"maxFileSize") + dict.setSectionKey("firejail", "maxPendingSignals", @"maxPendingSignals") + dict.setSectionKey("firejail", "timeout", @"timeout") + dict.setSectionKey("firejail", "maxCpu", @"maxCpu") + dict.setSectionKey("firejail", "maxRam", @"maxRam") + dict.setSectionKey("firejail", "cpuCoresByNumber", @"cpuCoresByNumber") + dict.setSectionKey("firejail", "hostsFile", @"hostsFile") + dict.setSectionKey("firejail", "dns0", @"dns0") + dict.setSectionKey("firejail", "dns1", @"dns1") + dict.setSectionKey("firejail", "dns2", @"dns2") + dict.setSectionKey("firejail", "dns3", @"dns3") + dict.writeConfig(konfig) + except: + resp $getCurrentExceptionMsg() + redirect("/settings") + get "/settings/config": + createTFD() + restrictAccessTo(c, [Admin]) + let konfig = replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg" + resp genMainAdmin(c, genEditConfig(readFile(konfig))) + + post "/settings/config/save": + createTFD() + restrictAccessTo(c, [Admin]) + try: + discard loadConfig(newStringStream(@"config")) # Not a strong Validation. + except: + resp $getCurrentExceptionMsg() + let konfig = replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg" + writeFile(konfig, strip(@"config")) + redirect("/settings") - #[ - Files +# +# Files +# - ]# get "/files": createTFD() @@ -360,6 +477,11 @@ routes: if not fileExists(filepath): resp("Error: File was not found") + var downloadCount = + try: parseInt(getValue(db, sql"SELECT downloadCount FROM files where url = ?", filepath)) + except: 0 + inc downloadCount + exec(db, sql"UPDATE files SET downloadCount = ? where url = ?", downloadCount, filepath) sendFile(filepath) @@ -378,7 +500,12 @@ routes: try: writeFile(path, request.formData.getOrDefault("file[]").body) + when defined(webp): + if path.endsWith(".png") or path.endsWith(".jpg") or path.endsWith(".jpeg"): + discard cwebp(path, path, "drawing", quality=25) # This sets quality of WEBP if fileExists(path): + # Do not insert into DB due to being a public image file + #exec(db, sql"INSERT INTO files(url, downloadCount) VALUES (?, 0)", path) resp("[\"/images/" & filename & "\"]") except: @@ -400,24 +527,33 @@ routes: let filename = request.formData["file"].fields["filename"] var path: string + const efspublic = storageEFS & "/files/public/" + const efsprivate = storageEFS & "/files/private/" if @"access" == "publicimage": path = "public/images/" & filename - + elif @"access" == "public": + assert existsDir(efspublic), "storageEFS Public Folder not found: " & efspublic + path = efspublic & filename else: - path = storageEFS & "/files/" & @"access" & "/" & filename + assert existsDir(efsprivate), "storageEFS Private Folder not found: " & efsprivate + path = efsprivate & filename if fileExists(path): resp("Error: A file with the same name exists") - try: - writeFile(path, request.formData.getOrDefault("file").body) - if fileExists(path): - redirect("/files") - - except: - resp("Error: Something went wrong adding the file") + writeFile(path, request.formData.getOrDefault("file").body) + when defined(webp): + if @"webpstatus" == "true": + if path.endsWith(".png") or path.endsWith(".jpg") or path.endsWith(".jpeg"): + discard cwebp(path, path, "drawing", quality=25) # This sets quality of WEBP + if fileExists(path) and @"access" != "publicimage": + # TODO: There should not be a row with the file. But if the user manually + # deletes the file and reuploads it, it will still be present in th DB. + # This query fails due to UNIQUE requirement in the DB. To prevent error and + # try-except, it uses tryExec(). We could solve this by doing a sweep with walkDir(). + discard tryExec(db, sql"INSERT INTO files(url, downloadCount) VALUES (?, 0)", path) - resp("Error: Something went wrong") + redirect("/files") get "/files/delete/@access/@filename": @@ -433,7 +569,9 @@ routes: fileDeleted = tryRemoveFile("public/images/" & decodeUrl(@"filename")) else: - fileDeleted = tryRemoveFile(storageEFS & "/files/" & @"access" & "/" & decodeUrl(@"filename")) + let path = storageEFS & "/files/" & @"access" & "/" & decodeUrl(@"filename") + fileDeleted = tryRemoveFile(path) + exec(db, sql"DELETE FROM files WHERE url = ?", path) if fileDeleted: redirect("/files") @@ -442,14 +580,11 @@ routes: resp("Error: File not found") +# +# Users +# - #[ - - Users - - ]# - get "/users": createTFD() if not c.loggedIn: @@ -492,6 +627,48 @@ routes: redirect("/users/profile") + post "/users/profile/update/test2fa": + createTFD() + restrictTestuser(HttpGet) + + if not c.loggedIn: + redirect("/") + + try: + if $newTotp(@"twofakey").now() == @"testcode": + resp("Success, the code matched") + else: + resp("Error, code did not match") + except: + resp("Error generating 2FA") + + + post "/users/profile/update/save2fa": + createTFD() + restrictTestuser(HttpGet) + + if not c.loggedIn: + redirect("/") + + if tryExec(db, sql"UPDATE person SET twofa = ? WHERE id = ?", @"twofakey", c.userid): + resp("Saved 2FA key") + else: + resp("Error saving 2FA key") + + + post "/users/profile/update/disable2fa": + createTFD() + restrictTestuser(HttpGet) + + if not c.loggedIn: + redirect("/") + + if tryExec(db, sql"UPDATE person SET twofa = ? WHERE id = ?", "", c.userid): + resp("Disabled 2FA key") + else: + resp("Error disabling 2FA key") + + get "/users/delete/@userID": createTFD() restrictTestuser(c.req.reqMethod) @@ -538,10 +715,11 @@ routes: if emailExist != "": redirect("/error/" & encodeUrl("Error: A user with that email does already exists")) - let salt = makeSalt() - let passwordOriginal = randomString(12) - let password = makePassword(passwordOriginal, salt) - let secretUrl = randomStringDigitAlpha(99) + let + salt = makeSalt() + passwordOriginal = $rand(10_00_00_00_00_01.int..89_99_99_99_99_98.int) # User Must change it anyways. + password = makePassword(passwordOriginal, salt) + secretUrl = repeat($rand(10_00_00_00_00_00_00_00_00.int..int.high), 5).center(99, rand(toSeq('a'..'z'))) let userID = insertID(db, sql"INSERT INTO person (name, email, status, password, salt, secretUrl) VALUES (?, ?, ?, ?, ?, ?)", @"name", emailReady, @"status", password, salt, secretUrl) @@ -568,23 +746,17 @@ routes: ## Get a file createTFD() let filename = decodeUrl(@"filename") - var filepath = storageEFS & "/users/" & filename - - if not fileExists(filepath): - resp("") - + if not fileExists(filepath): resp("") sendFile(filepath) post "/users/photo/upload": ## Uploads a new profile image for a user - createTFD() restrictTestuser(c.req.reqMethod) - if not c.loggedIn: - redirect("/") + if not c.loggedIn: redirect("/") let path = storageEFS & "/users/" & c.userid let base64 = split(c.req.body, ",")[1] @@ -593,23 +765,18 @@ routes: writeFile(path & ".txt", base64) discard execProcess("base64 -d > " & path & ".png < " & path & ".txt") removeFile(path & ".txt") - if fileExists(path & ".png"): - resp("File saved") - + if fileExists(path & ".png"): resp("File saved") except: resp("Error") resp("Error: Something went wrong") +# +# Blog +# - #[ - - Blog - - ]# - get "/blogpagenew": createTFD() restrictAccessTo(c, [Admin, Moderator]) @@ -625,7 +792,7 @@ routes: if url == getValue(db, sql"SELECT url FROM blog WHERE url = ?", url): redirect("/error/" & encodeUrl("Error, a blogpost with the same URL already exists")) - let blogID = insertID(db, sql"INSERT INTO blog (author_id, status, url, name, description, standardhead, standardnavbar, standardfooter, title, metadescription, metakeywords, category, tags) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", c.userid, @"status", url, @"name", @"editordata", checkboxToInt(@"standardhead"), checkboxToInt(@"standardnavbar"), checkboxToInt(@"standardfooter"), @"title", @"metadescription", @"metakeywords", @"category", @"tags") + let blogID = insertID(db, sql"INSERT INTO blog (author_id, status, url, name, description, standardhead, standardnavbar, standardfooter, title, metadescription, metakeywords, category, tags, pubDate, viewCount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", c.userid, @"status", url, @"name", @"editordata", checkboxToInt(@"standardhead"), checkboxToInt(@"standardnavbar"), checkboxToInt(@"standardfooter"), @"title", @"metadescription", @"metakeywords", @"category", @"tags", @"pubdate", @"viewcount") resp genMainAdmin(c, genEditBlog(c, $blogID, true), "edit") @@ -640,7 +807,7 @@ routes: resp("Error: A page with same URL already exists") redirect("/error/" & encodeUrl("Error, a blogpost with the same URL already exists")) - discard execAffectedRows(db, sql"UPDATE blog SET author_id = ?, status = ?, url = ?, name = ?, description = ?, standardhead = ?, standardnavbar = ?, standardfooter = ?, title = ?, metadescription = ?, metakeywords = ?, category = ?, tags = ? WHERE id = ?", c.userid, @"status", url, @"name", @"editordata", checkboxToInt(@"standardhead"), checkboxToInt(@"standardnavbar"), checkboxToInt(@"standardfooter"), @"title", @"metadescription", @"metakeywords", @"category", @"tags", @"blogid") + discard execAffectedRows(db, sql"UPDATE blog SET author_id = ?, status = ?, url = ?, name = ?, description = ?, standardhead = ?, standardnavbar = ?, standardfooter = ?, title = ?, metadescription = ?, metakeywords = ?, category = ?, tags = ?, pubDate = ?, viewCount = ? WHERE id = ?", c.userid, @"status", url, @"name", @"editordata", checkboxToInt(@"standardhead"), checkboxToInt(@"standardnavbar"), checkboxToInt(@"standardfooter"), @"title", @"metadescription", @"metakeywords", @"category", @"tags", @"pubdate", @"viewcount", @"blogid") if @"inbackground" == "true": resp("OK") @@ -677,16 +844,17 @@ routes: get re"/blog//*.": createTFD() let blogid = getValue(db, sql"SELECT id FROM blog WHERE url = ?", c.req.path.replace("/blog/", "")) - resp genPageBlog(c, blogid) - + if blogid == "": + redirect("/") + resp genPageBlog(c, blogid) - #[ - Pages +# +# Pages +# - ]# get "/pagenew": createTFD() @@ -757,11 +925,11 @@ routes: resp genPage(c, pageid) - #[ +# +# Sitemap +# - Sitemap - ]# get "/sitemap.xml": writeFile("public/sitemap.xml", genSitemap()) sendFile("public/sitemap.xml") diff --git a/nimwcpkg/tmpl/blog.tmpl b/nimwcpkg/tmpl/blog.tmpl index 9c73d1f84..5ac744643 100644 --- a/nimwcpkg/tmpl/blog.tmpl +++ b/nimwcpkg/tmpl/blog.tmpl @@ -26,13 +26,13 @@ # var allBlogPages: seq[Row] # # if name.len() != 0: -# allBlogPages = getAllRows(db, sql("SELECT id, url, name, description, status, creation, metadescription, category, tags FROM blog WHERE status IN " & status & " AND name LIKE ? ORDER BY " & sortingOrder), "%" & name & "%") +# allBlogPages = getAllRows(db, sql("SELECT id, url, name, description, status, creation, metadescription, category, tags, viewCount, pubDate FROM blog WHERE status IN " & status & " AND name LIKE ? ORDER BY " & sortingOrder), "%" & name & "%") # elif category.len() != 0: -# allBlogPages = getAllRows(db, sql("SELECT id, url, name, description, status, creation, metadescription, category, tags FROM blog WHERE status IN " & status & " AND category = ? ORDER BY " & sortingOrder), category) +# allBlogPages = getAllRows(db, sql("SELECT id, url, name, description, status, creation, metadescription, category, tags, viewCount, pubDate FROM blog WHERE status IN " & status & " AND category = ? ORDER BY " & sortingOrder), category) # elif tags.len() != 0: -# allBlogPages = getAllRows(db, sql("SELECT id, url, name, description, status, creation, metadescription, category, tags FROM blog WHERE status IN " & status & " AND tags LIKE ? ORDER BY " & sortingOrder), "%" & tags & "%") +# allBlogPages = getAllRows(db, sql("SELECT id, url, name, description, status, creation, metadescription, category, tags, viewCount, pubDate FROM blog WHERE status IN " & status & " AND tags LIKE ? ORDER BY " & sortingOrder), "%" & tags & "%") # else: -# allBlogPages = getAllRows(db, sql("SELECT id, url, name, description, status, creation, metadescription, category, tags FROM blog WHERE status IN " & status & " ORDER BY " & sortingOrder)) +# allBlogPages = getAllRows(db, sql("SELECT id, url, name, description, status, creation, metadescription, category, tags, viewCount, pubDate FROM blog WHERE status IN " & status & " ORDER BY " & sortingOrder)) # end if
    @@ -75,7 +75,8 @@ #
    - ${epochDate(blog[5], "YYYY-MM-DD")} + ${if blog[10] != "": blog[10] else: epochDate(blog[5], "YYYY-MM-DD")} + Views: ${blog[9]} # if c.loggedIn: ${statusIntToText(blog[4])} # end if diff --git a/nimwcpkg/tmpl/blogedit.tmpl b/nimwcpkg/tmpl/blogedit.tmpl index 548d53b5f..179aac8c9 100644 --- a/nimwcpkg/tmpl/blogedit.tmpl +++ b/nimwcpkg/tmpl/blogedit.tmpl @@ -32,7 +32,7 @@
    - +
    @@ -48,8 +48,8 @@
    - - View blog + + View blog
    diff --git a/nimwcpkg/tmpl/blognew.tmpl b/nimwcpkg/tmpl/blognew.tmpl index b2a9b00b7..e3bc4610f 100644 --- a/nimwcpkg/tmpl/blognew.tmpl +++ b/nimwcpkg/tmpl/blognew.tmpl @@ -25,7 +25,7 @@
    - +
    diff --git a/nimwcpkg/tmpl/editconfig.tmpl b/nimwcpkg/tmpl/editconfig.tmpl new file mode 100644 index 000000000..d6d2ee4dc --- /dev/null +++ b/nimwcpkg/tmpl/editconfig.tmpl @@ -0,0 +1,22 @@ +#? stdtmpl | standard +# +#proc genEditConfig(configIni: string): string = +# result = "" +
    +

    Nim Website Creator Configuration

    +
    + +
    + +
    +
    +
    +

    + Its NOT recommended to change Firejail settings here, + change Firejail settings from Firejail page. +

    +
    +
    +#end proc diff --git a/nimwcpkg/tmpl/files.tmpl b/nimwcpkg/tmpl/files.tmpl index 46f7579af..4bdc90a33 100644 --- a/nimwcpkg/tmpl/files.tmpl +++ b/nimwcpkg/tmpl/files.tmpl @@ -1,6 +1,6 @@ #? stdtmpl | standard # -#import mimetypes, ospaths, os, md5 +#import mimetypes, ospaths, os # #template `%`(idx: untyped): untyped = # row[idx] @@ -15,7 +15,7 @@ # let mime = newMimetypes() # let allFilesPrivate = filesListPrivate() # let allFilesPublic = filesListPublic() -# let allFilesPublicImages = filesListPublicFolderImages() +# let allFilesPublicImages = filesListPublicFolderFiles()

    Files

    @@ -38,6 +38,8 @@
    + +
    @@ -45,7 +47,7 @@
    -

    Public images (public/images)

    +

    Public Files (/public/images/)

    @@ -54,7 +56,7 @@ - + @@ -64,7 +66,7 @@ - + @@ -77,9 +79,9 @@ - - - + + + @@ -91,7 +93,7 @@
    -

    Private files (only for logged in users)

    +

    Public files (available to all)

    Filename MimeType SizeMD5 CheckSumLast Modification Delete
    Filename MimeType SizeMD5 CheckSumLast Modification Delete
    ${extractFilename(file)} ${ mime.getMimetype(file.splitFile.ext).toUpperAscii } ${ file.getFileSize } ${ file.readFile.getMD5 } ${ mime.getMimetype(file.splitFile.ext) } ${ formatSize(file.getFileSize, prefix = bpColloquial, includeSpace = true) } ${ getLastModificationTime(file) }
    @@ -100,7 +102,7 @@ - + @@ -110,24 +112,24 @@ - + # counter = 0 - # for file in allFilesPrivate: + # for file in allFilesPublic: # inc counter - - - - + + + # end for @@ -137,7 +139,7 @@
    -

    Public files (available to all)

    +

    Private files (only for logged in users)

    Filename MimeType SizeMD5 CheckSumLast Modification Delete
    Filename MimeType SizeMD5 CheckSumLast Modification Delete
    $counter + ${extractFilename(file)} ${ mime.getMimetype(file.splitFile.ext).toUpperAscii } ${ file.getFileSize } ${ file.readFile.getMD5 } ${ mime.getMimetype(file.splitFile.ext) } ${ formatSize(file.getFileSize, prefix = bpColloquial, includeSpace = true) } ${ getLastModificationTime(file) } - +
    @@ -146,7 +148,7 @@ - + @@ -156,30 +158,32 @@ - + # counter = 0 - # for file in allFilesPublic: + # for file in allFilesPrivate: # inc counter - - - - + + + # end for
    Filename MimeType SizeMD5 CheckSumLast Modification Delete
    Filename MimeType SizeMD5 CheckSumLast Modification Delete
    $counter + ${extractFilename(file)} ${ mime.getMimetype(file.splitFile.ext).toUpperAscii } ${ file.getFileSize } ${ file.readFile.getMD5 } ${ mime.getMimetype(file.splitFile.ext) } ${ formatSize(file.getFileSize, prefix = bpColloquial, includeSpace = true) } ${ getLastModificationTime(file) } - +
    Total files: $counter +
    +

    diff --git a/nimwcpkg/tmpl/firejail.tmpl b/nimwcpkg/tmpl/firejail.tmpl new file mode 100644 index 000000000..ee3bff4c7 --- /dev/null +++ b/nimwcpkg/tmpl/firejail.tmpl @@ -0,0 +1,437 @@ +#? stdtmpl | standard +# +#proc genFirejail(noDvd,noSound,noAutoPulse,no3d,noX,noVideo,noDbus,noShell, +# noDebuggers,noMachineId,noRoot,noAllusers,noU2f,privateTmp,privateCache, +# privateDev,forceEnUsUtf8,caps,seccomp,noTv,writables,noMnt: bool, +# maxSubProcesses, maxOpenFiles, maxFileSize, maxPendingSignals, +# timeout, maxCpu, maxRam, cpuCoresByNumber: int, +# hostsFile, dns0, dns1, dns2, dns3: string): string = +# result = "" +
    +

    Self-Firejailing Web Framework

    +

    + Firejail security is built-in on the Core of NimWC. +


    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Name & StatusDescription
    Name & StatusDescription
    + + No DVD/CD/BlueRay hardware access. The DVD from outside of NimWC are untouched.
    + + No Sound hardware access. The Sound from outside of NimWC are untouched.
    + + No PulseAudio Sound access (~/.config/pulse/). The PulseAudio from outside of NimWC are untouched.
    + + No 3D Accelerated hardware (GPU) access. The GPU from outside of NimWC are untouched.
    + + No Xorg access. Use XVFb instead, requires XVFb Installed. The X from outside of NimWC are untouched.
    + + No Video hardware access, runs with no Video hardware. The Video from outside of NimWC are untouched.
    + + No D-Bus (System Bus Protocol) access. The D-Bus from outside of NimWC are untouched.
    + + No System Shell access, runs without Shell. The Shell from outside of NimWC are untouched.
    + + No Source Code Debuggers like GDB, STrace, etc access. The Debuggers from outside of NimWC are untouched.
    + + No Machine ID unique identifier config (/etc/machine-id) access. The Machine ID from outside of NimWC are untouched.
    + + No root, no one can become root ever from inside of NimWC. Normal root and sudo from outside of NimWC are untouched.
    + + No home directories from other users are visible from inside of NimWC. The home directory of the user running NimWC are untouched.
    + + No U2F Universal 2 Factor Authentication hardware access. The U2F from outside of NimWC are untouched. 2 Factor Authentication Software are untouched.
    + + No DVB (Digital Video Broadcasting), Analog TV hardware, Digital TV hardware.
    + + Use a private temporary unique autogenerated TmpFS for /tmp/.
    + + Use a private temporary unique autogenerated TmpFS for ~/.cache/.
    + + Use a private temporary unique autogenerated TmpFS for /dev/.
    + + Linux Capabilities. This disables the default Capabilities inside NimWC.
    + + Linux Secure Computing Mode SecComp, enable using the default SecComp list (@default).
    + + Force Writable /etc/, /run/user/, /var/, /var/log/ (Readable too).
    + + No /mnt/, /media/, /run/mount/ and /run/media/ access.
    + + Force EN English and UTF-8 Unicode inside of NimWC. This sets several environment variables to EN and UTF-8 inside of NimWC.
    + + Maximum Sub-Processes on Hundreds that can be created per Linux user inside of NimWC. Positive integer number is Valid, 0 is Disabled, 0 is Default, 0 is Maximum Performance, 255 is Maximum, if you dont know or dont understand just leave it as 0. Anti-ForkBomb protection.
    + + Maximum number of opened files on Hundreds per process inside of NimWC. Positive integer number is Valid, 0 is Disabled, 0 is Default, if you dont know or dont understand just leave it as 0. IO Death Lock protection.
    + + Maximum file size on GigaBytes that can be created per process inside of NimWC. Positive integer number is Valid, 0 is Disabled, 0 is Default, 255 GigaBytes is Maximum, if you dont know or dont understand just leave it as 0.
    + + Maximum number of pending blocked signals per process inside of NimWC. Positive integer number is Valid, 0 is Disabled, 0 is Default, 0 is Maximum Performance, if you dont know or dont understand just leave it as 0.
    + + Force Restart after elapsed time on Hours. Positive integer number is Valid, 0 is Disabled, 0 is Default, 99 Hours is Maximum, 99 Hours is 4 Days, restart has 1 to 9 Seconds delay. Use this if you want your server to automatically restart every day, if you dont know or dont understand just leave it as 0.
    + + Maximum CPU time in seconds, you can control how much CPU NimWC uses. Positive integer number is Valid, 0 is Disabled, 0 is Default, 0 is Maximum Performance, 255 is Maximum, if you dont know or dont understand just leave it as 0.
    + + Maximum size of RAM on GigaBytes, you can control how much RAM NimWC uses. Positive integer number is Valid, 0 is Disabled, 0 is Default, 0 is Maximum Performance, 255 GigaBytes is Maximum, if you dont know or dont understand just leave it as 0.
    + + Dedicated CPU Cores to use, you can control how many CPU Cores NimWC uses. Positive integer number is Valid, 0 is Disabled, 0 is Default, 0 is Maximum Performance, ${countProcessors() - 1} is Maximum, if you dont know or dont understand just leave it as 0.
    + + Alternative or Fake /etc/hosts file to use, you can use a limited or tweaked /etc/hosts for NimWC. /etc/hosts is Default, /etc/hosts is the real hosts file, the file must exist, the hosts file of NimWC can be different than the hosts file of the operating system, you can use this to block suspicious domains (Spamm, Scamm, BotNets, etc), if you dont know or dont understand just leave it as /etc/hosts.
    + + Alternative or Custom DNS Server IP Address Number 0, the 4 DNS Servers must be provided or leave it Empty Blank, you can use a limited or tweaked DNS for NimWC. Empty blank field is Default, the DNS of NimWC can be different than the DNS of the operating system, if you dont know or dont understand just leave it as Empty Blank field (Empty string).
    + + Alternative or Custom DNS Server IP Address Number 1, the 4 DNS Servers must be provided or leave it Empty Blank, you can use a limited or tweaked DNS for NimWC. Empty blank field is Default, the DNS of NimWC can be different than the DNS of the operating system, if you dont know or dont understand just leave it as Empty Blank field (Empty string).
    + + Alternative or Custom DNS Server IP Address Number 2, the 4 DNS Servers must be provided or leave it Empty Blank, you can use a limited or tweaked DNS for NimWC. Empty blank field is Default, the DNS of NimWC can be different than the DNS of the operating system, if you dont know or dont understand just leave it as Empty Blank field (Empty string).
    + + Alternative or Custom DNS Server IP Address Number 3, the 4 DNS Servers must be provided or leave it Empty Blank, you can use a limited or tweaked DNS for NimWC. Empty blank field is Default, the DNS of NimWC can be different than the DNS of the operating system, if you dont know or dont understand just leave it as Empty Blank field (Empty string).
    + +
    +
    +
    Firejail Status
    +
    + # for capability in firejailFeatures.pairs: + $capability.key + # end for +
    +
    + You are protected by Firejail version $firejailVersion + , stay safe and use Nim. +
    +
    +#end proc diff --git a/nimwcpkg/tmpl/logs.tmpl b/nimwcpkg/tmpl/logs.tmpl index 527116374..147e612a6 100644 --- a/nimwcpkg/tmpl/logs.tmpl +++ b/nimwcpkg/tmpl/logs.tmpl @@ -2,13 +2,11 @@ # #proc genViewLogs(logcontent: string): string = # result = "" -
    -

    Logs

    - -
    - - - -
    +

    Logs

    + +
    + + + diff --git a/nimwcpkg/tmpl/main.tmpl b/nimwcpkg/tmpl/main.tmpl index 9a038a386..f43138bbd 100644 --- a/nimwcpkg/tmpl/main.tmpl +++ b/nimwcpkg/tmpl/main.tmpl @@ -4,7 +4,7 @@ #proc genMainAdmin(c: var TData, data: string, pageAction = ""): string = # result = "" # -# let title = getValue(db, sql"SELECT title FROM settings WHERE id = ?", "1") +# let title = getValue(db, sql"SELECT title FROM settings") @@ -93,7 +93,7 @@ #proc genMain(c: var TData, data: string, pageAction = ""): string = # result = "" # -# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings WHERE id = ?", "1") +# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings") # let loggedIn = if c.loggedIn == true: "true" else: "false" @@ -159,7 +159,7 @@ ${extensionCss()} #proc genPage(c: var TData, pageid: string): string = # result = "" # -# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings WHERE id = ?", "1") +# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings") # # # @@ -236,7 +236,7 @@ ${extensionCss()} #proc genPageBlog(c: var TData, blogid: string): string = # result = "" # -# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings WHERE id = ?", "1") +# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings") # # # var status = "2" @@ -245,7 +245,18 @@ ${extensionCss()} # end if # # let pageData = getRow(db, sql("SELECT standardhead, head, standardnavbar, navbar, description, standardfooter, footer, name, status, title, metadescription, metakeywords FROM blog WHERE id = ? AND status IN (" & status & ")"), blogid) +# +# var viewCount: int +# try: +# viewCount = parseInt(getValue(db, sql"SELECT viewCount FROM blog WHERE id = ?", blogid)) +# except: +# viewCount = 0 +# end try +# inc viewCount +# exec(db, sql"UPDATE blog SET viewCount = ? WHERE id = ?", viewCount, blogid) +# # let loggedIn = if c.loggedIn == true: "true" else: "false" +# diff --git a/nimwcpkg/tmpl/page.tmpl b/nimwcpkg/tmpl/page.tmpl index 036d08fd2..2bc953a94 100644 --- a/nimwcpkg/tmpl/page.tmpl +++ b/nimwcpkg/tmpl/page.tmpl @@ -41,4 +41,4 @@ # end if
    -#end proc \ No newline at end of file +#end proc diff --git a/nimwcpkg/tmpl/pageedit.tmpl b/nimwcpkg/tmpl/pageedit.tmpl index b2066c0a9..9d00b23f1 100644 --- a/nimwcpkg/tmpl/pageedit.tmpl +++ b/nimwcpkg/tmpl/pageedit.tmpl @@ -51,8 +51,8 @@
    - - View page + + View page
    diff --git a/nimwcpkg/tmpl/plugins.tmpl b/nimwcpkg/tmpl/plugins.tmpl index 678b7ea76..6cedcf964 100644 --- a/nimwcpkg/tmpl/plugins.tmpl +++ b/nimwcpkg/tmpl/plugins.tmpl @@ -22,12 +22,12 @@
    -

    Plugins repository

    +

    Plugin Store

    # if not pluginCheckGit():
    -

    Git (git) is not installed. Please install it. +

    Git (git) is not installed. Please install it. E.g. pacman -S git, apt install git, etc.

    @@ -36,7 +36,7 @@
    -

    Please download the repository with the plugins.

    +

    Please download the list of plugins.

    Download
    @@ -48,7 +48,7 @@

    Total Plugins: ${plugins.len}

      @@ -67,8 +67,8 @@ # var installedVersion = "" # for i in items(installedPlugin): installedVersion = i["version"].getStr() # end for - Installed: ${installedVersion} - Git version: ${plugin["version"].getStr()} + Installed ${installedVersion} + Git version ${plugin["version"].getStr()} # else: Version: ${plugin["version"].getStr()} @@ -78,12 +78,12 @@
    ${plugin["description"].getStr()} -
    +
    @@ -96,6 +96,13 @@

    Total Plugins: ${plugins.len}

    # end if +
    +
    + Plugins can do everything you want, HTML, CSS, JS, Nim, Canvas, WebGL, WASM, JavaScript Frameworks, use Dabatase etc. +

    + The Store only needs a Git URL so it can be Open Source or Private or Payed Plugins, + let NimWC be part of your Bussiness and Entrepreneurships. +
    #end proc diff --git a/nimwcpkg/tmpl/serverinfo.tmpl b/nimwcpkg/tmpl/serverinfo.tmpl index b1734fce4..1451a7a2a 100644 --- a/nimwcpkg/tmpl/serverinfo.tmpl +++ b/nimwcpkg/tmpl/serverinfo.tmpl @@ -1,40 +1,83 @@ #? stdtmpl | standard # -#import encodings, httpclient, nativesockets +#import httpclient #HACK: Do NOT move to main,leave it here. # #proc genServerInfo(): string = # result = "" -
    -

    Server Info

    -
    - +# +# +# when defined(demo): +# const uname = " Not available on Demo " +# const distr = " Not available on Demo " +# const uptim = " Not available on Demo " +# const pubip = " Not available on Demo " +# const disks = " Not available on Demo " +# const hostn = " Not available on Demo " +# const jailv = " Not available on Demo " +# const jailf = " Not available on Demo " +# else: +# let hostn = getHostname() +# let uptim = execCmdEx("uptime --pretty").output.strip +# let disks = execCmdEx("df --human-readable --local --output=avail " & getCurrentDir()).output.strip +# let jailf = when defined(firejail): $firejailFeatures.pretty.strip else: " Firejail is Disabled " +# const uname = staticExec("uname -a").strip +# const distr = staticExec("lsb_release -a").strip +# const jailv = when defined(firejail): $firejailVersion else: " Firejail is Disabled " +# let pubip = newHttpClient().getContent("http://api.ipify.org").strip +# end when +# +# +
    +

    Server Info

    +
    + + + + + + + + + + + + - + + + + + + + + + + - + - + - + - + - + - + - + - + @@ -51,6 +94,12 @@ + + + + + + @@ -61,25 +110,31 @@ - + + + + + + + - + - + - + - + - + - + @@ -90,11 +145,11 @@ - - -
    NameValue
    NameValue
    System ${execCmdEx("uname -a").output} System $uname
    Distro $distr
    Uptime $uptim
    Public IP $pubip
    Distro ${execCmdEx("lsb_release -a").output} Disk $disks
    Uptime ${execCmdEx("uptime --pretty").output} Hostname $hostn
    Public IP ${newHttpClient().getContent("http://api.ipify.org")} Compile Date $CompileDate
    Hostname ${getHostname()} Compile Time $CompileTime
    Compile Date $CompileDate Nim Version $NimVersion
    Compile Time $CompileTime Firejail Version $jailv
    Nim Version $NimVersion Firejail Status $jailf
    CPU $hostCPU.toUpperAscii CPU $hostCPU.toUpperAscii
    CPU Count ${countProcessors()}
    Current Directory ${getCurrentDir()}
    Log File ${defaultFilename()}
    App Directory ${getAppDir()}
    Biggest Integer $int.high
    Encoding ${getCurrentEncoding()}
    SSL? ${defined(ssl)} SSL enabled ${defined(ssl)}
    ReCaptcha enabled $useCaptcha
    WebP enabled ${defined(webp)}
    Release Build? ${defined(release)} Release Build ${defined(release)}
    Demo Mode? ${defined(demo)} Demo Mode enabled ${defined(demo)}
    Admin Notify? ${defined(adminnotify)} Admin Notify enabled ${defined(adminnotify)}
    Force Recompile? ${defined(rc)} Force Recompile enabled ${defined(rc)}
    Development Mode? ${defined(dev)} Development Mode enabled ${defined(dev)}
    Update from GIT? ${defined(gitupdate)} Update from GIT enabled ${defined(gitupdate)}
    Free Memory ${getFreeMem()}
    Occupied Memory ${getOccupiedMem()}
    Command Line Params ${commandLineParams()}
    Garbage Collector ${GC_getStatistics()}
    +
    + +#end proc diff --git a/nimwcpkg/tmpl/settings.tmpl b/nimwcpkg/tmpl/settings.tmpl index 4d4b91ac3..7643aaac9 100644 --- a/nimwcpkg/tmpl/settings.tmpl +++ b/nimwcpkg/tmpl/settings.tmpl @@ -10,7 +10,7 @@ #result = ""
    -

    Settings

    +

    Dashboard

    @@ -29,8 +29,8 @@

    @@ -42,47 +42,89 @@
    - # when defined(demo): - # if c.loggedIn and c.rank != Admin: -
    -

    The test user does not have access to edit the Settings, JS, - CSS and HTML of the core. Some options are hidden. -

    -
    - # end if - # end when - # - # if c.rank == Admin: - + # if c.rank == Admin or defined(demo): + +
    - + - +
    +
    + +
    + # when defined(firejail): + +
    + +
    +
    + # end when + # end if + # when defined(demo): +
    + + Some options are disabled on Demo!. + +
    + # end when +
    @@ -113,24 +155,20 @@
    -

    -
    HTML <head>
    - +
    HTML <head>

    -
    HTML <header> + <navbar>
    - +
    HTML <header> & <navbar>

    -
    HTML <footer>
    - +
    HTML <footer>
    diff --git a/nimwcpkg/tmpl/tos.html b/nimwcpkg/tmpl/tos.html new file mode 100644 index 000000000..baaa72013 --- /dev/null +++ b/nimwcpkg/tmpl/tos.html @@ -0,0 +1,40 @@ +
    +

    Terms Of Service

    +
    +

    These terms and conditions outline the rules and regulations for the use of This Website.


    + +

    + By accessing this website we assume you accept these terms and conditions in full. +

    +

    + Do not continue to use this web if you do not accept all of the terms and conditions stated on this page. +

    + +

    Cookies

    + +

    We may or may not use Cookies. By using this web you consent to the use of cookies.

    + +

    License

    + +

    You must not Re-License material from this web.

    + +

    User Comments

    + +

    This Website reserves the right to remove any Comments which it considers inappropriate.

    + +

    Approved organizations may hyperlink to our Web.

    + +

    Content Liability

    + +

    We shall have no responsibility or liability for any content appearing on this Web.

    + +

    Disclaimer

    + +

    This web is not liable for any loss or damage of any nature under any circunstance.

    + +

    Thank you for reading.

    +
    + +
    + + diff --git a/nimwcpkg/tmpl/user.tmpl b/nimwcpkg/tmpl/user.tmpl index a7d6fc272..401b35196 100644 --- a/nimwcpkg/tmpl/user.tmpl +++ b/nimwcpkg/tmpl/user.tmpl @@ -9,7 +9,7 @@ # result = "" # if not c.loggedIn: # -# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings WHERE id = ?", "1") +# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings") ${standardElements[0]} @@ -22,8 +22,9 @@ # when defined(demo): # end when @@ -44,22 +45,47 @@
    - +
    +
    +
    + +
    +
    - - #if useCaptcha:
    #end if + + + + + + ## DONT TOUCH, HoneyPot: https://github.com/ThomasTJdev/nim_websitecreator/issues/43#issue-403507393 + + ## DONT TOUCH, HoneyPot: https://stackoverflow.com/questions/36227376/better-honeypot-implementation-form-anti-spam/36227377
    @@ -82,7 +108,7 @@ #proc genUsers(c: var TData): string = # result = "" # -# let allUsers = getAllRows(db, sql"SELECT id, name, email, status, lastOnline, secretUrl FROM person") +# let allUsers = getAllRows(db, sql"SELECT id, name, email, status, lastOnline, secretUrl, twofa FROM person")
    @@ -124,20 +150,24 @@ # + ID User Mail Last online Rank + 2FA Delete # + ID User Mail Last online Rank + 2FA Delete @@ -152,6 +182,7 @@ # counter += 1 $counter + ${user[0]} ${user[1]} ${user[2]} # if user[5] == "": @@ -161,6 +192,11 @@ Mail unconfirmed Mail unconfirmed # end if + + # if c.rank == Admin: + ${toUpperAscii($(user[6].len > 6))} + # end if + # end for @@ -180,7 +216,7 @@ #proc genUsersProfile(c: var TData): string = # result = "" # -# let userData = getAllRows(db, sql"SELECT id, name, email, status, lastOnline FROM person WHERE id = ?", c.userid) +# let userData = getAllRows(db, sql"SELECT id, name, email, status, lastOnline, twofa FROM person WHERE id = ?", c.userid) @@ -209,12 +245,62 @@
    - +
    - + +
    + +
    + + # if user[5].len() > 0: + + Disable + # else: + Enable + + # end if
    @@ -222,6 +308,8 @@
    +
    +
    diff --git a/nimwcpkg/tmpl/utils.tmpl b/nimwcpkg/tmpl/utils.tmpl index 4ccdcf932..5496aa68a 100644 --- a/nimwcpkg/tmpl/utils.tmpl +++ b/nimwcpkg/tmpl/utils.tmpl @@ -100,9 +100,6 @@ # result = "" - - - @@ -135,8 +132,23 @@ # var metakeywords = "" # var category = "" # var tags = "" +# var pubDate = currentDatetime("date") +# var viewCount = "0" # -# if edit: +# if edit and blog: +# let pageOrBlog = if page == true: "pages" else: "blog" +# let details = getRow(db, sql("SELECT title, metadescription, metakeywords, category, tags, pubDate, creation, viewCount FROM " & pageOrBlog & " WHERE id = ?"), pageid) +# +# title = details[0] +# metadescription = details[1] +# metakeywords = details[2] +# category = details[3] +# tags = details[4] +# pubDate = if details[5] != "": details[5] else: epochDate(details[6], "YYYY-MM-DD") +# viewCount = details[7] +# end if +# +# if edit and page: # let pageOrBlog = if page == true: "pages" else: "blog" # let details = getRow(db, sql("SELECT title, metadescription, metakeywords, category, tags FROM " & pageOrBlog & " WHERE id = ?"), pageid) # @@ -151,18 +163,42 @@

    Change editor

    - +
    - +
    - +

    # end if +# if blog: +

    Customize blog

    +
    + +
    +
    + + + If no date is specified, the creation date will be used. The date has no effect and will only be shown on the blog overview page. Format the date: YYYY-MM-DD +
    +
    + +
    +
    + + +
    +
    + +
    + +
    +# end if +

    Categorize

    @@ -375,8 +411,13 @@ # # elif c.req.cookies.hasKey("editor") and c.req.cookies["editor"] == "summernote": # - - + + + + + + + diff --git a/public/css/style_admin.css b/public/css/style_admin.css index ad619ccc5..9211cea54 100644 --- a/public/css/style_admin.css +++ b/public/css/style_admin.css @@ -229,13 +229,6 @@ div#settingsEdit { max-width: 1400px; padding: 10px; } -div#settingsEdit pre.templateCode { - border-radius: 2px; - border: 1px solid grey; - padding: 5px; -} - - /* @@ -455,6 +448,20 @@ div#user #editProfilePhoto { text-align: center; background: white; } +div#user div.twofa-container { + border: 1px solid black; + padding: 5px; +} +div#user div.twofa-container input { + margin: 5px 0 5px 0; +} +div#user input.twofaEnabled { + display: inline-block; + font-weight: 700; + background-color: #a1ffb1; + color: #3a3a3a; + width: auto; +} @media only screen and (max-width: 768px) { div#user label { margin-top: 15px; @@ -489,7 +496,7 @@ div#fileAddContainer { } form#fileAdd { border: 1px solid grey; - width: 300px; + width: 320px; padding: 10px; border-radius: 10px; margin-top: 10px; @@ -573,12 +580,12 @@ li.pluginSettings .disablePlugin { li.pluginSettings .enablePlugin { background: rgba(0, 128, 0, 0.5); } -li.pluginSettings.enabled .enablePlugin { - display: none; -} li.pluginSettings .disablePlugin { background: rgba(194, 54, 54, 0.5); } +li.pluginSettings.enabled .enablePlugin { + display: none; +} li.pluginSettings.disabled .disablePlugin { display: none; } @@ -627,6 +634,44 @@ li.pluginRepo span.version.git { font-weight: bold; } + +/* + Server info +*/ +#serverinfo { + width: 700px; + margin-left: auto; + margin-right: auto; + background-color: white; + padding: 20px; +} + + + +/* + Config +*/ +#config { + width: 600px; + margin-left: auto; + margin-right: auto; + background-color: white; +} + + + +/* + Firejail +*/ +#firejail { + width: 800px; + margin-left: auto; + margin-right: auto; + background-color: white; + padding: 20px; +} + + /* Saved notification */ diff --git a/public/js/codemirror_custom.js b/public/js/codemirror_custom.js index a440c80be..90efa5c22 100644 --- a/public/js/codemirror_custom.js +++ b/public/js/codemirror_custom.js @@ -11,4 +11,4 @@ !function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";var l=e.Pos;function c(e,n){return e.line-n.line||e.ch-n.ch}var n="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",i=new RegExp("<(/?)(["+n+"][A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*)","g");function a(e,n,t,i){this.line=n,this.ch=t,this.cm=e,this.text=e.getLine(n),this.min=i?Math.max(i.from,e.firstLine()):e.firstLine(),this.max=i?Math.min(i.to-1,e.lastLine()):e.lastLine()}function r(e,n){var t=e.cm.getTokenTypeAt(l(e.line,n));return t&&/\btag\b/.test(t)}function u(e){if(!(e.line>=e.max))return e.ch=0,e.text=e.cm.getLine(++e.line),!0}function f(e){if(!(e.line<=e.min))return e.text=e.cm.getLine(--e.line),e.ch=e.text.length,!0}function s(e){for(;;){var n=e.text.indexOf(">",e.ch);if(-1==n){if(u(e))continue;return}if(r(e,n+1)){var t=e.text.lastIndexOf("/",n),i=-1",e.ch-1):-1;if(-1==n){if(f(e))continue;return}if(r(e,n+1)){var t=e.text.lastIndexOf("/",n),i=-1")||-1!=i.text.indexOf("<")){var r=s(i),u=r&&l(i.line,i.ch),f=r&&h(i);if(r&&f&&!(00;)1&t&&(n+=e),t>>=1,e+=e;return n}},function(e,t,n){(function(t){function n(e,t){function n(){if(!r){if(a("throwDeprecation"))throw new Error(t);a("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}if(a("noDeprecation"))return e;var r=!1;return n}function a(e){try{if(!t.localStorage)return!1}catch(e){return!1}var n=t.localStorage[e];return null!=n&&"true"===String(n).toLowerCase()}e.exports=n}).call(t,n(60))},function(e,t,n){"use strict";!function(e){function n(){var e=arguments[0],t=n.cache;return t[e]&&t.hasOwnProperty(e)||(t[e]=n.parse(e)),n.format.call(null,t[e],arguments)}function a(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function r(e,t){return Array(t+1).join(e)}var o={not_string:/[^s]/,number:/[diefg]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};n.format=function(e,t){var i,s,l,c,u,p,d,f=1,m=e.length,g="",h=[],v=!0,b="";for(s=0;s=0),c[8]){case"b":i=i.toString(2);break;case"c":i=String.fromCharCode(i);break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,c[6]?parseInt(c[6]):0);break;case"e":i=c[7]?i.toExponential(c[7]):i.toExponential();break;case"f":i=c[7]?parseFloat(i).toFixed(c[7]):parseFloat(i);break;case"g":i=c[7]?parseFloat(i).toPrecision(c[7]):parseFloat(i);break;case"o":i=i.toString(8);break;case"s":i=(i=String(i))&&c[7]?i.substring(0,c[7]):i;break;case"u":i>>>=0;break;case"x":i=i.toString(16);break;case"X":i=i.toString(16).toUpperCase()}o.json.test(c[8])?h[h.length]=i:(!o.number.test(c[8])||v&&!c[3]?b="":(b=v?"+":"-",i=i.toString().replace(o.sign,"")),p=c[4]?"0"===c[4]?"0":c[4].charAt(1):" ",d=c[6]-(b+i).length,u=c[6]&&d>0?r(p,d):"",h[h.length]=c[5]?b+i+u:"0"===p?b+u+i:u+b+i)}return h.join("")},n.cache={},n.parse=function(e){for(var t=e,n=[],a=[],r=0;t;){if(null!==(n=o.text.exec(t)))a[a.length]=n[0];else if(null!==(n=o.modulo.exec(t)))a[a.length]="%";else{if(null===(n=o.placeholder.exec(t)))throw new SyntaxError("[sprintf] unexpected placeholder");if(n[2]){r|=1;var i=[],s=n[2],l=[];if(null===(l=o.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(i[i.length]=l[1];""!==(s=s.substring(l[0].length));)if(null!==(l=o.key_access.exec(s)))i[i.length]=l[1];else{if(null===(l=o.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");i[i.length]=l[1]}n[2]=i}else r|=2;if(3===r)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");a[a.length]=n}t=t.substring(n[0].length)}return a};var i=function(e,t,a){return a=(t||[]).slice(0),a.splice(0,0,e),n.apply(null,a)};t.sprintf=n,t.vsprintf=i}("undefined"==typeof window||window)},function(e,t,n){var a=n(8);e.exports=function(e,t,n,r){t=t||", ",n=n||" and ";var o=e.slice(),i=o.pop();return e.length>2&&r&&(n=a(t)+n),o.length?o.join(t)+n+i:i}},function(e,t){e.exports=function(e,t){return[t,e,t].join("")}},function(e,t,n){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{};window.editor=e;var n=t.blocks||{},a=t.labels||{},o=t.blockCategories||{};delete t.blocks,delete t.labels,delete t.blockCategories;var i={default:!0,text:!0,link:!0,image:!0,container:!0,row:!0,column:!0,column_break:!0,media_object:!0,alert:!0,badge:!0,button:!0,button_group:!0,button_toolbar:!0,card:!0,card_container:!0,collapse:!0,dropdown:!0,header:!0,paragraph:!0,list:!0},s={container:"Container",row:"Row",column:"Column",column_break:"Column Break",media_object:"Media Object",alert:"Alert",badge:"Badge",button:"Button",button_group:"Button Group",button_toolbar:"Button Toolbar",card:"Card",card_container:"Card Container",collapse:"Collapse",dropdown:"Dropdown",dropdown_menu:"Dropdown Menu",dropdown_item:"Dropdown Item",text:"Text",header:"Header",paragraph:"Paragraph",image:"Image",link:"Link",list:"Simple List"},c={layout:!0,components:!0,typography:!0,basic:!0},p=r({blocks:Object.assign(i,n),labels:Object.assign(s,a),blockCategories:Object.assign(c,o),gridDevices:!0,gridDevicesPanel:!1},t);e.addComponents('\n \n '),(0,l.default)(e,p),(0,u.default)(e,p),(0,d.default)(e,p),(0,m.default)(e,p),(0,h.default)(e,p)})},function(t,n){t.exports=e},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=n(2);!function(e){e&&e.__esModule}(a);t.default=function(e){arguments.length>1&&void 0!==arguments[1]&&arguments[1],e.Commands}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=n(2),r=function(e){return e&&e.__esModule?e:{default:e}}(a);t.default=function(e){arguments.length>1&&void 0!==arguments[1]&&arguments[1];e.TraitManager.addType("class_select",{events:{change:"onChange"},getInputEl:function(){if(!this.inputEl){for(var e=this.model,t=e.get("options")||[],n=document.createElement("select"),a=(this.target,this.target.view.el),o=0;o0)for(var n=e[t].split(" "),a=0;a0&&this.target.removeClass(n[a]);var r=this.model.get("value");if(r.length>0&&"GJS_NO_CLASS"!=r)for(var o=r.split(" "),i=0;i1&&void 0!==arguments[1]?arguments[1]:{},n=["primary","secondary","success","info","warning","danger","light","dark"],a=n.concat(["white"]),o={lg:"Large",sm:"Small"},s=t,c=e.DomComponents,p=s.blocks,f=s.blockCategories,m=c.getType("default"),g=m.model,h=m.view,v=c.getType("text"),b=v.model,y=v.view,x=c.getType("link"),w=x.model,_=x.view,C=c.getType("image"),j=C.model,k=C.view;f.basic&&(p.default&&(c.addType("default",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{tagName:"div",traits:[{type:"class_select",options:[{value:"",name:"Default"}].concat(r(a.map(function(e){return{value:"text-"+e,name:l.default.capitalize(e)}}))),label:"Text color"},{type:"class_select",options:[{value:"",name:"Default"}].concat(r(a.map(function(e){return{value:"bg-"+e,name:l.default.capitalize(e)}}))),label:"Background color"},{type:"class_select",options:[{value:"",name:"Default"},{value:"border",name:"Full"},{value:"border-top-0",name:"No top"},{value:"border-right-0",name:"No right"},{value:"border-bottom-0",name:"No bottom"},{value:"border-left-0",name:"No left"},{value:"border-0",name:"None"}],label:"Border width"},{type:"class_select",options:[{value:"",name:"Default"}].concat(r(a.map(function(e){return{value:"border border-"+e,name:l.default.capitalize(e)}}))),label:"Border color"},{type:"class_select",options:[{value:"",name:"Default"},{value:"rounded",name:"Rounded"},{value:"rounded-top",name:"Rounded top"},{value:"rounded-right",name:"Rounded right"},{value:"rounded-bottom",name:"Rounded bottom"},{value:"rounded-left",name:"Rounded left"},{value:"rounded-circle",name:"Circle"},{value:"rounded-0",name:"Square"}],label:"Border radius"},{type:"text",label:"ID",name:"id",placeholder:"my_element"},{type:"text",label:"Title",name:"title",placeholder:"My Element"}]}),init:function(){var e=this.get("classes");e.bind("add",this.classesChanged.bind(this)),e.bind("change",this.classesChanged.bind(this)),e.bind("remove",this.classesChanged.bind(this)),this.init2()},init2:function(){},classesChanged:function(){},changeType:function(e){var t=this.collection,n=t.indexOf(this),a={type:e,style:this.getStyle(),attributes:this.getAttributes(),content:this.view.el.innerHTML};t.remove(this),t.add(a,{at:n}),this.destroy()}}),view:h}),m=c.getType("default"),g=m.model,h=m.view),p.text&&(c.addType("text",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Text",tagName:"div",droppable:!0,editable:!0})},{}),view:y}),v=c.getType("text"),b=v.model,y=v.view),p.link&&(c.addType("link",{model:b.extend({defaults:Object.assign({},b.prototype.defaults,{"custom-name":"Link",tagName:"a",droppable:!0,editable:!0,traits:[{type:"text",label:"Href",name:"href",placeholder:"https://www.grapesjs.com"},{type:"select",options:[{value:"",name:"This window"},{value:"_blank",name:"New window"}],label:"Target",name:"target"},{type:"select",options:[{value:"",name:"None"},{value:"button",name:"Self"},{value:"collapse",name:"Collapse"},{value:"dropdown",name:"Dropdown"}],label:"Toggles",name:"data-toggle",changeProp:1}].concat(b.prototype.defaults.traits)}),init2:function(){this.listenTo(this,"change:data-toggle",this.setupToggle),this.listenTo(this,"change:attributes",this.setupToggle)},setupToggle:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!0!==n.ignore||!0===n.force){console.log("setup toggle");var a=this.getAttributes(),r=a.href;if(delete a["data-toggle"],delete a["aria-expanded"],delete a["aria-controls"],delete a["aria-haspopup"],r&&r.length>0&&r.match(/^#/)){console.log("link has href");var o=this.em.get("Editor").DomComponents.getWrapper().find(r);if(o.length>0){console.log("referenced el found");var s=o[0],l=s.getAttributes(),c=l.class;if(c){console.log("el has classes");var u=c.split(" "),p=i.default.intersection(["collapse","dropdown-menu"],u);if(p.length){switch(console.log("link data-toggle matches el class"),p[0]){case"collapse":a["data-toggle"]="collapse"}a["aria-expanded"]=u.includes("show"),"collapse"==p[0]&&(a["aria-controls"]=r.substring(1))}}}}this.set("attributes",a,{ignore:!0})}},classesChanged:function(e){console.log("classes changed"),"link"==this.attributes.type&&this.attributes.classes.filter(function(e){return"btn"==e.id}).length>0&&this.changeType("button")}},{isComponent:function(e){if(e&&e.tagName&&"A"==e.tagName)return{type:"link"}}}),view:_}),x=c.getType("link"),w=x.model,_=x.view),p.image&&(c.addType("image",{model:j.extend({defaults:Object.assign({},j.prototype.defaults,{"custom-name":"Image",tagName:"img",resizable:1,attributes:{src:"https://dummyimage.com/450x250/999/222"},traits:[{type:"text",label:"Source (URL)",name:"src"},{type:"text",label:"Alternate text",name:"alt"}].concat(j.prototype.defaults.traits)})},{isComponent:function(e){if(e&&"IMG"==e.tagName)return{type:"image"}}}),view:k}),C=c.getType("image"),j=C.model,k=C.view)),f.layout&&(p.container&&c.addType("container",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Container",tagName:"div",droppable:!0,traits:[{type:"class_select",options:[{value:"container",name:"Fixed"},{value:"container-fluid",name:"Fluid"}],label:"Width"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&(e.classList.contains("container")||e.classList.contains("container-fluid")))return{type:"container"}}}),view:h}),p.row&&c.addType("row",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Row",tagName:"div",draggable:".container, .container-fluid",droppable:!0,traits:[{type:"class_select",options:[{value:"",name:"Yes"},{value:"no-gutters",name:"No"}],label:"Gutters?"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("row"))return{type:"row"}}}),view:h}),p.column&&(c.addType("column",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Column",draggable:".row",droppable:!0,traits:[{type:"class_select",options:[{value:"col",name:"Equal"},{value:"col-auto",name:"Variable"}].concat(r([1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"col-"+e,name:e+"/12"}}))),label:"XS Width"},{type:"class_select",options:[{value:"",name:"None"},{value:"col-sm",name:"Equal"},{value:"col-sm-auto",name:"Variable"}].concat(r([1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"col-sm-"+e,name:e+"/12"}}))),label:"SM Width"},{type:"class_select",options:[{value:"",name:"None"},{value:"col-md",name:"Equal"},{value:"col-md-auto",name:"Variable"}].concat(r([1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"col-md-"+e,name:e+"/12"}}))),label:"MD Width"},{type:"class_select",options:[{value:"",name:"None"},{value:"col-lg",name:"Equal"},{value:"col-lg-auto",name:"Variable"}].concat(r([1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"col-lg-"+e,name:e+"/12"}}))),label:"LG Width"},{type:"class_select",options:[{value:"",name:"None"},{value:"col-xl",name:"Equal"},{value:"col-xl-auto",name:"Variable"}].concat(r([1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"col-xl-"+e,name:e+"/12"}}))),label:"XL Width"},{type:"class_select",options:[{value:"",name:"None"}].concat(r([0,1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"offset-"+e,name:e+"/12"}}))),label:"XS Offset"},{type:"class_select",options:[{value:"",name:"None"}].concat(r([0,1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"offset-sm-"+e,name:e+"/12"}}))),label:"SM Offset"},{type:"class_select",options:[{value:"",name:"None"}].concat(r([0,1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"offset-md-"+e,name:e+"/12"}}))),label:"MD Offset"},{type:"class_select",options:[{value:"",name:"None"}].concat(r([0,1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"offset-lg-"+e,name:e+"/12"}}))),label:"LG Offset"},{type:"class_select",options:[{value:"",name:"None"}].concat(r([0,1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"offset-xl-"+e,name:e+"/12"}}))),label:"XL Offset"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){var t=!1;if(e&&e.classList&&e.classList.forEach(function(e){("col"==e||e.match(/^col-/))&&(t=!0)}),t)return{type:"column"}}}),view:h}),c.addType("column_break",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Column Break",tagName:"div",classes:["w-100"]})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("w-100"))return{type:"column_break"}}}),view:h}),c.addType("media_object",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Media Object",tagName:"div",classes:["media"]})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("media"))return{type:"media"}}}),view:h}),c.addType("media_body",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Media Body",tagName:"div",classes:["media-body"]})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("media-body"))return{type:"media_body"}}}),view:h}))),f.components&&(p.alert&&c.addType("alert",{model:b.extend({defaults:Object.assign({},b.prototype.defaults,{"custom-name":"Alert",tagName:"div",classes:["alert"],traits:[{type:"class_select",options:[{value:"",name:"None"}].concat(r(n.map(function(e){return{value:"alert-"+e,name:l.default.capitalize(e)}}))),label:"Context"}].concat(b.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("alert"))return{type:"alert"}}}),view:y}),p.badge&&c.addType("badge",{model:b.extend({defaults:Object.assign({},b.prototype.defaults,{"custom-name":"Badge",tagName:"span",classes:["badge"],traits:[{type:"class_select",options:[{value:"",name:"None"}].concat(r(n.map(function(e){return{value:"badge-"+e,name:l.default.capitalize(e)}}))),label:"Context"},{type:"class_select",options:[{value:"",name:"Default"},{value:"badge-pill",name:"Pill"}],label:"Shape"}].concat(b.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("badge"))return{type:"badge"}}}),view:y}),p.button&&c.addType("button",{model:w.extend({defaults:Object.assign({},w.prototype.defaults,{"custom-name":"Button",attributes:{role:"button"},classes:["btn"],traits:[{type:"class_select",options:[{value:"",name:"None"}].concat(r(n.map(function(e){return{value:"btn-"+e,name:l.default.capitalize(e)}})),r(n.map(function(e){return{value:"btn-outline-"+e,name:l.default.capitalize(e)+" (Outline)"}}))),label:"Context"},{type:"class_select",options:[{value:"",name:"Default"}].concat(r(Object.keys(o).map(function(e){return{value:"btn-"+e,name:o[e]}}))),label:"Size"},{type:"class_select",options:[{value:"",name:"Inline"},{value:"btn-block",name:"Block"}],label:"Width"}].concat(w.prototype.defaults.traits)}),afterChange:function(e){"button"==this.attributes.type&&0==this.attributes.classes.filter(function(e){return"btn"==e.id}).length&&this.changeType("link")}},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("btn"))return{type:"button"}}}),view:_}),p.button_group&&c.addType("button_group",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Button Group",tagName:"div",classes:["btn-group"],droppable:".btn",attributes:{role:"group"},traits:[{type:"class_select",options:[{value:"",name:"Default"}].concat(r(Object.keys(o).map(function(e){return{value:"btn-group-"+e,name:o[e]}}))),label:"Size"},{type:"class_select",options:[{value:"",name:"Horizontal"},{value:"btn-group-vertical",name:"Vertical"}],label:"Size"},{type:"Text",label:"ARIA Label",name:"aria-label",placeholder:"A group of buttons"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("btn-group"))return{type:"button_group"}}}),view:h}),p.button_toolbar&&c.addType("button_toolbar",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Button Toolbar",tagName:"div",classes:["btn-toolbar"],droppable:".btn-group",attributes:{role:"toolbar"},traits:[{type:"Text",label:"ARIA Label",name:"aria-label",placeholder:"A toolbar of button groups"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("btn-toolbar"))return{type:"button_toolbar"}}}),view:h}),p.card&&(c.addType("card",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card",classes:["card"],traits:[{type:"checkbox",label:"Image Top",name:"card-img-top",changeProp:1},{type:"checkbox",label:"Header",name:"card-header",changeProp:1},{type:"checkbox",label:"Image",name:"card-img",changeProp:1},{type:"checkbox",label:"Image Overlay",name:"card-img-overlay",changeProp:1},{type:"checkbox",label:"Body",name:"card-body",changeProp:1},{type:"checkbox",label:"Footer",name:"card-footer",changeProp:1},{type:"checkbox",label:"Image Bottom",name:"card-img-bottom",changeProp:1}].concat(g.prototype.defaults.traits)}),init2:function(){this.listenTo(this,"change:card-img-top",this.cardImageTop),this.listenTo(this,"change:card-header",this.cardHeader),this.listenTo(this,"change:card-img",this.cardImage),this.listenTo(this,"change:card-img-overlay",this.cardImageOverlay),this.listenTo(this,"change:card-body",this.cardBody),this.listenTo(this,"change:card-footer",this.cardFooter),this.listenTo(this,"change:card-img-bottom",this.cardImageBottom),this.components().comparator="card-order",this.set("card-img-top",!0),this.set("card-body",!0)},cardImageTop:function(){this.createCardComponent("card-img-top")},cardHeader:function(){this.createCardComponent("card-header")},cardImage:function(){this.createCardComponent("card-img")},cardImageOverlay:function(){this.createCardComponent("card-img-overlay")},cardBody:function(){this.createCardComponent("card-body")},cardFooter:function(){this.createCardComponent("card-footer")},cardImageBottom:function(){this.createCardComponent("card-img-bottom")},createCardComponent:function(e){var t=this.get(e),n=e.replace(/-/g,"_").replace(/img/g,"image"),a=this.components(),r=a.filter(function(e){return e.attributes.type==n})[0];if(t&&!r){var o=a.add({type:n}),i=o.components();"card-header"==e&&i.add({type:"header",tagName:"h4",style:{"margin-bottom":"0px"},content:"Card Header"}),"card-img-overlay"==e&&(i.add({type:"header",tagName:"h4",classes:["card-title"],content:"Card title"}),i.add({type:"text",tagName:"p",classes:["card-text"],content:"Some quick example text to build on the card title and make up the bulk of the card's content."})),"card-body"==e&&(i.add({type:"header",tagName:"h4",classes:["card-title"],content:"Card title"}),i.add({type:"header",tagName:"h6",classes:["card-subtitle","text-muted","mb-2"],content:"Card subtitle"}),i.add({type:"text",tagName:"p",classes:["card-text"],content:"Some quick example text to build on the card title and make up the bulk of the card's content."}),i.add({type:"link",classes:["card-link"],href:"#",content:"Card link"}),i.add({type:"link",classes:["card-link"],href:"#",content:"Another link"})),this.order()}else t||r.destroy()},order:function(){}},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card"))return{type:"card"}}}),view:h}),c.addType("card_image_top",{model:j.extend({defaults:Object.assign({},j.prototype.defaults,{"custom-name":"Card Image Top",classes:["card-img-top"],"card-order":1})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-img-top"))return{type:"card_image_top"}}}),view:k}),c.addType("card_header",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card Header",classes:["card-header"],"card-order":2})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-header"))return{type:"card_header"}}}),view:h}),c.addType("card_image",{model:j.extend({defaults:Object.assign({},j.prototype.defaults,{"custom-name":"Card Image",classes:["card-img"],"card-order":3})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-img"))return{type:"card_image"}}}),view:k}),c.addType("card_image_overlay",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card Image Overlay",classes:["card-img-overlay"],"card-order":4})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-img-overlay"))return{type:"card_image_overlay"}}}),view:h}),c.addType("card_body",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card Body",classes:["card-body"],"card-order":5})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-body"))return{type:"card_body"}}}),view:h}),c.addType("card_footer",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card Footer",classes:["card-footer"],"card-order":6})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-footer"))return{type:"card_footer"}}}),view:h}),c.addType("card_image_bottom",{model:j.extend({defaults:Object.assign({},j.prototype.defaults,{"custom-name":"Card Image Bottom",classes:["card-img-bottom"],"card-order":7})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-img-bottom"))return{type:"card_image_bottom"}}}),view:k}),c.addType("card_container",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card Container",classes:["card-group"],droppable:".card",traits:[{type:"class_select",options:[{value:"card-group",name:"Group"},{value:"card-deck",name:"Deck"},{value:"card-columns",name:"Columns"}],label:"Layout"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&i.default.intersection(e.classList,["card-group","card-deck","card-columns"]).length)return{type:"card_container"}}}),view:h})),p.collapse&&(0,u.default)(e,t),p.dropdown&&(0,d.default)(e,t)),f.typography&&(p.header&&c.addType("header",{model:b.extend({defaults:Object.assign({},b.prototype.defaults,{"custom-name":"Header",tagName:"h1",traits:[{type:"select",options:[{value:"h1",name:"One (largest)"},{value:"h2",name:"Two"},{value:"h3",name:"Three"},{value:"h4",name:"Four"},{value:"h5",name:"Five"},{value:"h6",name:"Six (smallest)"}],label:"Size",name:"tagName",changeProp:1},{type:"class_select",options:[{value:"",name:"None"},{value:"display-1",name:"One (largest)"},{value:"display-2",name:"Two "},{value:"display-3",name:"Three "},{value:"display-4",name:"Four (smallest)"}],label:"Display Heading"}].concat(b.prototype.defaults.traits)})},{isComponent:function(e){if(e&&["H1","H2","H3","H4","H5","H6"].includes(e.tagName))return{type:"header"}}}),view:y}),p.paragraph&&c.addType("paragraph",{model:b.extend({defaults:Object.assign({},b.prototype.defaults,{"custom-name":"Paragraph",tagName:"p",traits:[{type:"class_select",options:[{value:"",name:"No"},{value:"lead",name:"Yes"}],label:"Lead?"}].concat(b.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.tagName&&"P"==e.tagName)return{type:"paragraph"}}}),view:y}))}},function(e,t,n){var a=n(0);e.exports=function(e){return a(e).replace(/<\/?[^>]+>/g,"")}},function(e,t){e.exports=function(e,t){return null==e?[]:(e=String(e),t=~~t,t>0?e.match(new RegExp(".{1,"+t+"}","g")):[e])}},function(e,t,n){var a=n(1);e.exports=function(e){return a(e).replace(/\s\s+/g," ")}},function(e,t,n){var a=n(0);e.exports=function(e,t){return e=a(e),t=a(t),0===e.length||0===t.length?0:e.split(t).length-1}},function(e,t,n){var a=n(0);e.exports=function(e){return a(e).replace(/\S/g,function(e){return e===e.toUpperCase()?e.toLowerCase():e.toUpperCase()})}},function(e,t,n){var a=n(0),r=n(35),o="[";for(var i in r)o+=i;o+="]";var s=new RegExp(o,"g");e.exports=function(e){return a(e).replace(s,function(e){return"&"+r[e]+";"})}},function(e,t){var n={"¢":"cent","£":"pound","¥":"yen","€":"euro","©":"copy","®":"reg","<":"lt",">":"gt",'"':"quot","&":"amp","'":"#39"};e.exports=n},function(e,t,n){var a=n(0),r=n(37);e.exports=function(e){return a(e).replace(/\&([^;]+);/g,function(e,t){var n;return t in r?r[t]:(n=t.match(/^#x([\da-fA-F]+)$/))?String.fromCharCode(parseInt(n[1],16)):(n=t.match(/^#(\d+)$/))?String.fromCharCode(~~n[1]):e})}},function(e,t){var n={nbsp:" ",cent:"¢",pound:"£",yen:"¥",euro:"€",copy:"©",reg:"®",lt:"<",gt:">",quot:'"',amp:"&",apos:"'"};e.exports=n},function(e,t,n){var a=n(13);e.exports=function(e,t,n){return a(e,t,0,n)}},function(e,t,n){var a=n(0);e.exports=function(e,t,n,r){var o=!0===r?"gi":"g",i=new RegExp(t,o);return a(e).replace(i,n)}},function(e,t,n){var a=n(0);e.exports=function(e,t){return""===t||-1!==a(e).indexOf(t)}},function(e,t,n){var a=n(0),r=[].slice;e.exports=function(){var e=r.call(arguments),t=e.shift();return e.join(a(t))}},function(e,t){e.exports=function(e){return null==e?[]:String(e).split(/\r\n?|\n/)}},function(e,t,n){function a(e){for(var t=e.match(/^[\s\\t]*/gm),n=t[0].length,a=1;a=0&&e.indexOf(t,n)===n}},function(e,t,n){var a=n(15);e.exports=function(e){return a(e,-1)}},function(e,t,n){var a=n(15);e.exports=function(e){return a(e,1)}},function(e,t,n){var a=n(0);e.exports=function(e){return a(e).toLowerCase().replace(/(?:^|\s|-)\S/g,function(e){return e.toUpperCase()})}},function(e,t,n){var a=n(5),r=n(16),o=n(0);e.exports=function(e){return e=o(e),a(r(e.replace(/[\W_]/g," ")).replace(/\s/g,""))}},function(e,t,n){var a=n(5),r=n(17),o=n(1);e.exports=function(e){return a(o(r(e).replace(/_id$/,"").replace(/_/g," ")))}},function(e,t,n){var a=n(0),r=n(6),o=String.prototype.trimLeft;e.exports=function(e,t){return e=a(e),!t&&o?o.call(e):(t=r(t),e.replace(new RegExp("^"+t+"+"),""))}},function(e,t,n){var a=n(0);e.exports=function(e,t,n){return e=a(e),n=n||"...",t=~~t,e.length>t?e.slice(0,t)+n:e}},function(e,t,n){var a=n(0),r=n(8);e.exports=function(e,t,n){if(e=a(e),t=~~t,n=null!=n?String(n):"...",e.length<=t)return e;var o=function(e){return e.toUpperCase()!==e.toLowerCase()?"A":" "},i=e.slice(0,t+1).replace(/.(?=\W*\w*$)/g,o);return i=i.slice(i.length-2).match(/\w\w/)?i.replace(/\s*\S+$/,""):r(i.slice(0,i.length-1)),(i+n).length>e.length?e:e.slice(0,i.length)+n}},function(e,t,n){var a=n(9),r=n(1);e.exports=function(e,t){return a(e)?[]:r(e,t).split(t||/\s+/)}},function(e,t,n){var a=n(3);e.exports=function(e,t,n){return a(e,t,n)}},function(e,t,n){var a=n(3);e.exports=function(e,t,n){return a(e,t,n,"right")}},function(e,t,n){var a=n(3);e.exports=function(e,t,n){return a(e,t,n,"both")}},function(e,t,n){var a=n(20);e.exports=a(n(21).sprintf,"sprintf() will be removed in the next major release, use the sprintf-js package instead.")},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){var a=n(20);e.exports=a(n(21).vsprintf,"vsprintf() will be removed in the next major release, use the sprintf-js package instead.")},function(e,t){e.exports=function(e,t){if(null==e)return 0;var n=Math.pow(10,isFinite(t)?t:0);return Math.round(e*n)/n}},function(e,t){e.exports=function(e,t,n,a){if(isNaN(e)||null==e)return"";e=e.toFixed(~~t),a="string"==typeof a?a:",";var r=e.split("."),o=r[0],i=r[1]?(n||".")+r[1]:"";return o.replace(/(\d)(?=(?:\d{3})+$)/g,"$1"+a)+i}},function(e,t,n){var a=n(0);e.exports=function(e,t){e=a(e),t=a(t);var n=t?e.indexOf(t):-1;return~n?e.slice(n+t.length,e.length):e}},function(e,t,n){var a=n(0);e.exports=function(e,t){e=a(e),t=a(t);var n=t?e.lastIndexOf(t):-1;return~n?e.slice(n+t.length,e.length):e}},function(e,t,n){var a=n(0);e.exports=function(e,t){e=a(e),t=a(t);var n=t?e.indexOf(t):-1;return~n?e.slice(0,n):e}},function(e,t,n){var a=n(0);e.exports=function(e,t){e=a(e),t=a(t);var n=e.lastIndexOf(t);return~n?e.slice(0,n):e}},function(e,t,n){var a=n(22);e.exports=function(e,t,n){return a(e,t,n,!0)}},function(e,t,n){var a=n(1),r=n(18),o=n(12);e.exports=function(e){return a(r(o(e).replace(/[^\w\s-]/g,"-").toLowerCase()),"-")}},function(e,t,n){var a=n(23);e.exports=function(e,t){return a(e,t||'"')}},function(e,t){e.exports=function(e,t){return t=t||'"',e[0]===t&&e[e.length-1]===t?e.slice(1,e.length-1):e}},function(e,t,n){var a=n(0),r=n(19);e.exports=function(e,t,n){if(e=a(e),t=~~t,null==n)return r(e,t);for(var o=[];t>0;o[--t]=e);return o.join(n)}},function(e,t){e.exports=function(e,t){if(e==t)return 0;if(!e)return-1;if(!t)return 1;for(var n=/(\.\d+|\d+|\D+)/g,a=String(e).match(n),r=String(t).match(n),o=Math.min(a.length,r.length),i=0;iu?1:-1:sl&&(o=l),l=n[i+1]+1,o>l&&(o=l),n[i]=s}n[i]=o}return o}},function(e,t,n){function a(e,t){var n,a,r=e.toLowerCase();for(t=[].concat(t),n=0;n0&&(n+=o),n+=e.charAt(c),c++;if(l)for(;c%r>0;)n+=" ",c++;return n}var u=e.split(" "),p=0;for(n="";u.length>0;){if(1+u[0].length+p>r&&p>0){if(s)n+=" ",p++;else if(l)for(;p0&&(n+=" ",p++),n+=u[0],p+=u[0].length,u.shift()}if(l)for(;p1&&void 0!==arguments[1]&&arguments[1],e.DomComponents),n=t.getType("default"),a=n.model,r=n.view;t.addType("collapse",{model:a.extend({defaults:Object.assign({},a.prototype.defaults,{"custom-name":"Dropdown",classes:["collapse"],droppable:!0,traits:[{type:"class_select",options:[{value:"",name:"Closed"},{value:"show",name:"Open"}],label:"Initial state"}].concat(a.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("dropdown"))return{type:"dropdown"}}}),view:r.extend({})})}},function(e,t,n){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(2),o=(a(r),n(4));a(o);t.default=function(e){var t=(arguments.length>1&&void 0!==arguments[1]&&arguments[1],e.DomComponents),n=t.getType("default"),a=n.model,r=n.view;t.addType("dropdown",{model:a.extend({defaults:Object.assign({},a.prototype.defaults,{"custom-name":"Dropdown",classes:["dropdown"],droppable:"a, button, .dropdown-menu",traits:[{type:"class_select",options:[{value:"",name:"Closed"},{value:"show",name:"Open"}],label:"Initial state"}].concat(a.prototype.defaults.traits)}),init2:function(){window.asdf=this;var e={type:"button",content:"Click to toggle",classes:["btn","dropdown-toggle"]},t=(this.append(e)[0],{type:"dropdown_menu"});this.append(t)[0];this.setupToggle(null,null,{force:!0});var n=this.components();n.bind("add",this.setupToggle.bind(this)),n.bind("change",this.setupToggle.bind(this)),n.bind("remove",this.setupToggle.bind(this));var a=this.get("classes");a.bind("add",this.setupToggle.bind(this)),a.bind("change",this.setupToggle.bind(this)),a.bind("remove",this.setupToggle.bind(this))},setupToggle:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=this.components().filter(function(e){return e.getAttributes().class.split(" ").includes("dropdown-toggle")})[0],r=this.components().filter(function(e){return e.getAttributes().class.split(" ").includes("dropdown-menu")})[0];if((!0===n.force||!0!==n.ignore)&&a&&r){var o=function(e){var t=e._events["change:attributes"];return!!t&&0!=t.filter(function(e){return"setupToggle"==e.callback.name}).length};o(a)||this.listenTo(a,"change:attributes",this.setupToggle),o(r)||this.listenTo(r,"change:attributes",this.setupToggle);var i=a.getAttributes();i.role="button";var s=r.getAttributes();i.hasOwnProperty("data-toggle")||(i["data-toggle"]="dropdown"),i.hasOwnProperty("aria-haspopup")||(i["aria-haspopup"]=!0);var l=this.getAttributes().class.split(" ");i["aria-expanded"]=l.includes("show"),a.set("attributes",i,{ignore:!0}),i.hasOwnProperty("id")?s["aria-labelledby"]=i.id:delete s["aria-labelledby"],r.set("attributes",s,{ignore:!0})}}},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("dropdown"))return{type:"dropdown"}}}),view:r.extend({})}),t.addType("dropdown_menu",{model:a.extend({defaults:Object.assign({},a.prototype.defaults,{"custom-name":"Dropdown Menu",classes:["dropdown-menu"],draggable:".dropdown",droppable:!0}),init2:function(){var e={type:"header",tagName:"h6",classes:["dropdown-header"],content:"Dropdown header"},t={type:"link",classes:["dropdown-item"],content:"Dropdown item"},n={type:"default",classes:["dropdown-divider"]};this.append(e),this.append(t),this.append(n),this.append(t)}},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("dropdown-menu"))return{type:"dropdown_menu"}}}),view:r})}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t,a=e.BlockManager,r=n.blocks,o=n.blockCategories;o.layout&&(r.container&&a.add("container").set({label:n.labels.container,category:"Layout",attributes:{class:"fa fa-columns"},content:{type:"container",classes:["container"]}}),r.row&&a.add("row").set({label:n.labels.row,category:"Layout",attributes:{class:"fa fa-columns"},content:{type:"row",classes:["row"]}}),r.column&&a.add("column").set({label:n.labels.column,category:"Layout",attributes:{class:"fa fa-columns"},content:{type:"column",classes:["col"]}}),r.column_break&&a.add("column_break").set({label:n.labels.column_break,category:"Layout",attributes:{class:"fa fa-columns"},content:{type:"column_break"}}),r.media_object&&a.add("media_object").set({label:n.labels.media_object,category:"Layout",attributes:{class:"fa fa-columns"},content:'
    \n \n
    \n
    Media heading
    \n
    Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.
    \n
    \n
    '})),o.components&&(r.alert&&a.add("alert",{label:n.labels.alert,category:"Components",attributes:{class:"fa fa-exclamation-triangle"},content:{type:"alert",content:"This is an alert—check it out!"}}),r.badge&&a.add("badge",{label:n.labels.badge,category:"Components",attributes:{class:"fa fa-certificate"},content:{type:"badge",content:"New!"}}),r.button&&a.add("button",{label:n.labels.button,category:"Components",attributes:{class:"fa fa-link"},content:{type:"button",content:"Click me!"}}),r.button_group&&a.add("button_group",{label:n.labels.button_group,category:"Components",attributes:{class:"fa fa-link"},content:{type:"button_group"}}),r.button_toolbar&&a.add("button_toolbar",{label:n.labels.button_toolbar,category:"Components",attributes:{class:"fa fa-link"},content:{type:"button_toolbar"}}),r.card&&(a.add("card",{label:n.labels.card,category:"Components",attributes:{class:"fa fa-credit-card"},content:{type:"card"}}),a.add("card_container",{label:n.labels.card_container,category:"Components",attributes:{class:"fa fa-credit-card"},content:{type:"card_container"}})),r.collapse&&a.add("collapse",{label:n.labels.collapse,category:"Components",attributes:{class:"fa fa-compress"},content:{type:"collapse"}}),r.dropdown&&a.add("dropdown",{label:n.labels.dropdown,category:"Components",attributes:{class:"fa fa-caret-down"},content:{type:"dropdown"}})),o.typography&&(r.text&&a.add("text",{label:n.labels.text,category:"Typography",attributes:{class:"fa fa-font"},content:{type:"text",content:"Insert your text here"}}),r.header&&a.add("header",{label:n.labels.header,category:"Typography",attributes:{class:"fa fa-header"},content:{type:"header",content:"Bootstrap heading"}}),r.paragraph&&a.add("paragraph",{label:n.labels.paragraph,category:"Typography",attributes:{class:"fa fa-paragraph"},content:{type:"paragraph",content:"Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Duis mollis, est non commodo luctus."}})),o.basic&&(r.link&&a.add("link",{label:n.labels.link,category:"Basic",attributes:{class:"fa fa-link"},content:{type:"link",content:"Link text"}}),r.image&&a.add("image",{label:n.labels.image,category:"Basic",attributes:{class:"fa fa-picture-o"},content:{type:"image"}}))}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t,a=e.DeviceManager;if(n.gridDevices&&(a.add("Extra Small","575px"),a.add("Small","767px"),a.add("Medium","991px"),a.add("Large","1199px"),a.add("Extra Large","100%"),n.gridDevicesPanel)){var r=e.Panels,o=e.Commands;r.addPanel({id:"devices-buttons"}).get("buttons").add([{id:"deviceXl",command:"set-device-xl",className:"fa fa-desktop",text:"XL",attributes:{title:"Extra Large"},active:1},{id:"deviceLg",command:"set-device-lg",className:"fa fa-desktop",attributes:{title:"Large"}},{id:"deviceMd",command:"set-device-md",className:"fa fa-tablet",attributes:{title:"Medium"}},{id:"deviceSm",command:"set-device-sm",className:"fa fa-mobile",attributes:{title:"Small"}},{id:"deviceXs",command:"set-device-xs",className:"fa fa-mobile",attributes:{title:"Extra Small"}}]),o.add("set-device-xs",{run:function(e){e.setDevice("Extra Small")}}),o.add("set-device-sm",{run:function(e){e.setDevice("Small")}}),o.add("set-device-md",{run:function(e){e.setDevice("Medium")}}),o.add("set-device-lg",{run:function(e){e.setDevice("Large")}}),o.add("set-device-xl",{run:function(e){e.setDevice("Extra Large")}})}}}])}); \ No newline at end of file +function a(e){if(!(this instanceof a))return new a(e);this._wrapped=e}function r(e,t){"function"==typeof t&&(a.prototype[e]=function(){var e=[this._wrapped].concat(Array.prototype.slice.call(arguments)),n=t.apply(null,e);return"string"==typeof n?new a(n):n})}a.VERSION="3.3.4",a.isBlank=n(9),a.stripTags=n(29),a.capitalize=n(5),a.decapitalize=n(10),a.chop=n(30),a.trim=n(1),a.clean=n(31),a.cleanDiacritics=n(12),a.count=n(32),a.chars=n(7),a.swapCase=n(33),a.escapeHTML=n(34),a.unescapeHTML=n(36),a.splice=n(13),a.insert=n(38),a.replaceAll=n(39),a.include=n(40),a.join=n(41),a.lines=n(42),a.dedent=n(43),a.reverse=n(44),a.startsWith=n(45),a.endsWith=n(46),a.pred=n(47),a.succ=n(48),a.titleize=n(49),a.camelize=n(16),a.underscored=n(17),a.dasherize=n(18),a.classify=n(50),a.humanize=n(51),a.ltrim=n(52),a.rtrim=n(8),a.truncate=n(53),a.prune=n(54),a.words=n(55),a.pad=n(3),a.lpad=n(56),a.rpad=n(57),a.lrpad=n(58),a.sprintf=n(59),a.vsprintf=n(61),a.toNumber=n(62),a.numberFormat=n(63),a.strRight=n(64),a.strRightBack=n(65),a.strLeft=n(66),a.strLeftBack=n(67),a.toSentence=n(22),a.toSentenceSerial=n(68),a.slugify=n(69),a.surround=n(23),a.quote=n(70),a.unquote=n(71),a.repeat=n(72),a.naturalCmp=n(73),a.levenshtein=n(74),a.toBoolean=n(75),a.exports=n(76),a.escapeRegExp=n(11),a.wrap=n(77),a.map=n(78),a.strip=a.trim,a.lstrip=a.ltrim,a.rstrip=a.rtrim,a.center=a.lrpad,a.rjust=a.lpad,a.ljust=a.rpad,a.contains=a.include,a.q=a.quote,a.toBool=a.toBoolean,a.camelcase=a.camelize,a.mapChars=a.map,a.prototype={value:function(){return this._wrapped}};for(var o in a)r(o,a[o]);r("tap",function(e,t){return t(e)});var i=["toUpperCase","toLowerCase","split","replace","slice","substring","substr","concat"];for(var s in i)!function(e){r(e,function(t){var n=Array.prototype.slice.call(arguments,1);return String.prototype[e].apply(t,n)})}(i[s]);e.exports=a},function(e,t,n){var a=n(0);e.exports=function(e,t){e=a(e);var n=t?e.slice(1).toLowerCase():e.slice(1);return e.charAt(0).toUpperCase()+n}},function(e,t,n){var a=n(11);e.exports=function(e){return null==e?"\\s":e.source?e.source:"["+a(e)+"]"}},function(e,t,n){var a=n(0);e.exports=function(e){return a(e).split("")}},function(e,t,n){var a=n(0),r=n(6),o=String.prototype.trimRight;e.exports=function(e,t){return e=a(e),!t&&o?o.call(e):(t=r(t),e.replace(new RegExp(t+"+$"),""))}},function(e,t,n){var a=n(0);e.exports=function(e){return/^\s*$/.test(a(e))}},function(e,t,n){var a=n(0);e.exports=function(e){return e=a(e),e.charAt(0).toLowerCase()+e.slice(1)}},function(e,t,n){var a=n(0);e.exports=function(e){return a(e).replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}},function(e,t,n){var a=n(0),r="ąàáäâãåæăćčĉęèéëêĝĥìíïîĵłľńňòóöőôõðøśșşšŝťțţŭùúüűûñÿýçżźž",o="aaaaaaaaaccceeeeeghiiiijllnnoooooooossssstttuuuuuunyyczzz";r+=r.toUpperCase(),o+=o.toUpperCase(),o=o.split(""),r+="ß",o.push("ss"),e.exports=function(e){return a(e).replace(/.{1}/g,function(e){var t=r.indexOf(e);return-1===t?e:o[t]})}},function(e,t,n){var a=n(7);e.exports=function(e,t,n,r){var o=a(e);return o.splice(~~t,~~n,r),o.join("")}},function(e,t){e.exports=function(e){return e<0?0:+e||0}},function(e,t,n){var a=n(0);e.exports=function(e,t){return e=a(e),0===e.length?"":e.slice(0,-1)+String.fromCharCode(e.charCodeAt(e.length-1)+t)}},function(e,t,n){var a=n(1),r=n(10);e.exports=function(e,t){return e=a(e).replace(/[-_\s]+(.)?/g,function(e,t){return t?t.toUpperCase():""}),!0===t?r(e):e}},function(e,t,n){var a=n(1);e.exports=function(e){return a(e).replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()}},function(e,t,n){var a=n(1);e.exports=function(e){return a(e).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()}},function(e,t){e.exports=function(e,t){if(t<1)return"";for(var n="";t>0;)1&t&&(n+=e),t>>=1,e+=e;return n}},function(e,t,n){(function(t){function n(e,t){function n(){if(!r){if(a("throwDeprecation"))throw new Error(t);a("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}if(a("noDeprecation"))return e;var r=!1;return n}function a(e){try{if(!t.localStorage)return!1}catch(e){return!1}var n=t.localStorage[e];return null!=n&&"true"===String(n).toLowerCase()}e.exports=n}).call(t,n(60))},function(e,t,n){"use strict";!function(e){function n(){var e=arguments[0],t=n.cache;return t[e]&&t.hasOwnProperty(e)||(t[e]=n.parse(e)),n.format.call(null,t[e],arguments)}function a(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function r(e,t){return Array(t+1).join(e)}var o={not_string:/[^s]/,number:/[diefg]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};n.format=function(e,t){var i,s,l,c,u,p,d,f=1,m=e.length,g="",h=[],v=!0,b="";for(s=0;s=0),c[8]){case"b":i=i.toString(2);break;case"c":i=String.fromCharCode(i);break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,c[6]?parseInt(c[6]):0);break;case"e":i=c[7]?i.toExponential(c[7]):i.toExponential();break;case"f":i=c[7]?parseFloat(i).toFixed(c[7]):parseFloat(i);break;case"g":i=c[7]?parseFloat(i).toPrecision(c[7]):parseFloat(i);break;case"o":i=i.toString(8);break;case"s":i=(i=String(i))&&c[7]?i.substring(0,c[7]):i;break;case"u":i>>>=0;break;case"x":i=i.toString(16);break;case"X":i=i.toString(16).toUpperCase()}o.json.test(c[8])?h[h.length]=i:(!o.number.test(c[8])||v&&!c[3]?b="":(b=v?"+":"-",i=i.toString().replace(o.sign,"")),p=c[4]?"0"===c[4]?"0":c[4].charAt(1):" ",d=c[6]-(b+i).length,u=c[6]&&d>0?r(p,d):"",h[h.length]=c[5]?b+i+u:"0"===p?b+u+i:u+b+i)}return h.join("")},n.cache={},n.parse=function(e){for(var t=e,n=[],a=[],r=0;t;){if(null!==(n=o.text.exec(t)))a[a.length]=n[0];else if(null!==(n=o.modulo.exec(t)))a[a.length]="%";else{if(null===(n=o.placeholder.exec(t)))throw new SyntaxError("[sprintf] unexpected placeholder");if(n[2]){r|=1;var i=[],s=n[2],l=[];if(null===(l=o.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(i[i.length]=l[1];""!==(s=s.substring(l[0].length));)if(null!==(l=o.key_access.exec(s)))i[i.length]=l[1];else{if(null===(l=o.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");i[i.length]=l[1]}n[2]=i}else r|=2;if(3===r)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");a[a.length]=n}t=t.substring(n[0].length)}return a};var i=function(e,t,a){return a=(t||[]).slice(0),a.splice(0,0,e),n.apply(null,a)};t.sprintf=n,t.vsprintf=i}("undefined"==typeof window||window)},function(e,t,n){var a=n(8);e.exports=function(e,t,n,r){t=t||", ",n=n||" and ";var o=e.slice(),i=o.pop();return e.length>2&&r&&(n=a(t)+n),o.length?o.join(t)+n+i:i}},function(e,t){e.exports=function(e,t){return[t,e,t].join("")}},function(e,t,n){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{};window.editor=e;var n=t.blocks||{},a=t.labels||{},o=t.blockCategories||{};delete t.blocks,delete t.labels,delete t.blockCategories;var i={default:!0,text:!0,link:!0,image:!0,container:!0,row:!0,column:!0,column_break:!0,media_object:!0,alert:!0,badge:!0,button:!0,button_group:!0,button_toolbar:!0,card:!0,card_container:!0,collapse:!0,dropdown:!0,header:!0,paragraph:!0,list:!0},s={container:"Container",row:"Row",column:"Column",column_break:"Column Break",media_object:"Media Object",alert:"Alert",badge:"Badge",button:"Button",button_group:"Button Group",button_toolbar:"Button Toolbar",card:"Card",card_container:"Card Container",collapse:"Collapse",dropdown:"Dropdown",dropdown_menu:"Dropdown Menu",dropdown_item:"Dropdown Item",text:"Text",header:"Header",paragraph:"Paragraph",image:"Image",link:"Link",list:"Simple List"},c={layout:!0,components:!0,typography:!0,basic:!0},p=r({blocks:Object.assign(i,n),labels:Object.assign(s,a),blockCategories:Object.assign(c,o),gridDevices:!0,gridDevicesPanel:!1},t);e.addComponents('\n \n '),(0,l.default)(e,p),(0,u.default)(e,p),(0,d.default)(e,p),(0,m.default)(e,p),(0,h.default)(e,p)})},function(t,n){t.exports=e},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=n(2);!function(e){e&&e.__esModule}(a);t.default=function(e){arguments.length>1&&void 0!==arguments[1]&&arguments[1],e.Commands}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var a=n(2),r=function(e){return e&&e.__esModule?e:{default:e}}(a);t.default=function(e){arguments.length>1&&void 0!==arguments[1]&&arguments[1];e.TraitManager.addType("class_select",{events:{change:"onChange"},getInputEl:function(){if(!this.inputEl){for(var e=this.model,t=e.get("options")||[],n=document.createElement("select"),a=(this.target,this.target.view.el),o=0;o0)for(var n=e[t].split(" "),a=0;a0&&this.target.removeClass(n[a]);var r=this.model.get("value");if(r.length>0&&"GJS_NO_CLASS"!=r)for(var o=r.split(" "),i=0;i1&&void 0!==arguments[1]?arguments[1]:{},n=["primary","secondary","success","info","warning","danger","light","dark"],a=n.concat(["white"]),o={lg:"Large",sm:"Small"},s=t,c=e.DomComponents,p=s.blocks,f=s.blockCategories,m=c.getType("default"),g=m.model,h=m.view,v=c.getType("text"),b=v.model,y=v.view,x=c.getType("link"),w=x.model,_=x.view,C=c.getType("image"),j=C.model,k=C.view;f.basic&&(p.default&&(c.addType("default",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{tagName:"div",traits:[{type:"class_select",options:[{value:"",name:"Default"}].concat(r(a.map(function(e){return{value:"text-"+e,name:l.default.capitalize(e)}}))),label:"Text color"},{type:"class_select",options:[{value:"",name:"Default"}].concat(r(a.map(function(e){return{value:"bg-"+e,name:l.default.capitalize(e)}}))),label:"Background color"},{type:"class_select",options:[{value:"",name:"Default"},{value:"border",name:"Full"},{value:"border-top-0",name:"No top"},{value:"border-right-0",name:"No right"},{value:"border-bottom-0",name:"No bottom"},{value:"border-left-0",name:"No left"},{value:"border-0",name:"None"}],label:"Border width"},{type:"class_select",options:[{value:"",name:"Default"}].concat(r(a.map(function(e){return{value:"border border-"+e,name:l.default.capitalize(e)}}))),label:"Border color"},{type:"class_select",options:[{value:"",name:"Default"},{value:"rounded",name:"Rounded"},{value:"rounded-top",name:"Rounded top"},{value:"rounded-right",name:"Rounded right"},{value:"rounded-bottom",name:"Rounded bottom"},{value:"rounded-left",name:"Rounded left"},{value:"rounded-circle",name:"Circle"},{value:"rounded-0",name:"Square"}],label:"Border radius"},{type:"text",label:"ID",name:"id",placeholder:"my_element"},{type:"text",label:"Title",name:"title",placeholder:"My Element"}]}),init:function(){var e=this.get("classes");e.bind("add",this.classesChanged.bind(this)),e.bind("change",this.classesChanged.bind(this)),e.bind("remove",this.classesChanged.bind(this)),this.init2()},init2:function(){},classesChanged:function(){},changeType:function(e){var t=this.collection,n=t.indexOf(this),a={type:e,style:this.getStyle(),attributes:this.getAttributes(),content:this.view.el.innerHTML};t.remove(this),t.add(a,{at:n}),this.destroy()}}),view:h}),m=c.getType("default"),g=m.model,h=m.view),p.text&&(c.addType("text",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Text",tagName:"div",droppable:!0,editable:!0})},{}),view:y}),v=c.getType("text"),b=v.model,y=v.view),p.link&&(c.addType("link",{model:b.extend({defaults:Object.assign({},b.prototype.defaults,{"custom-name":"Link",tagName:"a",droppable:!0,editable:!0,traits:[{type:"text",label:"Href",name:"href",placeholder:"https://www.grapesjs.com"},{type:"select",options:[{value:"",name:"This window"},{value:"_blank",name:"New window"}],label:"Target",name:"target"},{type:"select",options:[{value:"",name:"None"},{value:"button",name:"Self"},{value:"collapse",name:"Collapse"},{value:"dropdown",name:"Dropdown"}],label:"Toggles",name:"data-toggle",changeProp:1}].concat(b.prototype.defaults.traits)}),init2:function(){this.listenTo(this,"change:data-toggle",this.setupToggle),this.listenTo(this,"change:attributes",this.setupToggle)},setupToggle:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!0!==n.ignore||!0===n.force){console.log("setup toggle");var a=this.getAttributes(),r=a.href;if(delete a["data-toggle"],delete a["aria-expanded"],delete a["aria-controls"],delete a["aria-haspopup"],r&&r.length>0&&r.match(/^#/)){console.log("link has href");var o=this.em.get("Editor").DomComponents.getWrapper().find(r);if(o.length>0){console.log("referenced el found");var s=o[0],l=s.getAttributes(),c=l.class;if(c){console.log("el has classes");var u=c.split(" "),p=i.default.intersection(["collapse","dropdown-menu"],u);if(p.length){switch(console.log("link data-toggle matches el class"),p[0]){case"collapse":a["data-toggle"]="collapse"}a["aria-expanded"]=u.includes("show"),"collapse"==p[0]&&(a["aria-controls"]=r.substring(1))}}}}this.set("attributes",a,{ignore:!0})}},classesChanged:function(e){console.log("classes changed"),"link"==this.attributes.type&&this.attributes.classes.filter(function(e){return"btn"==e.id}).length>0&&this.changeType("button")}},{isComponent:function(e){if(e&&e.tagName&&"A"==e.tagName)return{type:"link"}}}),view:_}),x=c.getType("link"),w=x.model,_=x.view),p.image&&(c.addType("image",{model:j.extend({defaults:Object.assign({},j.prototype.defaults,{"custom-name":"Image",tagName:"img",resizable:1,attributes:{src:"https://dummyimage.com/450x250/999/222"},traits:[{type:"text",label:"Source (URL)",name:"src"},{type:"text",label:"Alternate text",name:"alt"}].concat(j.prototype.defaults.traits)})},{isComponent:function(e){if(e&&"IMG"==e.tagName)return{type:"image"}}}),view:k}),C=c.getType("image"),j=C.model,k=C.view)),f.layout&&(p.container&&c.addType("container",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Container",tagName:"div",droppable:!0,traits:[{type:"class_select",options:[{value:"container",name:"Fixed"},{value:"container-fluid",name:"Fluid"}],label:"Width"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&(e.classList.contains("container")||e.classList.contains("container-fluid")))return{type:"container"}}}),view:h}),p.row&&c.addType("row",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Row",tagName:"div",draggable:".container, .container-fluid",droppable:!0,traits:[{type:"class_select",options:[{value:"",name:"Yes"},{value:"no-gutters",name:"No"}],label:"Gutters?"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("row"))return{type:"row"}}}),view:h}),p.column&&(c.addType("column",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Column",draggable:".row",droppable:!0,traits:[{type:"class_select",options:[{value:"col",name:"Equal"},{value:"col-auto",name:"Variable"}].concat(r([1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"col-"+e,name:e+"/12"}}))),label:"XS Width"},{type:"class_select",options:[{value:"",name:"None"},{value:"col-sm",name:"Equal"},{value:"col-sm-auto",name:"Variable"}].concat(r([1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"col-sm-"+e,name:e+"/12"}}))),label:"SM Width"},{type:"class_select",options:[{value:"",name:"None"},{value:"col-md",name:"Equal"},{value:"col-md-auto",name:"Variable"}].concat(r([1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"col-md-"+e,name:e+"/12"}}))),label:"MD Width"},{type:"class_select",options:[{value:"",name:"None"},{value:"col-lg",name:"Equal"},{value:"col-lg-auto",name:"Variable"}].concat(r([1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"col-lg-"+e,name:e+"/12"}}))),label:"LG Width"},{type:"class_select",options:[{value:"",name:"None"},{value:"col-xl",name:"Equal"},{value:"col-xl-auto",name:"Variable"}].concat(r([1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"col-xl-"+e,name:e+"/12"}}))),label:"XL Width"},{type:"class_select",options:[{value:"",name:"None"}].concat(r([0,1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"offset-"+e,name:e+"/12"}}))),label:"XS Offset"},{type:"class_select",options:[{value:"",name:"None"}].concat(r([0,1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"offset-sm-"+e,name:e+"/12"}}))),label:"SM Offset"},{type:"class_select",options:[{value:"",name:"None"}].concat(r([0,1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"offset-md-"+e,name:e+"/12"}}))),label:"MD Offset"},{type:"class_select",options:[{value:"",name:"None"}].concat(r([0,1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"offset-lg-"+e,name:e+"/12"}}))),label:"LG Offset"},{type:"class_select",options:[{value:"",name:"None"}].concat(r([0,1,2,3,4,5,6,7,8,9,10,11,12].map(function(e){return{value:"offset-xl-"+e,name:e+"/12"}}))),label:"XL Offset"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){var t=!1;if(e&&e.classList&&e.classList.forEach(function(e){("col"==e||e.match(/^col-/))&&(t=!0)}),t)return{type:"column"}}}),view:h}),c.addType("column_break",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Column Break",tagName:"div",classes:["w-100"]})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("w-100"))return{type:"column_break"}}}),view:h}),c.addType("media_object",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Media Object",tagName:"div",classes:["media"]})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("media"))return{type:"media"}}}),view:h}),c.addType("media_body",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Media Body",tagName:"div",classes:["media-body"]})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("media-body"))return{type:"media_body"}}}),view:h}))),f.components&&(p.alert&&c.addType("alert",{model:b.extend({defaults:Object.assign({},b.prototype.defaults,{"custom-name":"Alert",tagName:"div",classes:["alert"],traits:[{type:"class_select",options:[{value:"",name:"None"}].concat(r(n.map(function(e){return{value:"alert-"+e,name:l.default.capitalize(e)}}))),label:"Context"}].concat(b.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("alert"))return{type:"alert"}}}),view:y}),p.badge&&c.addType("badge",{model:b.extend({defaults:Object.assign({},b.prototype.defaults,{"custom-name":"Badge",tagName:"span",classes:["badge"],traits:[{type:"class_select",options:[{value:"",name:"None"}].concat(r(n.map(function(e){return{value:"badge-"+e,name:l.default.capitalize(e)}}))),label:"Context"},{type:"class_select",options:[{value:"",name:"Default"},{value:"badge-pill",name:"Pill"}],label:"Shape"}].concat(b.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("badge"))return{type:"badge"}}}),view:y}),p.button&&c.addType("button",{model:w.extend({defaults:Object.assign({},w.prototype.defaults,{"custom-name":"Button",attributes:{role:"button"},classes:["btn"],traits:[{type:"class_select",options:[{value:"",name:"None"}].concat(r(n.map(function(e){return{value:"btn-"+e,name:l.default.capitalize(e)}})),r(n.map(function(e){return{value:"btn-outline-"+e,name:l.default.capitalize(e)+" (Outline)"}}))),label:"Context"},{type:"class_select",options:[{value:"",name:"Default"}].concat(r(Object.keys(o).map(function(e){return{value:"btn-"+e,name:o[e]}}))),label:"Size"},{type:"class_select",options:[{value:"",name:"Inline"},{value:"btn-block",name:"Block"}],label:"Width"}].concat(w.prototype.defaults.traits)}),afterChange:function(e){"button"==this.attributes.type&&0==this.attributes.classes.filter(function(e){return"btn"==e.id}).length&&this.changeType("link")}},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("btn"))return{type:"button"}}}),view:_}),p.button_group&&c.addType("button_group",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Button Group",tagName:"div",classes:["btn-group"],droppable:".btn",attributes:{role:"group"},traits:[{type:"class_select",options:[{value:"",name:"Default"}].concat(r(Object.keys(o).map(function(e){return{value:"btn-group-"+e,name:o[e]}}))),label:"Size"},{type:"class_select",options:[{value:"",name:"Horizontal"},{value:"btn-group-vertical",name:"Vertical"}],label:"Size"},{type:"Text",label:"ARIA Label",name:"aria-label",placeholder:"A group of buttons"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("btn-group"))return{type:"button_group"}}}),view:h}),p.button_toolbar&&c.addType("button_toolbar",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Button Toolbar",tagName:"div",classes:["btn-toolbar"],droppable:".btn-group",attributes:{role:"toolbar"},traits:[{type:"Text",label:"ARIA Label",name:"aria-label",placeholder:"A toolbar of button groups"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("btn-toolbar"))return{type:"button_toolbar"}}}),view:h}),p.card&&(c.addType("card",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card",classes:["card"],traits:[{type:"checkbox",label:"Image Top",name:"card-img-top",changeProp:1},{type:"checkbox",label:"Header",name:"card-header",changeProp:1},{type:"checkbox",label:"Image",name:"card-img",changeProp:1},{type:"checkbox",label:"Image Overlay",name:"card-img-overlay",changeProp:1},{type:"checkbox",label:"Body",name:"card-body",changeProp:1},{type:"checkbox",label:"Footer",name:"card-footer",changeProp:1},{type:"checkbox",label:"Image Bottom",name:"card-img-bottom",changeProp:1}].concat(g.prototype.defaults.traits)}),init2:function(){this.listenTo(this,"change:card-img-top",this.cardImageTop),this.listenTo(this,"change:card-header",this.cardHeader),this.listenTo(this,"change:card-img",this.cardImage),this.listenTo(this,"change:card-img-overlay",this.cardImageOverlay),this.listenTo(this,"change:card-body",this.cardBody),this.listenTo(this,"change:card-footer",this.cardFooter),this.listenTo(this,"change:card-img-bottom",this.cardImageBottom),this.components().comparator="card-order",this.set("card-img-top",!0),this.set("card-body",!0)},cardImageTop:function(){this.createCardComponent("card-img-top")},cardHeader:function(){this.createCardComponent("card-header")},cardImage:function(){this.createCardComponent("card-img")},cardImageOverlay:function(){this.createCardComponent("card-img-overlay")},cardBody:function(){this.createCardComponent("card-body")},cardFooter:function(){this.createCardComponent("card-footer")},cardImageBottom:function(){this.createCardComponent("card-img-bottom")},createCardComponent:function(e){var t=this.get(e),n=e.replace(/-/g,"_").replace(/img/g,"image"),a=this.components(),r=a.filter(function(e){return e.attributes.type==n})[0];if(t&&!r){var o=a.add({type:n}),i=o.components();"card-header"==e&&i.add({type:"header",tagName:"h4",style:{"margin-bottom":"0px"},content:"Card Header"}),"card-img-overlay"==e&&(i.add({type:"header",tagName:"h4",classes:["card-title"],content:"Card title"}),i.add({type:"text",tagName:"p",classes:["card-text"],content:"Some quick example text to build on the card title and make up the bulk of the card's content."})),"card-body"==e&&(i.add({type:"header",tagName:"h4",classes:["card-title"],content:"Card title"}),i.add({type:"header",tagName:"h6",classes:["card-subtitle","text-muted","mb-2"],content:"Card subtitle"}),i.add({type:"text",tagName:"p",classes:["card-text"],content:"Some quick example text to build on the card title and make up the bulk of the card's content."}),i.add({type:"link",classes:["card-link"],href:"#",content:"Card link"}),i.add({type:"link",classes:["card-link"],href:"#",content:"Another link"})),this.order()}else t||r.destroy()},order:function(){}},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card"))return{type:"card"}}}),view:h}),c.addType("card_image_top",{model:j.extend({defaults:Object.assign({},j.prototype.defaults,{"custom-name":"Card Image Top",classes:["card-img-top"],"card-order":1})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-img-top"))return{type:"card_image_top"}}}),view:k}),c.addType("card_header",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card Header",classes:["card-header"],"card-order":2})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-header"))return{type:"card_header"}}}),view:h}),c.addType("card_image",{model:j.extend({defaults:Object.assign({},j.prototype.defaults,{"custom-name":"Card Image",classes:["card-img"],"card-order":3})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-img"))return{type:"card_image"}}}),view:k}),c.addType("card_image_overlay",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card Image Overlay",classes:["card-img-overlay"],"card-order":4})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-img-overlay"))return{type:"card_image_overlay"}}}),view:h}),c.addType("card_body",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card Body",classes:["card-body"],"card-order":5})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-body"))return{type:"card_body"}}}),view:h}),c.addType("card_footer",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card Footer",classes:["card-footer"],"card-order":6})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-footer"))return{type:"card_footer"}}}),view:h}),c.addType("card_image_bottom",{model:j.extend({defaults:Object.assign({},j.prototype.defaults,{"custom-name":"Card Image Bottom",classes:["card-img-bottom"],"card-order":7})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("card-img-bottom"))return{type:"card_image_bottom"}}}),view:k}),c.addType("card_container",{model:g.extend({defaults:Object.assign({},g.prototype.defaults,{"custom-name":"Card Container",classes:["card-group"],droppable:".card",traits:[{type:"class_select",options:[{value:"card-group",name:"Group"},{value:"card-deck",name:"Deck"},{value:"card-columns",name:"Columns"}],label:"Layout"}].concat(g.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&i.default.intersection(e.classList,["card-group","card-deck","card-columns"]).length)return{type:"card_container"}}}),view:h})),p.collapse&&(0,u.default)(e,t),p.dropdown&&(0,d.default)(e,t)),f.typography&&(p.header&&c.addType("header",{model:b.extend({defaults:Object.assign({},b.prototype.defaults,{"custom-name":"Header",tagName:"h1",traits:[{type:"select",options:[{value:"h1",name:"One (largest)"},{value:"h2",name:"Two"},{value:"h3",name:"Three"},{value:"h4",name:"Four"},{value:"h5",name:"Five"},{value:"h6",name:"Six (smallest)"}],label:"Size",name:"tagName",changeProp:1},{type:"class_select",options:[{value:"",name:"None"},{value:"display-1",name:"One (largest)"},{value:"display-2",name:"Two "},{value:"display-3",name:"Three "},{value:"display-4",name:"Four (smallest)"}],label:"Display Heading"}].concat(b.prototype.defaults.traits)})},{isComponent:function(e){if(e&&["H1","H2","H3","H4","H5","H6"].includes(e.tagName))return{type:"header"}}}),view:y}),p.paragraph&&c.addType("paragraph",{model:b.extend({defaults:Object.assign({},b.prototype.defaults,{"custom-name":"Paragraph",tagName:"p",traits:[{type:"class_select",options:[{value:"",name:"No"},{value:"lead",name:"Yes"}],label:"Lead?"}].concat(b.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.tagName&&"P"==e.tagName)return{type:"paragraph"}}}),view:y}))}},function(e,t,n){var a=n(0);e.exports=function(e){return a(e).replace(/<\/?[^>]+>/g,"")}},function(e,t){e.exports=function(e,t){return null==e?[]:(e=String(e),t=~~t,t>0?e.match(new RegExp(".{1,"+t+"}","g")):[e])}},function(e,t,n){var a=n(1);e.exports=function(e){return a(e).replace(/\s\s+/g," ")}},function(e,t,n){var a=n(0);e.exports=function(e,t){return e=a(e),t=a(t),0===e.length||0===t.length?0:e.split(t).length-1}},function(e,t,n){var a=n(0);e.exports=function(e){return a(e).replace(/\S/g,function(e){return e===e.toUpperCase()?e.toLowerCase():e.toUpperCase()})}},function(e,t,n){var a=n(0),r=n(35),o="[";for(var i in r)o+=i;o+="]";var s=new RegExp(o,"g");e.exports=function(e){return a(e).replace(s,function(e){return"&"+r[e]+";"})}},function(e,t){var n={"¢":"cent","£":"pound","¥":"yen","€":"euro","©":"copy","®":"reg","<":"lt",">":"gt",'"':"quot","&":"amp","'":"#39"};e.exports=n},function(e,t,n){var a=n(0),r=n(37);e.exports=function(e){return a(e).replace(/\&([^;]+);/g,function(e,t){var n;return t in r?r[t]:(n=t.match(/^#x([\da-fA-F]+)$/))?String.fromCharCode(parseInt(n[1],16)):(n=t.match(/^#(\d+)$/))?String.fromCharCode(~~n[1]):e})}},function(e,t){var n={nbsp:" ",cent:"¢",pound:"£",yen:"¥",euro:"€",copy:"©",reg:"®",lt:"<",gt:">",quot:'"',amp:"&",apos:"'"};e.exports=n},function(e,t,n){var a=n(13);e.exports=function(e,t,n){return a(e,t,0,n)}},function(e,t,n){var a=n(0);e.exports=function(e,t,n,r){var o=!0===r?"gi":"g",i=new RegExp(t,o);return a(e).replace(i,n)}},function(e,t,n){var a=n(0);e.exports=function(e,t){return""===t||-1!==a(e).indexOf(t)}},function(e,t,n){var a=n(0),r=[].slice;e.exports=function(){var e=r.call(arguments),t=e.shift();return e.join(a(t))}},function(e,t){e.exports=function(e){return null==e?[]:String(e).split(/\r\n?|\n/)}},function(e,t,n){function a(e){for(var t=e.match(/^[\s\\t]*/gm),n=t[0].length,a=1;a=0&&e.indexOf(t,n)===n}},function(e,t,n){var a=n(15);e.exports=function(e){return a(e,-1)}},function(e,t,n){var a=n(15);e.exports=function(e){return a(e,1)}},function(e,t,n){var a=n(0);e.exports=function(e){return a(e).toLowerCase().replace(/(?:^|\s|-)\S/g,function(e){return e.toUpperCase()})}},function(e,t,n){var a=n(5),r=n(16),o=n(0);e.exports=function(e){return e=o(e),a(r(e.replace(/[\W_]/g," ")).replace(/\s/g,""))}},function(e,t,n){var a=n(5),r=n(17),o=n(1);e.exports=function(e){return a(o(r(e).replace(/_id$/,"").replace(/_/g," ")))}},function(e,t,n){var a=n(0),r=n(6),o=String.prototype.trimLeft;e.exports=function(e,t){return e=a(e),!t&&o?o.call(e):(t=r(t),e.replace(new RegExp("^"+t+"+"),""))}},function(e,t,n){var a=n(0);e.exports=function(e,t,n){return e=a(e),n=n||"...",t=~~t,e.length>t?e.slice(0,t)+n:e}},function(e,t,n){var a=n(0),r=n(8);e.exports=function(e,t,n){if(e=a(e),t=~~t,n=null!=n?String(n):"...",e.length<=t)return e;var o=function(e){return e.toUpperCase()!==e.toLowerCase()?"A":" "},i=e.slice(0,t+1).replace(/.(?=\W*\w*$)/g,o);return i=i.slice(i.length-2).match(/\w\w/)?i.replace(/\s*\S+$/,""):r(i.slice(0,i.length-1)),(i+n).length>e.length?e:e.slice(0,i.length)+n}},function(e,t,n){var a=n(9),r=n(1);e.exports=function(e,t){return a(e)?[]:r(e,t).split(t||/\s+/)}},function(e,t,n){var a=n(3);e.exports=function(e,t,n){return a(e,t,n)}},function(e,t,n){var a=n(3);e.exports=function(e,t,n){return a(e,t,n,"right")}},function(e,t,n){var a=n(3);e.exports=function(e,t,n){return a(e,t,n,"both")}},function(e,t,n){var a=n(20);e.exports=a(n(21).sprintf,"sprintf() will be removed in the next major release, use the sprintf-js package instead.")},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){var a=n(20);e.exports=a(n(21).vsprintf,"vsprintf() will be removed in the next major release, use the sprintf-js package instead.")},function(e,t){e.exports=function(e,t){if(null==e)return 0;var n=Math.pow(10,isFinite(t)?t:0);return Math.round(e*n)/n}},function(e,t){e.exports=function(e,t,n,a){if(isNaN(e)||null==e)return"";e=e.toFixed(~~t),a="string"==typeof a?a:",";var r=e.split("."),o=r[0],i=r[1]?(n||".")+r[1]:"";return o.replace(/(\d)(?=(?:\d{3})+$)/g,"$1"+a)+i}},function(e,t,n){var a=n(0);e.exports=function(e,t){e=a(e),t=a(t);var n=t?e.indexOf(t):-1;return~n?e.slice(n+t.length,e.length):e}},function(e,t,n){var a=n(0);e.exports=function(e,t){e=a(e),t=a(t);var n=t?e.lastIndexOf(t):-1;return~n?e.slice(n+t.length,e.length):e}},function(e,t,n){var a=n(0);e.exports=function(e,t){e=a(e),t=a(t);var n=t?e.indexOf(t):-1;return~n?e.slice(0,n):e}},function(e,t,n){var a=n(0);e.exports=function(e,t){e=a(e),t=a(t);var n=e.lastIndexOf(t);return~n?e.slice(0,n):e}},function(e,t,n){var a=n(22);e.exports=function(e,t,n){return a(e,t,n,!0)}},function(e,t,n){var a=n(1),r=n(18),o=n(12);e.exports=function(e){return a(r(o(e).replace(/[^\w\s-]/g,"-").toLowerCase()),"-")}},function(e,t,n){var a=n(23);e.exports=function(e,t){return a(e,t||'"')}},function(e,t){e.exports=function(e,t){return t=t||'"',e[0]===t&&e[e.length-1]===t?e.slice(1,e.length-1):e}},function(e,t,n){var a=n(0),r=n(19);e.exports=function(e,t,n){if(e=a(e),t=~~t,null==n)return r(e,t);for(var o=[];t>0;o[--t]=e);return o.join(n)}},function(e,t){e.exports=function(e,t){if(e==t)return 0;if(!e)return-1;if(!t)return 1;for(var n=/(\.\d+|\d+|\D+)/g,a=String(e).match(n),r=String(t).match(n),o=Math.min(a.length,r.length),i=0;iu?1:-1:sl&&(o=l),l=n[i+1]+1,o>l&&(o=l),n[i]=s}n[i]=o}return o}},function(e,t,n){function a(e,t){var n,a,r=e.toLowerCase();for(t=[].concat(t),n=0;n0&&(n+=o),n+=e.charAt(c),c++;if(l)for(;c%r>0;)n+=" ",c++;return n}var u=e.split(" "),p=0;for(n="";u.length>0;){if(1+u[0].length+p>r&&p>0){if(s)n+=" ",p++;else if(l)for(;p0&&(n+=" ",p++),n+=u[0],p+=u[0].length,u.shift()}if(l)for(;p1&&void 0!==arguments[1]&&arguments[1],e.DomComponents),n=t.getType("default"),a=n.model,r=n.view;t.addType("collapse",{model:a.extend({defaults:Object.assign({},a.prototype.defaults,{"custom-name":"Dropdown",classes:["collapse"],droppable:!0,traits:[{type:"class_select",options:[{value:"",name:"Closed"},{value:"show",name:"Open"}],label:"Initial state"}].concat(a.prototype.defaults.traits)})},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("dropdown"))return{type:"dropdown"}}}),view:r.extend({})})}},function(e,t,n){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(2),o=(a(r),n(4));a(o);t.default=function(e){var t=(arguments.length>1&&void 0!==arguments[1]&&arguments[1],e.DomComponents),n=t.getType("default"),a=n.model,r=n.view;t.addType("dropdown",{model:a.extend({defaults:Object.assign({},a.prototype.defaults,{"custom-name":"Dropdown",classes:["dropdown"],droppable:"a, button, .dropdown-menu",traits:[{type:"class_select",options:[{value:"",name:"Closed"},{value:"show",name:"Open"}],label:"Initial state"}].concat(a.prototype.defaults.traits)}),init2:function(){window.asdf=this;var e={type:"button",content:"Click to toggle",classes:["btn","dropdown-toggle"]},t=(this.append(e)[0],{type:"dropdown_menu"});this.append(t)[0];this.setupToggle(null,null,{force:!0});var n=this.components();n.bind("add",this.setupToggle.bind(this)),n.bind("change",this.setupToggle.bind(this)),n.bind("remove",this.setupToggle.bind(this));var a=this.get("classes");a.bind("add",this.setupToggle.bind(this)),a.bind("change",this.setupToggle.bind(this)),a.bind("remove",this.setupToggle.bind(this))},setupToggle:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=this.components().filter(function(e){return e.getAttributes().class.split(" ").includes("dropdown-toggle")})[0],r=this.components().filter(function(e){return e.getAttributes().class.split(" ").includes("dropdown-menu")})[0];if((!0===n.force||!0!==n.ignore)&&a&&r){var o=function(e){var t=e._events["change:attributes"];return!!t&&0!=t.filter(function(e){return"setupToggle"==e.callback.name}).length};o(a)||this.listenTo(a,"change:attributes",this.setupToggle),o(r)||this.listenTo(r,"change:attributes",this.setupToggle);var i=a.getAttributes();i.role="button";var s=r.getAttributes();i.hasOwnProperty("data-toggle")||(i["data-toggle"]="dropdown"),i.hasOwnProperty("aria-haspopup")||(i["aria-haspopup"]=!0);var l=this.getAttributes().class.split(" ");i["aria-expanded"]=l.includes("show"),a.set("attributes",i,{ignore:!0}),i.hasOwnProperty("id")?s["aria-labelledby"]=i.id:delete s["aria-labelledby"],r.set("attributes",s,{ignore:!0})}}},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("dropdown"))return{type:"dropdown"}}}),view:r.extend({})}),t.addType("dropdown_menu",{model:a.extend({defaults:Object.assign({},a.prototype.defaults,{"custom-name":"Dropdown Menu",classes:["dropdown-menu"],draggable:".dropdown",droppable:!0}),init2:function(){var e={type:"header",tagName:"h6",classes:["dropdown-header"],content:"Dropdown header"},t={type:"link",classes:["dropdown-item"],content:"Dropdown item"},n={type:"default",classes:["dropdown-divider"]};this.append(e),this.append(t),this.append(n),this.append(t)}},{isComponent:function(e){if(e&&e.classList&&e.classList.contains("dropdown-menu"))return{type:"dropdown_menu"}}}),view:r})}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t,a=e.BlockManager,r=n.blocks,o=n.blockCategories;o.layout&&(r.container&&a.add("container").set({label:n.labels.container,category:"Layout",attributes:{class:"fa fa-columns"},content:{type:"container",classes:["container"]}}),r.row&&a.add("row").set({label:n.labels.row,category:"Layout",attributes:{class:"fa fa-columns"},content:{type:"row",classes:["row"]}}),r.column&&a.add("column").set({label:n.labels.column,category:"Layout",attributes:{class:"fa fa-columns"},content:{type:"column",classes:["col"]}}),r.column_break&&a.add("column_break").set({label:n.labels.column_break,category:"Layout",attributes:{class:"fa fa-columns"},content:{type:"column_break"}}),r.media_object&&a.add("media_object").set({label:n.labels.media_object,category:"Layout",attributes:{class:"fa fa-columns"},content:'
    \n \n
    \n
    Media heading
    \n
    Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.
    \n
    \n
    '})),o.components&&(r.alert&&a.add("alert",{label:n.labels.alert,category:"Components",attributes:{class:"fa fa-exclamation-triangle"},content:{type:"alert",content:"This is an alert—check it out!"}}),r.badge&&a.add("badge",{label:n.labels.badge,category:"Components",attributes:{class:"fa fa-certificate"},content:{type:"badge",content:"New!"}}),r.button&&a.add("button",{label:n.labels.button,category:"Components",attributes:{class:"fa fa-link"},content:{type:"button",content:"Click me!"}}),r.button_group&&a.add("button_group",{label:n.labels.button_group,category:"Components",attributes:{class:"fa fa-link"},content:{type:"button_group"}}),r.button_toolbar&&a.add("button_toolbar",{label:n.labels.button_toolbar,category:"Components",attributes:{class:"fa fa-link"},content:{type:"button_toolbar"}}),r.card&&(a.add("card",{label:n.labels.card,category:"Components",attributes:{class:"fa fa-credit-card"},content:{type:"card"}}),a.add("card_container",{label:n.labels.card_container,category:"Components",attributes:{class:"fa fa-credit-card"},content:{type:"card_container"}})),r.collapse&&a.add("collapse",{label:n.labels.collapse,category:"Components",attributes:{class:"fa fa-compress"},content:{type:"collapse"}}),r.dropdown&&a.add("dropdown",{label:n.labels.dropdown,category:"Components",attributes:{class:"fa fa-caret-down"},content:{type:"dropdown"}})),o.typography&&(r.text&&a.add("text",{label:n.labels.text,category:"Typography",attributes:{class:"fa fa-font"},content:{type:"text",content:"Insert your text here"}}),r.header&&a.add("header",{label:n.labels.header,category:"Typography",attributes:{class:"fa fa-header"},content:{type:"header",content:"Bootstrap heading"}}),r.paragraph&&a.add("paragraph",{label:n.labels.paragraph,category:"Typography",attributes:{class:"fa fa-paragraph"},content:{type:"paragraph",content:"Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Duis mollis, est non commodo luctus."}})),o.basic&&(r.link&&a.add("link",{label:n.labels.link,category:"Basic",attributes:{class:"fa fa-link"},content:{type:"link",content:"Link text"}}),r.image&&a.add("image",{label:n.labels.image,category:"Basic",attributes:{class:"fa fa-picture-o"},content:{type:"image"}}))}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t,a=e.DeviceManager;if(n.gridDevices&&(a.add("Extra Small","575px"),a.add("Small","767px"),a.add("Medium","991px"),a.add("Large","1199px"),a.add("Extra Large","100%"),n.gridDevicesPanel)){var r=e.Panels,o=e.Commands;r.addPanel({id:"devices-buttons"}).get("buttons").add([{id:"deviceXl",command:"set-device-xl",className:"fa fa-desktop",text:"XL",attributes:{title:"Extra Large"},active:1},{id:"deviceLg",command:"set-device-lg",className:"fa fa-desktop",attributes:{title:"Large"}},{id:"deviceMd",command:"set-device-md",className:"fa fa-tablet",attributes:{title:"Medium"}},{id:"deviceSm",command:"set-device-sm",className:"fa fa-mobile",attributes:{title:"Small"}},{id:"deviceXs",command:"set-device-xs",className:"fa fa-mobile",attributes:{title:"Extra Small"}}]),o.add("set-device-xs",{run:function(e){e.setDevice("Extra Small")}}),o.add("set-device-sm",{run:function(e){e.setDevice("Small")}}),o.add("set-device-md",{run:function(e){e.setDevice("Medium")}}),o.add("set-device-lg",{run:function(e){e.setDevice("Large")}}),o.add("set-device-xl",{run:function(e){e.setDevice("Extra Large")}})}}}])}); diff --git a/public/js/js_admin.js b/public/js/js_admin.js index 7ecb5c134..b42a680db 100644 --- a/public/js/js_admin.js +++ b/public/js/js_admin.js @@ -28,20 +28,6 @@ function pluginChangeStatus(pluginName, pluginStatus) { } -/* - Settings -*/ -const btnTemplateCode = document.querySelector("button.templateCode"); -if (btnTemplateCode != null) { - btnTemplateCode.addEventListener('click', function () { - document.querySelectorAll("pre.templateCode").forEach( el => { - el.classList.toggle("hidden"); - }); - }); -} - - - /* Files */ @@ -68,13 +54,14 @@ if ($btnFileDelete.length) { } function uploadFile(projectID) { - var access = $('input[name=fileRadio]:checked').attr("data-value"); - var file = $('#file').get(0).files[0]; + var access = $("input[name=fileRadio]:checked").attr("data-value"); + var webp = $("#webpstatus").is(":checked"); + var file = $("#file").get(0).files[0]; var filename = file.name; var formData = new FormData(); formData.append('file', file); $.ajax({ - url: "/files/upload/" + access, + url: "/files/upload/" + access + "?webpstatus=" + webp, data: formData, type: 'POST', cache: false, @@ -110,6 +97,71 @@ if (btnUserAdd != null) { /* Users profile */ +/* + 2FA +_____________________*/ +$(function() { + $(".show2fa").click(function () { + $(".twofa-container").css("display", "inline-block"); + $(".show2fa").hide(); + }); + $(".test2fa").click(function () { + var twofaTest = $("#twofa-testcode").val(); + var twofaKey = $("#twofa-key").val(); + twoFAtest(twofaTest, twofaKey); + }); + $(".save2fa").click(function () { + var twofaKey = $("#twofa-key").val(); + twoFAsave(twofaKey); + }); + $(".disable2fa").click(function () { + twoFAdisable(); + }); +}); + +function twoFAtest(twofaTest, twofaKey) { + $.ajax({ + url: "/users/profile/update/test2fa?twofakey=" + twofaKey + "&testcode=" + twofaTest, + type: 'POST', + success: function(response) { + if (response.slice(0,5) == "Error") { + alert("WARNING: The code did not match!"); + $("#twofa-testcode").css("background-color", "#ff6363"); + $(".save2fa").hide(); + } else { + $("#twofa-testcode").css("background-color", "#a1ffb1"); + $(".save2fa").show(); + } + } + }); +} +function twoFAsave(twofaKey) { + $.ajax({ + url: "/users/profile/update/save2fa?twofakey=" + twofaKey, + type: 'POST', + success: function(response) { + if (response.slice(0,5) == "Error") { + alert("Error, something went wrong"); + } else { + location.reload(); + } + } + }); +} +function twoFAdisable() { + $.ajax({ + url: "/users/profile/update/disable2fa", + type: 'POST', + success: function(response) { + if (response.slice(0,5) == "Error") { + alert("Error, something went wrong"); + } else { + location.reload(); + } + } + }); +} + /* Modal: Profile picture @@ -181,4 +233,4 @@ function userUploadProfilePictures(dataURL) { } } }); -} \ No newline at end of file +}