From f8925f07d65fffacf2bc3975b3f36b5e649aa0ab Mon Sep 17 00:00:00 2001 From: pezcurrel Date: Thu, 24 Oct 2024 06:53:20 +0200 Subject: [PATCH] First commit --- LICENSE.txt | 674 ++++++++++++++++ README.md | 97 +++ gancioff | 498 ++++++++++++ lib/curl.php | 110 +++ lib/gettlds.php | 1515 +++++++++++++++++++++++++++++++++++ lib/hashtag.php | 22 + lib/html2text.php | 17 + lib/iso-639-1-langcodes.txt | 183 +++++ lib/mastodon-postLength.php | 16 + systemd/gancioff.service | 22 + systemd/gancioff.timer | 10 + todo.txt | 19 + 12 files changed, 3183 insertions(+) create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100755 gancioff create mode 100644 lib/curl.php create mode 100644 lib/gettlds.php create mode 100644 lib/hashtag.php create mode 100644 lib/html2text.php create mode 100644 lib/iso-639-1-langcodes.txt create mode 100644 lib/mastodon-postLength.php create mode 100644 systemd/gancioff.service create mode 100644 systemd/gancioff.timer create mode 100644 todo.txt diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..43e578d --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ +```text +[[[ SYNOPSIS ]]] + +gancioff [options] + +[[[ DESCRIPTION ]]] + +This is GancioFF v0.1, a CLI PHP script that can be used to periodically +fetch the RSS feed from a Gancio¹ instance and post its entries – the events – +on the fediverse through a Mastodon account, keeping track of already posted +events in order to post only the new ones. It can be useful, for example, when +the admins of a Gancio instance chose not to use its federation feature +because it would be too heavy on its server: in this case GancioFF is quite +a light alternative, moving from the server running Gancio to the one running +Mastodon the burden of posting each event to all the instances that host at +least one follower, and of sending to them the image a Gancio user can and +almost always do attach to each event, because GancioFF will fetch it only +once and attach it to the corresponding Mastdon post. + GancioFF is meant to be periodically run (every half an hour, or so) by a +cron job or systemd timer or the likes (you can find a sample «gancioff.timer» +and a sample «gancioff.service» in the «systemd» directory). + In order to work, GancioFF needs a configuration file to be passed to it +as an argument on the command line, and the directory containing the specified +configuration file needs to be not only readable, but also writeable by the +user running GancioFF, because that’s where it will save the corresponding +state file that it will use to keep track of already posted events. + +¹ https://gancio.org + +[[[ CONFIGURATION FILE ]]] + +The configuration file needs to be like this: + +--- Example configuration file --- +# Lines beginnig with a «#» and empty lines will be ignored + +# «feed_url» is required to specify the URL to fetch the RSS feed from, +# for example: +feed_url = https://gancio.some.domain/feed/rss?show_recurrent=true + +# «fedi_hostname» is required to specify the hostname of the Mastodon instance +# you want to post to, for example: +fedi_hostname = mastodon.another.domain + +# «fedi_token» is required to specify an «app token» to access the account +# that you want to use on the instance defined by «fedi_hostname». On Mastodon +# default web frontend you can get such a token under «Preferences» -> +# «Development», by clicking on the «New application» button; the new +# application should have at least the «write:statuses» privilege, and when +# you’ll be done setting it up, it will be listed under «Your applications», +# and by clicking on its name you’ll be able to copy «Your access token» and +# paste it here; for example: +fedi_token = w6oQ_Ot2LSAm_Q31hrvp0asfl22ip3O4ipYq1kV1ceY + +# «max_post_length» is optional and lets you override the automatically +# detected maximum length that a post can have on the instance specified with +# «fedi_hostname»; it can be used for testing purposes or just to keep the +# posts shorter than they would be otherwise. For example: +max_post_length = 840 +--- End of example configuration file --- + +[[[ OPTIONS ]]] + +-h / --help + Show this help text and exit. +-p / --do-post + By default the first run with a given configuration file, i.e. when there’s + no corresponding state file yet, will be a “dry run”, that is: the script + will automatically avoid posting the events it finds in the feed, to avoid + flooding the timelines, but save their IDs in the state filejust as if «--do-not-post» or «-P» were given (see next option description). With «-p» + or «--do-post» it will post them, instead. + Also, if given after «-P» or «--do-not-post», it turns posting back on. +-I / --ignore-ids + Ignore events’ IDs, that is: don’t try to load and save already posted + events’ IDs from and to the state file. +-P / --do-not-post + Don’t post new events that could be found in the feed. Unless you also + specify «-I» or «--ignore-guids» (see previous option), this will add the IDs + of possible new events to the state file, just as if they were posted, so + those events will never be posted. +-v / --verbose + Show some more messages about what the script is doing. +-- + Treat every possible subsequent argument as non-options. Useful only in the + very improbable case your config file is named «--help» or as another option. + +[[[ EXIT VALUES ]]] + +0: regular run +1: some error occurred + +[[[ DISCLAIMER AND LICENSE ]]] + +This program comes with ABSOLUTELY NO WARRANTY; for details see the source. +This is free software, and you are welcome to redistribute it under certain +conditions; see for details. +``` diff --git a/gancioff b/gancioff new file mode 100755 index 0000000..03cc56b --- /dev/null +++ b/gancioff @@ -0,0 +1,498 @@ +#!/usr/bin/php +. +*/ + +$SNAME='GancioFF'; +$ENAME=strtolower($SNAME); +$SVERS='0.1'; + +require __DIR__.'/lib/gettlds.php'; +$tldsregex=gettlds(__DIR__.'/storage/tlds.txt',true); +require __DIR__.'/lib/mastodon-postLength.php'; +require __DIR__.'/lib/hashtag.php'; +require __DIR__.'/lib/html2text.php'; +require __DIR__.'/lib/curl.php'; + +$help= +"[[[ SYNOPSIS ]]] + +{$ENAME} [options] + +[[[ DESCRIPTION ]]] + +This is {$SNAME} v{$SVERS}, a CLI PHP script that can be used to periodically +fetch the RSS feed from an instance of Gancio (https://gancio.org) and post +its new entries – the events – on the fediverse through a Mastodon account, +keeping track of already posted events’ GUIDs (Global Unique IDentifiers) in +order to post only the new ones on each run. + It can be useful, for example, when the admins of a Gancio instance chose not +to use its federation feature because it would be too heavy on its server: in +this case {$SNAME} is a quite light alternative, moving from the server +running Gancio to the one running Mastodon the burden of posting each event to +all the instances that host at least one follower, and of sending them the +image a Gancio user can and almost always do attach to each event, because +{$SNAME} will fetch it only once and attach it to the post for the event. + {$SNAME} is meant to be periodically run, every half an hour or so, by a cron +job, or systemd timer, or the likes (you can find a sample «{$ENAME}.timer» +and a commented sample «{$ENAME}.service» in the «systemd» directory). + In order to work, {$SNAME} needs a configuration file to be passed to it as +an argument on the command line. + +[[[ CONFIGURATION FILE ]]] + +The configuration file needs to be like this: + +--- Example configuration file --- +# Lines beginnig with a «#» and empty lines will be ignored + +# «feed_url» is required to specify the URL to fetch the RSS feed from; +# for example: +feed_url = https://gancio.some.domain/feed/rss?show_recurrent=true + +# «fedi_hostname» is required to specify the hostname of the Mastodon instance +# you want to post to; for example: +fedi_hostname = mastodon.another.domain + +# «fedi_token» is required to specify an «app token» to access the account +# that you want to use on the instance defined by «fedi_hostname». On Mastodon +# default web frontend you can get such a token under «Preferences» -> +# «Development», by clicking on the «New application» button; the new +# application should have at least the «write:statuses» privilege; when you’ll +# be done setting it up, it will be listed under «Your applications», and by +# clicking on its name you’ll be able to copy «Your access token» and paste it +# here. For example: +fedi_token = w6oQ_Ot2LSAm_Q31hrvp0asfl22ip3O4ipYq1kV1ceY + +# «state_file_absolute_path» is required to specify the absolute path of the +# state file where {$SNAME} will store the GUIDs of already posted events and +# the timestamps of the moments when it posted them (on each run, {$SNAME} +# will check for entries older than one year and discard them, in order to +# avoid the state file to grow too much). For example: +state_file_absolute_path = /var/local/cache/gancio.some.domain.feed.state + +# «posts_language» is required to specify the ISO 639-1 code for the language +# of posts (see https://www.loc.gov/standards/iso639-2/php/code_list.php for +# a complete list); for example: +posts_language = it + +# «posts_visibility» is optional and lets you override the default “public” +# visibility of posts; it can be set to «public» (posts will be visible in the +# «Local» and «Federated» timelines, and any user will be able to boost them), +# «unlisted» (posts will be visible only in the «Home» timeline of followers +# and on the profile of the Mastodon account in use, not in the «Local» or +# «Federated» timelines, but any user will still be able to boost them), +# «private» (AKA «followers only»: posts will be visible only by followers and +# won’t be boostable by anyone), and «direct» (since {$SNAME} posts won’t ever +# explicitly mention any account, posts with this visibility will be visible +# only from the Mastodon account in use»). For example: +post_visibility = unlisted + +# «max_post_length» is optional and lets you override the automatically +# detected maximum length that a post can have on the instance specified with +# «fedi_hostname»; it can be used for testing purposes or just to keep the +# posts shorter than they would be otherwise; for example: +max_post_length = 840 +--- End of example configuration file --- + +[[[ OPTIONS ]]] + +-h / --help + Show this help text and exit. +-p / --do-post + Setting this option to «n» («no») will make {$SNAME} skip posting. Note that + even in this case it will save into the state file the GUIDs of new events + it may find in the feed, so it won’t post them even on the subsequent runs. + You may want to set this option to «n» on the first run on a given feed, i.e. + when the state file doesn’t exist yet and all events in the feed will be + considered new, to avoid flooding the timeline of the given Mastodon + instance. That’s why when the state file doesn’t exist yet, {$SNAME} refuses + to run unless you explicitly set this option to «n» («no») or «y» («yes»). + When the state file exists, this option defaults to «y» («yes»). +-v / --verbose + Show some more messages about what the script is doing. +-- + Treat every possible subsequent argument as non-options. Useful only in the + very improbable case your config file is named «--help» or as another option. + +[[[ EXIT VALUES ]]] + +0: regular run +1: some error occurred + +[[[ DISCLAIMER AND LICENSE ]]] + +This program comes with ABSOLUTELY NO WARRANTY; for details see the source. +This is free software, and you are welcome to redistribute it under certain +conditions; see for details.\n"; + +$confFP=null; + +$conf=[ + 'feed_url'=>['required'=>true, 'default'=>null], + 'fedi_hostname'=>['required'=>true, 'default'=>null], + 'fedi_token'=>['required'=>true, 'default'=>null], + 'state_file_absolute_path'=>['required'=>true, 'default'=>null], + 'posts_language'=>['required'=>true, 'default'=>null], + 'posts_visibility'=>['required'=>false, 'default'=>'public'], + 'max_post_length'=>['required'=>false, 'default'=>null] +]; + +$opts=[ + 'do-post'=>null, + 'verbose'=>false, + 'update-language-codes'=>false +]; + +$canBeOpt=true; +for ($i=1; $i<$argc; $i++) { + if ($canBeOpt && $argv[$i][0]=='-') { + if ($argv[$i]=='--') { + $canBeOpt=false; + } elseif ($argv[$i]=='-h' || $argv[$i]=='--help') { + echo $help; + exit(0); + } elseif ($argv[$i]=='-p' || $argv[$i]=='--do-post') { + if ($i+1>=$argc) dieYoung("Error: option «{$argv[$i]}» requires an argument; use «-h» or «--help» to display help.\n",1); + if ($argv[$i+1]=='y') + $opts['do-post']=true; + elseif ($argv[$i+1]=='n') + $opts['do-post']=false; + else + dieYoung("Error: option «{$argv[$i]}» requires an argument of «y» for «yes» or «n» for «no»; use «-h» or «--help» to display help.\n",1); + $i++; + } elseif ($argv[$i]=='-v' || $argv[$i]=='--verbose') { + $opts['verbose']=true; + } elseif ($argv[$i]=='-u' || $argv[$i]=='--update-language-codes') { + $opts['update-language-codes']=true; + } elseif ($argv[$i]=='--make-readme') { + file_put_contents(__DIR__.'/README.md',"```text\n{$help}```\n"); + exit(0); + } else { + dieYoung("Error: «{$argv[$i]}» is not a known option; use «-h» or «--help» to display help.\n",1); + } + } elseif (is_null($confFP)) { + $confFP=$argv[$i]; + } else { + dieYoung("Error: could not interpret «{$argv[$i]}» (configuration file has already been set to «{$confFP}»); use «-h» or «--help» to display help.\n",1); + } +} + +$langsFP=__DIR__.'/lib/iso-639-1-langcodes.txt'; +if ($opts['update-language-codes']) { + $langCodes=[]; + $url='https://www.loc.gov/standards/iso639-2/ISO-639-2_8859-1.txt'; + $res=curl($url); + if ($res['content']===false) dieYoung("Error: could not connect to «{$url}».\n",1); + if ($res['httpcode']!='200') dieYoung("Error: got http code «{$res['httpcode']}» from «{$url}».\n",1); + $res=explode("\r\n",$res['content']); +// alb|sqi|sq|Albanian|albanais +// tup|||Tupi languages|tupi, langues + foreach ($res as $val) + if (preg_match('#^[a-z]{3}\|([a-z]{3})?\|([a-z]{2})\|.+\|.+$#',$val,$matches)===1) + $langCodes[]=$matches[2]; + $count=count($langCodes); + if (@file_put_contents($langsFP,implode("\n",$langCodes)."\n")===false) dieYoung("Error: could not save the {$count} ISO 639-1 language code(s) i got from «{$url}» into «{$langsFP}».\n",1); + echo "Info: successfully saved the {$count} ISO 639-1 language code(s) i got from «{$url}» into «{$langsFP}».\n"; + exit(0); +} +if (($langs=@file($langsFP,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES))===false) dieYoung("Error: could not load ISO 639-1 language codes from «{$langsFP}».\n",1); + +if (is_null($confFP)) dieYoung("Error: you have not specified a configuration file; use «-h» or «--help» to display help.\n",1); +echo "Info: trying to load configuration file «{$confFP}» from directory «".getcwd()."».\n"; +if (!file_exists($confFP)) dieYoung("Error: «{$confFP}» does not exist.\n",1); +if (!is_file($confFP)) dieYoung("Error: «{$confFP}» is not a file.\n",1); +if (!is_readable($confFP)) dieYoung("Error: «{$confFP}» is not readable.\n",1); +getConf($conf,$confFP); +if (preg_match('#^/.*$#',$conf['state_file_absolute_path'])!==1) dieYoung("Error: in configuration file: «state_file_absolute_path» must be an absolute path.\n",1); +if (!in_array($conf['posts_language'],$langs)) dieYoung("Error: in configuration file: «posts_language»: «{$conf['posts_language']}» is not a known language code.\n",1); +if (!in_array($conf['posts_visibility'],['public', 'unlisted', 'private', 'direct'])) dieYoung("Error: in configuration file: «posts_visibility» must be one of «public», «unlisted», «private» or «direct».\n",1); +if (!is_null($conf['max_post_length'])) { + if (preg_match('#^\d+$#',$conf['max_post_length'])!==1 || $conf['max_post_length']+0<10) dieYoung("Error: configuration file: «max_post_length» must be an integer greater than or equal to 10.\n",1); + $conf['max_post_length']+=0; + echo "Info: got «{$conf['max_post_length']}» as «max_post_length» from configuration file.\n"; +} + +$url="https://{$conf['fedi_hostname']}/api/v2/instance"; +echo "Info: trying to fetch instance info from «{$url}».\n"; +$res=curl($url,null,["Authorization: Bearer {$conf['fedi_token']}", 'Accept: application/json']); +if ($res['content']===false) dieYoung("Error: could not connect to «{$url}» (error: «{$res['error']}»).\n",1); +$res['content']=@json_decode($res['content'],true); +if (is_null($res['content'])) dieYoung("Error: content from «{$url}» was not good JSON.\n",1); +(isset($res['content']['error'])) ? $buff=" («{$res['content']['error']}»)" : $buff=''; +if ($res['httpcode']!='200') dieYoung("Error: got http code «{$res['httpcode']}»{$buff} from «{$url}».\n",1); +if (!isset($res['content']['configuration']['media_attachments']['image_size_limit'])) dieYoung("Error: JSON from «{$url}» doesn’t declare «image_size_limit».\n",1); +if (!is_int($res['content']['configuration']['media_attachments']['image_size_limit'])) dieYoung("Error: JSON from «{$url}» declares «image_size_limit» with an unexpected format.\n",1); +$conf['max_image_size']=$res['content']['configuration']['media_attachments']['image_size_limit']+0; +echo "Info: got «{$conf['max_image_size']}» as «max_image_size» from «{$url}».\n"; +if (!isset($res['content']['configuration']['statuses']['max_characters'])) dieYoung("Error: JSON from «{$url}» doesn’t declare «max_characters».\n",1); +if (!is_int($res['content']['configuration']['statuses']['max_characters'])) dieYoung("Error: JSON from «{$url}» declares «max_characters» with an unexpected format.\n",1); +if (is_null($conf['max_post_length'])) { + $conf['max_post_length']=$res['content']['configuration']['statuses']['max_characters']+0; + echo "Info: got «{$conf['max_post_length']}» as «max_post_length» from «{$url}».\n"; +} +//print_r($conf); + +echo "Info: trying to fetch feed from «{$conf['feed_url']}».\n"; +$feed=curl($conf['feed_url'],null,['Accept: application/xml']); +if ($feed['content']===false) dieYoung("Error: could not connect to «{$conf['feed_url']}» (error: «{$feed['error']}»).\n",1); +if ($feed['httpcode']!='200') dieYoung("Error: «{$conf['feed_url']} returned http code «{$res['httpcode']}».\n",1); +$feed=@simplexml_load_string($feed['content'],null,LIBXML_NOCDATA); +if ($feed===false) dieYoung("Error: got no valid XML from «{$conf['feed_url']}».\n",1); +//print_r($feed); +if (!isset($feed->channel->item) || !is_iterable($feed->channel->item) || !is_countable($feed->channel->item)) dieYoung("Error: feed from «{$conf['feed_url']}» had unexpected format.\n",1); +$itemsCount=$feed->channel->item->count(); +if ($itemsCount==0) exitYoung("Info: feed from «{$conf['feed_url']}» was empty, bye.\n"); +echo "Info: got good feed from «{$conf['feed_url']}».\n"; + +$guids=[]; +echo "Info: trying to load GUIDs of already posted events from state file «{$conf['state_file_absolute_path']}».\n"; +if (!file_exists($conf['state_file_absolute_path']) && is_null($opts['do-post'])) dieYoung("Error: state file «{$conf['state_file_absolute_path']}» does not exist: this seems to be a first run on feed «{$conf['feed_url']}», so you should explicitly declare whether you want {$SNAME} to post all of its events or not, setting option «-p» or «--do-post» to «y» («yes») or «n» («no»); use «-h» or «--help» to display help.\n",1); +if (is_null($opts['do-post'])) $opts['do-post']=true; +if (file_exists($conf['state_file_absolute_path'])) { + if (!is_file($conf['state_file_absolute_path'])) dieYoung("Error: «{$conf['state_file_absolute_path']}» exists but it’s not a file.\n",1); + if (!is_readable($conf['state_file_absolute_path'])) dieYoung("Error: «{$conf['state_file_absolute_path']}» exists but it’s not readable.\n",1); + if (!is_readable($conf['state_file_absolute_path'])) dieYoung("Error: «{$conf['state_file_absolute_path']}» exists but it’s not writable.\n",1); + $guids=[]; + $buff=file($conf['state_file_absolute_path'],FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); + $graceTime=365*24*60*60; + $graceLine=time()-$graceTime; + $i=0; + $fh=fopen($conf['state_file_absolute_path'],'w'); + foreach ($buff as $key=>$val) { + if (preg_match('#^(\d+)\t(\S+)$#',$val,$matches)===1) { + if ($matches[1]+0>=$graceLine) { + fwrite($fh,"{$matches[1]}\t{$matches[2]}\n"); + $guids[$matches[2]]=$matches[1]; + } else { + $i++; + } + } else { + fwrite(STDERR,"Warning: in state file «{$conf['state_file_absolute_path']}», line ".($key+1)." had unexpected format.\n"); + } + } + fclose($fh); + echo 'Info: got '.count($guids)." GUID(s) for already posted event(s) from state file «{$conf['state_file_absolute_path']}»; removed {$i} line(s) older than one year.\n"; +} + +if (($fh=@fopen($conf['state_file_absolute_path'],'a'))===false) dieYoung("Error: could not open «{$conf['state_file_absolute_path']}» in «append» mode.\n",1); +$newItemsCount=0; +$goodPostsCount=0; +$index=0; +foreach ($feed->channel->item as $item) { + $index++; +// print_r($item); + if (!isset($item->guid) || ($guid=$item->guid->__toString())=='') { + fwrite(STDERR,"Warning: event #{$index} has no GUID, skipping.\n"); + } elseif (!array_key_exists($guid,$guids)) { + $newItemsCount++; + $file=null; + if (isset($item->enclosure[0]['url']) && isset($item->enclosure[0]['type']) && isset($item->enclosure[0]['length'])) + $file=['url'=>$item->enclosure[0]['url']->__toString(), 'type'=>$item->enclosure[0]['type']->__toString(), 'length'=>$item->enclosure[0]['length']->__toString()]; + if (isset($item->description)) { + $buff=$item->description->__toString(); + if ($buff=='') { + $ptext=''; + } elseif (preg_match('#^\n?

(.+)

(.+)
\((\w+)\W+(\d+)\W+(\w+)\W+(\d+:\d+)\)
(.+)$#iuU',$buff,$matches)===1) { +// print_r($matches); + $matches[1]=hent($matches[1]); + $matches[2]=hent($matches[2]); + $ptext="{$matches[1]}\n\n".ucfirst($matches[3])." {$matches[4]} {$matches[5]} alle {$matches[6]} presso {$matches[2]}\n\n".html2text($matches[7]); + } else { + $ptext=html2text($item->description); + } + } + if (isset($item->link) && $item->link->__toString()!='') { + $plink="\n\n".$item->link->__toString(); + } else { + $plink=''; + } + if (isset($item->category) && is_countable($item->category) && is_iterable($item->category) && $item->category->count()>0) { + $pcats=[]; + foreach ($item->category as $val) $pcats[]=hashtag($val->__toString()); + $pcats="\n\n".implode(' ',$pcats); + } else { + $pcats=''; + } + $post="{$ptext}{$plink}{$pcats}"; + while (postLength($post,$tldsregex['tlds'])>$conf['max_post_length'] && $ptext!='') { + $ptext=preg_replace('#\S+\W*$#','',$ptext); +// echo "[[[{$ptext}]]]\n"; + $post="{$ptext}[…]{$plink}{$pcats}"; + } + if (postLength($post,$tldsregex['tlds'])>$conf['max_post_length']) $post=$plink; + if (postLength($post,$tldsregex['tlds'])>$conf['max_post_length']) { + fwrite(STDERR,"Warning: could not shorten post for event «{$guid}» to make it fit into {$conf['max_post_length']} characters; will not post.\n"); + } else { + if ($opts['verbose']) echo "--- #{$index}: {$guid} ---\n{$post}\n--- (length: ".postLength($post,$tldsregex['tlds']).") ---\n\n"; + if ($opts['do-post']) { + $postData=[]; +// print_r($file); + if (is_null($file)) { + if ($opts['verbose']) echo "Info: event «{$guid}» has no attachment.\n"; + } elseif ($file['length']>$conf['max_image_size']) { + fwrite(STDERR,"Warning: ignoring attachment of event «{$guid}» because its size is greater than image upload max size on «{$conf['fedi_hostname']}».\n"); + } else { + $res=curl($file['url']); + if ($res['content']===false) { + fwrite(STDERR,"Warning: could not connect to «{$file['url']}» (error: «{$res['error']}»); won’t post file as attachment.\n"); + } elseif ($res['httpcode']!='200') { + fwrite(STDERR,"Warning: «{$file['url']}» returned http code «{$res['httpcode']}»; won’t post file as attachment.\n"); + } else { + $pd=['file'=>new CURLStringFile($res['content'],'file',$file['type']), 'description'=>'Flyer dell’evento']; + $url="https://{$conf['fedi_hostname']}/api/v2/media"; + $res=curl($url,'/api/v2/media',["Authorization: Bearer {$conf['fedi_token']}", 'Accept: application/json'],$pd); + if ($res['content']===false) { + fwrite(STDERR,"Warning: could not connect to «{$url}» (error: «{$res['error']}»); won’t post file as attachment.\n"); + } elseif (is_null($res['content']=@json_decode($res['content'],true))) { + fwrite(STDERR,"Warning: «{$url}» did not return valid JSON; won’t post file as attachment.\n"); + } elseif ($res['httpcode']!='200' && $res['httpcode']!='202') { + (isset($res['content']['error'])) ? $buff=" (error: «{$res['content']['error']}»)" : $buff=''; + fwrite(STDERR,"Warning: «{$url}» returned http code «{$res['httpcode']}»{$buff}; won’t post file as attachment.\n"); + } elseif (!isset($res['content']['id'])) { + fwrite(STDERR,"Warning: no «id» in JSON from «{$url}»; won’t post file as attachment.\n"); + } else { + $id=$res['content']['id']; + if ($res['httpcode']=='202') { + $id=null; + $i=1; + while ($res['httpcode']!='200' && $i<5) { + sleep(2); + $url="https://{$conf['fedi_hostname']}/api/v1/media/{$res['id']}"; + $res=curl($url,'/api/v1/media',["Authorization: Bearer {$conf['fedi_token']}", 'Accept: application/json']); + if ($res['content']!==false && $res['httpcode']=='200' && !is_null($res['content']=@json_decode($res,true)) && isset($res['content']['id'])) $id=$res['content']['id']; + $i++; + } + } + if (!is_null($id)) + $postData['media_ids[]']=$id; + else + fwrite(STDERR,"Warning: server took too long to process file, or could not; won’t post file as attachment.\n"); + } + } + } + $postData['status']=$post; + $postData['visibility']=$conf['posts_visibility']; + $postData['language']='it'; + $url="https://{$conf['fedi_hostname']}/api/v1/statuses"; + $headers=["Authorization: Bearer {$conf['fedi_token']}", 'Accept: application/json', 'Idempotency-Key: '.md5(implode('-',$postData).time())]; + $res=curl($url,'/api/v1/statuses',$headers,$postData); + if ($res['content']===false) { + fwrite(STDERR,"Warning: could not connect to «{$url}» (error: «{$res['error']}»); could not post status for event «{$guid}».\n"); + } elseif (is_null($res['content']=@json_decode($res['content'],true))) { + fwrite(STDERR,"Warning: «{$url}» did not return good JSON; could not post status for event «{$guid}».\n"); + } elseif ($res['httpcode']!='200') { + (isset($res['content']['error'])) ? $buff=" (error: «{$res['content']['error']}»)" : $buff=''; + fwrite(STDERR,"Warning: «{$url}» returned http code «{$res['httpcode']}»{$buff}; could not post status for event «{$guid}».\n"); + } elseif (!isset($res['content']['url'])) { + fwrite(STDERR,"Warning: JSON from «{$url}» had unexpected format; could not post status for event «{$guid}».\n"); + } else { + echo "Info: successfully posted status for event «{$guid}» (URL: «{$res['content']['url']}»).\n"; +// print_r($res['content']); + $now=time(); + $guids[$guid]=$now; + fwrite($fh,"{$now}\t{$guid}\n"); + $goodPostsCount++; + } + } else { + echo "Info: would have posted status for event «{$guid}».\n"; + $now=time(); + $guids[$guid]=$now; + fwrite($fh,"{$now}\t{$guid}\n"); + $goodPostsCount++; + } + } + } else { + if ($opts['verbose']) echo "Info: event «{$guid}» has already been posted on ".date('c',$guids[$guid]).", skipping.\n"; + } +// fclose($fh); exit(0);// to test a single post +} +fclose($fh); +if ($opts['do-post']) + echo "Info: feed got {$itemsCount} events; succesfully posted {$goodPostsCount} of {$newItemsCount} new event(s).\n"; +else + echo "Info: feed got {$itemsCount} event(s), {$newItemsCount} new.\n"; + +exit(0); + + +function getConf(&$conf,&$confFP) { + $errors=[]; + $nconf=[]; + $buff=@file($confFP,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); + if ($buff===false) dieYoung("Error: could not read configuration file «$confFP}».\n",1); + $i=0; + foreach ($buff as $line) { + $i++; + if ($line[0]!=='#') { + if (preg_match('#^([^=]+)=(.+)$#',$line,$matches)===1) { + $matches[1]=trim($matches[1]); + $matches[2]=trim($matches[2]); + if (array_key_exists($matches[1],$conf)) + $nconf[$matches[1]]=$matches[2]; + else + $errors[]="line {$i}: «{$matches[1]}» is an unknown key.\n"; + } else { + $errors[]="could not interpret line {$i} («{$line}»)"; + } + } + } + //print_r($nconf); + foreach ($conf as $key=>$val) { + if ($conf[$key]['required'] && !array_key_exists($key,$nconf)) + $errors[]="«{$key}» is not defined"; + if (array_key_exists($key,$nconf)) + $conf[$key]=$nconf[$key]; + else + $conf[$key]=$conf[$key]['default']; + } + $errorsCount=count($errors); + if ($errorsCount>0) { + fwrite(STDERR,"Sorry, there are errors in configuration file «{$confFP}»:\n"); + for ($i=1; $i<=$errorsCount; $i++) + fwrite(STDERR," {$i}. {$errors[$i-1]}\n"); + fwrite(STDERR,"Use «-h» or «--help» to display help.\n"); + exit(1); + } +} + +function cknap($napid) { + global $naps; + $now=time(); + if (isset($naps[$napid]) && $naps[$napid]>$now) { + $sleepsecs=$naps[$napid]-$now; + echo "Info: reached rate limit on «{$napid}»; sleeping until ".date('c',$naps[$napid]).' ...'; + sleep($sleepsecs); + echo "\n"; + $naps[$napid]=0; + } +} + +function hent($str) { + return html_entity_decode($str,ENT_QUOTES,'UTF-8'); +} + +function dieYoung($msg,$ec) { + fwrite(STDERR,$msg); + die($ec); +} + +function exitYoung($msg) { + echo $msg; + exit(0); +} + +?> diff --git a/lib/curl.php b/lib/curl.php new file mode 100644 index 0000000..c8e5f01 --- /dev/null +++ b/lib/curl.php @@ -0,0 +1,110 @@ +$now) { + echo "Info: reached rate limit on «{$napid}»; sleeping until ".date('c',$naps[$napid]).' ...'; + sleep($naps[$napid]-$now); + echo "\n"; + $naps[$napid]=0; + } +} +--- + +Example usage: + +--- +$postData=['file'=>new CURLStringFile($file['content'],$file['name'],$file['type']), 'description'=>$file['description']; +$url="https://{$conf['fedi_hostname']}/api/v2/media"; +$res=curl($url,'/api/v2/media',["Authorization: Bearer {$conf['fedi_token']}", 'Accept: application/json'],$postData); +if ($res['content']===false) { + echo "Warning: could not connect to «{$url}» (error: «{$res['error']}»).\n"; +} elseif (is_null($res['content']=@json_decode($res['content'],true))) { + echo "Warning: «{$url}» did not return valid JSON.\n"; +} elseif ($res['httpcode']!='200' && $res['httpcode']!='202') { + (isset($res['content']['error'])) ? $buff=" (error: «{$res['content']['error']}»)" : $buff=''; + echo "Warning: «{$url}» returned http code «{$res['httpcode']}»{$buff}.\n"; +} elseif (!isset($res['content']['id'])) { + echo "Warning: no «id» in JSON from «{$url}».\n"; +} else { + $id=$res['content']['id']; + [...] +} +--- +*/ + +function curl($url,$napid=null,$headers=null,$postdata=null,$conntimeout=null,$functimeout=null,$proxy=null) { + if (!is_null($napid)) cknap($napid); + if (is_null($conntimeout)) $conntimeout=5; + if (is_null($functimeout)) $functimeout=20; + $ch=curl_init(); + curl_setopt($ch,CURLOPT_URL,$url); + curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); + curl_setopt($ch,CURLOPT_FAILONERROR,false); + curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$conntimeout); + curl_setopt($ch,CURLOPT_TIMEOUT,$functimeout); + curl_setopt($ch,CURLOPT_HEADER,true); +// example $headers: ['Content-type: text/plain', 'Content-length: 100'] + if (is_array($headers)) curl_setopt($ch,CURLOPT_HTTPHEADER,$headers); + curl_setopt($ch,CURLOPT_ENCODING,''); + curl_setopt($ch,CURLOPT_USERAGENT,'curl/1.0'); +// curl automatically uses a "Content-Type" of "multipart/form-data" if $postdata is an array, of "application/x-www-form-urlencoded" if it's a string + if (!is_null($postdata)) curl_setopt($ch,CURLOPT_POSTFIELDS,$postdata); + if (!is_null($proxy)) { + curl_setopt($ch,CURLOPT_PROXY,$proxy); + curl_setopt($ch,CURLOPT_PROXYTYPE,CURLPROXY_SOCKS5); + } + $gheaders=null; + $httpcode=null; + $error=false; + $res=curl_exec($ch); + if ($res!==false) { + $now=time(); + $gheaders_sz=curl_getinfo($ch,CURLINFO_HEADER_SIZE); + $gheaders=substr($res,0,$gheaders_sz-4);// "-4" accounts for the 2 "\r\n" that separates headers from body +// echo "{$gheaders}\n"; + $gheaders=explode("\r\n",$gheaders); + $res=substr($res,$gheaders_sz); + $httpcode=preg_replace('#^\S+\s+(\d+).*$#','$1',$gheaders[0]); + if (!is_null($napid)) { + global $naps; + foreach ($gheaders as $header) { + if (preg_match('#^date: (.*)$#i',$header,$matches)===1) { + $sdate=@strtotime($matches[1]); + if ($sdate===false) break; + } elseif (preg_match('#^x-ratelimit-remaining: (\d+)$#i',$header,$matches)===1) { + $rlrem=$matches[1]+0; +// echo "Ratelimit-remaining: {$rlrem}\n"; + } elseif (preg_match('#^x-ratelimit-reset: (.*)$#i',$header,$matches)===1) { + $rlres=@strtotime($matches[1]); + if ($rlres===false) break; + } + if (isset($sdate) && isset($rlrem) && isset($rlres)) { +// echo "date: {$sdate}; rem: {$rlrem}; res: {$rlres}.\n"; + if ($rlrem==0) $naps[$napid]=$now+$rlres-$sdate+1; + break; + } + } + } + } else { + $error=curl_errno($ch).': '.trim(curl_error($ch)); + } + curl_close($ch); + return ['content'=>$res,'httpcode'=>$httpcode,'headers'=>$gheaders,'error'=>$error]; +} + +?> diff --git a/lib/gettlds.php b/lib/gettlds.php new file mode 100644 index 0000000..8543b9e --- /dev/null +++ b/lib/gettlds.php @@ -0,0 +1,1515 @@ +=3 && $tlds[0][0]=='#' && preg_match('#^\d+$#',$tlds[1])===1) { + array_shift($tlds); + $ts=array_shift($tlds); + if (preg_match('#^\d+$#',$ts)===1) { + foreach ($tlds as $val) { + if (preg_match('#^[a-z\-\d]+$#',$val)!==1) { + $warnings[]="TLDs cache file «{$cachefp}» had unexpected format (3)"; + $tlds=false; + break; + } + } + } else { + $warnings[]="TLDs cache file «{$cachefp}» had unexpected format (2)"; + $tlds=false; + } + } else { + $warnings[]="TLDs cache file «{$cachefp}» had unexpected format (1)"; + $tlds=false; + } + $now=time(); +// if cache file doesn't exist, is not readable or has wrong format, or if its timestamp is more than 1 day old, try to load tlds from the web + if ($tlds===false || $now-$ts>86400) { + $url='https://data.iana.org/TLD/tlds-alpha-by-domain.txt'; + $tlds=@file($url,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); + if ($tlds===false) { + $warnings[]="could not load TLDs from «{$url}»"; + } else { + if ($tlds[0][0]=='#') array_shift($tlds);// remove first line if it's comment + foreach ($tlds as $key=>$val) { + if (preg_match('#^[A-Z\-\d]+$#',$val)!==1) { + echo "{$val}\n"; + $tlds=false; + break; + } else { + $tlds[$key]=strtolower($val); + } + } + if ($tlds===false) $warnings[]="TLDs from «{$url}» had unexpected format"; + } + } + if ($tlds===false) { + $tlds=$deftlds; + $warnings[]='resorted to embedded TLDs (1)'; + } else { + if (@file_put_contents($cachefp,"# This file is automatically generated, please do not modify it\n{$now}\n".implode("\n",$tlds)."\n")===false) { + $warnings[]="could not write TLDs into cache file «{$cachefp}»"; + $tlds=$deftlds; + $warnings[]='resorted to embedded TLDs (2)'; + } +// uncomment next line to output tlds for $deftlds +// echo "'".implode("',\n'",$tlds)."'\n"; + } + if ($regexformat) { + rsort($tlds); + $tlds=implode('|',$tlds); + } + (count($warnings)==0) ? $warnings=null : $warnings=implode('; ',$warnings); + return ['tlds'=>$tlds, 'warnings'=>$warnings]; +} + +?> diff --git a/lib/hashtag.php b/lib/hashtag.php new file mode 100644 index 0000000..dd6044d --- /dev/null +++ b/lib/hashtag.php @@ -0,0 +1,22 @@ +1) { + ($ucfirst) ? $beg=0 : $beg=1; + for ($i=$beg; $i<$c; $i++) { + if (preg_match('#^.#u',$str[$i],$matches)===1) { + $first=mb_strtoupper($matches[0],'UTF-8'); + $str[$i]=preg_replace('#^.#u',$first,$str[$i]); + } + } + $str=implode('',$str); + } else { + $str=$str[0]; + } + $str="#{$str}"; + return $str; +} + +?> diff --git a/lib/html2text.php b/lib/html2text.php new file mode 100644 index 0000000..c3c0387 --- /dev/null +++ b/lib/html2text.php @@ -0,0 +1,17 @@ +#',"\n",$str); + $str=preg_replace('#

|||||#',"\n\n",$str); + $str=str_replace('
  • ',' • ',$str); + $str=preg_replace('#
  • \n*#',"\n",$str); + $str=strip_tags($str); + $str=html_entity_decode($str,ENT_QUOTES,'UTF-8'); + $str=preg_replace('#\n{3,}#',"\n\n",$str); + $str=trim($str,"\n"); + return $str; +} + +?> diff --git a/lib/iso-639-1-langcodes.txt b/lib/iso-639-1-langcodes.txt new file mode 100644 index 0000000..0bdd27c --- /dev/null +++ b/lib/iso-639-1-langcodes.txt @@ -0,0 +1,183 @@ +aa +ab +af +ak +sq +am +ar +an +hy +as +av +ae +ay +az +ba +bm +eu +be +bn +bi +bs +br +bg +my +ca +ch +ce +zh +cu +cv +kw +co +cr +cs +da +dv +nl +dz +en +eo +et +ee +fo +fj +fi +fr +fy +ff +ka +de +gd +ga +gl +gv +el +gn +gu +ht +ha +he +hz +hi +ho +hr +hu +ig +is +io +ii +iu +ie +ia +id +ik +it +jv +ja +kl +kn +ks +kr +kk +km +ki +rw +ky +kv +kg +ko +kj +ku +lo +la +lv +li +ln +lt +lb +lu +lg +mk +mh +ml +mi +mr +ms +mg +mt +mn +na +nv +nr +nd +ng +ne +nn +nb +no +ny +oc +oj +or +om +os +pa +fa +pi +pl +pt +ps +qu +rm +ro +rn +ru +sg +sa +si +sk +sl +se +sm +sn +sd +so +st +es +sc +sr +ss +su +sw +sv +ty +ta +tt +te +tg +tl +th +bo +ti +to +tn +ts +tk +tr +tw +ug +uk +ur +uz +ve +vi +vo +cy +wa +wo +xh +yi +yo +za +zu diff --git a/lib/mastodon-postLength.php b/lib/mastodon-postLength.php new file mode 100644 index 0000000..0202ce9 --- /dev/null +++ b/lib/mastodon-postLength.php @@ -0,0 +1,16 @@ + |{$post}|\n"; + // for some reason, mastodon seems to check tld existence only on http(s) links - see next regexp + $res=preg_replace('#(^|\W)(@[a-zA-Z0-9_]+)@(([a-z0-9]([a-z0-9-]+[a-z0-9])?){1,63}\.)+([a-z0-9]([a-z0-9-]+[a-z0-9])?){1,63}\b#u', '$1$2', $post); + if (!is_null($res)) $post=$res; +// $res=preg_replace('#(^|\W)https?://(([a-z0-9]([a-z0-9-]+[a-z0-9])?){1,63}\.)+([a-z0-9]([a-z0-9-]+[a-z0-9])?){1,63}(/\S*[\w=?_-])?#u', '$1HTTP://UUUUUUUUUUUUUUUU', $post); + // on http(s) links mastodon checks if tld exists... + $res=preg_replace('#(^|\W)https?://(([a-z0-9]([a-z0-9-]+[a-z0-9])?){1,63}\.)+('.$tldsregex.')(/\S*[\w/=_\-])?#u', '$1UUUUUUUUUUUUUUUUUUUUUUU', $post); + if (!is_null($res)) $post=$res; +// echo "-B-> |{$post}|\n"; + return mb_strlen($post,'UTF-8'); +} + +?> diff --git a/systemd/gancioff.service b/systemd/gancioff.service new file mode 100644 index 0000000..5fdf382 --- /dev/null +++ b/systemd/gancioff.service @@ -0,0 +1,22 @@ +[Unit] +Description=GancioFF +After=network.target + +[Service] +# «oneshot» is the good «Type» +Type=oneshot + +# Uncomment next directive if you want to set a specific working directory. +# Note that in this case “” and “” +# will need to be relative to the working directory (or absolute). +#WorkingDirectory= + +# Uncomment next directive if you want to avoid running GancioFF as root; +# note that the user specified here needs to have read access to the +# configuration file specified in «ExecStart» (see below), read-write access +# to the state file specified in the configuration file, and read-write access +# to the GancioFF «storage» sub-directory. +#User= + +# Uncomment the directive below and edit it to set GancioFF’s command line. +#ExecStart=php diff --git a/systemd/gancioff.timer b/systemd/gancioff.timer new file mode 100644 index 0000000..3c98a68 --- /dev/null +++ b/systemd/gancioff.timer @@ -0,0 +1,10 @@ +[Unit] +Description=GancioFF +After=network.target + +[Timer] +OnBootSec=5m +OnUnitInactiveSec=30m + +[Install] +WantedBy=timers.target diff --git a/todo.txt b/todo.txt new file mode 100644 index 0000000..e24ad81 --- /dev/null +++ b/todo.txt @@ -0,0 +1,19 @@ +- = to do; ? = to do?; * = done; ~ = half done; ! = don't + +- gettlds and --update-language-codes should save elsewhere +- add "[pubDate] => Wed, 09 Oct 2024 20:52:33 GMT" from XML items to post +- verify that "lib/" stays 777 when downloaded by git +- add runtime control for clean exits (possible "fclose($fh);") in case of ctrl+c and the likes +- verify "wait for server to process file" code works by uploading a big video, and whether on mastodon < 4.0.0 it is really triggered for images too +- config file: make it possible to define how long to wait for server to process a file +- config file: make it possible to define how old records in state file can be before they get discarded +- report Gancio flaw: api/events (https://demo.gancio.org/api/events) does not return descriptions (maybe it would have been easier to write gancioff using api/events) +* config file: make it possible to define posts language +* config file: make it possible to define posts visibility +* systemd sample unit files +* check maximum upload size and check it against file size +! make it possible to define a "defaul hashtag" to be put before the others (no, if one wants to only see the events they just need to open the profile) +* make it possible to define a maximum period of time for storing guids (done, set it to 365 days, not configurable atm) +* use the state file to save every id of correctly posted events +* set cknap on recurring curl usage +* add (optional) image upload